@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
@@ -665,14 +665,8 @@ export function hostBridgeScript(bindingName: string) {
665
665
  {
666
666
  const STYLE_ID = '__clopen-fullscreen-style';
667
667
  const MAX_Z = 2147483647;
668
- /** How long the exit hint stays up before fading, as in Chrome itself. */
669
- const EXIT_HINT_MS = 3200;
670
- /** What counts as "the user is still there" and brings the hint back. */
671
- const ACTIVITY_EVENTS = ['mousemove', 'touchstart', 'keydown'];
672
668
 
673
669
  let fullscreenElement: Element | null = null;
674
- let exitButton: HTMLElement | null = null;
675
- let hideHintTimer: ReturnType<typeof setTimeout> | undefined;
676
670
 
677
671
  // Captured before the patches further down shadow them. Every replacement
678
672
  // below is installed as an *own* property of `document`, while the real
@@ -731,87 +725,14 @@ export function hostBridgeScript(bindingName: string) {
731
725
  (document.head || document.documentElement).appendChild(style);
732
726
  };
733
727
 
734
- /**
735
- * Bring the hint back and start its countdown again.
736
- *
737
- * It stays clickable while faded — the fade is there so the corner of a
738
- * video is not permanently covered, not to withdraw the way out. A phone
739
- * has no pointer to move, so a tap has to land on something.
740
- */
741
- const revealExitButton = () => {
742
- if (!exitButton) return;
743
- exitButton.style.opacity = '1';
744
- clearTimeout(hideHintTimer);
745
- hideHintTimer = setTimeout(() => {
746
- if (exitButton) exitButton.style.opacity = '0.12';
747
- }, EXIT_HINT_MS);
748
- };
749
-
750
- /**
751
- * The exit affordance.
752
- *
753
- * Rendered inside the page on purpose: it is then part of the captured
754
- * frame and answers a normal click or tap, so it works on a phone and on
755
- * a second viewer's screen. Anything app-side would need a channel of its
756
- * own and would still miss the pages that swallow Escape.
757
- *
758
- * It fades the way Chrome's own "Press Esc to exit full screen" notice
759
- * does and returns on the next sign of life. A badge pinned over the
760
- * corner of a video for the whole of playback is not what full screen
761
- * looks like anywhere else.
762
- */
763
- const showExitButton = () => {
764
- if (exitButton) {
765
- revealExitButton();
766
- return;
767
- }
768
-
769
- const button = document.createElement('button');
770
- button.type = 'button';
771
- button.setAttribute('data-clopen-fullscreen-ui', '');
772
- button.textContent = 'Exit full screen (Esc)';
773
- button.style.cssText = [
774
- 'position:fixed',
775
- 'top:12px',
776
- 'right:12px',
777
- `z-index:${MAX_Z}`,
778
- 'margin:0',
779
- 'padding:6px 12px',
780
- 'border:0',
781
- 'border-radius:9999px',
782
- 'font:500 12px/1.4 system-ui,-apple-system,Segoe UI,sans-serif',
783
- 'color:#fff',
784
- 'background:rgba(15,23,42,0.82)',
785
- 'box-shadow:0 2px 10px rgba(0,0,0,0.45)',
786
- 'cursor:pointer',
787
- 'opacity:1',
788
- 'transition:opacity 220ms ease'
789
- ].join(';');
790
- button.addEventListener('click', (event) => {
791
- event.preventDefault();
792
- event.stopPropagation();
793
- void exit();
794
- });
795
- (document.body || document.documentElement).appendChild(button);
796
- exitButton = button;
797
-
798
- // Capture phase: a player that swallows pointer events over its own
799
- // surface would otherwise keep the hint from ever coming back.
800
- for (const type of ACTIVITY_EVENTS) {
801
- document.addEventListener(type, revealExitButton, true);
802
- }
803
- revealExitButton();
804
- };
805
-
806
- const removeChrome = () => {
807
- clearTimeout(hideHintTimer);
808
- hideHintTimer = undefined;
809
- for (const type of ACTIVITY_EVENTS) {
810
- document.removeEventListener(type, revealExitButton, true);
811
- }
812
- exitButton?.remove();
813
- exitButton = null;
814
- };
728
+ // No in-page exit affordance is drawn any more. There used to be an
729
+ // "Exit full screen (Esc)" badge here, which put two buttons saying the
730
+ // same thing over the same frame — the page's, painted into the captured
731
+ // picture, and the app's, drawn over it. Only one can be the way out, and
732
+ // the app-side control is the one that survives a page re-render, reaches
733
+ // every viewer, and still works when Chrome granted a fullscreen from its
734
+ // own C++ that this shim never saw. All the page draws now is the style
735
+ // rule that fakes the fullscreen in the first place.
815
736
 
816
737
  /**
817
738
  * Chrome fires this *on the element*; listeners on `document` only see it
@@ -832,10 +753,25 @@ export function hostBridgeScript(bindingName: string) {
832
753
  element.removeAttribute('data-clopen-fullscreen');
833
754
  };
834
755
 
756
+ /**
757
+ * Tell the host whether this page is showing something full screen.
758
+ *
759
+ * The in-page exit affordance is drawn by the page, which means the page
760
+ * can lose it — a re-render that empties the body, a stacking context
761
+ * that buries it, a fullscreen Chrome granted from C++ that this shim
762
+ * never saw. The viewer needs its own way out, and it can only offer one
763
+ * if it knows. Fire-and-forget: a frame with no route to the host still
764
+ * has a working CSS fullscreen, it just cannot be rescued from outside.
765
+ */
766
+ const reportState = (active: boolean) => {
767
+ void call('fullscreen-state', { active }).catch(() => {});
768
+ };
769
+
835
770
  const enter = (element: Element) => {
836
771
  ensureStyle();
837
772
  if (fullscreenElement && fullscreenElement !== element) clearMarks(fullscreenElement);
838
773
 
774
+ const wasActive = fullscreenElement !== null;
839
775
  fullscreenElement = element;
840
776
  // The root and the body already fill the viewport; pinning them as
841
777
  // fixed boxes only breaks their own layout.
@@ -844,8 +780,8 @@ export function hostBridgeScript(bindingName: string) {
844
780
  }
845
781
  document.documentElement.classList.add('clopen-fullscreen-active');
846
782
  document.body?.classList.add('clopen-fullscreen-active');
847
- showExitButton();
848
783
  notify(element);
784
+ if (!wasActive) reportState(true);
849
785
  return Promise.resolve();
850
786
  };
851
787
 
@@ -857,11 +793,47 @@ export function hostBridgeScript(bindingName: string) {
857
793
  fullscreenElement = null;
858
794
  document.documentElement.classList.remove('clopen-fullscreen-active');
859
795
  document.body?.classList.remove('clopen-fullscreen-active');
860
- removeChrome();
861
796
  notify(previous);
797
+ reportState(false);
862
798
  return Promise.resolve();
863
799
  };
864
800
 
801
+ /**
802
+ * Leave full screen no matter how the page got there.
803
+ *
804
+ * `exit()` alone is not enough as a rescue: it returns immediately when
805
+ * this shim holds no element, which is exactly the case that strands the
806
+ * preview — Chrome granted a fullscreen from its own C++ (a `<video>`
807
+ * control bar, a double-click) and the conversion did not take, so the
808
+ * composited surface is collapsed with nothing in the page marked. This
809
+ * clears every trace unconditionally: the shim's state, any stray marks
810
+ * left by a document that changed underneath it, the scroll lock, and
811
+ * Chrome's own fullscreen.
812
+ */
813
+ const forceExit = () => {
814
+ void exit();
815
+
816
+ for (const marked of Array.from(document.querySelectorAll('[data-clopen-fullscreen]'))) {
817
+ marked.removeAttribute('data-clopen-fullscreen');
818
+ }
819
+ document.documentElement.classList.remove('clopen-fullscreen-active');
820
+ document.body?.classList.remove('clopen-fullscreen-active');
821
+
822
+ try {
823
+ if (readNativeElement()) nativeExit?.();
824
+ } catch {
825
+ // Already leaving, or never was.
826
+ }
827
+
828
+ reportState(false);
829
+ };
830
+
831
+ // The viewer's own escape hatch, reachable from the host in every frame.
832
+ scope.__clopenFullscreen = {
833
+ active: () => fullscreenElement !== null || readNativeElement() !== null,
834
+ forceExit
835
+ };
836
+
865
837
  /**
866
838
  * Read the current element, dropping it if the page has since replaced it.
867
839
  *
@@ -58,6 +58,19 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
58
58
  const viewers = new Map<string, ViewerPeer>();
59
59
  let videoEncoder: VideoEncoder | null = null;
60
60
  let isCapturing = false;
61
+
62
+ /**
63
+ * Which injection this object came from.
64
+ *
65
+ * The backend stamps every injection with an id and keeps the last one it
66
+ * issued. Anything else — a peer left over from a document the page has
67
+ * since navigated away from, or one injected by a different backend session
68
+ * — reads as a mismatch, and the backend rebuilds rather than talking to an
69
+ * object whose encoder and viewers belong to a page that no longer exists.
70
+ * That mismatch is invisible from the outside: `window.__webCodecsPeer` is
71
+ * present and every method answers, they just answer for the wrong page.
72
+ */
73
+ const epoch = config.epoch || '';
61
74
  let videoFrameCount = 0;
62
75
  let audioFrameCount = 0;
63
76
  let lastKeyframeTime = 0;
@@ -1240,8 +1253,27 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
1240
1253
  }
1241
1254
  }
