@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
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Request/response broker between the agent tool and the in-app browser.
3
+ *
4
+ * The browser lives in the renderer, not the server, so the server cannot act
5
+ * on a page directly. It publishes a request over the existing OpenChamber
6
+ * event stream and waits for the client that owns the browser view to post the
7
+ * result back.
8
+ *
9
+ * The request goes to every client that could serve it, because the server
10
+ * cannot know which one is showing a page. Exactly one must act on it, so a
11
+ * client claims the request before touching anything and only the first claim
12
+ * is granted. Without that, two connected desktop clients would both click, and
13
+ * the losing one's late result would not undo what it had already done.
14
+ *
15
+ * Two failure modes matter and are handled explicitly rather than as timeouts:
16
+ *
17
+ * - No client is listening. The agent is told immediately that the browser is
18
+ * not open, instead of blocking for the full timeout and then reporting
19
+ * something ambiguous.
20
+ * - The client accepted the request and then went away. That still times out,
21
+ * because the alternative — assuming success — would be a lie.
22
+ */
23
+
24
+ const DEFAULT_TIMEOUT_MS = 20_000;
25
+ const MAX_TIMEOUT_MS = 120_000;
26
+
27
+ export class BrowserControlError extends Error {
28
+ constructor(message, status = 400) {
29
+ super(message);
30
+ this.name = 'BrowserControlError';
31
+ this.status = status;
32
+ }
33
+ }
34
+
35
+ export const createBrowserControlBroker = ({
36
+ emitRequest,
37
+ createId,
38
+ setTimer = setTimeout,
39
+ clearTimer = clearTimeout,
40
+ } = {}) => {
41
+ if (typeof emitRequest !== 'function') {
42
+ throw new TypeError('emitRequest is required');
43
+ }
44
+
45
+ const pending = new Map();
46
+
47
+ const settle = (requestId, outcome) => {
48
+ const entry = pending.get(requestId);
49
+ if (!entry) return false;
50
+ pending.delete(requestId);
51
+ clearTimer(entry.timer);
52
+ entry.finish(outcome);
53
+ return true;
54
+ };
55
+
56
+ return {
57
+ /** Number of requests still awaiting a client response. */
58
+ get pendingCount() {
59
+ return pending.size;
60
+ },
61
+
62
+ /**
63
+ * Publishes one browser action and resolves with the client's result.
64
+ * Rejects with a BrowserControlError the agent can act on.
65
+ */
66
+ request(action, parameters = {}, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}) {
67
+ const requestId = typeof createId === 'function' ? createId() : `browser-${Date.now()}-${pending.size}`;
68
+ const boundedTimeout = Math.min(Math.max(1_000, Number(timeoutMs) || DEFAULT_TIMEOUT_MS), MAX_TIMEOUT_MS);
69
+
70
+ const listenerCount = emitRequest({ requestId, action, parameters });
71
+ if (!listenerCount) {
72
+ // Written for the agent reading it, not the user: state what this
73
+ // environment can do, and leave deciding whether it matters to the
74
+ // caller rather than handing it an instruction it cannot carry out.
75
+ return Promise.reject(new BrowserControlError(
76
+ 'No OpenChamber client connected here can control a page. Reading and '
77
+ + 'interacting with a page works when OpenChamber runs as its desktop '
78
+ + 'application; a web browser tab can display a page but cannot be '
79
+ + 'driven. Nothing was changed. Mention this to the user only if it '
80
+ + 'affects what they asked for.',
81
+ 503,
82
+ ));
83
+ }
84
+
85
+ return new Promise((resolve, reject) => {
86
+ const finish = (outcome) => {
87
+ if (signal && onAbort) signal.removeEventListener('abort', onAbort);
88
+ if (outcome.ok) resolve(outcome.data ?? null);
89
+ else reject(new BrowserControlError(outcome.message || 'Browser action failed', outcome.status || 400));
90
+ };
91
+
92
+ const onAbort = signal
93
+ ? () => settle(requestId, { ok: false, message: 'Browser action was cancelled', status: 499 })
94
+ : null;
95
+ if (signal) {
96
+ if (signal.aborted) {
97
+ reject(new BrowserControlError('Browser action was cancelled', 499));
98
+ return;
99
+ }
100
+ signal.addEventListener('abort', onAbort, { once: true });
101
+ }
102
+
103
+ const timer = setTimer(() => {
104
+ settle(requestId, {
105
+ ok: false,
106
+ message: `The in-app browser did not respond within ${Math.round(boundedTimeout / 1000)}s`,
107
+ status: 504,
108
+ });
109
+ }, boundedTimeout);
110
+
111
+ pending.set(requestId, { finish, timer, claimed: false });
112
+ });
113
+ },
114
+
115
+ /**
116
+ * Grants the right to perform one request, to one client.
117
+ *
118
+ * The first caller wins; everyone else is told no and must do nothing. An
119
+ * unknown id is also a refusal: the request has already been settled, and
120
+ * acting on it now would change a page nobody is waiting on.
121
+ */
122
+ claim(requestId) {
123
+ if (typeof requestId !== 'string' || !requestId) return false;
124
+ const entry = pending.get(requestId);
125
+ if (!entry || entry.claimed) return false;
126
+ entry.claimed = true;
127
+ return true;
128
+ },
129
+
130
+ /**
131
+ * Accepts a result posted by the client. Returns false for an unknown id,
132
+ * which is the normal outcome for a response that lost a race with the
133
+ * timeout and must not be treated as an error.
134
+ */
135
+ resolve(requestId, result) {
136
+ if (typeof requestId !== 'string' || !requestId) return false;
137
+ if (result && result.ok === true) {
138
+ return settle(requestId, { ok: true, data: result.data ?? null });
139
+ }
140
+ return settle(requestId, {
141
+ ok: false,
142
+ message: typeof result?.error === 'string' && result.error ? result.error : 'Browser action failed',
143
+ status: 400,
144
+ });
145
+ },
146
+
147
+ /** Fails everything in flight, e.g. when the owning client disconnects. */
148
+ rejectAll(message) {
149
+ for (const requestId of [...pending.keys()]) {
150
+ settle(requestId, { ok: false, message, status: 503 });
151
+ }
152
+ },
153
+ };
154
+ };
@@ -0,0 +1,191 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { BrowserControlError, createBrowserControlBroker } from './broker.js';
4
+
5
+ const createBroker = (options = {}) => {
6
+ const emitted = [];
7
+ let sequence = 0;
8
+ const broker = createBrowserControlBroker({
9
+ emitRequest: (payload) => {
10
+ emitted.push(payload);
11
+ return options.listeners ?? 1;
12
+ },
13
+ createId: () => {
14
+ sequence += 1;
15
+ return `req-${sequence}`;
16
+ },
17
+ ...options.overrides,
18
+ });
19
+ return { broker, emitted };
20
+ };
21
+
22
+ describe('browser control broker', () => {
23
+ test('resolves with the data the client posted back', async () => {
24
+ const { broker, emitted } = createBroker();
25
+ const inflight = broker.request('browser.snapshot', {});
26
+ expect(emitted[0]?.action).toBe('browser.snapshot');
27
+
28
+ broker.resolve(emitted[0].requestId, { ok: true, data: { url: 'http://localhost:5173/' } });
29
+ expect(await inflight).toEqual({ url: 'http://localhost:5173/' });
30
+ });
31
+
32
+ test('fails fast when no client is connected instead of blocking', async () => {
33
+ const { broker } = createBroker({ listeners: 0 });
34
+ await expect(broker.request('browser.open', { url: 'http://a/' })).rejects.toThrow(BrowserControlError);
35
+ });
36
+
37
+ test('describes the environment rather than telling the agent what to do', async () => {
38
+ const { broker } = createBroker({ listeners: 0 });
39
+ try {
40
+ await broker.request('browser.snapshot', {});
41
+ throw new Error('expected rejection');
42
+ } catch (error) {
43
+ expect(error.status).toBe(503);
44
+ // The agent reads this, not the user: it must state the limitation and
45
+ // where the capability exists, without issuing an instruction the agent
46
+ // cannot carry out.
47
+ expect(error.message).toContain('desktop application');
48
+ expect(error.message).toContain('Nothing was changed');
49
+ expect(error.message).not.toContain('Ask the user to open');
50
+ }
51
+ });
52
+
53
+ test('surfaces a client-reported failure with its message', async () => {
54
+ const { broker, emitted } = createBroker();
55
+ const inflight = broker.request('browser.click', { selector: '#missing' });
56
+ broker.resolve(emitted[0].requestId, { ok: false, error: 'No element matches #missing' });
57
+ await expect(inflight).rejects.toThrow('No element matches #missing');
58
+ });
59
+
60
+ test('times out when the client accepted the request and never answered', async () => {
61
+ let fire = null;
62
+ const { broker } = createBroker({
63
+ overrides: {
64
+ setTimer: (callback) => { fire = callback; return 1; },
65
+ clearTimer: () => {},
66
+ },
67
+ });
68
+ const inflight = broker.request('browser.snapshot', {}, { timeoutMs: 5_000 });
69
+ fire();
70
+ await expect(inflight).rejects.toThrow('did not respond within 5s');
71
+ });
72
+
73
+ test('ignores a late response that lost the race with the timeout', async () => {
74
+ let fire = null;
75
+ const { broker, emitted } = createBroker({
76
+ overrides: {
77
+ setTimer: (callback) => { fire = callback; return 1; },
78
+ clearTimer: () => {},
79
+ },
80
+ });
81
+ const inflight = broker.request('browser.snapshot', {});
82
+ fire();
83
+ await expect(inflight).rejects.toThrow();
84
+ expect(broker.resolve(emitted[0].requestId, { ok: true, data: {} })).toBe(false);
85
+ });
86
+
87
+ test('rejects an unknown request id without throwing', () => {
88
+ const { broker } = createBroker();
89
+ expect(broker.resolve('nope', { ok: true })).toBe(false);
90
+ expect(broker.resolve('', { ok: true })).toBe(false);
91
+ });
92
+
93
+ test('clears pending state once a request settles', async () => {
94
+ const { broker, emitted } = createBroker();
95
+ const inflight = broker.request('browser.snapshot', {});
96
+ expect(broker.pendingCount).toBe(1);
97
+ broker.resolve(emitted[0].requestId, { ok: true, data: null });
98
+ await inflight;
99
+ expect(broker.pendingCount).toBe(0);
100
+ });
101
+
102
+ test('fails everything in flight when the owning client disconnects', async () => {
103
+ const { broker } = createBroker();
104
+ const inflight = broker.request('browser.snapshot', {});
105
+ broker.rejectAll('The OpenChamber client disconnected');
106
+ await expect(inflight).rejects.toThrow('disconnected');
107
+ expect(broker.pendingCount).toBe(0);
108
+ });
109
+
110
+ test('propagates cancellation from the caller', async () => {
111
+ const { broker } = createBroker();
112
+ const controller = new AbortController();
113
+ const inflight = broker.request('browser.snapshot', {}, { signal: controller.signal });
114
+ controller.abort();
115
+ await expect(inflight).rejects.toThrow('cancelled');
116
+ });
117
+
118
+ test('rejects immediately when the caller is already cancelled', async () => {
119
+ const { broker } = createBroker();
120
+ const controller = new AbortController();
121
+ controller.abort();
122
+ await expect(broker.request('browser.snapshot', {}, { signal: controller.signal })).rejects.toThrow('cancelled');
123
+ });
124
+ });
125
+
126
+ /**
127
+ * Whether a page can be driven depends on which client is connected, not on the
128
+ * server: a desktop shell and a browser tab can be attached to one server at
129
+ * once, and either may arrive or leave at any moment. The broker is told how
130
+ * many clients could actually perform each action.
131
+ */
132
+ describe('client capability', () => {
133
+ const createCapabilityBroker = (capableFor) => {
134
+ const emitted = [];
135
+ let sequence = 0;
136
+ const broker = createBrowserControlBroker({
137
+ emitRequest: (payload) => {
138
+ emitted.push(payload);
139
+ return capableFor(payload.action);
140
+ },
141
+ createId: () => { sequence += 1; return `req-${sequence}`; },
142
+ });
143
+ return { broker, emitted };
144
+ };
145
+
146
+ test('opening a page works with a client that cannot drive one', async () => {
147
+ // A browser tab can display a page even though it cannot be controlled.
148
+ const { broker, emitted } = createCapabilityBroker((action) => (action === 'browser.open' ? 1 : 0));
149
+ const inflight = broker.request('browser.open', { url: 'http://localhost:3000/' });
150
+ broker.resolve(emitted[0].requestId, { ok: true, data: { opened: true } });
151
+ expect(await inflight).toEqual({ opened: true });
152
+ });
153
+
154
+ test('driving a page fails immediately when no client can', async () => {
155
+ const { broker } = createCapabilityBroker((action) => (action === 'browser.open' ? 1 : 0));
156
+ await expect(broker.request('browser.click', { selector: '#a' })).rejects.toThrow('desktop application');
157
+ });
158
+
159
+ test('driving a page works as soon as a capable client is connected', async () => {
160
+ // No restart, no setting: a desktop client attaching is enough.
161
+ const { broker, emitted } = createCapabilityBroker(() => 1);
162
+ const inflight = broker.request('browser.snapshot', {});
163
+ broker.resolve(emitted[0].requestId, { ok: true, data: { url: 'http://localhost:3000/' } });
164
+ expect(await inflight).toEqual({ url: 'http://localhost:3000/' });
165
+ });
166
+ });
167
+
168
+ describe('one request, one performer', () => {
169
+ test('grants the request to the first claimant and refuses the rest', async () => {
170
+ const broker = createBrowserControlBroker({ emitRequest: () => 2, createId: () => 'req-1' });
171
+ const pending = broker.request('browser.click', { selector: 'button' });
172
+
173
+ expect(broker.claim('req-1')).toBe(true);
174
+ // A second desktop client is told no, so it never clicks.
175
+ expect(broker.claim('req-1')).toBe(false);
176
+
177
+ broker.resolve('req-1', { ok: true, data: { clicked: true } });
178
+ await expect(pending).resolves.toEqual({ clicked: true });
179
+ });
180
+
181
+ test('refuses a claim for a request that is already over', () => {
182
+ const broker = createBrowserControlBroker({ emitRequest: () => 1, createId: () => 'req-1' });
183
+ const pending = broker.request('browser.click', {});
184
+ broker.resolve('req-1', { ok: true, data: null });
185
+ void pending.catch(() => undefined);
186
+
187
+ // Acting now would change a page nobody is waiting on.
188
+ expect(broker.claim('req-1')).toBe(false);
189
+ expect(broker.claim('unknown')).toBe(false);
190
+ });
191
+ });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Result callback for in-app browser actions.
3
+ *
4
+ * The client that owns the browser view posts here with the outcome of a
5
+ * request it received over the event stream. Only the request id is trusted to
6
+ * correlate; an unknown id is accepted with `matched: false` rather than an
7
+ * error, because a client answering after a timeout has done nothing wrong.
8
+ */
9
+ export function registerBrowserControlRoutes(app, { express, broker }) {
10
+ // Claiming is separate from answering so that a client learns whether it may
11
+ // act *before* it acts. Deciding by whose result arrives first would be too
12
+ // late: by then every client has already clicked.
13
+ app.post('/api/browser-control/claim', express.json({ limit: '4kb' }), (req, res) => {
14
+ const requestId = typeof req.body?.requestId === 'string' ? req.body.requestId.trim() : '';
15
+ if (!requestId) {
16
+ res.status(400).json({ error: 'requestId is required' });
17
+ return;
18
+ }
19
+ res.json({ granted: broker.claim(requestId) });
20
+ });
21
+
22
+ // This server attaches body parsing per route rather than globally. Without
23
+ // it `req.body` is undefined here, the client's result is rejected, and the
24
+ // agent sees an unexplained timeout instead of its answer. A page snapshot
25
+ // carries the visible text plus every interactive element, so the limit is
26
+ // sized for that rather than for a small control message.
27
+ app.post('/api/browser-control/result', express.json({ limit: '2mb' }), (req, res) => {
28
+ const body = req.body;
29
+ if (!body || typeof body !== 'object') {
30
+ res.status(400).json({ error: 'A JSON body is required' });
31
+ return;
32
+ }
33
+
34
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
35
+ if (!requestId) {
36
+ res.status(400).json({ error: 'requestId is required' });
37
+ return;
38
+ }
39
+
40
+ const matched = broker.resolve(requestId, {
41
+ ok: body.ok === true,
42
+ data: body.data ?? null,
43
+ error: typeof body.error === 'string' ? body.error : '',
44
+ });
45
+
46
+ res.json({ matched });
47
+ });
48
+ }
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import express from 'express';
3
+ import request from 'supertest';
4
+
5
+ import { createBrowserControlBroker } from './broker.js';
6
+ import { registerBrowserControlRoutes } from './routes.js';
7
+
8
+ /**
9
+ * These run against a real Express app on purpose. This server attaches body
10
+ * parsing per route, so a route that forgets it still *registers* fine and only
11
+ * fails when a client posts to it — which surfaces to the agent as an
12
+ * unexplained timeout, nowhere near the cause.
13
+ */
14
+ const createApp = ({ listeners = 1 } = {}) => {
15
+ const emitted = [];
16
+ let sequence = 0;
17
+ const broker = createBrowserControlBroker({
18
+ emitRequest: (payload) => {
19
+ emitted.push(payload);
20
+ return listeners;
21
+ },
22
+ createId: () => {
23
+ sequence += 1;
24
+ return `req-${sequence}`;
25
+ },
26
+ });
27
+
28
+ const app = express();
29
+ registerBrowserControlRoutes(app, { express, broker });
30
+ return { app, broker, emitted };
31
+ };
32
+
33
+ describe('browser control result route', () => {
34
+ it('parses a posted JSON body and resolves the waiting request', async () => {
35
+ const { app, broker, emitted } = createApp();
36
+ const inflight = broker.request('browser.snapshot', {});
37
+
38
+ await request(app)
39
+ .post('/api/browser-control/result')
40
+ .send({ requestId: emitted[0].requestId, ok: true, data: { url: 'http://localhost:3000/' } })
41
+ .expect(200, { matched: true });
42
+
43
+ expect(await inflight).toEqual({ url: 'http://localhost:3000/' });
44
+ });
45
+
46
+ it('accepts a snapshot large enough to carry a real page', async () => {
47
+ const { app, broker, emitted } = createApp();
48
+ const inflight = broker.request('browser.snapshot', {});
49
+
50
+ const data = {
51
+ url: 'http://localhost:3000/',
52
+ text: 'x'.repeat(200_000),
53
+ elements: Array.from({ length: 120 }, (_, index) => ({
54
+ selector: `div:nth-of-type(${index})`,
55
+ label: 'y'.repeat(100),
56
+ })),
57
+ };
58
+
59
+ await request(app)
60
+ .post('/api/browser-control/result')
61
+ .send({ requestId: emitted[0].requestId, ok: true, data })
62
+ .expect(200, { matched: true });
63
+
64
+ const result = await inflight;
65
+ expect(result.text).toHaveLength(200_000);
66
+ expect(result.elements).toHaveLength(120);
67
+ });
68
+
69
+ it('propagates a client-reported failure', async () => {
70
+ const { app, broker, emitted } = createApp();
71
+ // Capture the outcome before posting: the rejection lands while the POST is
72
+ // still in flight, and an unattached handler surfaces as an unhandled one.
73
+ const outcome = broker.request('browser.click', { selector: '#nope' })
74
+ .then(() => null, (error) => error);
75
+
76
+ await request(app)
77
+ .post('/api/browser-control/result')
78
+ .send({ requestId: emitted[0].requestId, ok: false, error: 'No element matches #nope' })
79
+ .expect(200, { matched: true });
80
+
81
+ expect((await outcome)?.message).toBe('No element matches #nope');
82
+ });
83
+
84
+ it('reports matched: false for a response that arrived after the timeout', async () => {
85
+ const { app } = createApp();
86
+ await request(app)
87
+ .post('/api/browser-control/result')
88
+ .send({ requestId: 'expired', ok: true, data: {} })
89
+ .expect(200, { matched: false });
90
+ });
91
+
92
+ it('rejects a body with no request id', async () => {
93
+ const { app } = createApp();
94
+ await request(app)
95
+ .post('/api/browser-control/result')
96
+ .send({ ok: true })
97
+ .expect(400);
98
+ });
99
+
100
+ it('rejects a body that is not an object', async () => {
101
+ const { app } = createApp();
102
+ await request(app)
103
+ .post('/api/browser-control/result')
104
+ .set('Content-Type', 'application/json')
105
+ .send('"just-a-string"')
106
+ .expect(400);
107
+ });
108
+ });