@myrialabs/clopen 0.4.22 → 0.4.24

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 (33) hide show
  1. package/backend/chat/stream-manager.ts +41 -13
  2. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
  3. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
  4. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
  5. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +25 -6
  6. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +26 -0
  7. package/backend/mcp/internal/servers/browser-automation/context.ts +43 -19
  8. package/backend/mcp/internal/servers/browser-automation/description.ts +2 -1
  9. package/backend/mcp/internal/servers/browser-automation/format.ts +6 -0
  10. package/backend/mcp/internal/servers/browser-automation/runner.ts +62 -33
  11. package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
  12. package/backend/module-shadowing.test.ts +135 -0
  13. package/backend/preview/browser/browser-host-bridge.ts +8 -2
  14. package/backend/preview/browser/browser-interaction-handler.ts +70 -0
  15. package/backend/preview/browser/browser-mcp-control.ts +247 -13
  16. package/backend/preview/browser/browser-preview-service.ts +146 -8
  17. package/backend/preview/browser/browser-video-capture.ts +551 -247
  18. package/backend/preview/browser/scripts/host-bridge.ts +61 -89
  19. package/backend/preview/browser/scripts/video-stream.ts +32 -0
  20. package/backend/preview/browser/types.ts +22 -0
  21. package/backend/preview/index.ts +6 -1
  22. package/backend/ws/preview/browser/interact.ts +16 -2
  23. package/backend/ws/preview/browser/native-ui.ts +22 -1
  24. package/backend/ws/preview/browser/tab-info.ts +20 -2
  25. package/backend/ws/preview/browser/webcodecs.ts +6 -1
  26. package/backend/ws/preview/index.ts +22 -0
  27. package/dist/assets/{index-DH_GO0Lf.js → index-CNDHpafl.js} +1 -1
  28. package/dist/assets/{index-igSQ3JaM.js → index-NF77n8kP.js} +1 -1
  29. package/dist/assets/{main-D-d8SFfW.js → main-BJ0PUVTW.js} +381 -376
  30. package/dist/assets/main-DSirC670.css +1 -0
  31. package/dist/index.html +2 -2
  32. package/package.json +1 -1
  33. package/dist/assets/main-BD3-qPfT.css +0 -1
@@ -243,6 +243,22 @@ class StreamManager extends EventEmitter {
243
243
  super();
244
244
  // Increase max listeners for high concurrency
245
245
  this.setMaxListeners(1000);
246
+
247
+ // MCP browser locks are scoped to a chat session, and every release path
248
+ // runs from this class. Teaching the lock manager how to check liveness
249
+ // closes the gap those paths can't: a tool call that lands after its
250
+ // stream ended used to be able to take a lock nothing would release.
251
+ browserMcpControl.setSessionLivenessProbe((chatSessionId) =>
252
+ this.isChatSessionStreaming(chatSessionId)
253
+ );
254
+ }
255
+
256
+ /** Whether any stream for this chat session is still running. */
257
+ private isChatSessionStreaming(chatSessionId: string): boolean {
258
+ for (const stream of this.activeStreams.values()) {
259
+ if (stream.chatSessionId === chatSessionId && stream.status === 'active') return true;
260
+ }
261
+ return false;
246
262
  }
247
263
 
