@myrialabs/clopen 0.4.21 → 0.4.22

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 (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -2,13 +2,15 @@ import { EventEmitter } from 'events';
2
2
  import type { Page } from 'puppeteer-core';
3
3
  import { BrowserTabManager } from './browser-tab-manager.js';
4
4
  import { BrowserConsoleManager } from './browser-console-manager.js';
5
- import { BrowserInteractionHandler } from './browser-interaction-handler.js';
5
+ import { BrowserInteractionHandler, type AutonomousRunOutcome } from './browser-interaction-handler.js';
6
6
  import { BrowserNavigationTracker } from './browser-navigation-tracker.js';
7
7
  import { BrowserVideoCapture } from './browser-video-capture.js';
8
8
  import { BrowserDialogHandler } from './browser-dialog-handler.js';
9
9
  import { BrowserNativeUIHandler } from './browser-native-ui-handler.js';
10
+ import { BrowserHostBridge, type HostResponse } from './browser-host-bridge.js';
10
11
  import { browserMcpControl } from './browser-mcp-control.js';
11
12
  import { ws } from '$backend/utils/ws';
13
+ import { getViewportDimensions } from '$shared/constants/preview.js';
12
14
  import { debug } from '$shared/utils/logger';
13
15
  import type {
14
16
  BrowserTab,
@@ -20,7 +22,12 @@ import type {
20
22
  BrowserDialogResponse,
21
23
  BrowserSelectResponse,
22
24
  BrowserContextMenuResponse,
23
- BrowserContextMenuInfo
25
+ BrowserContextMenuInfo,
26
+ BrowserHistoryState,
27
+ BrowserTabMeta,
28
+ ClientCodecSupport,
29
+ ClientDisplayMetrics,
30
+ ClientStreamFeedback
24
31
  } from './types';
25
32
 
26
33
  /**
@@ -44,6 +51,7 @@ export class BrowserPreviewService extends EventEmitter {
44
51
  private videoCapture: BrowserVideoCapture;
45
52
  private dialogHandler: BrowserDialogHandler;
46
53
  private nativeUIHandler: BrowserNativeUIHandler;
54
+ private hostBridge: BrowserHostBridge;
47
55
 
48
56
  // Store context menu info for later action execution
49
57
  private contextMenus = new Map<string, BrowserContextMenuInfo>();
@@ -68,6 +76,7 @@ export class BrowserPreviewService extends EventEmitter {
68
76
  this.videoCapture = new BrowserVideoCapture();
69
77
  this.dialogHandler = new BrowserDialogHandler();
70
78
  this.nativeUIHandler = new BrowserNativeUIHandler();
79
+ this.hostBridge = new BrowserHostBridge();
71
80
 
72
81
  // Forward events from handlers to main service
73
82
  this.setupEventForwarding();
@@ -82,13 +91,11 @@ export class BrowserPreviewService extends EventEmitter {
82
91
  this.emit('preview:browser-console-clear', data);
83
92
  });
84
93
 
85
- // Forward interaction events (MCP cursor)
86
- this.interactionHandler.on('cursor-position', (data) => {
87
- this.emit('preview:browser-mcp-cursor-position', data);
88
- });
89
- this.interactionHandler.on('cursor-click', (data) => {
90
- this.emit('preview:browser-mcp-cursor-click', data);
91
- });
94
+ // Cursor position/click are NOT forwarded here. They are published on the
95
+ // browserMcpControl singleton, which setupMcpControlForwarding() relays
96
+ // with the `source` stamp the client contract requires. Forwarding them
97
+ // from here as well delivered every cursor update twice, once without
98
+ // that field.
92
99
  this.interactionHandler.on('test-completed', (data) => {
93
100
  this.emit('preview:browser-mcp-test-completed', data);
94
101
  });
@@ -101,6 +108,10 @@ export class BrowserPreviewService extends EventEmitter {
101
108
  // After navigation completes, restart video streaming for the tab
102
109
  // This re-injects the peer script and restarts CDP screencast
103
110
  const { sessionId } = data;
111
+
112
+ // Title/favicon/history changed with the document — push the new
113
+ // values so the tab strip and Back/Forward buttons stay truthful.
114
+ void this.refreshTabMeta(sessionId);
104
115
  if (this.videoCapture.isStreaming(sessionId)) {
105
116
  const tab = this.getTab(sessionId);
106
117
  if (tab) {
@@ -126,6 +137,9 @@ export class BrowserPreviewService extends EventEmitter {
126
137
  // No streaming restart needed — page context is unchanged
127
138
  this.navigationTracker.on('navigation-spa', (data) => {
128
139
  this.emit('preview:browser-navigation-spa', data);
140
+ // pushState/replaceState mutate history without a document swap, so
141
+ // the Back/Forward affordances still have to be recomputed.
142
+ void this.refreshTabMeta(data.sessionId);
129
143
  });
130
144
 
131
145
  // Forward new window events
@@ -169,10 +183,31 @@ export class BrowserPreviewService extends EventEmitter {
169
183
  this.dialogHandler.on('dialog', (data) => {
170
184
  this.emit('preview:browser-dialog', data);
171
185
  });
186
+ this.dialogHandler.on('dialog-closed', (data) => {
187
+ this.emit('preview:browser-dialog-closed', data);
188
+ });
172
189
  this.dialogHandler.on('print', (data) => {
173
190
  this.emit('preview:browser-print', data);
174
191
  });
175
192
 
193
+ // Forward host bridge events (capability requests + relayed downloads)
194
+ this.hostBridge.on('request', (data) => {
195
+ // Not every bridge request is a question for the viewer. Restoring the
196
+ // emulated viewport is the host's own business, and raising a prompt for
197
+ // it would put an unanswerable dialog on every screen watching the tab.
198
+ if (data.kind === 'viewport-restore') {
199
+ void this.restoreEmulatedViewport(data.tabId, data.requestId);
200
+ return;
201
+ }
202
+ this.emit('preview:browser-host-request', data);
203
+ });
204
+ this.hostBridge.on('download', (data) => {
205
+ this.emit('preview:browser-download', data);
206
+ });
207
+ this.hostBridge.on('request-settled', (data) => {
208
+ this.emit('preview:browser-host-request-settled', data);
209
+ });
210
+
176
211
  // Forward native UI events
177
212
  this.nativeUIHandler.on('copy-to-clipboard', (data) => {
178
213
  this.emit('preview:browser-copy-to-clipboard', data);
@@ -186,6 +221,15 @@ export class BrowserPreviewService extends EventEmitter {
186
221
  this.nativeUIHandler.on('copy-image-to-clipboard', (data) => {
187
222
  this.emit('preview:browser-copy-image-to-clipboard', data);
188
223
  });
224
+ this.nativeUIHandler.on('open-url-host-browser', (data) => {
225
+ this.emit('preview:browser-open-url-host', data);
226
+ });
227
+ this.nativeUIHandler.on('print-page', (data) => {
228
+ this.emit('preview:browser-print', { sessionId: this.getActiveTab()?.id ?? '', ...data });
229
+ });
230
+ this.nativeUIHandler.on('open-inspector', (data) => {
231
+ this.emit('preview:browser-open-inspector', data);
232
+ });
189
233
  }
190
234
 
191
235
  /**
@@ -212,9 +256,14 @@ export class BrowserPreviewService extends EventEmitter {
212
256
  async createTab(url?: string, deviceSize: DeviceSize = 'laptop', rotation?: Rotation): Promise<BrowserTab> {
213
257
  // Use device-appropriate default rotation if not specified
214
258
  const actualRotation = rotation || ((deviceSize === 'desktop' || deviceSize === 'laptop') ? 'landscape' : 'portrait');
215
- // Pre-navigation setup callback for dialog bindings
216
- const preNavigationSetup = async (page: Page) => {
217
- // Note: We'll setup dialog bindings using tabId after tab is created
259
+
260
+ // Dialog interception and the capability shims both have to be in place
261
+ // before the first navigation: a page can call alert() or getUserMedia()
262
+ // from its very first inline script, and anything installed afterwards
263
+ // would miss it.
264
+ const preNavigationSetup = async (page: Page, tabId: string) => {
265
+ await this.dialogHandler.setupDialogHandling(tabId, page);
266
+ await this.hostBridge.setup(tabId, page);
218
267
  };
219
268
 
220
269
  // Create tab
@@ -233,6 +282,9 @@ export class BrowserPreviewService extends EventEmitter {
233
282
  // Fire-and-forget: failure here is non-fatal, startStreaming() will retry injection
234
283
  this.videoCapture.preInjectScripts(tab.id, tab).catch(() => {});
235
284
 
285
+ await this.captureHistoryBase(tab.id);
286
+ void this.refreshTabMeta(tab.id);
287
+
236
288
  return tab;
237
289
  }
238
290
 
@@ -240,14 +292,157 @@ export class BrowserPreviewService extends EventEmitter {
240
292
  * Navigate tab to a new URL
241
293
  */
242
294
  async navigateTab(tabId: string, url: string): Promise<string> {
295
+ const wasBlank = this.getTab(tabId)?.url === 'about:blank';
296
+
243
297
  const actualUrl = await this.tabManager.navigateTab(tabId, url);
244
298
 
245
299
  // Mark navigation for frame deduplication
246
300
  this.markNavigation(tabId, url);
247
301
 
302
+ // Chrome replaces a new tab's blank entry rather than stacking on top of
303
+ // it, so Back stays disabled after the first real navigation. Re-baselining
304
+ // here reproduces that instead of offering "back to about:blank".
305
+ if (wasBlank) {
306
+ await this.captureHistoryBase(tabId);
307
+ }
308
+
309
+ void this.refreshTabMeta(tabId);
310
+
248
311
  return actualUrl;
249
312
  }
250
313
 
314
+ // ============================================================================
315
+ // Navigation History (Back / Forward)
316
+ // ============================================================================
317
+
318
+ /**
319
+ * Read the tab's history, clamped to the entries it actually owns.
320
+ *
321
+ * CDP reports every entry including the `about:blank` the tab was born on.
322
+ * Offering that as a Back target would let the user reverse out of their page
323
+ * into a blank one — Chrome replaces that entry instead, so we hide anything
324
+ * before the index the tab settled on after its first navigation.
325
+ */
326
+ async getHistoryState(tabId: string): Promise<BrowserHistoryState | null> {
327
+ const tab = this.getTab(tabId);
328
+ if (!tab) return null;
329
+
330
+ const history = await this.navigationTracker.getNavigationHistory(tabId, tab.page);
331
+ if (!history) return null;
332
+
333
+ const base = Math.min(tab.historyBaseIndex ?? 0, history.currentIndex);
334
+ const entries = history.entries.slice(base);
335
+ const currentIndex = history.currentIndex - base;
336
+
337
+ return {
338
+ entries,
339
+ currentIndex,
340
+ canGoBack: currentIndex > 0,
341
+ canGoForward: currentIndex < entries.length - 1
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Move the tab by `delta` steps through its history.
347
+ * Returns false when the move would leave the tab's own range.
348
+ */
349
+ async goHistory(tabId: string, delta: number): Promise<boolean> {
350
+ const tab = this.getTab(tabId);
351
+ if (!tab || delta === 0) return false;
352
+
353
+ const state = await this.getHistoryState(tabId);
354
+ if (!state) return false;
355
+
356
+ const targetIndex = state.currentIndex + delta;
357
+ const target = state.entries[targetIndex];
358
+ if (!target) return false;
359
+
360
+ const moved = await this.navigationTracker.navigateToHistoryEntry(tabId, tab.page, target.id);
361
+ if (moved) {
362
+ this.markNavigation(tabId, target.url);
363
+ // The entry is committed asynchronously; let the navigation settle
364
+ // before reading title/favicon back off the page.
365
+ setTimeout(() => void this.refreshTabMeta(tabId), 250);
366
+ }
367
+ return moved;
368
+ }
369
+
370
+ /**
371
+ * Record where a freshly created tab's own history begins.
372
+ */
373
+ private async captureHistoryBase(tabId: string): Promise<void> {
374
+ const tab = this.getTab(tabId);
375
+ if (!tab) return;
376
+
377
+ const history = await this.navigationTracker.getNavigationHistory(tabId, tab.page);
378
+ if (history) {
379
+ tab.historyBaseIndex = history.currentIndex;
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Re-read the page's own title, favicon and history state, then push them to
385
+ * the frontend. Called after every navigation — these are the three things
386
+ * the toolbar and tab strip cannot derive from the URL alone.
387
+ */
388
+ async refreshTabMeta(tabId: string): Promise<void> {
389
+ const tab = this.getTab(tabId);
390
+ if (!tab) return;
391
+
392
+ try {
393
+ const [pageTitle, favicon] = await Promise.all([
394
+ tab.page.title().catch(() => ''),
395
+ this.readFavicon(tab.page)
396
+ ]);
397
+
398
+ if (pageTitle && pageTitle.trim()) {
399
+ tab.title = pageTitle.trim();
400
+ }
401
+ if (favicon) {
402
+ tab.favicon = favicon;
403
+ }
404
+
405
+ const history = await this.getHistoryState(tabId);
406
+ tab.canGoBack = history?.canGoBack ?? false;
407
+ tab.canGoForward = history?.canGoForward ?? false;
408
+
409
+ const meta: BrowserTabMeta = {
410
+ tabId,
411
+ url: tab.url,
412
+ title: tab.title,
413
+ favicon: tab.favicon,
414
+ canGoBack: tab.canGoBack,
415
+ canGoForward: tab.canGoForward,
416
+ timestamp: Date.now()
417
+ };
418
+
419
+ this.emit('preview:browser-tab-meta', meta);
420
+ } catch (error) {
421
+ debug.warn('preview', `⚠️ Failed to refresh tab meta for ${tabId}:`, error);
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Resolve the page's favicon to an absolute URL, falling back to the
427
+ * origin's /favicon.ico the way a browser does.
428
+ */
429
+ private async readFavicon(page: Page): Promise<string | undefined> {
430
+ try {
431
+ return await page.evaluate(() => {
432
+ const link = document.querySelector<HTMLLinkElement>(
433
+ 'link[rel~="icon"], link[rel="shortcut icon"], link[rel="apple-touch-icon"]'
434
+ );
435
+ if (link?.href) return link.href;
436
+ if (location.origin && location.origin !== 'null') {
437
+ return `${location.origin}/favicon.ico`;
438
+ }
439
+ return undefined;
440
+ });
441
+ } catch {
442
+ return undefined;
443
+ }
444
+ }
445
+
251
446
  /**
252
447
  * Close a tab and cleanup its resources
253
448
  */
@@ -269,6 +464,9 @@ export class BrowserPreviewService extends EventEmitter {
269
464
  // Clear dialogs for this tab
270
465
  this.dialogHandler.clearSessionDialogs(tabId);
271
466
 
467
+ // Settle anything the page left waiting on the viewer, drop its scratch dir
468
+ await this.hostBridge.teardown(tabId);
469
+
272
470
  // Close the tab (this will cleanup context, page, etc.)
273
471
  const result = await this.tabManager.closeTab(tabId);
274
472
 
@@ -366,7 +564,10 @@ export class BrowserPreviewService extends EventEmitter {
366
564
  // ============================================================================
367
565
  // WebCodecs Streaming Methods (optimized, ~20-40ms, lower bandwidth)
368
566
  // ============================================================================
369
- async startWebCodecsStreaming(tabId: string, allowVp9 = true): Promise<boolean> {
567
+ async startWebCodecsStreaming(
568
+ tabId: string,
569
+ options: { viewerId: string; codecSupport?: ClientCodecSupport; display?: ClientDisplayMetrics }
570
+ ): Promise<boolean> {
370
571
  const tab = this.getTab(tabId);
371
572
  if (!tab) {
372
573
  return false;
@@ -375,12 +576,50 @@ export class BrowserPreviewService extends EventEmitter {
375
576
  tabId,
376
577
  tab,
377
578
  () => this.isValidTab(tabId),
378
- allowVp9
579
+ options
379
580
  );
380
581
  }
381
582
 
382
- async stopWebCodecsStreaming(tabId: string): Promise<void> {
583
+ /**
584
+ * Viewer display metrics (fit-scale + pixel density) — drives capture
585
+ * resolution so we never encode more pixels than the viewer can show.
586
+ */
587
+ applyWebCodecsDisplayMetrics(tabId: string, viewerId: string, metrics: ClientDisplayMetrics): boolean {
588
+ const tab = this.getTab(tabId);
589
+ if (!tab) {
590
+ return false;
591
+ }
592
+ this.videoCapture.applyDisplayMetrics(tabId, tab, viewerId, metrics);
593
+ return true;
594
+ }
595
+
596
+ /** Viewer decoder health — closes the adaptation loop back to the source. */
597
+ applyWebCodecsClientFeedback(tabId: string, viewerId: string, feedback: ClientStreamFeedback): boolean {
598
+ this.videoCapture.applyClientFeedback(tabId, viewerId, feedback);
599
+ return true;
600
+ }
601
+
602
+ /** Suspend capture once every viewer has the preview off screen. */
603
+ async setWebCodecsPaused(tabId: string, viewerId: string, paused: boolean): Promise<boolean> {
604
+ const tab = this.getTab(tabId);
605
+ if (!tab) {
606
+ return false;
607
+ }
608
+ return await this.videoCapture.setViewerVisibility(tabId, tab, viewerId, !paused);
609
+ }
610
+
611
+ /**
612
+ * One viewer left. The capture only stops when the last one does — a second
613
+ * device closing its panel must not blank the first.
614
+ */
615
+ async stopWebCodecsStreaming(tabId: string, viewerId?: string): Promise<void> {
383
616
  const tab = this.getTab(tabId);
617
+
618
+ if (viewerId) {
619
+ await this.videoCapture.detachViewer(tabId, tab ?? undefined, viewerId);
620
+ return;
621
+ }
622
+
384
623
  await this.videoCapture.stopStreaming(tabId, tab ?? undefined);
385
624
  }
386
625
 
@@ -400,6 +639,46 @@ export class BrowserPreviewService extends EventEmitter {
400
639
  return await this.videoCapture.requestKeyframe(tabId, tab);
401
640
  }
402
641
 
642
+ /**
643
+ * Re-assert the emulated viewport after the renderer was resized behind the
644
+ * emulation's back.
645
+ *
646
+ * Chrome's own fullscreen — the button on its built-in media controls, which
647
+ * no injected script can intercept — resizes the surface the renderer
648
+ * composites to the browser window, and leaves it there once the fullscreen
649
+ * ends. The page is still laid out against the emulated viewport, so what
650
+ * comes back is that layout seen through a window-sized hole: zoomed, cropped
651
+ * at the right and the bottom, and stranded that way until a reload.
652
+ *
653
+ * Nothing in the page reflects it — `innerWidth` and the visual viewport both
654
+ * read correctly the entire time — so there is nothing to test before acting.
655
+ * Re-sending the identical metrics override is what puts the surface back, and
656
+ * it only happens on a fullscreen the page did not ask for, which is rare
657
+ * enough that the restart it costs is not worth trying to avoid.
658
+ */
659
+ private async restoreEmulatedViewport(tabId: string, requestId: string): Promise<void> {
660
+ try {
661
+ const tab = this.getTab(tabId);
662
+ if (tab) {
663
+ const { width, height } = getViewportDimensions(tab.deviceSize, tab.rotation);
664
+
665
+ // The capture path re-sends the override and recomputes the screencast
666
+ // geometry with it. With no stream running there is no geometry to
667
+ // recompute and the override is all that is needed.
668
+ const restored = await this.videoCapture.updateViewport(tabId, tab, width, height);
669
+ if (!restored) await tab.page.setViewport({ width, height });
670
+
671
+ debug.log('preview', `🖥️ Restored emulated viewport for tab ${tabId}: ${width}x${height}`);
672
+ }
673
+ } catch (error) {
674
+ debug.warn('preview', `⚠️ Could not restore the emulated viewport for tab ${tabId}:`, error);
675
+ } finally {
676
+ // The page holds a promise on this. Nothing awaits it, but an unsettled
677
+ // request sits in the pending map until it times out.
678
+ this.hostBridge.respond(requestId, { ok: true });
679
+ }
680
+ }
681
+
403
682
  async updateWebCodecsViewport(tabId: string, width: number, height: number): Promise<boolean> {
404
683
  const tab = this.getTab(tabId);
405
684
  if (!tab) {
@@ -408,28 +687,36 @@ export class BrowserPreviewService extends EventEmitter {
408
687
  return await this.videoCapture.updateViewport(tabId, tab, width, height);
409
688
  }
410
689
 
411
- async getWebCodecsOffer(tabId: string): Promise<RTCSessionDescriptionInit | null> {
690
+ async getWebCodecsOffer(tabId: string, viewerId: string): Promise<RTCSessionDescriptionInit | null> {
412
691
  const tab = this.getTab(tabId);
413
692
  if (!tab) {
414
693
  return null;
415
694
  }
416
- return await this.videoCapture.createOffer(tabId, tab);
695
+ return await this.videoCapture.createOffer(tabId, tab, viewerId);
417
696
  }
418
697
 
419
- async handleWebCodecsAnswer(tabId: string, answer: RTCSessionDescriptionInit): Promise<boolean> {
698
+ async handleWebCodecsAnswer(
699
+ tabId: string,
700
+ viewerId: string,
701
+ answer: RTCSessionDescriptionInit
702
+ ): Promise<boolean> {
420
703
  const tab = this.getTab(tabId);
421
704
  if (!tab) {
422
705
  return false;
423
706
  }
424
- return await this.videoCapture.handleAnswer(tabId, tab, answer);
707
+ return await this.videoCapture.handleAnswer(tabId, tab, viewerId, answer);
425
708
  }
426
709
 
427
- async addWebCodecsIceCandidate(tabId: string, candidate: RTCIceCandidateInit): Promise<boolean> {
710
+ async addWebCodecsIceCandidate(
711
+ tabId: string,
712
+ viewerId: string,
713
+ candidate: RTCIceCandidateInit
714
+ ): Promise<boolean> {
428
715
  const tab = this.getTab(tabId);
429
716
  if (!tab) {
430
717
  return false;
431
718
  }
432
- return await this.videoCapture.addIceCandidate(tabId, tab, candidate);
719
+ return await this.videoCapture.addIceCandidate(tabId, tab, viewerId, candidate);
433
720
  }
434
721
 
435
722
  isWebCodecsActive(tabId: string): boolean {
@@ -488,33 +775,27 @@ export class BrowserPreviewService extends EventEmitter {
488
775
  // ============================================================================
489
776
  // Interaction & Autonomous Actions Methods
490
777
  // ============================================================================
491
- async performAutonomousActions(tabId: string, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
778
+ /**
779
+ * Run a batch of input gestures.
780
+ *
781
+ * Returns per-action outcomes plus whether the run was cut short, so the
782
+ * caller can report "3 of 7 ran" instead of claiming a success the user
783
+ * interrupted.
784
+ */
785
+ async performAutonomousActions(
786
+ tabId: string,
787
+ actions: BrowserAutonomousAction[],
788
+ abortSignal?: AbortSignal
789
+ ): Promise<AutonomousRunOutcome> {
492
790
  const tab = this.getTab(tabId);
493
791
  if (!tab) throw new Error('Tab not found or invalid');
494
792
 
495
- const results = await this.interactionHandler.performAutonomousActions(
793
+ return this.interactionHandler.performAutonomousActions(
496
794
  tabId,
497
795
  tab,
498
796
  actions,
499
797
  () => this.isValidTab(tabId) && !(abortSignal?.aborted ?? false)
500
798
  );
501
-
502
- return results;
503
- }
504
-
505
- /**
506
- * Perform autonomous actions using tab object directly
507
- * More efficient when tab is already available
508
- */
509
- async performAutonomousActionsWithTab(tab: BrowserTab, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
510
- const results = await this.interactionHandler.performAutonomousActions(
511
- tab.id,
512
- tab,
513
- actions,
514
- () => this.isValidTab(tab.id) && !(abortSignal?.aborted ?? false)
515
- );
516
-
517
- return results;
518
799
  }
519
800
 
520
801
  // ============================================================================
@@ -549,7 +830,13 @@ export class BrowserPreviewService extends EventEmitter {
549
830
  const tab = this.getTab(tabId);
550
831
  if (!tab) return null;
551
832
 
552
- const menuInfo = await this.nativeUIHandler.checkForContextMenu(tabId, tab.page, x, y);
833
+ // Back/Forward are page-level, so their availability comes from the tab's
834
+ // history rather than from the element under the cursor.
835
+ const history = await this.getHistoryState(tabId);
836
+ const menuInfo = await this.nativeUIHandler.checkForContextMenu(tabId, tab.page, x, y, {
837
+ canGoBack: history?.canGoBack ?? false,
838
+ canGoForward: history?.canGoForward ?? false
839
+ });
553
840
  if (menuInfo) {
554
841
  // Store menu info for later action execution
555
842
  this.contextMenus.set(menuInfo.menuId, menuInfo);
@@ -574,12 +861,61 @@ export class BrowserPreviewService extends EventEmitter {
574
861
  return result;
575
862
  }
576
863
 
864
+ // ============================================================================
865
+ // Host Bridge Methods
866
+ // ============================================================================
867
+
868
+ /**
869
+ * Deliver the viewer's answer to a pending capability request.
870
+ */
871
+ respondToHostRequest(requestId: string, response: HostResponse): boolean {
872
+ return this.hostBridge.respond(requestId, response);
873
+ }
874
+
875
+ /**
876
+ * Push a streamed host event into a tab's page — speech recognition results
877
+ * keep arriving long after the request that started them was answered.
878
+ */
879
+ async dispatchHostEvent(tabId: string, kind: string, payload: unknown): Promise<void> {
880
+ const tab = this.getTab(tabId);
881
+ if (!tab) return;
882
+ await this.hostBridge.dispatchEvent(tab.page, tabId, kind, payload);
883
+ }
884
+
885
+ // ============================================================================
886
+ // Native Picker Methods (colour / date inputs)
887
+ // ============================================================================
888
+
889
+ /**
890
+ * Chrome draws colour and date pickers in the browser process, so they never
891
+ * reach the screencast. Detecting the input lets the viewer render the
892
+ * equivalent control over the canvas instead.
893
+ */
894
+ async checkForNativePicker(tabId: string, x: number, y: number) {
895
+ const tab = this.getTab(tabId);
896
+ if (!tab) return null;
897
+
898
+ const info = await this.nativeUIHandler.checkForNativePicker(tabId, tab.page, x, y);
899
+ if (info) {
900
+ this.emit('preview:browser-native-picker', info);
901
+ }
902
+ return info;
903
+ }
904
+
905
+ async handleNativePickerResponse(tabId: string, pickerId: string, value: string): Promise<boolean> {
906
+ const tab = this.getTab(tabId);
907
+ if (!tab) return false;
908
+ return await this.nativeUIHandler.handleNativePickerResponse(tab.page, pickerId, value);
909
+ }
910
+
577
911
  // ============================================================================
578
912
  // Cleanup Methods
579
913
  // ============================================================================
580
914
  async cleanup() {
581
915
  // Clear all cursor tracking
582
916
  this.interactionHandler.clearAllSessionCursors();
917
+ // Release host-bridge scratch dirs and unblock any parked page promises
918
+ await this.hostBridge.cleanup();
583
919
  // Cleanup tabs (this will also cleanup all contexts/pages/browser pool)
584
920
  await this.tabManager.cleanup();
585
921
  }
@@ -607,6 +943,7 @@ export class BrowserPreviewService extends EventEmitter {
607
943
  this.videoCapture.removeAllListeners();
608
944
  this.dialogHandler.removeAllListeners();
609
945
  this.nativeUIHandler.removeAllListeners();
946
+ this.hostBridge.removeAllListeners();
610
947
  }
611
948
  }
612
949
 
@@ -627,8 +964,12 @@ class BrowserPreviewServiceManager {
627
964
  * Get or create a BrowserPreviewService for a project
628
965
  */
629
966
  getService(projectId: string): BrowserPreviewService {
630
- if (!projectId) {
631
- throw new Error('projectId is required and cannot be empty');
967
+ // Typed as string, but this is reached from MCP tool handlers whose
968
+ // arguments are untyped at runtime. A non-string key silently mints an
969
+ // empty service (and leaks its WS forwarding listeners), so reject it
970
+ // loudly rather than returning a service with no tabs.
971
+ if (typeof projectId !== 'string' || !projectId) {
972
+ throw new Error(`projectId must be a non-empty string, received: ${typeof projectId}`);
632
973
  }
633
974
 
634
975
  // Register singleton MCP control forwarding once (idempotent).
@@ -654,10 +995,15 @@ class BrowserPreviewServiceManager {
654
995
  private setupWebSocketForwarding(service: BrowserPreviewService, projectId: string): void {
655
996
  debug.log('preview', `🔌 Setting up WebSocket forwarding for project: ${projectId}...`);
656
997
 
657
- // Forward WebCodecs events
998
+ // Forward WebCodecs events.
999
+ //
1000
+ // The room is the whole project, so several viewers of the same tab all
1001
+ // receive these. `viewerId` is what lets each of them recognise the half
1002
+ // of the handshake that is theirs.
658
1003
  service.on('preview:browser-webcodecs-ice-candidate', (data) => {
659
1004
  ws.emit.project(projectId, 'preview:browser-stream-ice', {
660
1005
  sessionId: data.sessionId,
1006
+ viewerId: data.viewerId,
661
1007
  candidate: data.candidate,
662
1008
  from: data.from
663
1009
  });
@@ -710,6 +1056,26 @@ class BrowserPreviewServiceManager {
710
1056
  ws.emit.project(projectId, 'preview:browser-viewport-changed', { ...data, projectId });
711
1057
  });
712
1058
 
1059
+ // Forward live tab metadata (title, favicon, back/forward availability)
1060
+ service.on('preview:browser-tab-meta', (data) => {
1061
+ ws.emit.project(projectId, 'preview:browser-tab-meta', { ...data, projectId });
1062
+ });
1063
+
1064
+ // Forward host-capability requests (geolocation, camera, clipboard, …)
1065
+ // and relayed downloads — both are answered by the viewer's own browser.
1066
+ service.on('preview:browser-host-request', (data) => {
1067
+ ws.emit.project(projectId, 'preview:browser-host-request', data);
1068
+ });
1069
+
1070
+ // Answered (or expired) — every viewer that was shown this prompt drops it.
1071
+ service.on('preview:browser-host-request-settled', (data) => {
1072
+ ws.emit.project(projectId, 'preview:browser-host-request-settled', data);
1073
+ });
1074
+
1075
+ service.on('preview:browser-download', (data) => {
1076
+ ws.emit.project(projectId, 'preview:browser-download', data);
1077
+ });
1078
+
713
1079
  // Forward console events
714
1080
  service.on('preview:browser-console-message', (data) => {
715
1081
  ws.emit.project(projectId, 'preview:browser-console-message', data);
@@ -719,15 +1085,8 @@ class BrowserPreviewServiceManager {
719
1085
  ws.emit.project(projectId, 'preview:browser-console-clear', data);
720
1086
  });
721
1087
 
722
- // Forward MCP events
723
- service.on('preview:browser-mcp-cursor-position', (data) => {
724
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-position', data);
725
- });
726
-
727
- service.on('preview:browser-mcp-cursor-click', (data) => {
728
- ws.emit.project(projectId, 'preview:browser-mcp-cursor-click', data);
729
- });
730
-
1088
+ // Forward MCP events. Cursor position/click come from the singleton
1089
+ // instead (setupMcpControlForwarding) — see setupEventForwarding().
731
1090
  service.on('preview:browser-mcp-test-completed', (data) => {
732
1091
  ws.emit.project(projectId, 'preview:browser-mcp-test-completed', data);
733
1092
  });
@@ -737,11 +1096,21 @@ class BrowserPreviewServiceManager {
737
1096
  ws.emit.project(projectId, 'preview:browser-dialog', data);
738
1097
  });
739
1098
 
1099
+ // A dialog belongs to the page, not to whoever answered it: every viewer
1100
+ // was shown the same prompt, so all of them are told it is settled.
1101
+ service.on('preview:browser-dialog-closed', (data) => {
1102
+ ws.emit.project(projectId, 'preview:browser-dialog-closed', data);
1103
+ });
1104
+
740
1105
  service.on('preview:browser-print', (data) => {
741
1106
  ws.emit.project(projectId, 'preview:browser-print', data);
742
1107
  });
743
1108
 
744
1109
  // Forward native UI events
1110
+ service.on('preview:browser-native-picker', (data) => {
1111
+ ws.emit.project(projectId, 'preview:browser-native-picker', data);
1112
+ });
1113
+
745
1114
  service.on('preview:browser-select', (data) => {
746
1115
  ws.emit.project(projectId, 'preview:browser-select', data);
747
1116
  });
@@ -762,6 +1131,14 @@ class BrowserPreviewServiceManager {
762
1131
  ws.emit.project(projectId, 'preview:browser-download-image', data);
763
1132
  });
764
1133
 
1134
+ service.on('preview:browser-open-url-host', (data) => {
1135
+ ws.emit.project(projectId, 'preview:browser-open-url-host', data);
1136
+ });
1137
+
1138
+ service.on('preview:browser-open-inspector', (data) => {
1139
+ ws.emit.project(projectId, 'preview:browser-open-inspector', data);
1140
+ });
1141
+
765
1142
  service.on('preview:browser-copy-image-to-clipboard', (data) => {
766
1143
  ws.emit.project(projectId, 'preview:browser-copy-image-to-clipboard', data);
767
1144
  });
@@ -830,6 +1207,7 @@ class BrowserPreviewServiceManager {
830
1207
  sessionId: data.tabId,
831
1208
  x: data.x,
832
1209
  y: data.y,
1210
+ pressed: data.pressed ?? false,
833
1211
  timestamp: data.timestamp,
834
1212
  source: 'mcp'
835
1213
  });
@@ -840,6 +1218,7 @@ class BrowserPreviewServiceManager {
840
1218
  sessionId: data.tabId,
841
1219
  x: data.x,
842
1220
  y: data.y,
1221
+ button: data.button ?? 'left',
843
1222
  timestamp: data.timestamp,
844
1223
  source: 'mcp'
845
1224
  });