@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
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Guards against a module being shadowed by a file an *older* release left behind.
3
+ *
4
+ * Package upgrades are not guaranteed to be clean. On Windows, `bun add -g` has
5
+ * been observed to overlay the new version onto the old install instead of
6
+ * replacing it, so a file that a previous release shipped can still be sitting
7
+ * on disk long after we deleted it from the repo.
8
+ *
9
+ * That is harmless until a deleted file's path is reused as a directory. Import
10
+ * resolution tries `./x.ts` before `./x/index.ts`, so `import … from './x'`
11
+ * silently binds to the leftover — and the user gets a SyntaxError naming a file
12
+ * that does not exist in the version they installed. v0.4.23 shipped exactly
13
+ * this: `browser-automation/actions.ts` became `browser-automation/actions/`,
14
+ * and anyone upgrading from ≤0.4.21 on Windows could not start Clopen at all.
15
+ *
16
+ * The fix in that case is to import the index explicitly (`./actions/index`),
17
+ * which no leftover file can shadow. This test finds the next one for us.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+ import { existsSync, statSync } from 'node:fs';
22
+ import { dirname, extname, join, normalize, relative, resolve } from 'node:path';
23
+
24
+ const repoRoot = resolve(import.meta.dir, '..');
25
+
26
+ /** Directories we ship and therefore import from. */
27
+ const sourceRoots = ['backend', 'shared', 'frontend', 'bin', 'scripts'];
28
+
29
+ const aliases: Record<string, string> = {
30
+ $backend: 'backend',
31
+ $shared: 'shared',
32
+ $frontend: 'frontend'
33
+ };
34
+
35
+ const git = (...args: string[]) =>
36
+ Bun.spawnSync(['git', ...args], { cwd: repoRoot }).stdout.toString();
37
+
38
+ /**
39
+ * Every path git has ever seen deleted, which is the set of files that can be
40
+ * lingering in somebody's install. Needs full history — a shallow clone only
41
+ * knows about the last commit, so the answer would be a vacuous "none".
42
+ */
43
+ const deletedPaths = (): string[] =>
44
+ git('log', '--all', '--diff-filter=D', '--name-only', '--format=')
45
+ .split('\n')
46
+ .map((line) => line.trim())
47
+ .filter(Boolean);
48
+
49
+ const isDirectory = (path: string) => existsSync(path) && statSync(path).isDirectory();
50
+
51
+ /**
52
+ * A directory is shadowable when some earlier release shipped a file at the
53
+ * same path plus an extension, e.g. `actions/` against a deleted `actions.ts`.
54
+ */
55
+ const shadowableDirectories = (): Map<string, string> => {
56
+ const found = new Map<string, string>();
57
+
58
+ for (const path of deletedPaths()) {
59
+ const extension = extname(path);
60
+ if (!extension) continue;
61
+
62
+ const stem = path.slice(0, -extension.length);
63
+ const absolute = join(repoRoot, stem);
64
+
65
+ // Re-added under the same name? Then it is a file again, not a shadow.
66
+ if (existsSync(join(repoRoot, path))) continue;
67
+ if (!isDirectory(absolute)) continue;
68
+
69
+ found.set(stem, path);
70
+ }
71
+
72
+ return found;
73
+ };
74
+
75
+ const sourceFiles = async (): Promise<string[]> => {
76
+ const glob = new Bun.Glob('**/*.{ts,js,svelte,svelte.ts}');
77
+ const files: string[] = [];
78
+
79
+ for (const root of sourceRoots) {
80
+ if (!isDirectory(join(repoRoot, root))) continue;
81
+ for await (const file of glob.scan({ cwd: join(repoRoot, root), absolute: true })) {
82
+ files.push(file);
83
+ }
84
+ }
85
+
86
+ return files;
87
+ };
88
+
89
+ const SPECIFIER = /(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g;
90
+
91
+ /** Resolves a specifier to a repo-relative path, or null if it points elsewhere. */
92
+ const resolveSpecifier = (specifier: string, fromFile: string): string | null => {
93
+ if (specifier.startsWith('.')) {
94
+ return relative(repoRoot, resolve(dirname(fromFile), specifier));
95
+ }
96
+
97
+ const [head, ...rest] = specifier.split('/');
98
+ const aliased = aliases[head];
99
+ if (!aliased) return null;
100
+
101
+ return normalize(join(aliased, ...rest));
102
+ };
103
+
104
+ describe('module shadowing', () => {
105
+ test('no import can be captured by a file a previous release left behind', async () => {
106
+ if (git('rev-parse', '--is-shallow-repository').trim() === 'true') {
107
+ // CI checks out with fetch-depth: 0 so this only skips on shallow clones.
108
+ return;
109
+ }
110
+
111
+ const shadowable = shadowableDirectories();
112
+ if (shadowable.size === 0) return;
113
+
114
+ const violations: string[] = [];
115
+
116
+ for (const file of await sourceFiles()) {
117
+ const contents = await Bun.file(file).text();
118
+
119
+ for (const [, specifier] of contents.matchAll(SPECIFIER)) {
120
+ const target = resolveSpecifier(specifier, file);
121
+ if (!target) continue;
122
+
123
+ const shadowedBy = shadowable.get(target);
124
+ if (!shadowedBy) continue;
125
+
126
+ violations.push(
127
+ `${relative(repoRoot, file)}: '${specifier}' resolves to ${target}/, ` +
128
+ `which a stale ${shadowedBy} would shadow — import '${specifier}/index' instead`
129
+ );
130
+ }
131
+ }
132
+
133
+ expect(violations).toEqual([]);
134
+ });
135
+ });
@@ -42,7 +42,11 @@ export type HostRequestKind =
42
42
  // Not a capability and never shown to anyone: the page reporting that Chrome
43
43
  // resized the renderer behind the emulation's back, so the host can put the
44
44
  // viewport it captures from back the way it was. Answered by the service.
45
- | 'viewport-restore';
45
+ | 'viewport-restore'
46
+ // Also not a capability: the page telling the host it is (or is no longer)
47
+ // showing something full screen, so the viewer can offer a way out that the
48
+ // page cannot lose. Answered by the service.
49
+ | 'fullscreen-state';
46
50
 
47
51
  export interface HostRequestEvent {
48
52
  tabId: string;
@@ -112,7 +116,9 @@ const REQUEST_TIMEOUT_MS: Record<HostRequestKind, number> = {
112
116
  'file-pick': 300_000,
113
117
  // Nobody is asked anything — this is the host talking to itself, and the page
114
118
  // is blocked on it while a screencast restarts.
115
- 'viewport-restore': 15_000
119
+ 'viewport-restore': 15_000,
120
+ // A one-way notification; the page does not wait on the answer.
121
+ 'fullscreen-state': 5_000
116
122
  };
117
123
 
118
124
  /**
@@ -78,6 +78,56 @@ export class BrowserInteractionHandler extends EventEmitter {
78
78
  browserMcpControl.emitCursorClick(sessionId, x, y, button);
79
79
  }
80
80
 
81
+ /**
82
+ * A few words for the caption beside the agent's pointer.
83
+ *
84
+ * Written from the watcher's side of the screen, not the agent's: it answers
85
+ * "what is happening to my page right now", so it names the gesture rather
86
+ * than the action type, and never carries a selector or the text being typed
87
+ * — a password would end up on screen, and the caption has room for about
88
+ * three words before it stops being a caption.
89
+ */
90
+ private describeActivity(action: BrowserAutonomousAction): string {
91
+ switch (action.type) {
92
+ case 'click':
93
+ return action.button === 'right' ? 'Opening a menu' : 'Clicking';
94
+ case 'long_press':
95
+ return 'Holding';
96
+ case 'move':
97
+ return 'Moving';
98
+ case 'drag':
99
+ return 'Dragging';
100
+ case 'scroll':
101
+ return 'Scrolling';
102
+ case 'type':
103
+ return action.text !== undefined ? 'Typing' : 'Pressing a key';
104
+ case 'press':
105
+ return `Pressing ${action.keys || action.key}`;
106
+ case 'paste':
107
+ return 'Pasting';
108
+ case 'focus':
109
+ return 'Selecting a field';
110
+ case 'clear':
111
+ return 'Clearing a field';
112
+ case 'select_option':
113
+ return 'Choosing an option';
114
+ case 'upload':
115
+ return 'Attaching a file';
116
+ case 'tap':
117
+ return 'Tapping';
118
+ case 'swipe':
119
+ return 'Swiping';
120
+ case 'pinch':
121
+ return 'Zooming';
122
+ case 'extract_data':
123
+ return 'Reading the page';
124
+ case 'wait':
125
+ return 'Waiting';
126
+ default:
127
+ return 'Working';
128
+ }
129
+ }
130
+
81
131
  // MCP-optimized mouse movement with smooth curves and ease-out easing
82
132
  private async mcpMouseMove(
83
133
  page: Page,
@@ -382,6 +432,25 @@ export class BrowserInteractionHandler extends EventEmitter {
382
432
  isValidSession: () => boolean
383
433
  ): Promise<AutonomousRunOutcome> {
384
434
  const results: BrowserActionResult[] = [];
435
+
436
+ try {
437
+ return await this.runBatch(sessionId, session, actions, isValidSession, results);
438
+ } finally {
439
+ // The agent keeps the tab between batches, so the pointer stays — but
440
+ // it is no longer doing the last thing it said it was, and a caption
441
+ // left reading "Typing" over a page nothing is typing into is worse
442
+ // than no caption at all.
443
+ browserMcpControl.emitActivity(sessionId, null);
444
+ }
445
+ }
446
+
447
+ private async runBatch(
448
+ sessionId: string,
449
+ session: BrowserTab,
450
+ actions: BrowserAutonomousAction[],
451
+ isValidSession: () => boolean,
452
+ results: BrowserActionResult[]
453
+ ): Promise<AutonomousRunOutcome> {
385
454
  const page = session.page;
386
455
 
387
456
  // Store session ID on page for cursor tracking
@@ -402,6 +471,7 @@ export class BrowserInteractionHandler extends EventEmitter {
402
471
  }
403
472
 
404
473
  const action = actions[i];
474
+ browserMcpControl.emitActivity(sessionId, this.describeActivity(action));
405
475
 
406
476
  try {
407
477
  const outcome = await this.runAction(sessionId, session, action);
@@ -41,8 +41,32 @@ export interface McpControlEvent {
41
41
  timestamp: number;
42
42
  }
43
43
 
44
+ /**
45
+ * Which of a project's locked tabs the agent is working on right now.
46
+ *
47
+ * A session accumulates tabs, and a lock says only "hands off". With several
48
+ * locked at once that leaves the user unable to tell where the agent actually
49
+ * is — they can watch any tab freely, but not know which one to watch.
50
+ * `browserTabId` is null when the project has no focused tab any more.
51
+ */
52
+ export interface McpFocusEvent {
53
+ browserTabId: string | null;
54
+ projectId: string;
55
+ chatSessionId?: string;
56
+ timestamp: number;
57
+ }
58
+
59
+ /** Answers "does this chat session still have a stream running?". */
60
+ export type SessionLivenessProbe = (chatSessionId: string) => boolean;
61
+
44
62
  export interface McpCursorEvent {
45
63
  tabId: string;
64
+ /**
65
+ * Owning project. Tab ids repeat across projects (`tab-1` exists in every
66
+ * one), so a cursor broadcast to all of them could be drawn over a
67
+ * same-numbered tab in a project the agent has never touched.
68
+ */
69
+ projectId?: string;
46
70
  x: number;
47
71
  y: number;
48
72
  /** Mouse button held down — the difference between a move and a drag. */
@@ -53,6 +77,7 @@ export interface McpCursorEvent {
53
77
 
54
78
  export interface McpClickEvent {
55
79
  tabId: string;
80
+ projectId?: string;
56
81
  x: number;
57
82
  y: number;
58
83
  button?: 'left' | 'right' | 'middle';
@@ -60,6 +85,24 @@ export interface McpClickEvent {
60
85
  source: 'mcp';
61
86
  }
62
87
 
88
+ /**
89
+ * What the agent is doing on a tab, in the user's words.
90
+ *
91
+ * The pointer alone says "something else is driving this" and nothing more,
92
+ * which is the wrong amount of information for a run that can hold a tab for
93
+ * minutes: a page changing on its own with a nameless cursor on it reads as a
94
+ * glitch. `label` is a two-or-three-word gloss of the action about to run —
95
+ * "Typing", "Clicking", "Navigating" — and rides next to the cursor.
96
+ *
97
+ * `null` means the agent still holds the tab but is between actions.
98
+ */
99
+ export interface McpActivityEvent {
100
+ tabId: string;
101
+ projectId?: string;
102
+ label: string | null;
103
+ timestamp: number;
104
+ }
105
+
63
106
  export class BrowserMcpControl extends EventEmitter {
64
107
  /** Tab → ownership info (which chat session controls it) */
65
108
  private tabOwnership = new Map<string, TabOwnershipInfo>();
@@ -67,6 +110,23 @@ export class BrowserMcpControl extends EventEmitter {
67
110
  /** Chat session → set of tab IDs it controls */
68
111
  private sessionTabs = new Map<string, Set<string>>();
69
112
 
113
+ /** Project → the tab its controlling agent is pointed at right now. */
114
+ private focusedTabs = new Map<string, string>();
115
+
116
+ /** Tab → what the agent is doing on it, for the cursor's caption. */
117
+ private tabActivity = new Map<string, string>();
118
+
119
+ /**
120
+ * Whether the stream that owns a lock is still running.
121
+ *
122
+ * Registered by the chat stream manager. Without it a tool call that lands
123
+ * after its stream ended — the remote-MCP transports resolve their session
124
+ * from "most recent active stream", so a late call can name a session that
125
+ * has already been released — filed a lock under an owner nobody would ever
126
+ * release, and the tab stayed locked until the server restarted.
127
+ */
128
+ private livenessProbe: SessionLivenessProbe | null = null;
129
+
70
130
  // Pending tab requests (keyed by request type + timestamp)
71
131
  private pendingTabRequests = new Map<string, PendingTabRequest>();
72
132
  private requestCounter = 0;
@@ -93,6 +153,47 @@ export class BrowserMcpControl extends EventEmitter {
93
153
  debug.log('mcp', '🔗 Browser MCP Control initialized with event-based tab tracking');
94
154
  }
95
155
 
156
+ /**
157
+ * Teach this manager which chat sessions are still streaming.
158
+ *
159
+ * Called once by the chat stream manager. Absent, every session reads as
160
+ * live — the previous behaviour, which is the safe default for anything
161
+ * that constructs this without a chat layer (tests, tooling).
162
+ */
163
+ setSessionLivenessProbe(probe: SessionLivenessProbe): void {
164
+ this.livenessProbe = probe;
165
+ }
166
+
167
+ /** Whether a chat session is still streaming (true when no probe is set). */
168
+ isSessionLive(chatSessionId: string): boolean {
169
+ return this.livenessProbe ? this.livenessProbe(chatSessionId) : true;
170
+ }
171
+
172
+ /**
173
+ * Release every tab whose owning session has stopped streaming.
174
+ *
175
+ * The belt to `releaseSession`'s braces. Release is driven by the stream's
176
+ * terminal events, so anything that never reaches one — a lock acquired
177
+ * during the teardown window, an interrupt that took an unusual path —
178
+ * leaves ownership behind with nothing to collect it. Sweeping is cheap
179
+ * (the map holds a handful of entries) and makes a stuck lock recover on
180
+ * the next stream event or tab query instead of at the next restart.
181
+ */
182
+ releaseOrphans(): number {
183
+ if (!this.livenessProbe) return 0;
184
+
185
+ const orphans = [...this.tabOwnership.entries()]
186
+ .filter(([, info]) => !this.isSessionLive(info.chatSessionId))
187
+ .map(([tabId]) => tabId);
188
+
189
+ for (const tabId of orphans) {
190
+ debug.warn('mcp', `🧹 Releasing orphaned tab ${tabId} — its chat session is no longer streaming`);
191
+ this.releaseTab(tabId);
192
+ }
193
+
194
+ return orphans.length;
195
+ }
196
+
96
197
  /**
97
198
  * Handle tab destroyed event
98
199
  * Auto-release control for the destroyed tab only
@@ -224,6 +325,11 @@ export class BrowserMcpControl extends EventEmitter {
224
325
  sessionSet.delete(browserTabId);
225
326
  sessionSet.add(browserTabId);
226
327
  debug.log('mcp', `🔀 Promoted tab ${browserTabId} to end of session ${chatSessionId.slice(0, 8)} set`);
328
+
329
+ // The agent just changed where it is working; the focus marker is
330
+ // what tells the user that, so it moves with the promotion.
331
+ const projectId = this.tabOwnership.get(browserTabId)?.projectId;
332
+ if (projectId) this.focusTab(browserTabId, chatSessionId, projectId);
227
333
  }
228
334
  }
229
335
 
@@ -235,12 +341,21 @@ export class BrowserMcpControl extends EventEmitter {
235
341
  * - If the tab is free → acquire and add to session's controlled set
236
342
  */
237
343
  acquireControl(browserTabId: string, chatSessionId: string, projectId: string): boolean {
344
+ // A cancelled stream can still have a tool call in flight. Letting it
345
+ // take the lock re-locks a tab that was just handed back, and files the
346
+ // lock under an owner whose release already ran.
347
+ if (!this.isSessionLive(chatSessionId)) {
348
+ debug.warn('mcp', `❌ Session ${chatSessionId.slice(0, 8)} is no longer streaming, refusing control of ${browserTabId}`);
349
+ return false;
350
+ }
351
+
238
352
  // Check existing ownership
239
353
  const existingOwner = this.tabOwnership.get(browserTabId);
240
354
 
241
355
  if (existingOwner) {
242
356
  // Same session already owns it → idempotent success
243
357
  if (existingOwner.chatSessionId === chatSessionId) {
358
+ this.focusTab(browserTabId, chatSessionId, projectId);
244
359
  return true;
245
360
  }
246
361
  // Different session owns it → denied
@@ -266,11 +381,65 @@ export class BrowserMcpControl extends EventEmitter {
266
381
 
267
382
  // Emit control start event to frontend
268
383
  this.emitControlStart(browserTabId, chatSessionId, projectId);
384
+ this.focusTab(browserTabId, chatSessionId, projectId);
269
385
 
270
386
  debug.log('mcp', `🎮 Session ${chatSessionId.slice(0, 8)} acquired tab: ${browserTabId} (total: ${sessionSet.size} tabs)`);
271
387
  return true;
272
388
  }
273
389
 
390
+ // ============================================================================
391
+ // Focus
392
+ // ============================================================================
393
+
394
+ /**
395
+ * Mark the tab the agent is acting on. Idempotent and quiet when unchanged —
396
+ * it is called on every action, and only a change is worth telling the UI.
397
+ */
398
+ focusTab(browserTabId: string, chatSessionId: string, projectId: string): void {
399
+ if (this.focusedTabs.get(projectId) === browserTabId) return;
400
+
401
+ this.focusedTabs.set(projectId, browserTabId);
402
+ this.emitFocus(browserTabId, projectId, chatSessionId);
403
+ }
404
+
405
+ /** The tab a project's agent is currently pointed at, if any. */
406
+ getFocusedTab(projectId: string): string | null {
407
+ return this.focusedTabs.get(projectId) ?? null;
408
+ }
409
+
410
+ /**
411
+ * Re-derive a project's focus after ownership changed.
412
+ *
413
+ * Falls back to another tab the *same* session still holds, so a batch that
414
+ * closed the tab it was working on lands the marker where the work went
415
+ * rather than nowhere — and never onto a tab a different session owns,
416
+ * which would point the user at the wrong agent. Emits nothing when the
417
+ * focused tab is still held, so releasing several tabs at once produces one
418
+ * update rather than a burst.
419
+ */
420
+ private refreshFocus(projectId: string | undefined): void {
421
+ if (!projectId) return;
422
+
423
+ const focused = this.focusedTabs.get(projectId);
424
+ if (!focused) return;
425
+
426
+ const owner = this.tabOwnership.get(focused);
427
+ if (owner && owner.projectId === projectId) return; // Still held — nothing to say.
428
+
429
+ const successor = [...this.tabOwnership.entries()]
430
+ .reverse()
431
+ .find(([, info]) => info.projectId === projectId);
432
+
433
+ if (successor) {
434
+ this.focusedTabs.set(projectId, successor[0]);
435
+ this.emitFocus(successor[0], projectId, successor[1].chatSessionId);
436
+ return;
437
+ }
438
+
439
+ this.focusedTabs.delete(projectId);
440
+ this.emitFocus(null, projectId);
441
+ }
442
+
274
443
  // ============================================================================
275
444
  // Control Release
276
445
  // ============================================================================
@@ -295,8 +464,13 @@ export class BrowserMcpControl extends EventEmitter {
295
464
  }
296
465
  }
297
466
 
467
+ // Before the control-end, so the caption cannot outlive the cursor it
468
+ // belongs to on a viewer that processes the two in order.
469
+ this.emitActivity(browserTabId, null, ownership.projectId);
470
+
298
471
  // Emit control end event to frontend
299
472
  this.emitControlEnd(browserTabId, ownership.projectId);
473
+ this.refreshFocus(ownership.projectId);
300
474
 
301
475
  debug.log('mcp', `🎮 Released tab: ${browserTabId} (was owned by session ${ownership.chatSessionId.slice(0, 8)})`);
302
476
  }
@@ -307,23 +481,31 @@ export class BrowserMcpControl extends EventEmitter {
307
481
  */
308
482
  releaseSession(chatSessionId: string): void {
309
483
  const sessionSet = this.sessionTabs.get(chatSessionId);
310
- if (!sessionSet || sessionSet.size === 0) {
311
- this.sessionTabs.delete(chatSessionId);
312
- return;
313
- }
484
+ this.sessionTabs.delete(chatSessionId);
314
485
 
315
- const tabIds = Array.from(sessionSet);
316
- debug.log('mcp', `🎮 Releasing ${tabIds.length} tabs for session ${chatSessionId.slice(0, 8)}`);
486
+ const tabIds = Array.from(sessionSet ?? []);
487
+ if (tabIds.length > 0) {
488
+ debug.log('mcp', `🎮 Releasing ${tabIds.length} tabs for session ${chatSessionId.slice(0, 8)}`);
489
+
490
+ const projects = new Set<string>();
491
+ for (const tabId of tabIds) {
492
+ const ownership = this.tabOwnership.get(tabId);
493
+ this.tabOwnership.delete(tabId);
494
+ this.emitActivity(tabId, null, ownership?.projectId);
495
+ this.emitControlEnd(tabId, ownership?.projectId);
496
+ if (ownership?.projectId) projects.add(ownership.projectId);
497
+ }
317
498
 
318
- for (const tabId of tabIds) {
319
- const ownership = this.tabOwnership.get(tabId);
320
- this.tabOwnership.delete(tabId);
321
- this.emitControlEnd(tabId, ownership?.projectId);
322
- }
499
+ // After every deletion, so the successor search sees the final state
500
+ // rather than tabs that are about to go too.
501
+ for (const projectId of projects) this.refreshFocus(projectId);
323
502
 
324
- this.sessionTabs.delete(chatSessionId);
503
+ debug.log('mcp', `🎮 Session ${chatSessionId.slice(0, 8)} fully released`);
504
+ }
325
505
 
326
- debug.log('mcp', `🎮 Session ${chatSessionId.slice(0, 8)} fully released`);
506
+ // A tool call that acquired during this session's teardown is filed
507
+ // under an owner that is already gone; nothing else would collect it.
508
+ this.releaseOrphans();
327
509
  }
328
510
 
329
511
  /**
@@ -344,11 +526,18 @@ export class BrowserMcpControl extends EventEmitter {
344
526
  forceReleaseAll(): void {
345
527
  // Emit control-end for all controlled tabs
346
528
  for (const [tabId, info] of this.tabOwnership) {
529
+ this.emitActivity(tabId, null, info.projectId);
347
530
  this.emitControlEnd(tabId, info.projectId);
348
531
  }
349
532
 
533
+ for (const projectId of this.focusedTabs.keys()) {
534
+ this.emitFocus(null, projectId);
535
+ }
536
+
350
537
  this.tabOwnership.clear();
351
538
  this.sessionTabs.clear();
539
+ this.focusedTabs.clear();
540
+ this.tabActivity.clear();
352
541
 
353
542
  debug.log('mcp', '🧹 Force released all MCP control');
354
543
  }
@@ -363,6 +552,7 @@ export class BrowserMcpControl extends EventEmitter {
363
552
  emitCursorPosition(tabId: string, x: number, y: number, pressed = false): void {
364
553
  const event: McpCursorEvent = {
365
554
  tabId,
555
+ projectId: this.tabOwnership.get(tabId)?.projectId,
366
556
  x,
367
557
  y,
368
558
  pressed,
@@ -379,6 +569,7 @@ export class BrowserMcpControl extends EventEmitter {
379
569
  emitCursorClick(tabId: string, x: number, y: number, button: 'left' | 'right' | 'middle' = 'left'): void {
380
570
  const event: McpClickEvent = {
381
571
  tabId,
572
+ projectId: this.tabOwnership.get(tabId)?.projectId,
382
573
  x,
383
574
  y,
384
575
  button,
@@ -389,6 +580,36 @@ export class BrowserMcpControl extends EventEmitter {
389
580
  this.emit('cursor-click', event);
390
581
  }
391
582
 
583
+ /**
584
+ * Say what the agent is doing on a tab.
585
+ *
586
+ * Repeats are dropped: a batch of eight `type` actions would otherwise
587
+ * relabel the cursor eight times with the same word, and every one of those
588
+ * is a re-render on every viewer.
589
+ */
590
+ emitActivity(tabId: string, label: string | null, projectId?: string): void {
591
+ if ((this.tabActivity.get(tabId) ?? null) === label) return;
592
+
593
+ if (label === null) this.tabActivity.delete(tabId);
594
+ else this.tabActivity.set(tabId, label);
595
+
596
+ const event: McpActivityEvent = {
597
+ tabId,
598
+ // Explicit on release, where ownership has already been dropped and
599
+ // there is nothing left to look the project up in.
600
+ projectId: projectId ?? this.tabOwnership.get(tabId)?.projectId,
601
+ label,
602
+ timestamp: Date.now()
603
+ };
604
+
605
+ this.emit('activity', event);
606
+ }
607
+
608
+ /** What the agent last said it was doing on a tab, for a late-joining viewer. */
609
+ getActivity(tabId: string): string | null {
610
+ return this.tabActivity.get(tabId) ?? null;
611
+ }
612
+
392
613
  /**
393
614
  * Emit test completed event (hide virtual cursor)
394
615
  */
@@ -430,6 +651,19 @@ export class BrowserMcpControl extends EventEmitter {
430
651
 
431
652
  debug.log('mcp', `📢 Emitted mcp:control-end for tab: ${browserTabId}`);
432
653
  }
654
+
655
+ private emitFocus(browserTabId: string | null, projectId: string, chatSessionId?: string): void {
656
+ const event: McpFocusEvent = {
657
+ browserTabId,
658
+ projectId,
659
+ chatSessionId,
660
+ timestamp: Date.now()
661
+ };
662
+
663
+ this.emit('control-focus', event);
664
+
665
+ debug.log('mcp', `📢 Emitted mcp:control-focus for ${projectId}: ${browserTabId ?? 'none'}`);
666
+ }
433
667
  }
434
668
 
435
669
  // Singleton instance