@openchamber/web 1.18.2 → 1.18.4

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 (140) hide show
  1. package/bin/lib/commands-models.js +1 -1
  2. package/dist/assets/{CodeMirrorCommentWidgets-CxcJ5x9h.js → CodeMirrorCommentWidgets-4qZbrEXU.js} +1 -1
  3. package/dist/assets/{CommitSection-C9sBBYAJ.js → CommitSection-MJmntVPJ.js} +1 -1
  4. package/dist/assets/{DiagramEditor-C7nUw7p3.js → DiagramEditor-jnG3Hbxg.js} +1 -1
  5. package/dist/assets/{DiagramView-cYxZP-HS.js → DiagramView-CFXxgg_a.js} +1 -1
  6. package/dist/assets/{DiffView-1zd0slLu.js → DiffView-DZIoOnV7.js} +2 -2
  7. package/dist/assets/FilesView-BKL6YlKG.js +14 -0
  8. package/dist/assets/{GitView-OSVIn5V1.js → GitView-DBFrDDBv.js} +1 -1
  9. package/dist/assets/{JsonTreeView-Kgepz4pR.js → JsonTreeView-DLW2Wy1g.js} +1 -1
  10. package/dist/assets/MarkdownImageGallery-DKIylIK7.js +1 -0
  11. package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +12 -0
  12. package/dist/assets/OnboardingScreen-D2Y6djMw.js +1 -0
  13. package/dist/assets/{PatchDiff-Cddz02Ya.js → PatchDiff-BuLPx7AN.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-B5k0KvPW.js → PierreDiffViewer-BHm4Yr0X.js} +2 -2
  15. package/dist/assets/{PlanView-BYgHBHDt.js → PlanView-ZYEJn8A_.js} +3 -3
  16. package/dist/assets/{SessionSwitcherDropdown-ig2OT22Z.js → SessionSwitcherDropdown-rro-SsaO.js} +1 -1
  17. package/dist/assets/SettingsView-5RmswFZe.js +28 -0
  18. package/dist/assets/{SettingsWindow-CNHM8ifT.js → SettingsWindow-BZhAYFdS.js} +1 -1
  19. package/dist/assets/{ToolOutputDialog-DrGeYq2p.js → ToolOutputDialog-Za6V4VMJ.js} +7 -7
  20. package/dist/assets/{ToolPartDiffPreview-BRmPpe94.js → ToolPartDiffPreview-BL-9ixyC.js} +1 -1
  21. package/dist/assets/{VirtualizedFileDiff-Dcu8Q-5P.js → VirtualizedFileDiff-CwGocYQd.js} +1 -1
  22. package/dist/assets/{WalkthroughView-HStEYdD2.js → WalkthroughView-5DyvN03T.js} +2 -2
  23. package/dist/assets/{computeVirtualFileMetrics-DQE7R9IY.js → computeVirtualFileMetrics-Da00Jg7M.js} +2 -2
  24. package/dist/assets/contextPanelEmbeddedChat-B-bSg3P5.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-BzIpNlNE.css +1 -0
  29. package/dist/assets/{index-BgQEgA2a.js → index-C0yNhuZw.js} +1 -1
  30. package/dist/assets/index-DRpChWux.js +7 -0
  31. package/dist/assets/{isDiffPlainText-XyBCe4eD.js → isDiffPlainText-D9YpoLrV.js} +1 -1
  32. package/dist/assets/{isFilePlainText-JbqDfa3n.js → isFilePlainText-gTibdNIe.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-D7UcL3VQ.js} +2 -2
  36. package/dist/assets/main-DPMd2iKS.js +915 -0
  37. package/dist/assets/markdownCore-DDrHVneM.js +2 -0
  38. package/dist/assets/{miniChat-CUp_elRz.js → miniChat-O_GVoEbc.js} +2 -2
  39. package/dist/assets/{mobile-CBSN7BsH.js → mobile-Br4TtAqc.js} +2 -2
  40. package/dist/assets/{patchFileDiff-DCIXUHRJ.js → patchFileDiff-KNkxM1C1.js} +2 -2
  41. package/dist/assets/{pl-tHTP6XQx.js → pl-CcZILN8q.js} +4 -4
  42. package/dist/assets/pt-BR-DYHhVK6o.js +15 -0
  43. package/dist/assets/{renderElectronMiniChatApp-eZl-5STF.js → renderElectronMiniChatApp-CJpdxTT1.js} +2 -2
  44. package/dist/assets/renderMobileApp-toj9cXoh.js +25 -0
  45. package/dist/assets/runtimeEndpointReset-BVmispdD.js +13 -0
  46. package/dist/assets/scheduledTasksApi-ByKya3Un.js +1 -0
  47. package/dist/assets/{shikiHighlight-eU8abJ3T.js → shikiHighlight-C7LTbwFx.js} +1 -1
  48. package/dist/assets/uk-BA2kZR38.js +15 -0
  49. package/dist/assets/{useAppFontEffects-Bbpz77To.js → useAppFontEffects-BikB6enL.js} +138 -138
  50. package/dist/assets/useInlineCommentController-CYPvYJDt.js +2 -0
  51. package/dist/assets/{vendor-codemirror-language-data-Dzt9rWZZ.js → vendor-codemirror-language-data-CLHw8NWn.js} +2 -2
  52. package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
  53. package/dist/assets/{web-components-DGvnI0zx.js → web-components-GMc3oR3i.js} +1 -1
  54. package/dist/assets/zh-CN-dlOQK6v9.js +15 -0
  55. package/dist/assets/zh-TW-BnqQ-WL5.js +15 -0
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +2 -2
  60. package/server/index.js +65 -19
  61. package/server/lib/agent-tool/DOCUMENTATION.md +21 -6
  62. package/server/lib/agent-tool/runtime.js +90 -16
  63. package/server/lib/agent-tool/runtime.test.js +86 -0
  64. package/server/lib/browser-control/DOCUMENTATION.md +50 -0
  65. package/server/lib/browser-control/broker.js +154 -0
  66. package/server/lib/browser-control/broker.test.js +191 -0
  67. package/server/lib/browser-control/routes.js +48 -0
  68. package/server/lib/browser-control/routes.test.js +108 -0
  69. package/server/lib/dev-servers/parse.js +203 -0
  70. package/server/lib/dev-servers/parse.test.js +174 -0
  71. package/server/lib/dev-servers/routes.js +135 -0
  72. package/server/lib/dev-tunnel/DOCUMENTATION.md +57 -0
  73. package/server/lib/dev-tunnel/client.js +193 -0
  74. package/server/lib/dev-tunnel/runtime.js +189 -0
  75. package/server/lib/dev-tunnel/tunnel.test.js +291 -0
  76. package/server/lib/git/credentials.js +0 -33
  77. package/server/lib/github/DOCUMENTATION.md +1 -1
  78. package/server/lib/markdown-image-grants/DOCUMENTATION.md +36 -0
  79. package/server/lib/markdown-image-grants/routes.js +340 -0
  80. package/server/lib/markdown-image-grants/routes.test.js +221 -0
  81. package/server/lib/openchamber-control/DOCUMENTATION.md +9 -0
  82. package/server/lib/openchamber-control/actions.js +33 -1
  83. package/server/lib/openchamber-control/screenshots.js +83 -0
  84. package/server/lib/openchamber-control/screenshots.test.js +84 -0
  85. package/server/lib/openchamber-control/service.js +141 -2
  86. package/server/lib/openchamber-control/service.test.js +55 -0
  87. package/server/lib/opencode/core-routes.js +31 -52
  88. package/server/lib/opencode/core-routes.test.js +37 -9
  89. package/server/lib/opencode/feature-routes-runtime.js +15 -0
  90. package/server/lib/opencode/server-startup-runtime.js +22 -1
  91. package/server/lib/opencode/server-startup-runtime.test.js +44 -0
  92. package/server/lib/opencode/settings-helpers.js +3 -9
  93. package/server/lib/projects/project-config.js +181 -2
  94. package/server/lib/projects/project-config.test.js +295 -0
  95. package/server/lib/quota/DOCUMENTATION.md +4 -2
  96. package/server/lib/quota/credentials/providers.js +0 -7
  97. package/server/lib/quota/credentials/store.js +11 -1
  98. package/server/lib/quota/credentials/store.test.js +9 -1
  99. package/server/lib/quota/providers/opencode-go.js +35 -35
  100. package/server/lib/quota/providers/opencode-go.test.js +52 -7
  101. package/server/lib/quota/routes.js +0 -2
  102. package/server/lib/relay/DOCUMENTATION.md +2 -0
  103. package/server/lib/relay/tunnel-host.js +157 -33
  104. package/server/lib/relay/tunnel-host.test.js +147 -0
  105. package/server/lib/scheduled-tasks/DOCUMENTATION.md +49 -0
  106. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +488 -0
  107. package/server/lib/scheduled-tasks/routes.js +6 -0
  108. package/server/lib/scheduled-tasks/runtime.js +369 -108
  109. package/server/lib/scheduled-tasks/service.js +7 -1
  110. package/server/lib/scheduled-tasks/service.test.js +20 -0
  111. package/server/lib/walkthrough/index.js +0 -2
  112. package/server/sse-routes.test.js +3 -0
  113. package/dist/assets/FilesView-WkxsWHBE.js +0 -14
  114. package/dist/assets/MarkdownRendererImpl-CKAsRfIk.js +0 -12
  115. package/dist/assets/OnboardingScreen-BCgYA7J5.js +0 -1
  116. package/dist/assets/SettingsView-e7Fmxnz8.js +0 -28
  117. package/dist/assets/contextPanelEmbeddedChat-5VGWIT_J.js +0 -1
  118. package/dist/assets/de-B6t6T54h.js +0 -9
  119. package/dist/assets/es-DH9NUKge.js +0 -15
  120. package/dist/assets/fr-Do4t2KmA.js +0 -13
  121. package/dist/assets/index-B45s9aAX.css +0 -1
  122. package/dist/assets/index-CNrN5qDs.js +0 -7
  123. package/dist/assets/ja-DJT9EM80.js +0 -15
  124. package/dist/assets/ko-CfWRq2p4.js +0 -15
  125. package/dist/assets/main-B4oBRI9u.js +0 -193
  126. package/dist/assets/markdownCore-A3_L34oS.js +0 -2
  127. package/dist/assets/pt-BR-BDEzzltP.js +0 -15
  128. package/dist/assets/renderMobileApp-DA7wpIBi.js +0 -23
  129. package/dist/assets/runtimeEndpointReset-D5izT-u5.js +0 -13
  130. package/dist/assets/scheduledTasksApi-CTJdfSWc.js +0 -1
  131. package/dist/assets/uk-B6Q32nyk.js +0 -15
  132. package/dist/assets/useInlineCommentController-D7zs7-BQ.js +0 -2
  133. package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
  134. package/dist/assets/zh-CN-7MGcwGaC.js +0 -15
  135. package/dist/assets/zh-TW-CFPfqxlL.js +0 -15
  136. package/server/lib/preview/proxy-runtime.js +0 -1604
  137. package/server/lib/preview/proxy-runtime.test.js +0 -528
  138. package/server/lib/quota/opencode-go-credentials.js +0 -11
  139. package/server/lib/quota/opencode-go-credentials.test.js +0 -32
  140. package/server/lib/quota/routes.test.js +0 -40
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Two capabilities, two tools.
3
+ *
4
+ * Controlling sessions and driving a page are different intents, and a single
5
+ * tool description covering both is vaguer than either — which is how a model
6
+ * ends up calling the wrong one. Separate tools also mean turning one off
7
+ * removes it entirely, parameters included, rather than leaving its inputs
8
+ * visible in a shared schema.
9
+ */
1
10
  export const OPENCHAMBER_CONTROL_ACTION_DEFINITIONS = Object.freeze([
2
11
  { action: 'projects.list', title: 'List configured projects', description: 'List configured projects; no parameters' },
3
12
  { action: 'models.list', title: 'Show model preferences', description: 'Show default, favorite, and recent model preferences; no parameters' },
@@ -15,7 +24,7 @@ export const OPENCHAMBER_CONTROL_ACTION_DEFINITIONS = Object.freeze([
15
24
  { action: 'schedule.toggle', title: 'Enable or disable a scheduled task', description: 'Enable or disable taskId; requires the disabled boolean' },
16
25
  ]);
17
26
 
18
- export const OPENCHAMBER_CONTROL_ACTIONS = Object.freeze(
27
+ const OPENCHAMBER_CONTROL_ACTIONS = Object.freeze(
19
28
  OPENCHAMBER_CONTROL_ACTION_DEFINITIONS.map(({ action }) => action),
20
29
  );
21
30
 
@@ -26,3 +35,26 @@ export const OPENCHAMBER_AGENT_TOOL_ACTION_DEFINITIONS = Object.freeze(
26
35
  export const OPENCHAMBER_AGENT_TOOL_ACTIONS = Object.freeze(
27
36
  OPENCHAMBER_AGENT_TOOL_ACTION_DEFINITIONS.map(({ action }) => action),
28
37
  );
38
+
39
+ export const OPENCHAMBER_WEB_ACTION_DEFINITIONS = Object.freeze([
40
+ { action: 'browser.open', title: 'Open a page in the browser panel', description: 'Open url in the in-app browser panel; use it to look at the running app. Set viewport to mobile, tablet or desktop to lay the page out at that size' },
41
+ { action: 'browser.snapshot', title: 'Read the open page', description: 'Read the open page: url, title, visible text, and interactive elements with the selectors the other browser actions accept. Pass selector to read only that part of a long page. Reports any errors the page logged' },
42
+ { action: 'browser.click', title: 'Click on the open page', description: 'Click an element; give selector, or text to match a link or button by its visible label' },
43
+ { action: 'browser.type', title: 'Type into the open page', description: 'Type value into the field matched by selector; set submit to press Enter afterwards' },
44
+ { action: 'browser.scroll', title: 'Scroll the open page', description: 'Scroll the page; direction is up, down, top, or bottom, or pass selector to bring one element into view' },
45
+ { action: 'browser.back', title: 'Go back in the browser panel', description: 'Return to the previous page in this tab; no parameters' },
46
+ { action: 'browser.forward', title: 'Go forward in the browser panel', description: 'Move forward again in this tab; no parameters' },
47
+ { action: 'browser.inspect', title: 'Read how an element renders', description: 'Read the computed styles of the element matched by selector — colours, fonts, spacing, borders — as the page actually renders them' },
48
+ { action: 'browser.capture', title: 'Save a screenshot of the page', description: 'Save what is currently visible in the browser panel as an image file in the project and return its path, so a change can be shown rather than described. Pass label to name it (for example before-fix); the result reports the page, layout and path to reference in your answer' },
49
+ { action: 'browser.resize', title: 'Change the page viewport', description: 'Lay the open page out at a different size; viewport is mobile, tablet, desktop, or fill to use the whole panel' },
50
+ ]);
51
+
52
+ export const OPENCHAMBER_WEB_ACTIONS = Object.freeze(
53
+ OPENCHAMBER_WEB_ACTION_DEFINITIONS.map(({ action }) => action),
54
+ );
55
+
56
+ /** Everything the callback route will dispatch, whichever tool asked. */
57
+ export const OPENCHAMBER_ALL_ACTIONS = Object.freeze([
58
+ ...OPENCHAMBER_CONTROL_ACTIONS,
59
+ ...OPENCHAMBER_WEB_ACTIONS,
60
+ ]);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Where an agent's page screenshots land.
3
+ *
4
+ * The image is written on the server, next to the code it is evidence for,
5
+ * because that is the machine holding the repository — the client that took the
6
+ * picture may be somewhere else entirely. A file in the project is also the
7
+ * only form of this that survives past the chat: it can be referenced from an
8
+ * answer, committed, or attached to a review.
9
+ *
10
+ * A screenshot nobody can place is not evidence, so the name carries the label
11
+ * the agent chose and the moment it was taken, and the caller is handed back
12
+ * the page and layout it shows.
13
+ */
14
+ import path from 'node:path';
15
+ import fsPromises from 'node:fs/promises';
16
+
17
+ /** Project-relative home for agent screenshots. */
18
+ export const SCREENSHOT_DIRECTORY = path.join('.openchamber', 'screenshots');
19
+
20
+ const MAX_LABEL_LENGTH = 48;
21
+
22
+ /**
23
+ * Turns a label into a filename fragment.
24
+ *
25
+ * Everything outside a small safe set is dropped rather than escaped: this
26
+ * value reaches the filesystem, and a label is a name, never a path. `..`, a
27
+ * separator, or a leading dot cannot survive this.
28
+ */
29
+ export const screenshotSlug = (label) => {
30
+ const slug = String(label ?? '')
31
+ .toLowerCase()
32
+ .replace(/[^a-z0-9]+/g, '-')
33
+ .replace(/^-+|-+$/g, '')
34
+ .slice(0, MAX_LABEL_LENGTH)
35
+ .replace(/-+$/g, '');
36
+ return slug || 'page';
37
+ };
38
+
39
+ /** File-safe timestamp: sorts chronologically and reads as a date. */
40
+ const screenshotStamp = (date) => date.toISOString().replace(/[:.]/g, '-').replace('Z', '');
41
+
42
+ const EXTENSIONS = new Map([
43
+ ['image/jpeg', '.jpg'],
44
+ ['image/png', '.png'],
45
+ ['image/webp', '.webp'],
46
+ ]);
47
+
48
+ /**
49
+ * Writes one capture into the project and reports where it went.
50
+ *
51
+ * Returns both the project-relative path — what belongs in an answer or a
52
+ * commit — and the absolute one, so a caller that needs the file itself does
53
+ * not have to rebuild it.
54
+ */
55
+ export const writeScreenshot = async ({
56
+ directory,
57
+ base64,
58
+ mime = 'image/jpeg',
59
+ label,
60
+ now = new Date(),
61
+ fs = fsPromises,
62
+ }) => {
63
+ if (typeof directory !== 'string' || directory.trim().length === 0) {
64
+ throw new Error('A project directory is required to save a screenshot');
65
+ }
66
+ if (typeof base64 !== 'string' || base64.length === 0) {
67
+ throw new Error('The browser returned no image');
68
+ }
69
+
70
+ const extension = EXTENSIONS.get(mime) || '.jpg';
71
+ const relativePath = path.join(
72
+ SCREENSHOT_DIRECTORY,
73
+ `${screenshotSlug(label)}-${screenshotStamp(now)}${extension}`,
74
+ );
75
+ const absolutePath = path.join(directory, relativePath);
76
+
77
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
78
+ await fs.writeFile(absolutePath, Buffer.from(base64, 'base64'));
79
+
80
+ // Posix separators in the reported path: it is written into Markdown and
81
+ // commit messages, where a Windows separator is an escape character.
82
+ return { path: relativePath.split(path.sep).join('/'), absolutePath };
83
+ };
@@ -0,0 +1,84 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import path from 'node:path';
3
+
4
+ import { SCREENSHOT_DIRECTORY, screenshotSlug, writeScreenshot } from './screenshots.js';
5
+
6
+ const createFs = () => {
7
+ const written = new Map();
8
+ const made = [];
9
+ return {
10
+ written,
11
+ made,
12
+ mkdir: async (target) => { made.push(target); },
13
+ writeFile: async (target, data) => { written.set(target, data); },
14
+ };
15
+ };
16
+
17
+ describe('screenshot labels', () => {
18
+ it('keeps a readable name', () => {
19
+ expect(screenshotSlug('Before fix')).toBe('before-fix');
20
+ });
21
+
22
+ it('never lets a label become a path', () => {
23
+ expect(screenshotSlug('../../etc/passwd')).toBe('etc-passwd');
24
+ expect(screenshotSlug('/absolute')).toBe('absolute');
25
+ expect(screenshotSlug('..')).toBe('page');
26
+ expect(screenshotSlug('.hidden')).toBe('hidden');
27
+ });
28
+
29
+ it('falls back to a name rather than an empty one', () => {
30
+ expect(screenshotSlug('')).toBe('page');
31
+ expect(screenshotSlug('!!!')).toBe('page');
32
+ expect(screenshotSlug(undefined)).toBe('page');
33
+ });
34
+ });
35
+
36
+ describe('writing a screenshot', () => {
37
+ const base64 = Buffer.from('image-bytes').toString('base64');
38
+
39
+ it('writes into the project and reports a portable relative path', async () => {
40
+ const fs = createFs();
41
+ const result = await writeScreenshot({
42
+ directory: '/work/project',
43
+ base64,
44
+ mime: 'image/jpeg',
45
+ label: 'After fix',
46
+ now: new Date('2026-08-13T09:37:00.000Z'),
47
+ fs,
48
+ });
49
+
50
+ expect(result.path).toBe('.openchamber/screenshots/after-fix-2026-08-13T09-37-00-000.jpg');
51
+ expect(result.path.includes('\\')).toBe(false);
52
+ expect(result.absolutePath).toBe(path.join('/work/project', SCREENSHOT_DIRECTORY, 'after-fix-2026-08-13T09-37-00-000.jpg'));
53
+ expect(fs.written.get(result.absolutePath).toString()).toBe('image-bytes');
54
+ expect(fs.made[0]).toBe(path.join('/work/project', SCREENSHOT_DIRECTORY));
55
+ });
56
+
57
+ it('names the file after the image it actually holds', async () => {
58
+ const fs = createFs();
59
+ const result = await writeScreenshot({ directory: '/work/project', base64, mime: 'image/png', fs });
60
+ expect(result.path.endsWith('.png')).toBe(true);
61
+ });
62
+
63
+ it('refuses to write without a project directory', async () => {
64
+ let failed = false;
65
+ try {
66
+ await writeScreenshot({ directory: '', base64, fs: createFs() });
67
+ } catch {
68
+ failed = true;
69
+ }
70
+ expect(failed).toBe(true);
71
+ });
72
+
73
+ it('reports an empty capture instead of writing a zero-byte file', async () => {
74
+ const fs = createFs();
75
+ let failed = false;
76
+ try {
77
+ await writeScreenshot({ directory: '/work/project', base64: '', fs });
78
+ } catch {
79
+ failed = true;
80
+ }
81
+ expect(failed).toBe(true);
82
+ expect(fs.written.size).toBe(0);
83
+ });
84
+ });
@@ -1,12 +1,14 @@
1
1
  import path from 'node:path';
2
2
  import { createOpencodeClient } from '@opencode-ai/sdk/v2';
3
3
  import { OpenChamberControlError, asControlError } from './error.js';
4
- import { OPENCHAMBER_CONTROL_ACTIONS } from './actions.js';
4
+ import { OPENCHAMBER_ALL_ACTIONS } from './actions.js';
5
+ import { writeScreenshot } from './screenshots.js';
5
6
 
6
7
  const DEFAULT_WAIT_TIMEOUT_SECONDS = 600;
7
8
  const MAX_WAIT_TIMEOUT_SECONDS = 86_400;
8
9
  const WAIT_POLL_INTERVAL_MS = 500;
9
- const CONTROL_ACTIONS = new Set(OPENCHAMBER_CONTROL_ACTIONS);
10
+ // One service, both capabilities: which tool asked is the caller's concern.
11
+ const CONTROL_ACTIONS = new Set(OPENCHAMBER_ALL_ACTIONS);
10
12
  const SCHEDULE_TASK_ID_ACTIONS = new Set([
11
13
  'schedule.run',
12
14
  'schedule.delete',
@@ -141,6 +143,7 @@ export const createOpenChamberControlService = (dependencies) => {
141
143
  waitForOpenCodeReady,
142
144
  sessionService,
143
145
  scheduledTaskService,
146
+ browserControl = null,
144
147
  createClient = createOpencodeClient,
145
148
  sleep = (duration) => new Promise((resolve) => setTimeout(resolve, duration)),
146
149
  now = Date.now,
@@ -320,11 +323,147 @@ export const createOpenChamberControlService = (dependencies) => {
320
323
  return publicResult;
321
324
  };
322
325
 
326
+ /**
327
+ * Validates browser inputs here rather than in the renderer: an invalid call
328
+ * should come back as a usage error the agent can correct, without waking a
329
+ * client or waiting for a round trip.
330
+ */
331
+ const browserAction = async (action, input, signal, contextDirectory) => {
332
+ const parameters = {};
333
+
334
+ const readViewport = (required) => {
335
+ const viewport = asNonEmptyString(input.viewport);
336
+ if (!viewport) {
337
+ if (required) throw new OpenChamberControlError('viewport is required for browser.resize', 400);
338
+ return;
339
+ }
340
+ if (!['mobile', 'tablet', 'desktop', 'fill'].includes(viewport)) {
341
+ throw new OpenChamberControlError('viewport must be mobile, tablet, desktop, or fill', 400);
342
+ }
343
+ parameters.viewport = viewport;
344
+ };
345
+
346
+ if (action === 'browser.resize') readViewport(true);
347
+
348
+ if (action === 'browser.capture') {
349
+ const label = asNonEmptyString(input.label);
350
+ if (label) parameters.label = label;
351
+ }
352
+
353
+ if (action === 'browser.open') {
354
+ readViewport(false);
355
+ const url = asNonEmptyString(input.url);
356
+ if (!url) throw new OpenChamberControlError('url is required for browser.open', 400);
357
+ let parsed;
358
+ try {
359
+ parsed = new URL(url);
360
+ } catch {
361
+ throw new OpenChamberControlError('url must be an absolute http(s) URL', 400);
362
+ }
363
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
364
+ throw new OpenChamberControlError('url must use http or https', 400);
365
+ }
366
+ parameters.url = parsed.toString();
367
+ }
368
+
369
+
370
+ if (action === 'browser.click') {
371
+ const selector = asNonEmptyString(input.selector);
372
+ const text = asNonEmptyString(input.text);
373
+ if (!selector && !text) {
374
+ throw new OpenChamberControlError('browser.click requires selector or text', 400);
375
+ }
376
+ if (selector) parameters.selector = selector;
377
+ if (text) parameters.text = text;
378
+ }
379
+
380
+ if (action === 'browser.snapshot') {
381
+ const selector = asNonEmptyString(input.selector);
382
+ if (selector) parameters.selector = selector;
383
+ }
384
+
385
+ if (action === 'browser.inspect') {
386
+ const selector = asNonEmptyString(input.selector);
387
+ if (!selector) throw new OpenChamberControlError('selector is required for browser.inspect', 400);
388
+ parameters.selector = selector;
389
+ }
390
+
391
+ if (action === 'browser.type') {
392
+ const selector = asNonEmptyString(input.selector);
393
+ if (!selector) throw new OpenChamberControlError('selector is required for browser.type', 400);
394
+ if (typeof input.value !== 'string') {
395
+ throw new OpenChamberControlError('value is required for browser.type', 400);
396
+ }
397
+ parameters.selector = selector;
398
+ parameters.value = input.value;
399
+ parameters.submit = input.submit === true;
400
+ }
401
+
402
+ if (action === 'browser.scroll') {
403
+ const selector = asNonEmptyString(input.selector);
404
+ const direction = asNonEmptyString(input.direction);
405
+ if (!selector && !direction) {
406
+ throw new OpenChamberControlError('browser.scroll requires direction or selector', 400);
407
+ }
408
+ if (direction && !['up', 'down', 'top', 'bottom'].includes(direction)) {
409
+ throw new OpenChamberControlError('direction must be up, down, top, or bottom', 400);
410
+ }
411
+ if (selector) parameters.selector = selector;
412
+ if (direction) parameters.direction = direction;
413
+ }
414
+
415
+ // Opening a page waits for the navigation to settle, so its budget has to
416
+ // exceed the client's own wait; sharing one timeout with the quick actions
417
+ // made a slow page indistinguishable from an unreachable browser.
418
+ const timeoutMs = action === 'browser.open' ? 45_000 : 20_000;
419
+ const result = await browserControl.request(action, parameters, { signal, timeoutMs });
420
+
421
+ // The image is written here rather than in the renderer: the file belongs
422
+ // beside the code it documents, and the client that took it may be on a
423
+ // different machine than the repository.
424
+ if (action === 'browser.capture') {
425
+ const directory = asNonEmptyString(input.directory) || asNonEmptyString(contextDirectory);
426
+ if (!directory) {
427
+ throw new OpenChamberControlError('directory is required to save a screenshot', 400);
428
+ }
429
+ const capture = result && typeof result === 'object' ? result : {};
430
+ const saved = await writeScreenshot({
431
+ directory,
432
+ base64: capture.base64,
433
+ mime: capture.mime,
434
+ label: input.label,
435
+ });
436
+ // The base64 never goes back to the caller: it is large, and the path is
437
+ // what an answer, a commit, or a review can actually use.
438
+ return {
439
+ path: saved.path,
440
+ // Saving the file is only half of showing it. Chat collects the image
441
+ // paths written in a finished answer and renders them below it, so the
442
+ // agent is told the one thing it cannot infer: that writing the path is
443
+ // what puts the picture in front of the user.
444
+ hint: `Write ![](${saved.path}) in your reply to show this image to the user; it is rendered under your message.`,
445
+ url: capture.url ?? null,
446
+ title: capture.title ?? null,
447
+ viewport: capture.viewport ?? null,
448
+ width: capture.width ?? null,
449
+ height: capture.height ?? null,
450
+ };
451
+ }
452
+
453
+ return result;
454
+ };
455
+
323
456
  const execute = async (action, input = {}, contextDirectory, options = {}) => {
324
457
  try {
325
458
  if (!CONTROL_ACTIONS.has(action)) {
326
459
  throw new OpenChamberControlError(`Unsupported OpenChamber action: ${action || 'missing'}`, 400);
327
460
  }
461
+ if (action.startsWith('browser.')) {
462
+ if (!browserControl) {
463
+ throw new OpenChamberControlError('The in-app browser is not available on this server', 503);
464
+ }
465
+ return browserAction(action, input, options.signal, contextDirectory);
466
+ }
328
467
  if (action === 'projects.list') return { projects: await projects() };
329
468
  if (action === 'models.list') return models();
330
469
  if (action === 'schedule.status') return scheduledTaskService.status();
@@ -1,5 +1,9 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
 
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import fs from 'node:fs/promises';
6
+
3
7
  import { createOpenChamberControlService } from './service.js';
4
8
 
5
9
  const createService = (overrides = {}) => {
@@ -261,3 +265,54 @@ describe('OpenChamber control service', () => {
261
265
  await expect(service.execute('session.delete')).rejects.toThrow('Unsupported OpenChamber action');
262
266
  });
263
267
  });
268
+
269
+ describe('browser capture', () => {
270
+ const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
271
+
272
+ const createBrowserService = async (capture) => {
273
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'oc-capture-'));
274
+ const request = vi.fn(async () => capture);
275
+ const { service } = createService({ browserControl: { request } });
276
+ return { service, directory, request };
277
+ };
278
+
279
+ it('saves the image beside the code and hands back a path the answer can use', async () => {
280
+ const { service, directory } = await createBrowserService({
281
+ base64: pixel,
282
+ mime: 'image/png',
283
+ url: 'http://localhost:3000/',
284
+ title: 'App',
285
+ viewport: { mode: 'mobile', width: 390, height: 844 },
286
+ width: 390,
287
+ height: 844,
288
+ });
289
+
290
+ const result = await service.execute('browser.capture', { label: 'After fix' }, directory);
291
+
292
+ expect(result.path.startsWith('.openchamber/screenshots/after-fix-')).toBe(true);
293
+ expect(result.path.endsWith('.png')).toBe(true);
294
+ expect(result.url).toBe('http://localhost:3000/');
295
+ expect(result.viewport).toEqual({ mode: 'mobile', width: 390, height: 844 });
296
+ // The bytes stay on disk; a tool result is not a place to carry an image.
297
+ expect('base64' in result).toBe(false);
298
+ const written = await fs.readFile(path.join(directory, result.path));
299
+ expect(written.length > 0).toBe(true);
300
+ });
301
+
302
+ it('tells the agent how to actually show the image', async () => {
303
+ const { service, directory } = await createBrowserService({ base64: pixel, mime: 'image/png' });
304
+ const result = await service.execute('browser.capture', {}, directory);
305
+ expect(result.hint).toContain(`![](${result.path})`);
306
+ });
307
+
308
+ it('refuses to capture with no project to save into', async () => {
309
+ const { service } = await createBrowserService({ base64: pixel, mime: 'image/png' });
310
+ await expect(service.execute('browser.capture', {})).rejects.toThrow(/directory is required/);
311
+ });
312
+
313
+ it('passes a label through to the browser and leaves other actions untouched', async () => {
314
+ const { service, directory, request } = await createBrowserService({ base64: pixel, mime: 'image/png' });
315
+ await service.execute('browser.capture', { label: 'before' }, directory);
316
+ expect(request).toHaveBeenCalledWith('browser.capture', { label: 'before' }, expect.anything());
317
+ });
318
+ });
@@ -24,42 +24,6 @@ const parseLoopbackUrl = (rawUrl) => {
24
24
  return url;
25
25
  };
26
26
 
27
- const getRequestPathname = (req) => {
28
- const rawUrl = req?.originalUrl || req?.url || '';
29
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return '';
30
- try {
31
- return new URL(rawUrl, 'http://localhost').pathname;
32
- } catch {
33
- return '';
34
- }
35
- };
36
-
37
- const getQueryParam = (req, name) => {
38
- const rawUrl = req?.originalUrl || req?.url || '';
39
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return '';
40
- try {
41
- return new URL(rawUrl, 'http://localhost').searchParams.get(name)?.trim() || '';
42
- } catch {
43
- return '';
44
- }
45
- };
46
-
47
- const getCookieValue = (req, name) => {
48
- const cookieHeader = req?.headers?.cookie;
49
- if (typeof cookieHeader !== 'string' || cookieHeader.length === 0) return '';
50
- for (const segment of cookieHeader.split(';')) {
51
- const [rawName, ...rawValueParts] = segment.split('=');
52
- if (rawName?.trim() !== name) continue;
53
- return rawValueParts.join('=').trim();
54
- }
55
- return '';
56
- };
57
-
58
- const hasPreviewProxyCredential = (req) => {
59
- if (!getRequestPathname(req).startsWith('/api/preview/proxy/')) return false;
60
- return Boolean(getQueryParam(req, 'oc_preview_token') || getCookieValue(req, 'oc_preview_token'));
61
- };
62
-
63
27
  export const registerServerStatusRoutes = (app, dependencies) => {
64
28
  const {
65
29
  express,
@@ -560,6 +524,23 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
560
524
  }
561
525
  };
562
526
 
527
+ const candidateUrlType = (url) => {
528
+ try {
529
+ return new URL(url).protocol === 'https:' ? 'tunnel' : 'lan';
530
+ } catch {
531
+ return 'lan';
532
+ }
533
+ };
534
+
535
+ const isLoopbackCandidateUrl = (url) => {
536
+ try {
537
+ const hostname = new URL(url).hostname.toLowerCase();
538
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
539
+ } catch {
540
+ return true;
541
+ }
542
+ };
543
+
563
544
  // `preferredServerUrl` is the caller-supplied externally reachable URL (the
564
545
  // desktop UI reaches its own server over loopback, so the request origin is not
565
546
  // scannable — it passes the LAN URL instead). Falls back to the request origin
@@ -573,15 +554,21 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
573
554
  const pairingServerCandidates = async (req, { preferredServerUrl, includeRelay, includeDirect = true } = {}) => {
574
555
  const candidates = [];
575
556
  if (includeDirect) {
576
- const direct = normalizeCandidateUrl(preferredServerUrl) || requestOrigin(req);
557
+ const preferred = normalizeCandidateUrl(preferredServerUrl);
558
+ const origin = normalizeCandidateUrl(requestOrigin(req));
559
+ const direct = preferred || origin;
577
560
  if (direct) {
578
- let type = 'lan';
579
- try {
580
- const parsed = new URL(direct);
581
- type = parsed.protocol === 'https:' ? 'tunnel' : 'lan';
582
- } catch {
583
- }
584
- candidates.push({ type, url: direct, priority: 10 });
561
+ candidates.push({ type: candidateUrlType(direct), url: direct, priority: 10 });
562
+ }
563
+ // The origin the creator is browsing over (e.g. a public https domain in
564
+ // front of a reverse proxy) is a reachable address the server cannot
565
+ // discover from its own interfaces. Carry it as an additional direct
566
+ // candidate so the paired device can keep using that same domain instead
567
+ // of depending on LAN hairpin behavior or relay availability. Loopback
568
+ // origins (desktop shell, localhost dev) are unreachable from another
569
+ // device and are skipped.
570
+ if (origin && direct && origin !== direct && !isLoopbackCandidateUrl(origin)) {
571
+ candidates.push({ type: candidateUrlType(origin), url: origin, priority: 20 });
585
572
  }
586
573
  }
587
574
  // The client races candidates and falls back to relay only if the direct URL
@@ -603,14 +590,6 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
603
590
  };
604
591
 
605
592
  const requireApiAuth = async (req, res, next) => {
606
- // Preview proxy requests carry a target-scoped capability token that the
607
- // preview proxy validates against the registered target id/TTL. Let those
608
- // requests reach that stricter check instead of failing the global UI auth
609
- // gate when the short-lived browser URL auth token expires.
610
- if (hasPreviewProxyCredential(req)) {
611
- return next();
612
- }
613
-
614
593
  const requestScope = tunnelAuthController.classifyRequestScope(req);
615
594
  if (requestScope === 'tunnel' || requestScope === 'unknown-public') {
616
595
  return tunnelAuthController.requireTunnelSession(req, res, next);
@@ -331,12 +331,42 @@ describe('core-routes', () => {
331
331
  });
332
332
  });
333
333
 
334
- it('advertises the caller-supplied serverUrl as the direct candidate over the request origin', async () => {
334
+ it('advertises the caller-supplied serverUrl first and keeps the request origin as a fallback candidate', async () => {
335
335
  const { app } = createPairingRouteApp();
336
336
 
337
337
  const response = await request(app)
338
338
  .post('/api/client-auth/pairing/sessions')
339
- .set('Host', 'runtime.example')
339
+ .set('Host', 'chamber.example.com')
340
+ .set('X-Forwarded-Proto', 'https')
341
+ .send({ label: 'Pair phone', serverUrl: 'http://192.168.1.20:2606' })
342
+ .expect(201);
343
+
344
+ expect(response.body.server.candidates).toEqual([
345
+ { type: 'lan', url: 'http://192.168.1.20:2606', priority: 10 },
346
+ { type: 'tunnel', url: 'https://chamber.example.com', priority: 20 },
347
+ ]);
348
+ });
349
+
350
+ it('does not duplicate the request origin when it matches the caller-supplied serverUrl', async () => {
351
+ const { app } = createPairingRouteApp();
352
+
353
+ const response = await request(app)
354
+ .post('/api/client-auth/pairing/sessions')
355
+ .set('Host', '192.168.1.20:2606')
356
+ .send({ label: 'Pair phone', serverUrl: 'http://192.168.1.20:2606' })
357
+ .expect(201);
358
+
359
+ expect(response.body.server.candidates).toEqual([
360
+ { type: 'lan', url: 'http://192.168.1.20:2606', priority: 10 },
361
+ ]);
362
+ });
363
+
364
+ it('skips a loopback request origin as the fallback candidate', async () => {
365
+ const { app } = createPairingRouteApp();
366
+
367
+ const response = await request(app)
368
+ .post('/api/client-auth/pairing/sessions')
369
+ .set('Host', '127.0.0.1:2606')
340
370
  .send({ label: 'Pair phone', serverUrl: 'http://192.168.1.20:2606' })
341
371
  .expect(201);
342
372
 
@@ -461,7 +491,7 @@ describe('core-routes', () => {
461
491
  expect(dependencies.clientPairingRuntime.redeemPairingSession).toHaveBeenCalledTimes(11);
462
492
  });
463
493
 
464
- it('should let preview proxy credentials reach preview proxy validation', async () => {
494
+ it('no longer exempts preview-proxy style credentials from API auth', async () => {
465
495
  const app = express();
466
496
  const requireAuth = vi.fn((_req, res) => res.status(401).type('text/plain').send('Authentication required'));
467
497
 
@@ -493,20 +523,18 @@ describe('core-routes', () => {
493
523
 
494
524
  app.use('/api/preview/proxy', (_req, res) => res.json({ reached: true }));
495
525
 
526
+ // The preview proxy is gone; the token that used to bypass the auth gate
527
+ // must no longer open a hole for any route that happens to match the path.
496
528
  await request(app)
497
529
  .get('/api/preview/proxy/abc123/?oc_preview_token=preview-secret')
498
- .expect(200, { reached: true });
530
+ .expect(401, 'Authentication required');
499
531
 
500
532
  await request(app)
501
533
  .get('/api/preview/proxy/abc123/')
502
534
  .set('Cookie', 'oc_preview_token=preview-secret')
503
- .expect(200, { reached: true });
504
-
505
- await request(app)
506
- .get('/api/preview/proxy/abc123/')
507
535
  .expect(401, 'Authentication required');
508
536
 
509
- expect(requireAuth).toHaveBeenCalledTimes(1);
537
+ expect(requireAuth).toHaveBeenCalledTimes(2);
510
538
  });
511
539
  });
512
540