@myrialabs/clopen 0.4.23 → 0.4.25

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 (53) hide show
  1. package/backend/chat/stream-manager.ts +41 -13
  2. package/backend/engine/README.md +18 -0
  3. package/backend/engine/adapters/claude/message-converter.test.ts +36 -0
  4. package/backend/engine/adapters/claude/message-converter.ts +40 -4
  5. package/backend/engine/adapters/claude/stream.ts +68 -3
  6. package/backend/engine/adapters/claude/workflow-transcript.test.ts +65 -0
  7. package/backend/engine/adapters/claude/workflow-transcript.ts +248 -0
  8. package/backend/engine/adapters/coordination-tool-mapping.test.ts +17 -0
  9. package/backend/engine/adapters/copilot/message-converter.ts +20 -1
  10. package/backend/engine/adapters/opencode/message-converter.test.ts +80 -0
  11. package/backend/engine/adapters/opencode/message-converter.ts +32 -0
  12. package/backend/engine/adapters/opencode/stream.ts +29 -23
  13. package/backend/engine/adapters/qwen/message-converter.ts +5 -8
  14. package/backend/engine/docs/adapter-contract.md +29 -1
  15. package/backend/engine/docs/adding-an-engine.md +8 -1
  16. package/backend/engine/docs/frontend-and-chat.md +32 -1
  17. package/backend/engine/docs/lessons-learned.md +49 -2
  18. package/backend/engine/docs/quick-reference.md +2 -0
  19. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
  20. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
  24. package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
  25. package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
  26. package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
  27. package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
  28. package/backend/module-shadowing.test.ts +135 -0
  29. package/backend/preview/browser/browser-host-bridge.ts +8 -2
  30. package/backend/preview/browser/browser-interaction-handler.ts +95 -38
  31. package/backend/preview/browser/browser-mcp-control.ts +332 -22
  32. package/backend/preview/browser/browser-preview-service.ts +152 -33
  33. package/backend/preview/browser/browser-tab-manager.ts +25 -1
  34. package/backend/preview/browser/browser-video-capture.ts +551 -247
  35. package/backend/preview/browser/scripts/host-bridge.ts +61 -89
  36. package/backend/preview/browser/scripts/video-stream.ts +32 -0
  37. package/backend/preview/browser/types.ts +22 -0
  38. package/backend/preview/index.ts +6 -1
  39. package/backend/ws/preview/browser/console.ts +12 -10
  40. package/backend/ws/preview/browser/interact.ts +40 -10
  41. package/backend/ws/preview/browser/native-ui.ts +35 -10
  42. package/backend/ws/preview/browser/tab-info.ts +46 -7
  43. package/backend/ws/preview/browser/webcodecs.ts +6 -1
  44. package/backend/ws/preview/index.ts +23 -3
  45. package/dist/assets/{index-DH_GO0Lf.js → index-C4PD7B-x.js} +1 -1
  46. package/dist/assets/{index-igSQ3JaM.js → index-KBGloYDk.js} +1 -1
  47. package/dist/assets/{main-D-d8SFfW.js → main-B0AA-88X.js} +364 -358
  48. package/dist/assets/main-OsjA5Ab5.css +1 -0
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/unified/index.ts +7 -0
  52. package/shared/types/unified/tool.ts +57 -2
  53. package/dist/assets/main-BD3-qPfT.css +0 -1