1242
1255
 
1256
+ /**
1257
+ * Everything the backend needs to decide "is this page actually streaming?".
1258
+ *
1259
+ * Cheap on purpose — it is read on every handshake. `viewers` is the list
1260
+ * of peers that genuinely exist here, which is the only way the backend can
1261
+ * tell its own viewer table from wishful thinking: an entry it holds that
1262
+ * this page has never heard of is a viewer that will never receive a frame.
1263
+ */
1264
+ function health() {
1265
+ return {
1266
+ epoch,
1267
+ capturing: isCapturing,
1268
+ encoderReady: !!videoEncoder,
1269
+ captureMode,
1270
+ viewers: Array.from(viewers.keys())
1271
+ };
1272
+ }
1273
+
1243
1274
  // Expose API
1244
1275
  (window as any).__webCodecsPeer = {
1276
+ health,
1245
1277
  startStreaming,
1246
1278
  stopStreaming,
1247
1279
  createOffer,
@@ -462,8 +462,29 @@ export interface ClientStreamFeedback {
462
462
  *
463
463
  * Single source of truth for all codec settings.
464
464
  */
465
+ /**
466
+ * What the in-page peer reports about itself.
467
+ *
468
+ * The backend's session record and the page's encoder are two independent
469
+ * state machines — a navigation, a self-reload or a failed re-injection moves
470
+ * one without the other — and every "Loading preview…" that never resolved
471
+ * traced back to trusting the backend's copy. This is the page's own answer,
472
+ * read at every handshake so a mismatch is repaired instead of inherited.
473
+ */
474
+ export interface PeerHealth {
475
+ /** Injection id. A mismatch means this peer belongs to a different document. */
476
+ epoch: string;
477
+ capturing: boolean;
478
+ encoderReady: boolean;
479
+ captureMode: 'push' | 'native';
480
+ /** Viewer ids with a live peer here — the ground truth for the viewer table. */
481
+ viewers: string[];
482
+ }
483
+
465
484
  export interface StreamingConfig {
466
485
  video: {
486
+ /** Stamped onto the injected peer so the backend can recognise its own. */
487
+ epoch: string;
467
488
  codec: string; // Fallback codec (VP8, fixed-bitrate mode) when nothing better is negotiated
468
489
  width: number;
469
490
  height: number;
@@ -518,6 +539,7 @@ export interface StreamingConfig {
518
539
  */
519
540
  export const DEFAULT_STREAMING_CONFIG: StreamingConfig = {
520
541
  video: {
542
+ epoch: '',
521
543
  codec: 'vp8',
522
544
  width: 0,
523
545
  height: 0,
@@ -2,7 +2,12 @@
2
2
  export * from './browser/types';
3
3
 
4
4
  // Export MCP control types
5
- export type { McpControlEvent, McpCursorEvent, McpClickEvent } from './browser/browser-mcp-control';
5
+ export type {
6
+ McpControlEvent,
7
+ McpCursorEvent,
8
+ McpClickEvent,
9
+ McpFocusEvent
10
+ } from './browser/browser-mcp-control';
6
11
 
7
12
  // Export the main preview service class and manager
8
13
  export {
@@ -11,24 +11,24 @@ import { requireBrowserTabAccess } from '../access';
11
11
  export const consolePreviewHandler = createRouter()
12
12
  // Get console logs
13
13
  .http('preview:browser-console-get', {
14
- data: t.Object({}),
14
+ data: t.Object({ tabId: t.Optional(t.String()) }),
15
15
  response: t.Object({
16
16
  logs: t.Any()
17
17
  })
18
- }, async ({ conn }) => {
19
- const { previewService, tab } = requireBrowserTabAccess(conn);
18
+ }, async ({ data, conn }) => {
19
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
20
20
  const consoleLogs = previewService.getConsoleLogs(tab.id);
21
21
  return { logs: consoleLogs };
22
22
  })
23
23
 
24
24
  // Clear console logs
25
25
  .http('preview:browser-console-clear', {
26
- data: t.Object({}),
26
+ data: t.Object({ tabId: t.Optional(t.String()) }),
27
27
  response: t.Object({
28
28
  message: t.String()
29
29
  })
30
- }, async ({ conn }) => {
31
- const { previewService, tab } = requireBrowserTabAccess(conn);
30
+ }, async ({ data, conn }) => {
31
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
32
32
 
33
33
  const success = previewService.clearConsoleLogs(tab.id);
34
34
 
@@ -42,13 +42,14 @@ export const consolePreviewHandler = createRouter()
42
42
  // Execute console command
43
43
  .http('preview:browser-console-execute', {
44
44
  data: t.Object({
45
- command: t.String({ minLength: 1 })
45
+ command: t.String({ minLength: 1 }),
46
+ tabId: t.Optional(t.String())
46
47
  }),
47
48
  response: t.Object({
48
49
  result: t.Any()
49
50
  })
50
51
  }, async ({ data, conn }) => {
51
- const { previewService, tab } = requireBrowserTabAccess(conn);
52
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
52
53
 
53
54
  const result = await previewService.executeConsoleCommand(tab.id, data.command);
54
55
  return { result };
@@ -57,14 +58,15 @@ export const consolePreviewHandler = createRouter()
57
58
  // Toggle console logging
58
59
  .http('preview:browser-console-toggle', {
59
60
  data: t.Object({
60
- enabled: t.Boolean()
61
+ enabled: t.Boolean(),
62
+ tabId: t.Optional(t.String())
61
63
  }),
62
64
  response: t.Object({
63
65
  enabled: t.Boolean(),
64
66
  message: t.String()
65
67
  })
66
68
  }, async ({ data, conn }) => {
67
- const { previewService, tab } = requireBrowserTabAccess(conn);
69
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
68
70
 
69
71
  const success = previewService.toggleConsoleLogging(tab.id, data.enabled);
70
72
 
@@ -63,6 +63,17 @@ export const interactPreviewHandler = createRouter()
63
63
  deviceSize: t.Optional(t.String()),
64
64
  rotation: t.Optional(t.String())
65
65
  }),
66
+ /**
67
+ * The tab the viewer is looking at.
68
+ *
69
+ * Input used to be applied to whatever the project's "active tab"
70
+ * happened to be, which is a single value shared by everyone in the
71
+ * project. With two people watching, one of them switching tabs
72
+ * silently redirected the other's clicks onto the tab they had just
73
+ * moved to. Optional only so an older client keeps working; the
74
+ * panel always sends it.
75
+ */
76
+ tabId: t.Optional(t.String())
66
77
  })
67
78
  }, async ({ data, conn }) => {
68
79
  const { userId, projectId, previewService } = requireBrowserPreviewAccess(conn);
@@ -70,12 +81,13 @@ export const interactPreviewHandler = createRouter()
70
81
  try {
71
82
  const { action } = data;
72
83
 
73
- // Get active tab (mirip MCP pattern)
74
- const tab = previewService.getActiveTab();
84
+ const tab = data.tabId ? previewService.getTab(data.tabId) : previewService.getActiveTab();
75
85
  if (!tab) {
76
- debug.error('preview', `❌ NO ACTIVE TAB for project ${projectId} - Available tabs: ${previewService.getTabCount()}`);
86
+ debug.error('preview', `❌ NO TAB for project ${projectId} (requested: ${data.tabId ?? 'active'}) - Available tabs: ${previewService.getTabCount()}`);
77
87
  ws.emit.user(userId, 'preview:browser-error', {
78
- message: 'No active tab. Please open or switch to a tab first.'
88
+ message: data.tabId
89
+ ? 'That tab is no longer open.'
90
+ : 'No active tab. Please open or switch to a tab first.'
79
91
  });
80
92
  return;
81
93
  }
@@ -540,8 +552,22 @@ export const interactPreviewHandler = createRouter()
540
552
  // Handle viewport change (device/rotation) without reconnection
541
553
  if (action.width && action.height && action.scale && action.scale > 0 && action.scale <= 1) {
542
554
  session.scale = action.scale;
543
- if (action.deviceSize) session.deviceSize = action.deviceSize as any;
544
- if (action.rotation) session.rotation = action.rotation as any;
555
+
556
+ // Routed through the service rather than assigned here.
557
+ // Writing the fields directly left every *other* viewer of
558
+ // this tab out of the loop: their picture resized, because
559
+ // capture geometry follows the page, but their device
560
+ // selector and the mockup drawn around the canvas both read
561
+ // the tab's metadata — which nothing told them had changed.
562
+ // So a phone switched to Tablet from a laptop went on
563
+ // drawing a laptop frame around a tablet-shaped picture.
564
+ if (action.deviceSize || action.rotation) {
565
+ await previewService.setViewport(
566
+ session.id,
567
+ (action.deviceSize as any) ?? session.deviceSize,
568
+ (action.rotation as any) ?? session.rotation
569
+ );
570
+ }
545
571
 
546
572
  debug.log('preview', `📱 Viewport updated for tab ${tabId}: ${action.width}x${action.height}`);
547
573
 
@@ -605,13 +631,15 @@ export const interactPreviewHandler = createRouter()
605
631
  */
606
632
  .http('preview:browser-selection', {
607
633
  data: t.Object({
608
- cut: t.Optional(t.Boolean())
634
+ cut: t.Optional(t.Boolean()),
635
+ /** The tab the viewer is on — see `tabId` on browser-interact. */
636
+ tabId: t.Optional(t.String())
609
637
  }),
610
638
  response: t.Object({
611
639
  text: t.String()
612
640
  })
613
641
  }, async ({ data, conn }) => {
614
- const { tab } = requireBrowserTabAccess(conn);
642
+ const { tab } = requireBrowserTabAccess(conn, data.tabId);
615
643
 
616
644
  // Selections inside an iframe are invisible to the top document, so every
617
645
  // frame is asked until one reports a selection.
@@ -647,14 +675,16 @@ export const interactPreviewHandler = createRouter()
647
675
  .http('preview:browser-hit-test', {
648
676
  data: t.Object({
649
677
  x: t.Number(),
650
- y: t.Number()
678
+ y: t.Number(),
679
+ /** The tab the viewer is on — see `tabId` on browser-interact. */
680
+ tabId: t.Optional(t.String())
651
681
  }),
652
682
  response: t.Object({
653
683
  editable: t.Boolean(),
654
684
  inputType: t.Optional(t.String())
655
685
  })
656
686
  }, async ({ data, conn }) => {
657
- const { tab } = requireBrowserTabAccess(conn);
687
+ const { tab } = requireBrowserTabAccess(conn, data.tabId);
658
688
 
659
689
  try {
660
690
  // Fields inside an iframe are invisible to the top document, where
@@ -10,18 +10,41 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { requireBrowserPreviewAccess } from '../access';
13
+ import { requireBrowserPreviewAccess, requireBrowserTabAccess } from '../access';
14
14
 
15
15
  // Event forwarding is now handled automatically by BrowserPreviewServiceManager
16
16
  // when service instances are created, ensuring proper project isolation.
17
17
 
18
18
  export const nativeUIPreviewHandler = createRouter()
19
+ /**
20
+ * Take the page out of full screen on the viewer's behalf.
21
+ *
22
+ * The page draws its own exit hint, but it is a DOM node the page is free
23
+ * to destroy — and a fullscreen Chrome granted from its own C++ leaves no
24
+ * hint at all, just a collapsed capture surface that reads as a preview
25
+ * stuck full screen. This route is the way out that the page cannot lose.
26
+ */
27
+ .http('preview:browser-exit-fullscreen', {
28
+ data: t.Object({
29
+ tabId: t.Optional(t.String())
30
+ }),
31
+ response: t.Object({
32
+ success: t.Boolean()
33
+ })
34
+ }, async ({ data, conn }) => {
35
+ const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
36
+ const success = await previewService.exitPageFullscreen(tab.id);
37
+ return { success };
38
+ })
39
+
19
40
  // Action: Client responds to a dialog (alert, confirm, prompt)
20
41
  .on('preview:browser-dialog-input', {
21
42
  data: t.Object({
22
43
  dialogId: t.String({ minLength: 1 }),
23
44
  accept: t.Boolean(),
24
- promptText: t.Optional(t.String())
45
+ promptText: t.Optional(t.String()),
46
+ /** The tab whose dialog this is — see `tabId` on browser-interact. */
47
+ tabId: t.Optional(t.String())
25
48
  })
26
49
  }, async ({ data, conn }) => {
27
50
  try {
@@ -30,14 +53,13 @@ export const nativeUIPreviewHandler = createRouter()
30
53
 
31
54
  debug.log('preview', `📬 Dialog response received from frontend - dialogId: ${dialogId}, accept: ${accept}${promptText ? `, promptText: "${promptText}"` : ''} (project: ${projectId})`);
32
55
 
33
- // Get active tab
34
- const tab = previewService.getActiveTab();
56
+ const tab = data.tabId ? previewService.getTab(data.tabId) : previewService.getActiveTab();
35
57
  if (!tab) {
36
- debug.error('preview', `❌ No active tab for dialog input (project: ${projectId})`);
58
+ debug.error('preview', `❌ No tab for dialog input (project: ${projectId}, requested: ${data.tabId ?? 'active'})`);
37
59
  return;
38
60
  }
39
61
 
40
- debug.log('preview', `✅ Active tab found: ${tab.id}`);
62
+ debug.log('preview', `✅ Dialog target tab: ${tab.id}`);
41
63
 
42
64
  // Send response to dialog handler
43
65
  const result = await previewService.respondToDialog({
@@ -59,14 +81,17 @@ export const nativeUIPreviewHandler = createRouter()
59
81
 
60
82
  // Action: Client triggers print (in response to print event or manually)
61
83
  .on('preview:browser-print-input', {
62
- data: t.Object({})
63
- }, async ({ conn }) => {
84
+ data: t.Object({
85
+ /** The tab being printed — see `tabId` on browser-interact. */
86
+ tabId: t.Optional(t.String())
87
+ })
88
+ }, async ({ data, conn }) => {
64
89
  try {
65
90
  const { projectId, previewService } = requireBrowserPreviewAccess(conn);
66
91
 
67
- const tab = previewService.getActiveTab();
92
+ const tab = data.tabId ? previewService.getTab(data.tabId) : previewService.getActiveTab();
68
93
  if (!tab) {
69
- debug.error('preview', `No active tab for print input (project: ${projectId})`);
94
+ debug.error('preview', `No tab for print input (project: ${projectId}, requested: ${data.tabId ?? 'active'})`);
70
95
  return;
71
96
  }
72
97
 
@@ -63,7 +63,29 @@ export const tabInfoPreviewHandler = createRouter()
63
63
  isActive: t.Boolean(),
64
64
  canGoBack: t.Boolean(),
65
65
  canGoForward: t.Boolean(),
66
- isMcpControlled: t.Boolean()
66
+ isMcpControlled: t.Boolean(),
67
+ /** Whether an agent is acting on this tab right now. */
68
+ isMcpFocused: t.Boolean(),
69
+ /**
70
+ * What the agent is doing on this tab, for the caption beside its
71
+ * cursor. Recovered with the lock: a run holds a tab for minutes,
72
+ * so a panel opened in the middle of one must not have to wait for
73
+ * the next action before it can say anything.
74
+ */
75
+ mcpActivity: t.Optional(t.String()),
76
+ /**
77
+ * Where the agent's pointer stands, in page coordinates.
78
+ *
79
+ * Same reasoning as `mcpActivity`, and the same failure without
80
+ * it: the pointer only emits while it is moving, so a viewer
81
+ * arriving between two actions — a reload, a project switch, a
82
+ * colleague opening the panel mid-run — had a lock and a caption
83
+ * but no idea where on the page any of it was happening.
84
+ */
85
+ mcpCursor: t.Optional(t.Object({
86
+ x: t.Number(),
87
+ y: t.Number()
88
+ }))
67
89
  })),
68
90
  activeTabId: t.Union([t.String(), t.Null()]),
69
91
  count: t.Number()
@@ -73,6 +95,12 @@ export const tabInfoPreviewHandler = createRouter()
73
95
  ? requireBrowserPreviewAccessFor(conn, data.projectId)
74
96
  : requireBrowserPreviewAccess(conn);
75
97
 
98
+ // This is where the frontend rebuilds its lock state from scratch — a
99
+ // project switch, a page reload — so it is the natural point to collect
100
+ // locks whose chat session died without reaching a release path. Without
101
+ // it, a stuck lock would survive every reload until the server restarted.
102
+ browserMcpControl.releaseOrphans();
103
+
76
104
  const allTabsInfo = previewService.getAllTabsInfo();
77
105
  const activeTab = previewService.getActiveTab();
78
106
 
@@ -91,14 +119,26 @@ export const tabInfoPreviewHandler = createRouter()
91
119
  isActive: tab.isActive,
92
120
  canGoBack: tab.canGoBack,
93
121
  canGoForward: tab.canGoForward,
94
- isMcpControlled: browserMcpControl.isTabControlled(tab.id, projectId)
122
+ isMcpControlled: browserMcpControl.isTabControlled(tab.id, projectId),
123
+ isMcpFocused: browserMcpControl.isTabFocused(tab.id),
124
+ mcpActivity: browserMcpControl.getActivity(tab.id) ?? undefined,
125
+ mcpCursor: previewService.getMcpCursorPosition(tab.id) ?? undefined
95
126
  })),
96
127
  activeTabId: activeTab?.id || null,
97
128
  count: allTabsInfo.length
98
129
  };
99
130
  })
100
131
 
101
- // Switch to a specific tab (for session recovery)
132
+ /**
133
+ * "I am now looking at this tab."
134
+ *
135
+ * Deliberately does *not* make the tab the project's active one. Streaming
136
+ * is attached per (tab, viewer) already, so nothing here needs a shared
137
+ * notion of "the" tab — and making it shared is what let two people in one
138
+ * project fight: whoever clicked a tab last moved everyone else's target,
139
+ * including where their clicks landed. The agent still sets the active tab,
140
+ * because for the agent it means something.
141
+ */
102
142
  .http('preview:browser-tab-switch', {
103
143
  data: t.Object({
104
144
  tabId: t.String(),
@@ -116,16 +156,15 @@ export const tabInfoPreviewHandler = createRouter()
116
156
  ? requireBrowserPreviewAccessFor(conn, data.projectId)
117
157
  : requireBrowserPreviewAccess(conn);
118
158
 
119
- const success = previewService.switchTab(tabId);
120
- if (!success) {
159
+ if (!previewService.noteTabViewed(tabId)) {
121
160
  throw new Error(`Failed to switch to tab: ${tabId}`);
122
161
  }
123
162
 
124
- debug.log('preview', `🔄 Switched to tab: ${tabId} (project: ${projectId})`);
163
+ debug.log('preview', `👁️ Viewer is now watching tab: ${tabId} (project: ${projectId})`);
125
164
 
126
165
  return {
127
166
  success: true,
128
167
  tabId,
129
- message: `Switched to tab ${tabId}`
168
+ message: `Now viewing tab ${tabId}`
130
169
  };
131
170
  });
@@ -342,10 +342,15 @@ export const streamPreviewHandler = createRouter()
342
342
  })
343
343
  },
344
344
  async ({ data, conn }) => {
345
- const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId);
345
+ const { previewService, projectId, tab } = requireBrowserTabAccess(conn, data.tabId);
346
346
 
347
347
  await previewService.stopWebCodecsStreaming(tab.id, data.viewerId);
348
348
 
349
+ // The disconnect cleanup for this pair has nothing left to do.
350
+ // Dropping the key lets a later re-handshake register a fresh one
351
+ // instead of relying on a closure whose stop has already run.
352
+ registeredViewerCleanups.delete(`${projectId}:${tab.id}:${data.viewerId}`);
353
+
349
354
  return { success: true };
350
355
  }
351
356
  )