248
264
  /**
@@ -1302,6 +1318,27 @@ class StreamManager extends EventEmitter {
1302
1318
  }
1303
1319
  }
1304
1320
 
1321
+ // Abort first, then release the browser locks, and only then ask the
1322
+ // engine to stop.
1323
+ //
1324
+ // The order matters and used to be the other way round. `engine.cancel()`
1325
+ // is awaited for up to five seconds, and a browser-automation batch that
1326
+ // was mid-flight kept resolving its target tab throughout — re-acquiring
1327
+ // control of a tab moments after (or before) it was handed back, under a
1328
+ // chat session whose release had already run. That is the interrupt that
1329
+ // left the tab locked with nobody to unlock it. Aborting up front makes
1330
+ // the batch stop between actions, and releasing before the wait means
1331
+ // anything that slips through is refused rather than orphaned.
1332
+ if (!streamState.abortController?.signal.aborted) {
1333
+ streamState.abortController?.abort();
1334
+ }
1335
+
1336
+ // Auto-release all MCP-controlled tabs for this chat session
1337
+ if (streamState.chatSessionId) {
1338
+ browserMcpControl.releaseSession(streamState.chatSessionId);
1339
+ debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
1340
+ }
1341
+
1305
1342
  // Cancel the per-project engine with a bounded timeout.
1306
1343
  // engine.cancel() stops the SDK process (Claude Code: close() kills subprocess,
1307
1344
  // OpenCode: aborts controller + HTTP abort to server). If cancel() hangs
@@ -1320,14 +1357,6 @@ class StreamManager extends EventEmitter {
1320
1357
  debug.error('chat', 'Error cancelling engine (non-fatal):', error);
1321
1358
  }
1322
1359
 
1323
- // Abort the stream-manager's controller as a fallback.
1324
- // engine.cancel() already aborts the same controller, so this is
1325
- // typically a no-op but ensures cleanup if the engine timed out
1326
- // or wasn't active.
1327
- if (!streamState.abortController?.signal.aborted) {
1328
- streamState.abortController?.abort();
1329
- }
1330
-
1331
1360
  this.emitStreamEvent(streamState, 'cancelled', {
1332
1361
  processId: streamState.processId,
1333
1362
  timestamp: streamState.completedAt.toISOString()
@@ -1335,11 +1364,10 @@ class StreamManager extends EventEmitter {
1335
1364
 
1336
1365
  this.emitStreamLifecycle(streamState, 'cancelled', reason);
1337
1366
 
1338
- // Auto-release all MCP-controlled tabs for this chat session
1339
- if (streamState.chatSessionId) {
1340
- browserMcpControl.releaseSession(streamState.chatSessionId);
1341
- debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
1342
- }
1367
+ // Sweep again after the engine has actually stopped: a tool call still
1368
+ // in flight during the wait above may have taken a lock that its own
1369
+ // release path will never reach.
1370
+ browserMcpControl.releaseOrphans();
1343
1371
 
1344
1372
  return true;
1345
1373
  }
@@ -9,6 +9,7 @@ import { commonFields } from './shared';
9
9
  export const consoleLogs: ActionDef = {
10
10
  type: 'console_logs',
11
11
  kind: 'control',
12
+ activity: 'Reading the console',
12
13
  doc: `console_logs {limit?, level?} — the page's console output, oldest first.
13
14
  Where to look when an action "worked" but the page did not react: the error is usually here and invisible on screen.`,
14
15
  schema: z.object({
@@ -37,6 +38,7 @@ export const consoleLogs: ActionDef = {
37
38
  export const clearConsole: ActionDef = {
38
39
  type: 'clear_console',
39
40
  kind: 'control',
41
+ activity: 'Clearing the console',
40
42
  doc: `clear_console {} — drop stored console output.
41
43
  Put this before the step you are debugging so what follows is only that step's output.`,
42
44
  schema: z.object({ type: z.literal('clear_console'), ...commonFields }),
@@ -49,6 +51,7 @@ export const clearConsole: ActionDef = {
49
51
  export const evaluate: ActionDef = {
50
52
  type: 'eval',
51
53
  kind: 'control',
54
+ activity: 'Running a script',
52
55
  doc: `eval {expression} — run JavaScript in the page and return the result.
53
56
  For state that is not in the DOM: computed styles, localStorage, framework internals, window globals. The result must be JSON-serialisable.`,
54
57
  schema: z.object({
@@ -15,6 +15,7 @@ import { resolveWritePath } from '../paths';
15
15
  export const find: ActionDef = {
16
16
  type: 'find',
17
17
  kind: 'control',
18
+ activity: 'Looking for an element',
18
19
  doc: `find {selector?, text?, role?, limit?} — locate elements and get their positions.
19
20
  Returns tag, text, a reusable selector and a centre point for each match, iframes included.
20
21
  This is the cheap alternative to a screenshot: to click something you can name, find it and click by selector — no image, no vision, no coordinate guessing.`,
@@ -60,6 +61,7 @@ export const find: ActionDef = {
60
61
  export const analyzeDom: ActionDef = {
61
62
  type: 'analyze_dom',
62
63
  kind: 'control',
64
+ activity: 'Reading the page',
63
65
  doc: `analyze_dom {include?} — the page as text: links, headings, content, forms, metadata.
64
66
  The primary tool for reading and exploring. Far cheaper than a screenshot and it sees the whole document, not just the part currently on screen — scrolling to "see more" is never necessary.
65
67
  include: navigation | structure | content | forms | summary. Omit for all.
@@ -91,6 +93,7 @@ export const analyzeDom: ActionDef = {
91
93
  export const screenshot: ActionDef = {
92
94
  type: 'screenshot',
93
95
  kind: 'control',
96
+ activity: 'Taking a screenshot',
94
97
  doc: `screenshot {fullPage?, selector?, format?, quality?, saveTo?, return?} — capture the page.
95
98
  Needed for what the DOM cannot express: canvases, charts, iframes, captchas, and any visual check of layout or styling.
96
99
  saveTo writes a file under the project directory; with return:"file" the image is not sent back at all, which is what makes "capture twenty pages" affordable.
@@ -13,6 +13,7 @@ import { commonFields } from './shared';
13
13
  export const navigate: ActionDef = {
14
14
  type: 'navigate',
15
15
  kind: 'control',
16
+ activity: 'Navigating',
16
17
  doc: `navigate {url} — load a URL in the current tab.
17
18
  Following a link you already have the href for is cheaper and far more reliable than clicking it. Session state (cookies, storage) is kept.`,
18
19
  schema: z.object({
@@ -33,6 +34,7 @@ export const navigate: ActionDef = {
33
34
  export const goBack: ActionDef = {
34
35
  type: 'go_back',
35
36
  kind: 'control',
37
+ activity: 'Going back',
36
38
  doc: `go_back {steps?} — walk back through the tab's history.`,
37
39
  schema: z.object({
38
40
  type: z.literal('go_back'),
@@ -50,6 +52,7 @@ export const goBack: ActionDef = {
50
52
  export const goForward: ActionDef = {
51
53
  type: 'go_forward',
52
54
  kind: 'control',
55
+ activity: 'Going forward',
53
56
  doc: `go_forward {steps?} — walk forward through the tab's history.`,
54
57
  schema: z.object({
55
58
  type: z.literal('go_forward'),
@@ -67,6 +70,7 @@ export const goForward: ActionDef = {
67
70
  export const reload: ActionDef = {
68
71
  type: 'reload',
69
72
  kind: 'control',
73
+ activity: 'Reloading',
70
74
  doc: `reload {hard?} — reload the page. hard bypasses the cache.`,
71
75
  schema: z.object({
72
76
  type: z.literal('reload'),
@@ -87,6 +91,7 @@ export const reload: ActionDef = {
87
91
  export const waitFor: ActionDef = {
88
92
  type: 'wait_for',
89
93
  kind: 'control',
94
+ activity: 'Waiting for the page',
90
95
  doc: `wait_for {selector|text|urlContains|state, timeout?} — wait for the page to catch up.
91
96
  Returns the moment the condition holds, so it costs only what it has to.
92
97
  state: visible (default, with selector/text) · hidden · navigation · networkIdle.
@@ -5,12 +5,16 @@
5
5
  * calls `ctx.invalidateTab()` — without it a batch like
6
6
  * `[open_tab, navigate, screenshot]` would open a tab and then keep driving the
7
7
  * old one.
8
+ *
9
+ * Everything here except `set_viewport` is `needsTab: false`: these are the
10
+ * actions an empty browser has to be able to run, so they must not be gated on
11
+ * a tab already existing.
8
12
  */
