@openchamber/web 1.18.2 → 1.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/bin/lib/commands-models.js +1 -1
  2. package/dist/assets/{CodeMirrorCommentWidgets-CxcJ5x9h.js → CodeMirrorCommentWidgets-DbUi6I9s.js} +1 -1
  3. package/dist/assets/{CommitSection-C9sBBYAJ.js → CommitSection-Jc2_hNPE.js} +1 -1
  4. package/dist/assets/{DiagramEditor-C7nUw7p3.js → DiagramEditor-PCrYHBko.js} +1 -1
  5. package/dist/assets/{DiagramView-cYxZP-HS.js → DiagramView-CndEcZNu.js} +1 -1
  6. package/dist/assets/{DiffView-1zd0slLu.js → DiffView-DEGlNjMH.js} +2 -2
  7. package/dist/assets/FilesView-CzUgIvUm.js +14 -0
  8. package/dist/assets/{GitView-OSVIn5V1.js → GitView-C-n17voy.js} +1 -1
  9. package/dist/assets/{JsonTreeView-Kgepz4pR.js → JsonTreeView-BYcgdTOQ.js} +1 -1
  10. package/dist/assets/MarkdownImageGallery-DzHwkVIH.js +1 -0
  11. package/dist/assets/MarkdownRendererImpl-DUcIcWgs.js +12 -0
  12. package/dist/assets/OnboardingScreen-BmN0lhk4.js +1 -0
  13. package/dist/assets/{PatchDiff-Cddz02Ya.js → PatchDiff-Bn7bfgUv.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-B5k0KvPW.js → PierreDiffViewer-D1fWvrUn.js} +2 -2
  15. package/dist/assets/{PlanView-BYgHBHDt.js → PlanView-CWM0iyFk.js} +3 -3
  16. package/dist/assets/{SessionSwitcherDropdown-ig2OT22Z.js → SessionSwitcherDropdown-Cez-9xRh.js} +1 -1
  17. package/dist/assets/SettingsView-Bl1drwPw.js +28 -0
  18. package/dist/assets/{SettingsWindow-CNHM8ifT.js → SettingsWindow-DL5axjDZ.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-DrGeYq2p.js → ToolOutputDialog-BtIJkFno.js} +7 -7
  20. package/dist/assets/{ToolPartDiffPreview-BRmPpe94.js → ToolPartDiffPreview-i3PQo6_0.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-Dcu8Q-5P.js → VirtualizedFileDiff-DkcusvMa.js} +1 -1
  22. package/dist/assets/{WalkthroughView-HStEYdD2.js → WalkthroughView-Cc5Hd6P5.js} +2 -2
  23. package/dist/assets/{computeVirtualFileMetrics-DQE7R9IY.js → computeVirtualFileMetrics-xPena3W2.js} +2 -2
  24. package/dist/assets/contextPanelEmbeddedChat-tQekJUAF.js +1 -0
  25. package/dist/assets/de-u7gSnqWs.js +9 -0
  26. package/dist/assets/es-T9O7aAOr.js +15 -0
  27. package/dist/assets/fr-Oor7ewbE.js +13 -0
  28. package/dist/assets/index-CVNuER6G.css +1 -0
  29. package/dist/assets/{index-BgQEgA2a.js → index-Crz1YOFl.js} +1 -1
  30. package/dist/assets/index-iFY_N5aO.js +7 -0
  31. package/dist/assets/{isDiffPlainText-XyBCe4eD.js → isDiffPlainText-Dudf-dWx.js} +1 -1
  32. package/dist/assets/{isFilePlainText-JbqDfa3n.js → isFilePlainText-DS4QV1dd.js} +1 -1
  33. package/dist/assets/ja-DHpqbVmr.js +15 -0
  34. package/dist/assets/ko-CwLkS3nx.js +15 -0
  35. package/dist/assets/{main-LfcbGv7C.js → main-C0DyIwTb.js} +2 -2
  36. package/dist/assets/main-CAxX6DAN.js +915 -0
  37. package/dist/assets/markdownCore-DhfzuGXu.js +2 -0
  38. package/dist/assets/markdownImageAssets-BTNlRyjd.js +1 -0
  39. package/dist/assets/{miniChat-CUp_elRz.js → miniChat-CGfrxKpJ.js} +2 -2
  40. package/dist/assets/{mobile-CBSN7BsH.js → mobile-DEmhwNcV.js} +2 -2
  41. package/dist/assets/{patchFileDiff-DCIXUHRJ.js → patchFileDiff-C5D1OPCa.js} +2 -2
  42. package/dist/assets/{pl-tHTP6XQx.js → pl-CcZILN8q.js} +4 -4
  43. package/dist/assets/pt-BR-DYHhVK6o.js +15 -0
  44. package/dist/assets/{renderElectronMiniChatApp-eZl-5STF.js → renderElectronMiniChatApp-Dpbswpom.js} +2 -2
  45. package/dist/assets/renderMobileApp-B5HA4qbi.js +25 -0
  46. package/dist/assets/runtimeEndpointReset-cbahJ3hD.js +13 -0
  47. package/dist/assets/scheduledTasksApi-BxgGWTL8.js +1 -0
  48. package/dist/assets/{shikiHighlight-eU8abJ3T.js → shikiHighlight-CmanopUB.js} +1 -1
  49. package/dist/assets/uk-BA2kZR38.js +15 -0
  50. package/dist/assets/{useAppFontEffects-Bbpz77To.js → useAppFontEffects-sHmU5b8u.js} +137 -137
  51. package/dist/assets/useInlineCommentController-gt56WkxJ.js +2 -0
  52. package/dist/assets/{vendor-codemirror-language-data-Dzt9rWZZ.js → vendor-codemirror-language-data-Dihw9MtL.js} +2 -2
  53. package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
  54. package/dist/assets/{web-components-DGvnI0zx.js → web-components-BL-Ur2Tb.js} +1 -1
  55. package/dist/assets/zh-CN-dlOQK6v9.js +15 -0
  56. package/dist/assets/zh-TW-BnqQ-WL5.js +15 -0
  57. package/dist/index.html +4 -4
  58. package/dist/mini-chat.html +3 -3
  59. package/dist/mobile.html +3 -3
  60. package/package.json +2 -2
  61. package/server/index.js +65 -19
  62. package/server/lib/agent-tool/DOCUMENTATION.md +21 -6
  63. package/server/lib/agent-tool/runtime.js +90 -16
  64. package/server/lib/agent-tool/runtime.test.js +86 -0
  65. package/server/lib/browser-control/DOCUMENTATION.md +50 -0
  66. package/server/lib/browser-control/broker.js +154 -0
  67. package/server/lib/browser-control/broker.test.js +191 -0
  68. package/server/lib/browser-control/routes.js +48 -0
  69. package/server/lib/browser-control/routes.test.js +108 -0
  70. package/server/lib/dev-servers/parse.js +203 -0
  71. package/server/lib/dev-servers/parse.test.js +174 -0
  72. package/server/lib/dev-servers/routes.js +135 -0
  73. package/server/lib/dev-tunnel/DOCUMENTATION.md +57 -0
  74. package/server/lib/dev-tunnel/client.js +174 -0
  75. package/server/lib/dev-tunnel/runtime.js +189 -0
  76. package/server/lib/dev-tunnel/tunnel.test.js +282 -0
  77. package/server/lib/git/credentials.js +0 -33
  78. package/server/lib/github/DOCUMENTATION.md +1 -1
  79. package/server/lib/openchamber-control/DOCUMENTATION.md +9 -0
  80. package/server/lib/openchamber-control/actions.js +33 -1
  81. package/server/lib/openchamber-control/screenshots.js +83 -0
  82. package/server/lib/openchamber-control/screenshots.test.js +84 -0
  83. package/server/lib/openchamber-control/service.js +141 -2
  84. package/server/lib/openchamber-control/service.test.js +55 -0
  85. package/server/lib/opencode/core-routes.js +31 -52
  86. package/server/lib/opencode/core-routes.test.js +37 -9
  87. package/server/lib/opencode/feature-routes-runtime.js +4 -0
  88. package/server/lib/opencode/settings-helpers.js +3 -9
  89. package/server/lib/projects/project-config.js +181 -2
  90. package/server/lib/projects/project-config.test.js +295 -0
  91. package/server/lib/quota/DOCUMENTATION.md +4 -2
  92. package/server/lib/quota/credentials/providers.js +0 -7
  93. package/server/lib/quota/credentials/store.js +11 -1
  94. package/server/lib/quota/credentials/store.test.js +9 -1
  95. package/server/lib/quota/providers/opencode-go.js +35 -35
  96. package/server/lib/quota/providers/opencode-go.test.js +52 -7
  97. package/server/lib/quota/routes.js +0 -2
  98. package/server/lib/relay/DOCUMENTATION.md +2 -0
  99. package/server/lib/relay/tunnel-host.js +157 -33
  100. package/server/lib/relay/tunnel-host.test.js +147 -0
  101. package/server/lib/scheduled-tasks/DOCUMENTATION.md +49 -0
  102. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +488 -0
  103. package/server/lib/scheduled-tasks/routes.js +6 -0
  104. package/server/lib/scheduled-tasks/runtime.js +369 -108
  105. package/server/lib/scheduled-tasks/service.js +7 -1
  106. package/server/lib/scheduled-tasks/service.test.js +20 -0
  107. package/server/lib/walkthrough/index.js +0 -2
  108. package/server/sse-routes.test.js +3 -0
  109. package/dist/assets/FilesView-WkxsWHBE.js +0 -14
  110. package/dist/assets/MarkdownRendererImpl-CKAsRfIk.js +0 -12
  111. package/dist/assets/OnboardingScreen-BCgYA7J5.js +0 -1
  112. package/dist/assets/SettingsView-e7Fmxnz8.js +0 -28
  113. package/dist/assets/contextPanelEmbeddedChat-5VGWIT_J.js +0 -1
  114. package/dist/assets/de-B6t6T54h.js +0 -9
  115. package/dist/assets/es-DH9NUKge.js +0 -15
  116. package/dist/assets/fr-Do4t2KmA.js +0 -13
  117. package/dist/assets/index-B45s9aAX.css +0 -1
  118. package/dist/assets/index-CNrN5qDs.js +0 -7
  119. package/dist/assets/ja-DJT9EM80.js +0 -15
  120. package/dist/assets/ko-CfWRq2p4.js +0 -15
  121. package/dist/assets/main-B4oBRI9u.js +0 -193
  122. package/dist/assets/markdownCore-A3_L34oS.js +0 -2
  123. package/dist/assets/pt-BR-BDEzzltP.js +0 -15
  124. package/dist/assets/renderMobileApp-DA7wpIBi.js +0 -23
  125. package/dist/assets/runtimeEndpointReset-D5izT-u5.js +0 -13
  126. package/dist/assets/scheduledTasksApi-CTJdfSWc.js +0 -1
  127. package/dist/assets/uk-B6Q32nyk.js +0 -15
  128. package/dist/assets/useInlineCommentController-D7zs7-BQ.js +0 -2
  129. package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
  130. package/dist/assets/zh-CN-7MGcwGaC.js +0 -15
  131. package/dist/assets/zh-TW-CFPfqxlL.js +0 -15
  132. package/server/lib/preview/proxy-runtime.js +0 -1604
  133. package/server/lib/preview/proxy-runtime.test.js +0 -528
  134. package/server/lib/quota/opencode-go-credentials.js +0 -11
  135. package/server/lib/quota/opencode-go-credentials.test.js +0 -32
  136. package/server/lib/quota/routes.test.js +0 -40