@@ -56,6 +56,9 @@ export class BrowserPreviewService extends EventEmitter {
56
56
  // Store context menu info for later action execution
57
57
  private contextMenus = new Map<string, BrowserContextMenuInfo>();
58
58
 
59
+ /** Tabs whose page is showing something full screen — see applyFullscreenState. */
60
+ private fullscreenTabs = new Set<string>();
61
+
59
62
  // Project ID for isolation (REQUIRED)
60
63
  private projectId: string;
61
64
 
@@ -96,15 +99,18 @@ export class BrowserPreviewService extends EventEmitter {
96
99
  // with the `source` stamp the client contract requires. Forwarding them
97
100
  // from here as well delivered every cursor update twice, once without
98
101
  // that field.
99
- this.interactionHandler.on('test-completed', (data) => {
100
- this.emit('preview:browser-mcp-test-completed', data);
101
- });
102
-
103
102
  // Forward navigation events and handle video streaming restart
104
103
  // Only full navigations (framenavigated) need streaming restart
105
104
  this.navigationTracker.on('navigation', async (data) => {
106
105
  this.emit('preview:browser-navigation', data);
107
106
 
107
+ // A new document cannot still be full screen: the element that was
108
+ // went with the old one. Left set, the viewer would keep offering an
109
+ // exit for a state that no longer exists.
110
+ if (this.fullscreenTabs.delete(data.sessionId)) {
111
+ this.emit('preview:browser-fullscreen-state', { tabId: data.sessionId, active: false });
112
+ }
113
+
108
114
  // After navigation completes, restart video streaming for the tab
109
115
  // This re-injects the peer script and restarts CDP screencast
110
116
  const { sessionId } = data;
@@ -115,14 +121,21 @@ export class BrowserPreviewService extends EventEmitter {
115
121
  if (this.videoCapture.isStreaming(sessionId)) {
116
122
  const tab = this.getTab(sessionId);
117
123
  if (tab) {
118
- // Restart streaming immediately — page is already navigated
124
+ // Restart streaming immediately — page is already navigated.
125
+ // A failure here is logged rather than swallowed: it used to
126
+ // leave the session marked active over a page that could no
127
+ // longer encode, and the only visible symptom was a preview
128
+ // stuck loading. handleNavigation now clears `isActive` on
129
+ // failure so the next handshake rebuilds from scratch.
119
130
  try {
120
131
  const success = await this.videoCapture.handleNavigation(sessionId, tab);
121
132
  if (success) {
122
133
  this.emit('preview:browser-navigation-streaming-ready', { sessionId });
134
+ } else {
135
+ debug.warn('preview', `Streaming restore failed after navigation on ${sessionId}`);
123
136
  }
124
137
  } catch (error) {
125
- // Silently fail - frontend will request refresh if needed
138
+ debug.warn('preview', `Streaming restore threw after navigation on ${sessionId}:`, error);
126
139
  }
127
140
  }
128
141
  }
@@ -152,6 +165,15 @@ export class BrowserPreviewService extends EventEmitter {
152
165
  this.emit('preview:browser-tab-opened', data);
153
166
  });
154
167
  this.tabManager.on('preview:browser-tab-closed', (data) => {
168
+ // Hooked to the event rather than to closeTab(): the tab manager
169
+ // closes tabs on its own too (browser disconnect, pool teardown, a
170
+ // window the page closed), and those paths never pass through the
171
+ // service. The page is gone either way, and with it the bindings and
172
+ // on-new-document scripts this bookkeeping describes.
173
+ if (data?.tabId) {
174
+ this.videoCapture.disposeTab(data.tabId);
175
+ this.fullscreenTabs.delete(data.tabId);
176
+ }
155
177
  this.emit('preview:browser-tab-closed', data);
156
178
  });
157
179
  this.tabManager.on('preview:browser-tab-switched', (data) => {
@@ -199,6 +221,10 @@ export class BrowserPreviewService extends EventEmitter {
199
221
  void this.restoreEmulatedViewport(data.tabId, data.requestId);
200
222
  return;
201
223
  }
224
+ if (data.kind === 'fullscreen-state') {
225
+ this.applyFullscreenState(data.tabId, data.requestId, data.payload);
226
+ return;
227
+ }
202
228
  this.emit('preview:browser-host-request', data);
203
229
  });
204
230
  this.hostBridge.on('download', (data) => {
@@ -477,12 +503,31 @@ export class BrowserPreviewService extends EventEmitter {
477
503
  }
478
504
 
479
505
  /**
480
- * Switch to a specific tab
506
+ * Make a tab the project's active one.
507
+ *
508
+ * "Active" is a single value shared by everyone in the project, so this is
509
+ * for the agent (`switch_tab`, `open_tab`) and for tab creation — decisions
510
+ * that genuinely belong to the project. A viewer merely looking at a tab
511
+ * must use `noteTabViewed` instead: with two people watching, letting the
512
+ * act of looking reassign this made each of them move the other's target.
481
513
  */
482
514
  switchTab(tabId: string): boolean {
483
515
  return this.tabManager.setActiveTab(tabId);
484
516
  }
485
517
 
518
+ /**
519
+ * Note that some viewer is now watching this tab.
520
+ *
521
+ * Keeps the tab out of the idle-cleanup sweep without touching who the
522
+ * project considers active. Returns false if the tab is gone, which is how
523
+ * a viewer learns its tab strip is stale.
524
+ */
525
+ noteTabViewed(tabId: string): boolean {
526
+ if (!this.tabManager.getTab(tabId)) return false;
527
+ this.tabManager.markTabActivity(tabId);
528
+ return true;
529
+ }
530
+
486
531
  /**
487
532
  * Get a tab by ID
488
533
  */
@@ -679,6 +724,68 @@ export class BrowserPreviewService extends EventEmitter {
679
724
  }
680
725
  }
681
726
 
727
+ /**
728
+ * Record that a tab's page went full screen (or left it) and tell viewers.
729
+ *
730
+ * The state matters to the viewer because the way out cannot live only in
731
+ * the page: the hint the shim draws is a DOM node the page is free to
732
+ * destroy, and a fullscreen Chrome granted from its own C++ leaves no hint
733
+ * at all. Knowing lets the viewer render an exit control of its own, which
734
+ * nothing in the page can reach.
735
+ */
736
+ private applyFullscreenState(tabId: string, requestId: string, payload: unknown): void {
737
+ const active = !!(payload as { active?: boolean } | null)?.active;
738
+
739
+ if (active) this.fullscreenTabs.add(tabId);
740
+ else this.fullscreenTabs.delete(tabId);
741
+
742
+ debug.log('preview', `🖥️ Tab ${tabId} full screen: ${active}`);
743
+ this.emit('preview:browser-fullscreen-state', { tabId, active });
744
+ this.hostBridge.respond(requestId, { ok: true });
745
+ }
746
+
747
+ /** Whether a tab's page currently has something full screen. */
748
+ isPageFullscreen(tabId: string): boolean {
749
+ return this.fullscreenTabs.has(tabId);
750
+ }
751
+
752
+ /**
753
+ * Force a tab out of full screen, from outside the page.
754
+ *
755
+ * Every frame is asked, not just the main one: a video in an embed goes
756
+ * full screen inside its own document, and that frame is the only one that
757
+ * holds the state. The emulated viewport is re-asserted afterwards because
758
+ * a fullscreen Chrome granted itself collapses the composited surface and
759
+ * leaves it collapsed — the zoomed, cropped preview that looked like the
760
+ * fullscreen had never ended.
761
+ */
762
+ async exitPageFullscreen(tabId: string): Promise<boolean> {
763
+ const tab = this.getTab(tabId);
764
+ if (!tab?.page || tab.page.isClosed()) return false;
765
+
766
+ await Promise.all(
767
+ tab.page.frames().map((frame) =>
768
+ frame
769
+ .evaluate(() => {
770
+ (window as any).__clopenFullscreen?.forceExit();
771
+ })
772
+ .catch(() => {
773
+ // Detached or navigating — nothing of ours is left in it.
774
+ })
775
+ )
776
+ );
777
+
778
+ this.fullscreenTabs.delete(tabId);
779
+ this.emit('preview:browser-fullscreen-state', { tabId, active: false });
780
+
781
+ const { width, height } = getViewportDimensions(tab.deviceSize, tab.rotation);
782
+ const restored = await this.videoCapture.updateViewport(tabId, tab, width, height);
783
+ if (!restored) await tab.page.setViewport({ width, height }).catch(() => {});
784
+
785
+ debug.log('preview', `🖥️ Forced tab ${tabId} out of full screen`);
786
+ return true;
787
+ }
788
+
682
789
  async updateWebCodecsViewport(tabId: string, width: number, height: number): Promise<boolean> {
683
790
  const tab = this.getTab(tabId);
684
791
  if (!tab) {
@@ -782,6 +889,11 @@ export class BrowserPreviewService extends EventEmitter {
782
889
  * caller can report "3 of 7 ran" instead of claiming a success the user
783
890
  * interrupted.
784
891
  */
892
+ /** Where the agent's pointer stands on a tab, for a viewer building state. */
893
+ getMcpCursorPosition(tabId: string): { x: number; y: number } | null {
894
+ return this.interactionHandler.getCursorPosition(tabId);
895
+ }
896
+
785
897
  async performAutonomousActions(
786
898
  tabId: string,
787
899
  actions: BrowserAutonomousAction[],
@@ -1056,6 +1168,10 @@ class BrowserPreviewServiceManager {
1056
1168
  ws.emit.project(projectId, 'preview:browser-viewport-changed', { ...data, projectId });
1057
1169
  });
1058
1170
 
1171
+ service.on('preview:browser-fullscreen-state', (data) => {
1172
+ ws.emit.project(projectId, 'preview:browser-fullscreen-state', { ...data, projectId });
1173
+ });
1174
+
1059
1175
  // Forward live tab metadata (title, favicon, back/forward availability)
1060
1176
  service.on('preview:browser-tab-meta', (data) => {
1061
1177
  ws.emit.project(projectId, 'preview:browser-tab-meta', { ...data, projectId });
@@ -1085,12 +1201,6 @@ class BrowserPreviewServiceManager {
1085
1201
  ws.emit.project(projectId, 'preview:browser-console-clear', data);
1086
1202
  });
1087
1203
 
1088
- // Forward MCP events. Cursor position/click come from the singleton
1089
- // instead (setupMcpControlForwarding) — see setupEventForwarding().
1090
- service.on('preview:browser-mcp-test-completed', (data) => {
1091
- ws.emit.project(projectId, 'preview:browser-mcp-test-completed', data);
1092
- });
1093
-
1094
1204
  // Forward dialog events
1095
1205
  service.on('preview:browser-dialog', (data) => {
1096
1206
  ws.emit.project(projectId, 'preview:browser-dialog', data);
@@ -1161,23 +1271,19 @@ class BrowserPreviewServiceManager {
1161
1271
  *
1162
1272
  * Registered exactly once for the whole manager. The emitter is a singleton
1163
1273
  * shared across all projects, so attaching these listeners per-project would
1164
- * accumulate them without bound (MaxListenersExceededWarning). MCP control
1165
- * events are not project-scoped at the source, so we broadcast them to every
1166
- * currently-active project; the frontend filters by tab/session.
1274
+ * accumulate them without bound (MaxListenersExceededWarning).
1275
+ *
1276
+ * Every event here is addressed to exactly one project room. Tab ids repeat
1277
+ * across projects (`tab-1` exists in all of them), so an unaddressed event
1278
+ * has no safe destination: broadcasting it draws one project's agent onto a
1279
+ * same-numbered tab in another project, which on a shared server means onto
1280
+ * a colleague's screen. `browserMcpControl` remembers a tab's last owning
1281
+ * project precisely so this never has to guess.
1167
1282
  */
1168
1283
  private setupMcpControlForwarding(): void {
1169
1284
  if (this.mcpForwardingSetup) return;
1170
1285
  this.mcpForwardingSetup = true;
1171
1286
 
1172
- const emitToActiveProjects = <K extends Parameters<typeof ws.emit.project>[1]>(
1173
- event: K,
1174
- payload: Parameters<typeof ws.emit.project<K>>[2]
1175
- ) => {
1176
- for (const projectId of this.services.keys()) {
1177
- ws.emit.project(projectId, event, payload);
1178
- }
1179
- };
1180
-
1181
1287
  // Control events are project-scoped: emit ONLY to the owning project's room
1182
1288
  // and stamp projectId. Tab IDs (tab-N) repeat across projects, so a broadcast
1183
1289
  // would let project A's control event mismark a same-numbered tab in project B.
@@ -1202,33 +1308,46 @@ class BrowserPreviewServiceManager {
1202
1308
  });
1203
1309
  });
1204
1310
 
1311
+ browserMcpControl.on('control-focus', (data) => {
1312
+ ws.emit.project(data.projectId, 'preview:browser-mcp-control-focus', {
1313
+ browserTabId: data.browserTabId,
1314
+ focused: data.focused,
1315
+ projectId: data.projectId,
1316
+ timestamp: data.timestamp
1317
+ });
1318
+ });
1319
+
1205
1320
  browserMcpControl.on('cursor-position', (data) => {
1206
- emitToActiveProjects('preview:browser-mcp-cursor-position', {
1321
+ if (!data.projectId) return;
1322
+ ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-position', {
1207
1323
  sessionId: data.tabId,
1208
1324
  x: data.x,
1209
1325
  y: data.y,
1210
1326
  pressed: data.pressed ?? false,
1211
1327
  timestamp: data.timestamp,
1212
- source: 'mcp'
1328
+ source: 'mcp' as const
1213
1329
  });
1214
1330
  });
1215
1331
 
1216
1332
  browserMcpControl.on('cursor-click', (data) => {
1217
- emitToActiveProjects('preview:browser-mcp-cursor-click', {
1333
+ if (!data.projectId) return;
1334
+ ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-click', {
1218
1335
  sessionId: data.tabId,
1219
1336
  x: data.x,
1220
1337
  y: data.y,
1221
1338
  button: data.button ?? 'left',
1222
1339
  timestamp: data.timestamp,
1223
- source: 'mcp'
1340
+ source: 'mcp' as const
1224
1341
  });
1225
1342
  });
1226
1343
 
1227
- browserMcpControl.on('test-completed', (data) => {
1228
- emitToActiveProjects('preview:browser-mcp-test-completed', {
1344
+ // What the agent is doing, for the caption beside its cursor.
1345
+ browserMcpControl.on('activity', (data) => {
1346
+ if (!data.projectId) return;
1347
+ ws.emit.project(data.projectId, 'preview:browser-mcp-activity', {
1229
1348
  sessionId: data.tabId,
1230
- timestamp: data.timestamp,
1231
- source: 'mcp'
1349
+ label: data.label,
1350
+ timestamp: data.timestamp
1232
1351
  });
1233
1352
  });
1234
1353
  }
@@ -746,16 +746,40 @@ export class BrowserTabManager extends EventEmitter {
746
746
  return false;
747
747
  }
748
748
 
749
+ /**
750
+ * Defensive cleanup before a URL reaches CDP.
751
+ *
752
+ * `Page.navigate` rejects with a bare "Cannot navigate to invalid URL" for
753
+ * strings that look completely valid to a person — the usual cause is a
754
+ * copy-paste artefact CDP does not tolerate: leading/trailing whitespace,
755
+ * a stray newline, or zero-width/invisible Unicode that a real address
756
+ * bar strips silently but Puppeteer never sees. `URL` is the same class of
757
+ * parser Chromium uses internally, so whatever it rejects would have
758
+ * failed identically inside the browser — surfacing that here, with the
759
+ * exact string, turns a dead end into something explainable instead of
760
+ * three pointless retries against a string that was never going anywhere.
761
+ */
762
+ private sanitizeNavigationUrl(url: string): string {
763
+ const cleaned = url.replace(/[\u200B-\u200F\u202A-\u202E\uFEFF]/g, '').trim();
764
+ try {
765
+ new URL(cleaned);
766
+ } catch {
767
+ throw new Error(`Invalid URL: "${cleaned}"`);
768
+ }
769
+ return cleaned;
770
+ }
771
+
749
772
  /**
750
773
  * Navigate with retry, including Cloudflare auto-pass detection and CAPTCHA popup dismissal.
751
774
  */
752
775
  private async navigateWithRetry(page: Page, url: string): Promise<string> {
776
+ const cleanUrl = this.sanitizeNavigationUrl(url);
753
777
  let retries = 3;
754
778
  let actualUrl = '';
755
779
 
756
780
  while (retries > 0) {
757
781
  try {
758
- await page.goto(url, {
782
+ await page.goto(cleanUrl, {
759
783
  waitUntil: 'domcontentloaded',
760
784
  timeout: 30000
761
785
  });