9
13
 
10
14
  import { z } from 'zod';
11
15
  import { browserMcpControl } from '$backend/preview';
12
16
  import { debug } from '$shared/utils/logger';
13
- import type { ActionDef } from './types';
17
+ import type { ActionDef, TablessActionContext } from './types';
14
18
  import { commonFields } from './shared';
15
19
 
16
20
  const DEVICE_SIZES = ['desktop', 'laptop', 'tablet', 'mobile'] as const;
@@ -24,10 +28,12 @@ function defaultRotation(deviceSize: string): 'portrait' | 'landscape' {
24
28
  export const listTabs: ActionDef = {
25
29
  type: 'list_tabs',
26
30
  kind: 'control',
31
+ activity: 'Checking tabs',
27
32
  doc: `list_tabs {} — every open tab with its id, URL, viewport and who controls it.
28
33
  Use the id, not the position, with switch_tab/close_tab.`,
29
34
  schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
30
- run: async (_args, ctx) => {
35
+ needsTab: false,
36
+ run: async (_args, ctx: TablessActionContext) => {
31
37
  const tabs = ctx.service.getAllTabs();
32
38
  if (tabs.length === 0) return { summary: 'no tabs open' };
33
39
 
@@ -48,6 +54,7 @@ export const listTabs: ActionDef = {
48
54
  export const openTab: ActionDef = {
49
55
  type: 'open_tab',
50
56
  kind: 'control',
57
+ activity: 'Opening a tab',
51
58
  doc: `open_tab {url?, deviceSize?, rotation?} — open a tab and make it the target.
52
59
  deviceSize: desktop 1920×1080 · laptop 1440×900 (default) · tablet 834×1194 · mobile 402×874.
53
60
  rotation defaults to landscape for desktop/laptop, portrait for tablet/mobile.`,
@@ -58,7 +65,8 @@ export const openTab: ActionDef = {
58
65
  rotation: z.enum(ROTATIONS).optional().describe('Orientation. Omit for the device default.'),
59
66
  ...commonFields
60
67
  }),
61
- run: async (args, ctx) => {
68
+ needsTab: false,
69
+ run: async (args, ctx: TablessActionContext) => {
62
70
  const deviceSize = args.deviceSize || 'laptop';
63
71
  const rotation = args.rotation || defaultRotation(deviceSize);
64
72
 
@@ -74,19 +82,24 @@ export const openTab: ActionDef = {
74
82
  export const switchTab: ActionDef = {
75
83
  type: 'switch_tab',
76
84
  kind: 'control',
85
+ activity: 'Switching tab',
77
86
  doc: `switch_tab {tabId} — make another tab the target of following actions.`,
78
87
  schema: z.object({
79
88
  type: z.literal('switch_tab'),
80
89
  tabId: z.string().min(1).describe('Tab id from list_tabs.'),
81
90
  ...commonFields
82
91
  }),
83
- run: async (args, ctx) => {
92
+ needsTab: false,
93
+ run: async (args, ctx: TablessActionContext) => {
84
94
  if (!ctx.service.switchTab(args.tabId)) throw new Error(`Tab '${args.tabId}' not found`);
85
95
 
86
96
  const tab = ctx.service.getTab(args.tabId);
87
97
  if (tab) {
88
98
  const acquired = browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
89
99
  if (!acquired) {
100
+ if (!browserMcpControl.isSessionLive(ctx.chatSessionId)) {
101
+ throw new Error('This chat session is no longer running — the browser was released when it stopped.');
102
+ }
90
103
  const owner = browserMcpControl.getTabOwner(tab.id);
91
104
  throw new Error(`Tab '${args.tabId}' is controlled by another chat session (${owner?.slice(0, 8)}...)`);
92
105
  }
@@ -102,14 +115,19 @@ export const switchTab: ActionDef = {
102
115
  export const closeTab: ActionDef = {
103
116
  type: 'close_tab',
104
117
  kind: 'control',
118
+ activity: 'Closing a tab',
105
119
  doc: `close_tab {tabId?} — close a tab (default: the current one).`,
106
120
  schema: z.object({
107
121
  type: z.literal('close_tab'),
108
122
  tabId: z.string().optional().describe('Tab id from list_tabs. Omit to close the current tab.'),
109
123
  ...commonFields
110
124
  }),
111
- run: async (args, ctx) => {
112
- const tabId = args.tabId || ctx.tab.id;
125
+ // Closing is the one thing an empty browser cannot do — and opening a tab
126
+ // just to close it would be a strange way to find that out.
127
+ needsTab: false,
128
+ run: async (args, ctx: TablessActionContext) => {
129
+ const tabId = args.tabId || ctx.tab?.id;
130
+ if (!tabId) throw new Error('No open tab to close');
113
131
  const result = await ctx.service.closeTab(tabId);
114
132
  if (!result.success) throw new Error(`Tab '${tabId}' not found`);
115
133
 
@@ -124,6 +142,7 @@ export const closeTab: ActionDef = {
124
142
  export const setViewport: ActionDef = {
125
143
  type: 'set_viewport',
126
144
  kind: 'control',
145
+ activity: 'Changing the viewport',
127
146
  doc: `set_viewport {deviceSize?, rotation?} — resize the current tab.
128
147
  Changing this re-runs the page's media queries, so it is how responsive layouts get tested.`,
129
148
  schema: z.object({
@@ -26,6 +26,13 @@ export interface ActionContext {
26
26
  invalidateTab(): void;
27
27
  }
28
28
 
29
+ /**
30
+ * What a `needsTab: false` action gets: the same context, minus the guarantee
31
+ * that a tab exists. `tab` is whatever the batch was last pointed at, or null
32
+ * when the project has nothing open.
33
+ */
34
+ export type TablessActionContext = Omit<ActionContext, 'tab'> & { tab: BrowserTab | null };
35
+
29
36
  export interface ActionImage {
30
37
  data: string;
31
38
  mimeType: string;
@@ -56,6 +63,25 @@ export interface ActionDef {
56
63
  doc: string;
57
64
  /** Zod object whose `type` field is the discriminator. */
58
65
  schema: z.ZodObject<any>;
66
+ /**
67
+ * `false` for the actions that have to work on an empty browser — the ones
68
+ * that open or enumerate tabs. Everything else gets a tab opened for it
69
+ * before it runs, so a batch never has to start with `open_tab`.
70
+ *
71
+ * Such an action must declare its context as `TablessActionContext`: that is
72
+ * what stops it from reading a `tab` that may be null.
73
+ */
74
+ needsTab?: boolean;
75
+ /**
76
+ * Two or three words for the caption beside the agent's cursor while this
77
+ * runs — "Navigating", "Taking a screenshot".
78
+ *
79
+ * Only `control` actions carry one. An `input` action's caption is written by
80
+ * the interaction handler from the gesture itself, which is the only place
81
+ * that knows whether a `type` is text or a keystroke, or a `click` is a right
82
+ * click — and the runner has already coalesced the group by then anyway.
83
+ */
84
+ activity?: string;
59
85
  /** `input` actions: translate to the native gesture primitive. */
60
86
  toInput?: (args: any, ctx: ActionContext) => BrowserAutonomousAction | Promise<BrowserAutonomousAction>;
61
87
  /** `control` actions: run directly. */
@@ -46,37 +46,61 @@ export function getChatSessionId(): string {
46
46
  }
47
47
 
48
48
  /**
49
- * The tab this call should act on, with MCP control acquired for it.
49
+ * Which tab the batch is pointed at right now, or null when nothing is open.
50
50
  *
51
51
  * A chat session accumulates tabs (open/switch add to its set), and the most
52
52
  * recently used one is the target — not the frontend's active tab, which the
53
53
  * user may have changed while the agent was working.
54
+ *
55
+ * Takes no control and opens nothing, so it is safe for actions that only want
56
+ * to know where things stand.
54
57
  */
55
- export async function getActiveTabSession(projectId?: string): Promise<{ tab: BrowserTab; service: BrowserPreviewService }> {
56
- const service = getPreviewService(projectId);
57
- const resolvedProjectId = service.getProjectId();
58
- const chatSessionId = getChatSessionId();
59
-
58
+ export function peekSessionTab(service: BrowserPreviewService, chatSessionId: string): BrowserTab | null {
60
59
  const sessionTabs = browserMcpControl.getSessionTabs(chatSessionId);
61
60
  if (sessionTabs.length > 0) {
62
61
  const lastTabId = sessionTabs[sessionTabs.length - 1];
63
62
  const controlledTab = service.getTab(lastTabId);
64
- if (controlledTab) {
65
- debug.log('mcp', `🎮 Using session-controlled tab: ${controlledTab.id}`);
66
- return { tab: controlledTab, service };
67
- }
63
+ if (controlledTab) return controlledTab;
68
64
  }
69
65
 
70
- const tab = service.getActiveTab();
71
- if (!tab) {
72
- throw new Error("No open tab. Start with an `open_tab` action.");
73
- }
66
+ return service.getActiveTab();
67
+ }
68
+
69
+ /**
70
+ * The tab this call should act on, with MCP control acquired for it.
71
+ *
72
+ * Opens one when the project has none. Failing instead was a dead end: a fresh
73
+ * browser has no tab, so the first call failed no matter what it asked for, and
74
+ * the only way out was for someone to open a tab by hand in the UI.
75
+ */
76
+ export async function getActiveTabSession(
77
+ projectId?: string
78
+ ): Promise<{ tab: BrowserTab; service: BrowserPreviewService; opened: boolean }> {
79
+ const service = getPreviewService(projectId);
80
+ const resolvedProjectId = service.getProjectId();
81
+ const chatSessionId = getChatSessionId();
74
82
 
75
- const acquired = browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
76
- if (!acquired) {
77
- const owner = browserMcpControl.getTabOwner(tab.id);
78
- throw new Error(`Tab '${tab.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
83
+ const existing = peekSessionTab(service, chatSessionId);
84
+ if (existing) {
85
+ const acquired = browserMcpControl.acquireControl(existing.id, chatSessionId, resolvedProjectId);
86
+ if (!acquired) {
87
+ // Two very different refusals. Saying "another session" for both sent
88
+ // an agent looking for a tab conflict that does not exist, when what
89
+ // actually happened is that its own run was interrupted.
90
+ if (!browserMcpControl.isSessionLive(chatSessionId)) {
91
+ throw new Error('This chat session is no longer running — the browser was released when it stopped.');
92
+ }
93
+ const owner = browserMcpControl.getTabOwner(existing.id);
94
+ throw new Error(`Tab '${existing.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
95
+ }
96
+
97
+ debug.log('mcp', `🎮 Using tab: ${existing.id}`);
98
+ return { tab: existing, service, opened: false };
79
99
  }
80
100
 
81
- return { tab, service };
101
+ debug.log('mcp', `📑 No tab open for project ${resolvedProjectId} — opening a blank one`);
102
+ const tab = await service.createTab(undefined, 'laptop', 'landscape');
103
+ browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
104
+
105
+ return { tab, service, opened: true };
82
106
  }
@@ -7,7 +7,7 @@
7
7
  * is why it can never document an action that no longer exists.
8
8
  */
9
9
 
10
- import { ACTION_GROUPS } from './actions';
10
+ import { ACTION_GROUPS } from './actions/index';
11
11
 
12
12
  const PREAMBLE = `Drive the built-in preview browser: tabs, navigation, input, and reading the page.
13
13
 
@@ -45,6 +45,7 @@ const OUTRO = `NOTES
45
45
  - Coordinates are in the page's own viewport (CSS pixels), the same space a screenshot is captured in.
46
46
  - Selectors are searched in every frame, so an element inside an iframe is addressed the same way as one in the main document.
47
47
  - A tab opened, switched to or closed mid-batch becomes the target for the actions that follow it.
48
+ - You never have to open a tab first. On an empty browser the first action that needs a tab gets a blank one opened for it, and the report says so — \`navigate\` alone is a fine way to start.
48
49
  - The user can interrupt at any time; the batch stops and the report says how far it got.`;
49
50
 
50
51
  function renderReference(): string {
@@ -23,6 +23,12 @@ export function formatReport(report: RunReport): {
23
23
 
24
24
  const lines: string[] = [header.join(' · ')];
25
25
 
26
+ // Say it plainly: the agent asked for one thing and got a tab it never
27
+ // requested, and the blank page is why a screenshot may look empty.
28
+ if (report.openedTabId) {
29
+ lines.push(`No tab was open, so ${report.openedTabId} was opened (about:blank) for this batch.`);
30
+ }
31
+
26
32
  for (const step of report.steps) {
27
33
  const label = `[${step.index + 1}] ${step.type}`;
28
34
  lines.push(step.ok ? `${label} ok${step.summary ? ` → ${step.summary}` : ''}` : `${label} FAILED → ${step.error}`);
@@ -17,12 +17,13 @@
17
17
  * the agent then plans on top of a state that does not exist.
18
18
  */
19
19
 
20
- import type { BrowserAutonomousAction } from '$backend/preview/browser/types';
20
+ import type { BrowserAutonomousAction, BrowserTab } from '$backend/preview/browser/types';
21
21
  import { projectContextService } from '$backend/mcp/internal/project-context';
22
22
  import { debug } from '$shared/utils/logger';
23
- import { ACTIONS_BY_TYPE } from './actions';
24
- import type { ActionContext, ActionImage } from './actions/types';
25
- import { getActiveTabSession, getPreviewService } from './context';
23
+ import { ACTIONS_BY_TYPE } from './actions/index';
24
+ import type { ActionContext, ActionImage, TablessActionContext } from './actions/types';
25
+ import { getActiveTabSession, getPreviewService, peekSessionTab } from './context';
26
+ import { browserMcpControl } from '$backend/preview';
26
27
 
27
28
  interface ActionArgs {
28
29
  type: string;
@@ -54,6 +55,8 @@ export interface RunReport {
54
55
  failed: boolean;
55
56
  tabId?: string;
56
57
  url?: string;
58
+ /** Set when the batch had to open a tab because the browser had none. */
59
+ openedTabId?: string;
57
60
  }
58
61
 
59
62
  /** Consecutive input gestures form one native run; control actions stand alone. */
@@ -79,20 +82,38 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
79
82
  const signal = projectContextService.getCurrentSignal();
80
83
  const service = getPreviewService(args.projectId);
81
84
  const projectId = service.getProjectId();
85
+ const chatSessionId = projectContextService.getCurrentChatSessionId() ?? '';
82
86
 
83
87
  const report: RunReport = { steps: [], images: [], skipped: 0, aborted: false, failed: false };
84
88
 
85
89
  let tabStale = true;
86
- let tab: Awaited<ReturnType<typeof getActiveTabSession>>['tab'] | null = null;
90
+ let tab: BrowserTab | null = null;
87
91
 
92
+ /** The tab to act on — opened on the spot if the browser has none. */
88
93
  const resolveTab = async () => {
89
94
  if (!tabStale && tab) return tab;
90
95
  const resolved = await getActiveTabSession(args.projectId);
96
+ if (resolved.opened) report.openedTabId = resolved.tab.id;
91
97
  tab = resolved.tab;
92
98
  tabStale = false;
93
99
  return tab;
94
100
  };
95
101
 
102
+ /** Where the batch stands, without opening anything or taking control. */
103
+ const peekTab = () => (!tabStale && tab ? tab : peekSessionTab(service, chatSessionId));
104
+
105
+ // `needsTab: false` actions declare their context as TablessActionContext,
106
+ // so the null this can carry never reaches one that dereferences it.
107
+ const makeContext = (target: BrowserTab | null): ActionContext =>
108
+ ({
109
+ service,
110
+ tab: target,
111
+ projectId,
112
+ chatSessionId,
113
+ signal,
114
+ invalidateTab: () => (tabStale = true)
115
+ } satisfies TablessActionContext as ActionContext);
116
+
96
117
  const groups = groupActions(args.actions);
97
118
  let stopped = false;
98
119
  let consumed = 0;
@@ -104,7 +125,7 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
104
125
  for (const group of groups) {
105
126
  if (stopped || signal?.aborted) break;
106
127
 
107
- const deps: RunDeps = { args, service, projectId, signal, resolveTab, markTabStale: () => (tabStale = true) };
128
+ const deps: RunDeps = { args, service, signal, resolveTab, peekTab, makeContext };
108
129
  const before = report.steps.length;
109
130
 
110
131
  consumed += group.kind === 'input'
@@ -127,12 +148,14 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
127
148
 
128
149
  // Report where the batch left the browser: the next call's plan depends on
129
150
  // it, and it is the cheapest way to notice a navigation nobody asked for.
151
+ // Peeked, not resolved: a batch that closed its last tab should say so, not
152
+ // get a fresh one opened just to have something to report.
130
153
  try {
131
- // Through the resolver, not the cached handle: a tab opened or closed
132
- // mid-batch means the cached one is no longer where the agent is.
133
- const current = await resolveTab();
134
- report.tabId = current.id;
135
- report.url = current.page.url();
154
+ const current = peekTab();
155
+ if (current) {
156
+ report.tabId = current.id;
157
+ report.url = current.page.url();
158
+ }
136
159
  } catch {
137
160
  // No tab left (closed by the batch, or none was ever open).
138
161
  }
@@ -143,10 +166,10 @@ export async function runActions(args: RunArgs): Promise<RunReport> {
143
166
  interface RunDeps {
144
167
  args: RunArgs;
145
168
  service: ReturnType<typeof getPreviewService>;
146
- projectId: string;
147
169
  signal?: AbortSignal;
148
- resolveTab: () => Promise<NonNullable<Awaited<ReturnType<typeof getActiveTabSession>>['tab']>>;
149
- markTabStale: () => void;
170
+ resolveTab: () => Promise<BrowserTab>;
171
+ peekTab: () => BrowserTab | null;
172
+ makeContext: (target: BrowserTab | null) => ActionContext;
150
173
  }
151
174
 
152
175
  /** Run one control action. Returns how many actions were consumed. */
@@ -157,24 +180,37 @@ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDe
157
180
  return 1;
158
181
  }
159
182
 
183
+ // Remembered rather than re-read in the `finally`: `close_tab` and
184
+ // `switch_tab` change what the current tab is, and the caption has to be
185
+ // taken off the tab it was put on.
186
+ let labelled: string | null = null;
187
+
160
188
  try {
161
- const tab = await deps.resolveTab();
162
- const ctx: ActionContext = {
163
- service: deps.service,
164
- tab,
165
- projectId: deps.projectId,
166
- chatSessionId: projectContextService.getCurrentChatSessionId() ?? '',
167
- signal: deps.signal,
168
- invalidateTab: deps.markTabStale
169
- };
170
-
171
- const output = await def.run(item.args, ctx);
189
+ // The tab actions run on an empty browser — they are how it stops being
190
+ // empty. Everything else gets a tab opened for it first.
191
+ const tab = def.needsTab === false ? deps.peekTab() : await deps.resolveTab();
192
+
193
+ // Say what is about to happen while it happens. Input gestures label
194
+ // themselves from inside the engine (see ActionDef.activity); a control
195
+ // action has no gesture, and is often the longest step in a batch — a
196
+ // 30-second `wait_for` with a silent cursor on it reads as a hang.
197
+ if (tab && def.activity) {
198
+ labelled = tab.id;
199
+ browserMcpControl.emitActivity(tab.id, def.activity);
200
+ }
201
+
202
+ const output = await def.run(item.args, deps.makeContext(tab));
172
203
  report.steps.push({ index: item.index, type: def.type, ok: true, summary: output.summary, detail: output.detail });
173
204
  if (output.images?.length) report.images.push(...output.images);
174
205
  } catch (error) {
175
206
  const message = error instanceof Error ? error.message : 'Unknown error';
176
207
  debug.warn('mcp', `browser action ${item.args.type} failed: ${message}`);
177
208
  report.steps.push({ index: item.index, type: item.args.type, ok: false, error: message });
209
+ } finally {
210
+ // Back to a bare "Agent". The pointer stays for as long as the tab is
211
+ // held; only the caption is tied to a single action, and one left over
212
+ // from the last step describes a page that has already moved on.
213
+ if (labelled) browserMcpControl.emitActivity(labelled, null);
178
214
  }
179
215
 
180
216
  return 1;
@@ -196,14 +232,7 @@ async function runInputGroup(items: Array<{ index: number; args: ActionArgs }>,
196
232
  return 1;
197
233
  }
198
234
 
199
- const ctx: ActionContext = {
200
- service: deps.service,
201
- tab,
202
- projectId: deps.projectId,
203
- chatSessionId: projectContextService.getCurrentChatSessionId() ?? '',
204
- signal: deps.signal,
205
- invalidateTab: deps.markTabStale
206
- };
235
+ const ctx = deps.makeContext(tab);
207
236
 
208
237
  // Translation can fail on its own (a path outside the project, a missing
209
238
  // field). Those actions never reach the engine, so they are reported here
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { z } from 'zod';
6
- import { ALL_ACTIONS } from './actions';
6
+ import { ALL_ACTIONS } from './actions/index';
7
7
 
8
8
  const members = ALL_ACTIONS.map((action) => action.schema) as unknown as [
9
9
  z.ZodObject<any>,