@@ -1,68 +1,68 @@
1
- import { readOpenCodeGoCredential } from '../opencode-go-credentials.js';
2
- import { buildResult, toUsageWindow } from '../utils/index.js';
1
+ import { readAuthFile } from '../../opencode/auth.js';
2
+ import { deleteLegacyOpenCodeGoCredential } from '../credentials/store.js';
3
+ import { buildResult, getAuthEntry, normalizeAuthEntry, toUsageWindow } from '../utils/index.js';
3
4
 
4
5
  export const providerId = 'opencode-go';
5
6
  export const providerName = 'OpenCode Go';
6
7
  export const aliases = ['opencode-go'];
7
8
 
8
- const patterns = {
9
- '5h': 'rollingUsage',
10
- weekly: 'weeklyUsage',
11
- monthly: 'monthlyUsage',
9
+ const windowsByApiKey = {
10
+ '5h': 'rolling',
11
+ weekly: 'weekly',
12
+ monthly: 'monthly',
12
13
  };
13
14
 
14
- const captureNumber = (name, body) => {
15
- const match = body.match(new RegExp(`["']?${name}["']?\\s*:\\s*["']?(-?\\d+(?:\\.\\d+)?)`));
16
- const value = match ? Number(match[1]) : null;
17
- return Number.isFinite(value) ? value : null;
18
- };
19
-
20
- export const parseOpenCodeGoUsage = (html, now = Date.now()) => {
21
- if (typeof html !== 'string') return {};
22
- const normalized = html.replaceAll('"', '"').replaceAll('"', '"').replaceAll('\\u0022', '"').replaceAll('\\"', '"');
15
+ export const parseOpenCodeGoUsage = (payload) => {
16
+ const usage = payload && typeof payload === 'object' ? payload.usage : null;
17
+ if (!usage || typeof usage !== 'object') return {};
23
18
  const windows = {};
24
- for (const [key, field] of Object.entries(patterns)) {
25
- const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
- const match = normalized.match(new RegExp(`["']?${escaped}["']?\\s*:\\s*(?:\\$R\\[\\d+\\]\\s*=\\s*)?\\{([^{}]*)\\}`, 's'));
27
- if (!match) continue;
28
- const usedPercent = captureNumber('usagePercent', match[1]);
29
- const resetInSec = captureNumber('resetInSec', match[1]);
30
- if (usedPercent === null || resetInSec === null) continue;
19
+ for (const [key, apiKey] of Object.entries(windowsByApiKey)) {
20
+ const entry = usage[apiKey];
21
+ if (!entry || typeof entry !== 'object') continue;
22
+ const usedPercent = entry.percent;
23
+ const resetAt = entry.resetsAt;
24
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent)) continue;
25
+ if (typeof resetAt !== 'string' || !Number.isFinite(new Date(resetAt).getTime())) continue;
31
26
  windows[key] = toUsageWindow({
32
27
  usedPercent: Math.min(100, Math.max(0, usedPercent)),
33
- resetAt: now + Math.max(0, resetInSec) * 1000,
28
+ resetAt,
34
29
  windowSeconds: null,
35
30
  });
36
31
  }
37
32
  return windows;
38
33
  };
39
34
 
40
- export const fetchOpenCodeGoUsage = async (credential, fetchImpl = fetch) => {
41
- const response = await fetchImpl(`https://opencode.ai/workspace/${encodeURIComponent(credential.workspaceId)}/go`, {
35
+ export const fetchOpenCodeGoUsage = async (apiKey, fetchImpl = fetch) => {
36
+ const response = await fetchImpl('https://opencode.ai/zen/go/v1/usage', {
42
37
  headers: {
43
- Accept: 'text/html,application/xhtml+xml',
44
- Cookie: `auth=${credential.authCookie}`,
38
+ Accept: 'application/json',
39
+ Authorization: `Bearer ${apiKey}`,
45
40
  'User-Agent': 'OpenChamber quota provider',
46
41
  },
47
- redirect: 'manual',
48
42
  signal: AbortSignal.timeout(15_000),
49
43
  });
50
- if (response.status === 401 || response.status === 403 || (response.status >= 300 && response.status < 400)) {
44
+ if (response.status === 401 || response.status === 403) {
51
45
  throw new Error('OpenCode Go authentication failed');
52
46
  }
53
- if (!response.ok) throw new Error(`OpenCode Go dashboard returned HTTP ${response.status}`);
54
- const windows = parseOpenCodeGoUsage(await response.text());
47
+ if (!response.ok) throw new Error(`OpenCode Go usage API returned HTTP ${response.status}`);
48
+ const windows = parseOpenCodeGoUsage(await response.json().catch(() => null));
55
49
  if (Object.keys(windows).length === 0) throw new Error('OpenCode Go usage data could not be parsed');
56
50
  return windows;
57
51
  };
58
52
 
59
- export const isConfigured = () => Boolean(readOpenCodeGoCredential());
53
+ const getApiKey = () => {
54
+ const entry = normalizeAuthEntry(getAuthEntry(readAuthFile(), aliases));
55
+ return entry?.key ?? entry?.token ?? null;
56
+ };
57
+
58
+ export const isConfigured = () => Boolean(getApiKey());
60
59
 
61
60
  export const fetchQuota = async () => {
62
- const credential = readOpenCodeGoCredential();
63
- if (!credential) return buildResult({ providerId, providerName, ok: false, configured: false, error: 'Not configured' });
64
61
  try {
65
- const windows = await fetchOpenCodeGoUsage(credential);
62
+ deleteLegacyOpenCodeGoCredential();
63
+ const apiKey = getApiKey();
64
+ if (!apiKey) return buildResult({ providerId, providerName, ok: false, configured: false, error: 'Not configured' });
65
+ const windows = await fetchOpenCodeGoUsage(apiKey);
66
66
  return buildResult({ providerId, providerName, ok: true, configured: true, usage: { windows } });
67
67
  } catch (error) {
68
68
  return buildResult({ providerId, providerName, ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' });
@@ -1,17 +1,62 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { fetchOpenCodeGoUsage, parseOpenCodeGoUsage } from './opencode-go.js';
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ const previousDataDirectory = process.env.OPENCHAMBER_DATA_DIR;
7
+ const temporaryDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-opencode-go-'));
8
+ process.env.OPENCHAMBER_DATA_DIR = temporaryDataDirectory;
9
+
10
+ vi.mock('../../opencode/auth.js', () => ({
11
+ readAuthFile: () => ({ 'opencode-go': { key: 'test-key' } }),
12
+ }));
13
+
14
+ import { fetchOpenCodeGoUsage, fetchQuota, parseOpenCodeGoUsage } from './opencode-go.js';
15
+
16
+ afterEach(() => {
17
+ vi.unstubAllGlobals();
18
+ });
19
+
20
+ afterAll(() => {
21
+ if (previousDataDirectory === undefined) delete process.env.OPENCHAMBER_DATA_DIR;
22
+ else process.env.OPENCHAMBER_DATA_DIR = previousDataDirectory;
23
+ fs.rmSync(temporaryDataDirectory, { recursive: true, force: true });
24
+ });
3
25
 
4
26
  describe('OpenCode Go quota provider', () => {
5
- it('parses partial SSR usage windows in either field order', () => {
6
- const windows = parseOpenCodeGoUsage('rollingUsage:$R[1]={usagePercent:25,resetInSec:60} weeklyUsage:$R[2]={resetInSec:120,usagePercent:40}', 1_000);
27
+ it('parses partial API usage windows', () => {
28
+ const windows = parseOpenCodeGoUsage({ usage: { rolling: { percent: 25, resetsAt: '2026-08-12T12:00:00.000Z' }, weekly: { percent: 40, resetsAt: '2026-08-19T12:00:00.000Z' } } });
7
29
  expect(windows['5h'].usedPercent).toBe(25);
8
- expect(windows['5h'].resetAt).toBe(61_000);
30
+ expect(windows['5h'].resetAt).toBe('2026-08-12T12:00:00.000Z');
9
31
  expect(windows.weekly.usedPercent).toBe(40);
10
32
  expect(windows.monthly).toBeUndefined();
11
33
  });
12
34
 
13
35
  it('does not expose credentials in authentication errors', async () => {
14
- const credential = { workspaceId: 'wrk_test', authCookie: 'secret' };
15
- await expect(fetchOpenCodeGoUsage(credential, async () => new Response('', { status: 403 }))).rejects.toThrow('authentication failed');
36
+ await expect(fetchOpenCodeGoUsage('secret', async () => new Response('', { status: 403 }))).rejects.toThrow('authentication failed');
37
+ });
38
+
39
+ it('uses the Go usage API with bearer authentication', async () => {
40
+ let request;
41
+ const usage = await fetchOpenCodeGoUsage('secret', async (url, options) => {
42
+ request = { url, options };
43
+ return new Response(JSON.stringify({ usage: { rolling: { percent: 25, resetsAt: '2026-08-12T12:00:00.000Z' } } }));
44
+ });
45
+ expect(request.url).toBe('https://opencode.ai/zen/go/v1/usage');
46
+ expect(request.options.headers).toMatchObject({ Accept: 'application/json', Authorization: 'Bearer secret' });
47
+ expect(request.options.headers.Cookie).toBeUndefined();
48
+ expect(usage['5h'].usedPercent).toBe(25);
49
+ });
50
+
51
+ it('reads the API key from the OpenCode auth file', async () => {
52
+ const legacyPath = path.join(temporaryDataDirectory, 'quota', 'opencode-go.json');
53
+ fs.mkdirSync(path.dirname(legacyPath), { recursive: true });
54
+ fs.writeFileSync(legacyPath, '{not valid json', { mode: 0o600 });
55
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ usage: { rolling: { percent: 25, resetsAt: '2026-08-12T12:00:00.000Z' } } })));
56
+ vi.stubGlobal('fetch', fetchMock);
57
+ const result = await fetchQuota();
58
+ expect(result).toMatchObject({ providerId: 'opencode-go', ok: true, configured: true });
59
+ expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer test-key');
60
+ expect(fs.existsSync(legacyPath)).toBe(false);
16
61
  });
17
62
  });
@@ -1,11 +1,9 @@
1
1
  import express from 'express';
2
2
  import { deleteManagedCredential, getManagedCredentialStatus, normalizers, readManagedCredential, writeManagedCredential } from './credentials/providers.js';
3
- import { fetchOpenCodeGoUsage } from './providers/opencode-go.js';
4
3
  import { fetchOllamaCloudUsage } from './providers/ollama-cloud.js';
5
4
  import { importCursorCredential, validateCursorCredential } from './providers/cursor.js';
6
5
 
7
6
  const validators = {
8
- 'opencode-go': fetchOpenCodeGoUsage,
9
7
  'ollama-cloud': fetchOllamaCloudUsage,
10
8
  cursor: validateCursorCredential,
11
9
  };
@@ -45,6 +45,8 @@ Everything a client normally sends to the single OpenChamber origin:
45
45
 
46
46
  The host dispatcher restricts tunneled traffic to explicit path allowlists (one for HTTP, one for WS).
47
47
 
48
+ Request bodies crossing the tunnel are buffered on the host and forwarded to loopback only once the client's `StreamEnd` frame arrives (bodies above ~512 KB stream live instead). A body whose frames were lost in transit therefore never reaches the loopback server as an empty/truncated chunked body — the host aborts the stream and the client sees an ambiguous transport failure it can retry, instead of the loopback server's bare `400` ("Failed to send message (400)" from the mobile app).
49
+
48
50
  ## Authentication model
49
51
 
50
52
  - The tunnel is **transport only**. The OpenChamber server still authenticates every tunneled request exactly as it authenticates a direct remote client. The relay path grants reachability, not authorization.
@@ -62,6 +62,17 @@ const STRIPPED_RESPONSE_HEADERS = new Set([
62
62
  const BACKPRESSURE_LIMIT_BYTES = 4 * 1024 * 1024;
63
63
  const BACKPRESSURE_POLL_MS = 20;
64
64
 
65
+ // Bodies smaller than this are fully buffered before the loopback request is
66
+ // sent, so a tunneled body that lost frames (relay reconnect, dropped HttpBody
67
+ // frames) can never reach the loopback server as an empty/truncated chunked
68
+ // body — the server rejects those with a bare 400, surfacing as the mobile
69
+ // app's "Failed to send message (400)". Larger bodies stream live as before.
70
+ const BODY_BUFFER_MAX_BYTES = 512 * 1024;
71
+ // While the body is still being buffered, abort the stream if it never
72
+ // completes, so a stalled tunnel converts into an ambiguous transport failure
73
+ // (which the client already retries) instead of a hung loopback request.
74
+ const BODY_DELIVERY_TIMEOUT_MS = 15_000;
75
+
65
76
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
66
77
 
67
78
  const isHttpRequestPayload = (parsed) =>
@@ -85,10 +96,11 @@ const isWsClosePayload = (parsed) => Boolean(parsed && typeof parsed === 'object
85
96
  * getLocalPort: () => number,
86
97
  * sendFrame: (plaintextFrame: Uint8Array) => void | Promise<void>,
87
98
  * getBufferedAmount: () => number,
99
+ * bodyDeliveryTimeoutMs?: number,
88
100
  * }} deps
89
101
  */
90
- export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBufferedAmount }) => {
91
- /** @type {Map<number, { kind: 'http', abort: AbortController, body: ReadableStreamDefaultController | null } | { kind: 'ws', socket: WebSocket, opened: boolean }>} */
102
+ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBufferedAmount, bodyDeliveryTimeoutMs = BODY_DELIVERY_TIMEOUT_MS }) => {
103
+ /** @type {Map<number, { kind: 'http', abort: AbortController, body: { enqueue(payload: Uint8Array): void, close(): void, error(error: Error): void } | null, noBody: boolean } | { kind: 'ws', socket: WebSocket, opened: boolean }>} */
92
104
  const streams = new Map();
93
105
  const assembler = createFragmentAssembler();
94
106
  let closed = false;
@@ -168,39 +180,14 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
168
180
  await send(encodeTunnelFrame(TunnelFrameType.StreamEnd, streamId, new Uint8Array(0)));
169
181
  };
170
182
 
171
- const runHttpStream = async (streamId, request) => {
172
- const method = request.method.toUpperCase();
173
- if (!isAllowedHttpPath(request.path)) {
174
- dropStream(streamId);
175
- await syntheticResponse(streamId, 403, 'Path is not allowed through the relay');
176
- return;
177
- }
178
-
179
- const stream = streams.get(streamId);
180
- if (!stream || stream.kind !== 'http') return;
181
-
182
- const hasBody = method !== 'GET' && method !== 'HEAD';
183
- let requestBody;
184
- if (hasBody) {
185
- requestBody = new ReadableStream({
186
- start(controller) {
187
- stream.body = controller;
188
- },
189
- });
190
- } else {
191
- stream.body = null;
192
- stream.noBody = true;
193
- }
194
-
195
- const loopbackOrigin = `http://127.0.0.1:${getLocalPort()}`;
196
- const url = `${loopbackOrigin}${request.path}${request.query ? `?${request.query}` : ''}`;
183
+ const forwardRequest = async (streamId, stream, url, method, request, body, loopbackOrigin) => {
197
184
  let response;
198
185
  try {
199
186
  response = await fetch(url, {
200
187
  method,
201
188
  headers: buildRequestHeaders(request.headers, loopbackOrigin),
202
- body: requestBody,
203
- duplex: hasBody ? 'half' : undefined,
189
+ body,
190
+ duplex: body ? 'half' : undefined,
204
191
  signal: stream.abort.signal,
205
192
  });
206
193
  } catch (error) {
@@ -242,6 +229,143 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
242
229
  }
243
230
  };
244
231
 
232
+ const runHttpStream = async (streamId, request) => {
233
+ const method = request.method.toUpperCase();
234
+ if (!isAllowedHttpPath(request.path)) {
235
+ dropStream(streamId);
236
+ await syntheticResponse(streamId, 403, 'Path is not allowed through the relay');
237
+ return;
238
+ }
239
+
240
+ const stream = streams.get(streamId);
241
+ if (!stream || stream.kind !== 'http') return;
242
+
243
+ const hasBody = method !== 'GET' && method !== 'HEAD';
244
+ const loopbackOrigin = `http://127.0.0.1:${getLocalPort()}`;
245
+ const url = `${loopbackOrigin}${request.path}${request.query ? `?${request.query}` : ''}`;
246
+
247
+ if (!hasBody) {
248
+ stream.noBody = true;
249
+ await forwardRequest(streamId, stream, url, method, request, null, loopbackOrigin);
250
+ return;
251
+ }
252
+
253
+ // Body-carrying request. Buffer the tunneled body frames and forward the
254
+ // COMPLETE body only once StreamEnd arrives. Forwarding a body that lost
255
+ // frames through the tunnel (relay reconnect, dropped HttpBody frames)
256
+ // reaches the loopback server as an empty/truncated chunked body, which it
257
+ // rejects with a bare 400 (empty response body) — the "Failed to send
258
+ // message (400)" seen from the mobile APK. Bodies above BODY_BUFFER_MAX_BYTES
259
+ // stream live so large uploads are not fully buffered.
260
+ const buffered = [];
261
+ let bufferedBytes = 0;
262
+ let bodyFrameCount = 0;
263
+ let liveStream = null;
264
+ let liveController = null;
265
+ let completed = false;
266
+ let bodyFailure = null;
267
+ let resolveBodyEnd;
268
+ const bodyEnded = new Promise((resolve) => { resolveBodyEnd = resolve; });
269
+
270
+ const finishBody = (error) => {
271
+ if (completed) return;
272
+ completed = true;
273
+ bodyFailure = error ?? null;
274
+ if (liveController) {
275
+ try {
276
+ if (error) liveController.error(error);
277
+ else liveController.close();
278
+ } catch {
279
+ // stream already errored/closed
280
+ }
281
+ }
282
+ resolveBodyEnd();
283
+ };
284
+
285
+ let deliveryDeadline = null;
286
+ const switchToLive = () => {
287
+ liveStream = new ReadableStream({
288
+ start(controller) {
289
+ liveController = controller;
290
+ stream.body = controller;
291
+ },
292
+ });
293
+ for (const chunk of buffered) {
294
+ try { liveController.enqueue(chunk); } catch { break; }
295
+ }
296
+ buffered.length = 0;
297
+ // The loopback request is now streaming live; runHttpStream has nothing
298
+ // left to do — clear the deadline and let the async body forwarding own
299
+ // this stream from here (abort/StreamEnd close the controller).
300
+ if (deliveryDeadline) clearTimeout(deliveryDeadline);
301
+ resolveBodyEnd();
302
+ void forwardRequest(streamId, stream, url, method, request, liveStream, loopbackOrigin);
303
+ };
304
+
305
+ stream.body = {
306
+ enqueue(payload) {
307
+ if (completed) return;
308
+ bodyFrameCount += 1;
309
+ if (liveController) {
310
+ try { liveController.enqueue(payload); } catch {
311
+ // stream already errored/closed
312
+ }
313
+ return;
314
+ }
315
+ buffered.push(payload);
316
+ bufferedBytes += payload.length;
317
+ if (bufferedBytes > BODY_BUFFER_MAX_BYTES) {
318
+ switchToLive();
319
+ }
320
+ },
321
+ close() {
322
+ finishBody(null);
323
+ },
324
+ error(error) {
325
+ finishBody(error);
326
+ },
327
+ };
328
+
329
+ deliveryDeadline = setTimeout(() => {
330
+ if (streams.get(streamId) === stream && !completed && !liveStream) {
331
+ dropStream(streamId);
332
+ void sendAbort(streamId, 'tunnel request body was not delivered in time');
333
+ // Settle the buffered-body wait below so the stream's buffered chunks
334
+ // and this call frame are released (the post-wait guard sees the
335
+ // dropped stream and returns without a second abort).
336
+ finishBody(new Error('tunnel request body was not delivered in time'));
337
+ }
338
+ }, bodyDeliveryTimeoutMs);
339
+ deliveryDeadline.unref?.();
340
+
341
+ await bodyEnded;
342
+ if (deliveryDeadline) clearTimeout(deliveryDeadline);
343
+ if (streams.get(streamId) !== stream) return; // aborted or dropped meanwhile
344
+ if (bodyFailure) {
345
+ dropStream(streamId);
346
+ await sendAbort(streamId, bodyFailure.message ?? 'tunnel request body failed');
347
+ return;
348
+ }
349
+ if (liveStream) return; // already forwarded via the streaming path
350
+
351
+ // The client signaled it had a body but no HttpBody frame arrived before
352
+ // StreamEnd — the body frames were lost through the tunnel. Forwarding an
353
+ // empty body would make the loopback server reject the request with a bare
354
+ // 400. Abort instead so the client treats it as an ambiguous transport
355
+ // failure (dispatched, outcome unknown) and can safely retry.
356
+ if (request.hasBody === true && bodyFrameCount === 0) {
357
+ dropStream(streamId);
358
+ await sendAbort(streamId, 'tunnel request body frames were lost');
359
+ return;
360
+ }
361
+
362
+ // Buffered path: forward the complete body as a single buffer so Bun
363
+ // frames it with content-length — never as a chunked body that could be
364
+ // truncated. Reset the buffered handler so late frames cannot enqueue.
365
+ stream.body = null;
366
+ await forwardRequest(streamId, stream, url, method, request, Buffer.concat(buffered), loopbackOrigin);
367
+ };
368
+
245
369
  const handleHttpRequest = (streamId, payload) => {
246
370
  if (streams.has(streamId)) {
247
371
  abortLocalStream(streamId, 'duplicate stream id');
@@ -263,9 +387,9 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
263
387
  const handleHttpBody = (streamId, payload) => {
264
388
  const stream = streams.get(streamId);
265
389
  if (!stream || stream.kind !== 'http' || stream.noBody) return;
266
- // The body controller attaches synchronously in runHttpStream before any
267
- // await, so by the time body frames arrive it is set for body-carrying
268
- // methods; drop stray body bytes otherwise.
390
+ // runHttpStream installs a body sink (buffering handler, or the live stream
391
+ // controller once the buffer cap is crossed) before any HttpBody frame can
392
+ // arrive; drop stray bytes for request bodies already completed/aborted.
269
393
  try {
270
394
  stream.body?.enqueue(payload);
271
395
  } catch {
@@ -0,0 +1,147 @@
1
+ import { describe, test, expect } from 'bun:test';
2
+ import http from 'node:http';
3
+
4
+ import { createTunnelHost } from './tunnel-host.js';
5
+ import { decodeTunnelFrame, encodeTunnelFrame, encodeJsonPayload, TunnelFrameType } from './tunnel-codec.js';
6
+
7
+ const startLoopback = () =>
8
+ new Promise((resolve) => {
9
+ const requests = [];
10
+ const server = http.createServer((req, res) => {
11
+ const chunks = [];
12
+ req.on('data', (c) => chunks.push(c));
13
+ req.on('end', () => {
14
+ requests.push({
15
+ method: req.method,
16
+ url: req.url,
17
+ body: Buffer.concat(chunks).toString('utf8'),
18
+ });
19
+ res.writeHead(200, { 'content-type': 'application/json' });
20
+ res.end(JSON.stringify({ ok: true }));
21
+ });
22
+ });
23
+ server.listen(0, '127.0.0.1', () => resolve({
24
+ server,
25
+ port: server.address().port,
26
+ requests,
27
+ stop: () => new Promise((r) => server.close(() => r())),
28
+ }));
29
+ });
30
+
31
+ const createHarness = async (hostOverrides = {}) => {
32
+ const loopback = await startLoopback();
33
+ const sentFrames = [];
34
+ const host = createTunnelHost({
35
+ connectionId: 'conn-test',
36
+ getLocalPort: () => loopback.port,
37
+ sendFrame: async (frame) => {
38
+ sentFrames.push(decodeTunnelFrame(frame));
39
+ },
40
+ getBufferedAmount: () => 0,
41
+ ...hostOverrides,
42
+ });
43
+ return { host, loopback, sentFrames };
44
+ };
45
+
46
+ const httpHead = (overrides = {}) => encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
47
+ method: 'POST',
48
+ path: '/api/submit',
49
+ query: '',
50
+ headers: { 'content-type': 'application/json' },
51
+ ...overrides,
52
+ }));
53
+
54
+ const waitFor = async (predicate, timeoutMs = 2000) => {
55
+ const deadline = Date.now() + timeoutMs;
56
+ while (Date.now() < deadline) {
57
+ if (predicate()) return true;
58
+ await new Promise((r) => setTimeout(r, 20));
59
+ }
60
+ return predicate();
61
+ };
62
+
63
+ describe('tunnel-host HTTP body forwarding', () => {
64
+ test('buffers tunneled body frames and forwards the complete body', async () => {
65
+ const { host, loopback, sentFrames } = await createHarness();
66
+ await host.handleFrame(httpHead());
67
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpBody, 1, new TextEncoder().encode('alpha')));
68
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpBody, 1, new TextEncoder().encode('beta')));
69
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
70
+
71
+ const received = await waitFor(() => loopback.requests.length === 1);
72
+ expect(received).toBe(true);
73
+ expect(loopback.requests[0].method).toBe('POST');
74
+ expect(loopback.requests[0].body).toBe('alphabeta');
75
+ await waitFor(() => sentFrames.some((f) => f.frameType === TunnelFrameType.StreamEnd));
76
+ await loopback.stop();
77
+ });
78
+
79
+ test('body-expected request with zero delivered frames is aborted as ambiguous, not forwarded', async () => {
80
+ const { host, loopback, sentFrames } = await createHarness();
81
+ await host.handleFrame(httpHead({ hasBody: true }));
82
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
83
+
84
+ const aborted = await waitFor(() => sentFrames.some((f) => f.frameType === TunnelFrameType.StreamAbort));
85
+ expect(aborted).toBe(true);
86
+ // Loopback must never have seen a request with a lost body.
87
+ expect(loopback.requests.length).toBe(0);
88
+ await loopback.stop();
89
+ });
90
+
91
+ test('bodyless request (hasBody absent, legacy client) still forwards empty', async () => {
92
+ const { host, loopback } = await createHarness();
93
+ await host.handleFrame(httpHead());
94
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
95
+
96
+ const received = await waitFor(() => loopback.requests.length === 1);
97
+ expect(received).toBe(true);
98
+ expect(loopback.requests[0].body).toBe('');
99
+ await loopback.stop();
100
+ });
101
+
102
+ test('aborts a buffered body that never completes within the delivery deadline', async () => {
103
+ const { host, loopback, sentFrames } = await createHarness({ bodyDeliveryTimeoutMs: 50 });
104
+ await host.handleFrame(httpHead({ hasBody: true }));
105
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpBody, 1, new TextEncoder().encode('partial')));
106
+ // No StreamEnd — the tunnel stalled mid-body.
107
+
108
+ const aborted = await waitFor(() => sentFrames.some((f) => f.frameType === TunnelFrameType.StreamAbort));
109
+ expect(aborted).toBe(true);
110
+ expect(loopback.requests.length).toBe(0);
111
+ // A late StreamEnd for the dropped stream must not trigger a second abort
112
+ // or forward the stale body.
113
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
114
+ await new Promise((r) => setTimeout(r, 50));
115
+ expect(sentFrames.filter((f) => f.frameType === TunnelFrameType.StreamAbort).length).toBe(1);
116
+ expect(loopback.requests.length).toBe(0);
117
+ await loopback.stop();
118
+ });
119
+
120
+ test('forwards an empty body when the client delivered an explicit empty frame', async () => {
121
+ const { host, loopback } = await createHarness();
122
+ await host.handleFrame(httpHead({ hasBody: true }));
123
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpBody, 1, new Uint8Array(0)));
124
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
125
+
126
+ const received = await waitFor(() => loopback.requests.length === 1);
127
+ expect(received).toBe(true);
128
+ expect(loopback.requests[0].body).toBe('');
129
+ await loopback.stop();
130
+ });
131
+
132
+ test('GET forwards immediately with no body wait', async () => {
133
+ const { host, loopback } = await createHarness();
134
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
135
+ method: 'GET',
136
+ path: '/api/health',
137
+ query: '',
138
+ headers: {},
139
+ })));
140
+ await host.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, 1, new Uint8Array(0)));
141
+
142
+ const received = await waitFor(() => loopback.requests.length === 1);
143
+ expect(received).toBe(true);
144
+ expect(loopback.requests[0].method).toBe('GET');
145
+ await loopback.stop();
146
+ });
147
+ });
@@ -9,6 +9,55 @@ Server-owned scheduled task runtime and routes for OpenChamber-only automation.
9
9
  - Runtime orchestration and execution is owned by `packages/web/server/lib/scheduled-tasks/runtime.js`.
10
10
  - This module is OpenChamber feature logic; it is intentionally separate from OpenCode proxy/runtime internals.
11
11
 
12
+ ## Cross-instance occurrence claiming
13
+
14
+ Multiple OpenChamber server processes can share the same on-disk project config
15
+ (for example CLI `serve` on port 3000 and the Electron desktop server on port
16
+ 57123). Each process keeps its own timers, so without coordination a daily (or
17
+ weekly / cron / once) slot would dispatch twice.
18
+
19
+ Before a **scheduled** run creates a session, the runtime claims the occurrence
20
+ in shared project config under the project write lock:
21
+
22
+ - Writes `state.lastScheduledFor` to the armed `nextRunAt` timestamp and advances
23
+ `state.nextRunAt` to the following occurrence.
24
+ - A second instance that loses the claim skips session creation and reschedules
25
+ from the winner's persisted `nextRunAt`.
26
+ - Project config writes also take a cross-process `.json.lock` file so the
27
+ read-modify-write is serialized across processes, not only within one process.
28
+ - Lock timeout / filesystem errors on claim, manual-start, or completion state
29
+ writes always release the in-process running slot (via `finally`) and best-effort
30
+ re-arm the **next future** occurrence; they must not leave the task permanently
31
+ "running" or reject unhandled from the queue pump.
32
+ - Project write locks release the in-process promise chain even when
33
+ `acquireProjectFileLock` times out, so a later write for the same project can
34
+ proceed after the on-disk lock is cleared (a hung chain would permanently wedge
35
+ every mutating API and strand `runTask` before its `finally`).
36
+ - Re-arm helpers only schedule a persisted `nextRunAt` when it is still in the
37
+ future. A past slot (common for `once` after claim, which cannot advance
38
+ `nextRunAt`) falls back to `computeNextRunAt` — which returns null for a
39
+ consumed/past once occurrence — so a losing instance stops instead of
40
+ spinning delay-0 timers against the project lock.
41
+ - On claim lock/fs failure, best-effort persist `lastStatus: error` + `lastError`
42
+ when nobody else claimed the occurrence, so a past `once` task is not left
43
+ enabled-but-inert with only a warn log. Recurring schedules still re-arm the
44
+ next slot.
45
+ - On completion-write failure after a session already ran, in-memory status is
46
+ set to a terminal value and a single persist retry is attempted so
47
+ `lastStatus` does not stay `running`. Manual `runNow` still returns the
48
+ `sessionID` as a successful dispatch (`ok` follows run status, with
49
+ `persistError` set) rather than a hard 500; the run API and Scheduled Tasks
50
+ UI surface `persistError` as a warning toast.
51
+ - The claim predicate rejects a duplicate solely via `lastScheduledFor` within
52
+ slack of this occurrence. It does not consult advanced on-disk `nextRunAt`
53
+ (that field is routinely overwritten by a second instance syncing inside
54
+ `TASK_DUE_SLACK_MS`, including on later days when `lastScheduledFor` is already
55
+ set from a prior claim).
56
+ - Claiming always writes `nextRunAt` (including `undefined`) so a past once-slot
57
+ is cleared when there is no following occurrence.
58
+
59
+ Manual `runNow` does not claim a schedule occurrence.
60
+
12
61
  ## Files
13
62
 
14
63
  - `packages/web/server/lib/scheduled-tasks/runtime.js`