@myrialabs/clopen 0.4.35 → 0.4.36

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 (82) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/host/metrics.test.ts +110 -0
  13. package/backend/host/metrics.ts +235 -0
  14. package/backend/index.ts +5 -2
  15. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  16. package/backend/ports/attribute.test.ts +3 -2
  17. package/backend/ports/attribute.ts +5 -44
  18. package/backend/preview/browser/browser-pool.ts +81 -0
  19. package/backend/preview/browser/browser-preview-service.ts +142 -32
  20. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  21. package/backend/preview/browser/types.ts +9 -0
  22. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  23. package/backend/projects/project-cleanup.ts +7 -1
  24. package/backend/projects/shell-ownership.ts +65 -0
  25. package/backend/snapshot/snapshot-service.ts +6 -2
  26. package/backend/terminal/ptykit.ts +35 -6
  27. package/backend/utils/ws.ts +21 -1
  28. package/backend/worktrees/clone.ts +222 -0
  29. package/backend/worktrees/index.ts +29 -0
  30. package/backend/worktrees/merge.test.ts +93 -0
  31. package/backend/worktrees/merge.ts +232 -0
  32. package/backend/worktrees/paths.test.ts +60 -0
  33. package/backend/worktrees/paths.ts +60 -0
  34. package/backend/worktrees/resolve.ts +67 -0
  35. package/backend/worktrees/service.ts +315 -0
  36. package/backend/worktrees/tree.ts +59 -0
  37. package/backend/ws/access.ts +18 -0
  38. package/backend/ws/artifacts/generate.ts +2 -2
  39. package/backend/ws/chat/stream.ts +9 -2
  40. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  41. package/backend/ws/files/path-access.test.ts +93 -1
  42. package/backend/ws/files/path-access.ts +54 -5
  43. package/backend/ws/files/read.ts +15 -10
  44. package/backend/ws/files/search.ts +7 -7
  45. package/backend/ws/files/state.ts +70 -8
  46. package/backend/ws/files/watch.ts +16 -14
  47. package/backend/ws/git/branch-name.ts +3 -3
  48. package/backend/ws/git/branch.ts +15 -15
  49. package/backend/ws/git/commit-message.ts +3 -3
  50. package/backend/ws/git/commit.ts +17 -17
  51. package/backend/ws/git/conflict.ts +10 -10
  52. package/backend/ws/git/diff.ts +9 -9
  53. package/backend/ws/git/ignored.ts +9 -9
  54. package/backend/ws/git/log.ts +3 -3
  55. package/backend/ws/git/remote.ts +43 -43
  56. package/backend/ws/git/staging.ts +16 -16
  57. package/backend/ws/git/status.ts +13 -13
  58. package/backend/ws/index.ts +4 -0
  59. package/backend/ws/preview/access.ts +11 -3
  60. package/backend/ws/projects/index.ts +5 -1
  61. package/backend/ws/projects/info.test.ts +54 -0
  62. package/backend/ws/projects/info.ts +398 -0
  63. package/backend/ws/sessions/crud.ts +21 -6
  64. package/backend/ws/snapshot/restore.ts +11 -14
  65. package/backend/ws/system/device-info.ts +62 -144
  66. package/backend/ws/worktrees/crud.ts +187 -0
  67. package/backend/ws/worktrees/index.ts +33 -0
  68. package/backend/ws/worktrees/transfer.ts +88 -0
  69. package/dist/assets/{index-B0iIhSO9.js → index-Bg-SUCFg.js} +1 -1
  70. package/dist/assets/{index-BRJqss6F.js → index-Cz4YpHVi.js} +1 -1
  71. package/dist/assets/main-9G7IpQpK.css +1 -0
  72. package/dist/assets/main-BofFsH8E.js +1085 -0
  73. package/dist/index.html +2 -2
  74. package/package.json +1 -1
  75. package/shared/types/database/schema.ts +26 -0
  76. package/shared/utils/logger.ts +1 -0
  77. package/shared/utils/workspace-scope.test.ts +80 -0
  78. package/shared/utils/workspace-scope.ts +57 -0
  79. package/shared/utils/ws-client.ts +25 -5
  80. package/shared/utils/ws-server.ts +19 -3
  81. package/dist/assets/main-Buko4D0t.css +0 -1
  82. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
2
  import type { PortProcess, PortSocket } from '$shared/types/ports';
3
- import { findClopenPids, groupListenerPids, traceAncestry, type SessionPid } from './attribute';
3
+ import { findClopenPids, groupListenerPids, traceAncestry } from './attribute';
4
+ import type { ProjectShell } from '../projects/shell-ownership';
4
5
  import { findConnectionSshd, parseEnvironProbe, sameConnection } from './ssh-lineage';
5
6
 
6
7
  function proc(pid: number, parentPid: number | null, command: string): PortProcess {
@@ -75,7 +76,7 @@ describe('groupListenerPids', () => {
75
76
  });
76
77
 
77
78
  describe('traceAncestry', () => {
78
- const sessions = new Map<number, SessionPid>([
79
+ const sessions = new Map<number, ProjectShell>([
79
80
  [400, { pid: 400, sessionId: 'sess-1', projectId: 'proj-1', projectName: 'shop', cwd: '/srv/shop' }]
80
81
  ]);
81
82
 
@@ -23,47 +23,8 @@
23
23
 
24
24
  import type { PortOrigin, PortProcess, PortSocket } from '$shared/types/ports';
25
25
  import type { ProbePlatform } from '../host/runner';
26
- import { ptyKitManager } from '../terminal/ptykit';
27
- import { projectQueries } from '../database/queries';
26
+ import { collectSessionPids, type ProjectShell } from '../projects/shell-ownership';
28
27
  import { collectOwnedPorts, ownedPortKey, type OwnedPort } from './registry';
29
- import { debug } from '$shared/utils/logger';
30
-
31
- /** A live Clopen terminal session, keyed by the pid of its shell. */
32
- export interface SessionPid {
33
- pid: number;
34
- sessionId: string;
35
- projectId: string;
36
- projectName: string | null;
37
- cwd: string;
38
- }
39
-
40
- /**
41
- * Shell pids of every active PTY session. The manager lists per namespace and
42
- * a namespace is a project, so every project is asked in turn.
43
- */
44
- export function collectSessionPids(): Map<number, SessionPid> {
45
- const sessions = new Map<number, SessionPid>();
46
-
47
- try {
48
- for (const project of projectQueries.getAll()) {
49
- for (const session of ptyKitManager.list(project.id)) {
50
- const info = session.info();
51
- if (info.status !== 'active' || !info.pid) continue;
52
- sessions.set(info.pid, {
53
- pid: info.pid,
54
- sessionId: info.sessionId,
55
- projectId: project.id,
56
- projectName: project.name ?? null,
57
- cwd: info.cwd
58
- });
59
- }
60
- }
61
- } catch (error) {
62
- debug.log('ports', 'could not read terminal sessions:', error);
63
- }
64
-
65
- return sessions;
66
- }
67
28
 
68
29
  /** Guard against a malformed parent chain looping forever. */
69
30
  const MAX_ANCESTRY_DEPTH = 40;
@@ -118,7 +79,7 @@ export interface Ancestry {
118
79
  /** The chain from the process itself up to init, self first. */
119
80
  chain: PortProcess[];
120
81
  /** The Clopen terminal session it descends from, if any. */
121
- session: SessionPid | null;
82
+ session: ProjectShell | null;
122
83
  /**
123
84
  * True when the chain reaches a process Clopen is: one of its own instances
124
85
  * locally, or the sshd session it is using on a remote host.
@@ -137,13 +98,13 @@ function sshdUserOf(command: string): string | null {
137
98
  export function traceAncestry(
138
99
  pid: number,
139
100
  processes: Map<number, PortProcess>,
140
- sessions: Map<number, SessionPid>,
101
+ sessions: Map<number, ProjectShell>,
141
102
  clopenRootPids: ReadonlySet<number> = new Set()
142
103
  ): Ancestry {
143
104
  const chain: PortProcess[] = [];
144
105
  const seen = new Set<number>();
145
106
 
146
- let session: SessionPid | null = null;
107
+ let session: ProjectShell | null = null;
147
108
  let sshdUser: string | null = null;
148
109
  let fromClopen = false;
149
110
  let current: number | null = pid;
@@ -218,7 +179,7 @@ export interface AttributionContext {
218
179
  /** Ports Clopen opened on this host, whichever host it is. */
219
180
  owned: Map<string, OwnedPort>;
220
181
  /** Shell pids of local terminal sessions; empty on an SSH host. */
221
- sessions: Map<number, SessionPid>;
182
+ sessions: Map<number, ProjectShell>;
222
183
  /**
223
184
  * The processes that count as "Clopen" on this host: its own instances
224
185
  * locally, and remotely everything found to belong to Clopen's own SSH
@@ -129,12 +129,23 @@ function shouldDisableGpu(): boolean {
129
129
 
130
130
  const CHROME_ARGS = buildChromeArgs();
131
131
 
132
+ /**
133
+ * How long the shared browser stays up with no sessions left.
134
+ *
135
+ * Long enough that closing a tab and opening another does not pay for a
136
+ * relaunch, short enough that a machine is not left running a headless Chrome
137
+ * nobody is using. Chrome is only reachable through sessions, so once the last
138
+ * one goes the browser has no work left to do.
139
+ */
140
+ const IDLE_BROWSER_CLOSE_MS = 60_000;
141
+
132
142
  class BrowserPool {
133
143
  private browser: Browser | null = null;
134
144
  private sessions = new Map<string, PooledSession>();
135
145
  private config: PoolConfig;
136
146
  private isLaunching = false;
137
147
  private launchPromise: Promise<Browser> | null = null;
148
+ private idleCloseTimer: ReturnType<typeof setTimeout> | null = null;
138
149
 
139
150
  constructor(config: Partial<PoolConfig> = {}) {
140
151
  this.config = { ...DEFAULT_CONFIG, ...config };
@@ -146,6 +157,8 @@ class BrowserPool {
146
157
  * StealthPlugin hooks fire for every page created.
147
158
  */
148
159
  async getBrowser(): Promise<Browser> {
160
+ this.cancelIdleClose();
161
+
149
162
  if (this.browser?.connected) {
150
163
  return this.browser;
151
164
  }
@@ -206,6 +219,8 @@ class BrowserPool {
206
219
  * Each context has separate cookies, localStorage, sessionStorage, and cache.
207
220
  */
208
221
  async createSession(sessionId: string): Promise<PooledSession> {
222
+ this.cancelIdleClose();
223
+
209
224
  const existing = this.sessions.get(sessionId);
210
225
  if (existing) {
211
226
  debug.log('preview', `♻️ Reusing existing session: ${sessionId}`);
@@ -235,6 +250,37 @@ class BrowserPool {
235
250
  return session;
236
251
  }
237
252
 
253
+ /**
254
+ * Give a session a fresh page, reusing its context where the context lived.
255
+ *
256
+ * A crashed renderer takes the page but usually leaves the BrowserContext —
257
+ * and with it the cookies, localStorage and cache the tab has built up.
258
+ * Rebuilding the whole session would quietly sign the user out of whatever
259
+ * they were looking at, so the context is only recreated when it is really
260
+ * gone (the browser died, or it refuses to hand out a page).
261
+ */
262
+ async renewSessionPage(sessionId: string): Promise<PooledSession> {
263
+ this.cancelIdleClose();
264
+
265
+ const existing = this.sessions.get(sessionId);
266
+ if (existing && this.browser?.connected) {
267
+ try {
268
+ const page = await existing.context.newPage();
269
+ if (!existing.page.isClosed()) {
270
+ await existing.page.close().catch(() => {});
271
+ }
272
+ existing.page = page;
273
+ debug.log('preview', `♻️ Session ${sessionId}: new page in the surviving context`);
274
+ return existing;
275
+ } catch (error) {
276
+ debug.warn('preview', `⚠️ Context for ${sessionId} could not hand out a page: ${error}`);
277
+ }
278
+ }
279
+
280
+ await this.destroySession(sessionId);
281
+ return this.createSession(sessionId);
282
+ }
283
+
238
284
  /**
239
285
  * Get an existing session
240
286
  */
@@ -276,6 +322,40 @@ class BrowserPool {
276
322
 
277
323
  this.sessions.delete(sessionId);
278
324
  debug.log('preview', `✅ Session destroyed (remaining: ${this.sessions.size})`);
325
+
326
+ this.scheduleIdleClose();
327
+ }
328
+
329
+ /**
330
+ * Close the shared browser once nothing has referenced it for a while.
331
+ *
332
+ * The pool outlives every individual project — no single workspace may
333
+ * close it — so idleness is the only safe trigger left.
334
+ */
335
+ private scheduleIdleClose(): void {
336
+ this.cancelIdleClose();
337
+ if (this.sessions.size > 0 || !this.browser) return;
338
+
339
+ this.idleCloseTimer = setTimeout(() => {
340
+ this.idleCloseTimer = null;
341
+ if (this.sessions.size > 0) return;
342
+
343
+ const browser = this.browser;
344
+ this.browser = null;
345
+ debug.log('preview', '💤 No sessions left, closing the shared browser');
346
+ browser?.close().catch((error) => {
347
+ debug.warn('preview', `⚠️ Error closing idle browser: ${error}`);
348
+ });
349
+ }, IDLE_BROWSER_CLOSE_MS);
350
+
351
+ // Nothing here should hold the process open on its own.
352
+ this.idleCloseTimer.unref?.();
353
+ }
354
+
355
+ private cancelIdleClose(): void {
356
+ if (!this.idleCloseTimer) return;
357
+ clearTimeout(this.idleCloseTimer);
358
+ this.idleCloseTimer = null;
279
359
  }
280
360
 
281
361
  /**
@@ -310,6 +390,7 @@ class BrowserPool {
310
390
  */
311
391
  async cleanup(): Promise<void> {
312
392
  debug.log('preview', '🧹 Cleaning up browser pool...');
393
+ this.cancelIdleClose();
313
394
 
314
395
  const sessionIds = Array.from(this.sessions.keys());
315
396
  await Promise.all(sessionIds.map((id) => this.destroySession(id)));
@@ -9,9 +9,11 @@ import { BrowserDialogHandler } from './browser-dialog-handler.js';
9
9
  import { BrowserNativeUIHandler } from './browser-native-ui-handler.js';
10
10
  import { BrowserHostBridge, type HostResponse } from './browser-host-bridge.js';
11
11
  import { browserMcpControl } from './browser-mcp-control.js';
12
+ import { browserPool } from './browser-pool.js';
12
13
  import { ws } from '$backend/utils/ws';
13
14
  import { getViewportDimensions } from '$shared/constants/preview.js';
14
15
  import { debug } from '$shared/utils/logger';
16
+ import { scopeProjectId } from '$shared/utils/workspace-scope';
15
17
  import type {
16
18
  BrowserTab,
17
19
  BrowserTabInfo,
@@ -59,6 +61,15 @@ export class BrowserPreviewService extends EventEmitter {
59
61
  /** Tabs whose page is showing something full screen — see applyFullscreenState. */
60
62
  private fullscreenTabs = new Set<string>();
61
63
 
64
+ /**
65
+ * Page rebuilds in flight, per tab.
66
+ *
67
+ * A dead page is noticed by whatever touches the tab first — the stream's
68
+ * frame guard, the tab list, an MCP action — and often by several of them
69
+ * at once, so the first one to ask owns the rebuild and the rest wait on it.
70
+ */
71
+ private tabRecoveries = new Map<string, Promise<boolean>>();
72
+
62
73
  // Project ID for isolation (REQUIRED)
63
74
  private projectId: string;
64
75
 
@@ -179,6 +190,12 @@ export class BrowserPreviewService extends EventEmitter {
179
190
  this.tabManager.on('preview:browser-tab-switched', (data) => {
180
191
  this.emit('preview:browser-tab-switched', data);
181
192
  });
193
+
194
+ // A tab whose page died. The tab manager can replace the page but not
195
+ // the per-page state layered on top of it, so the rebuild is owned here.
196
+ this.tabManager.on('preview:browser-tab-unhealthy', (data: { tabId: string; reason: string }) => {
197
+ if (data?.tabId) void this.recoverTab(data.tabId, data.reason);
198
+ });
182
199
  this.tabManager.on('preview:browser-tab-navigated', (data) => {
183
200
  this.emit('preview:browser-tab-navigated', data);
184
201
  });
@@ -314,6 +331,87 @@ export class BrowserPreviewService extends EventEmitter {
314
331
  return tab;
315
332
  }
316
333
 
334
+ /**
335
+ * Rebuild a tab whose page died, in place.
336
+ *
337
+ * A crashed renderer, a Chrome that went away, a page a site closed on
338
+ * itself: every one of these used to delete the tab, which is how a preview
339
+ * could disappear mid-session — while an agent was driving it, even — with
340
+ * nobody having closed anything. The tab keeps its id, its slot in the strip
341
+ * and its URL; only the page underneath is replaced.
342
+ *
343
+ * Viewers are told about it as a navigation, because that is exactly what it
344
+ * looks like from their side and they already know how to restart a stream
345
+ * across one.
346
+ */
347
+ async recoverTab(tabId: string, reason = 'page-gone'): Promise<boolean> {
348
+ const inFlight = this.tabRecoveries.get(tabId);
349
+ if (inFlight) return inFlight;
350
+
351
+ const run = this.rebuildTab(tabId, reason).finally(() => {
352
+ this.tabRecoveries.delete(tabId);
353
+ });
354
+ this.tabRecoveries.set(tabId, run);
355
+
356
+ return run;
357
+ }
358
+
359
+ private async rebuildTab(tabId: string, reason: string): Promise<boolean> {
360
+ const before = this.tabManager.peekTab(tabId);
361
+ if (!before || before.isDestroyed) return false;
362
+
363
+ debug.warn('preview', `♻️ Rebuilding tab ${tabId} after ${reason}`);
364
+
365
+ this.emit('preview:browser-navigation-loading', {
366
+ sessionId: tabId,
367
+ type: 'recovery',
368
+ url: before.url,
369
+ timestamp: Date.now()
370
+ });
371
+
372
+ // Everything below is bound to the page that died — bindings, injected
373
+ // scripts, the CDP sessions behind navigation tracking and the host
374
+ // bridge. All of it is re-applied against the new page.
375
+ await this.videoCapture.stopStreaming(tabId).catch(() => {});
376
+ this.videoCapture.disposeTab(tabId);
377
+ await this.navigationTracker.cleanupSession(tabId).catch(() => {});
378
+ await this.hostBridge.teardown(tabId).catch(() => {});
379
+ this.fullscreenTabs.delete(tabId);
380
+
381
+ let tab: BrowserTab | null;
382
+ try {
383
+ tab = await this.tabManager.respawnPage(tabId);
384
+ } catch (error) {
385
+ // Left in place on purpose: the tab stays in the strip and the next
386
+ // read of it asks for another rebuild, so a host that is briefly out
387
+ // of memory recovers on its own instead of losing the tab.
388
+ debug.error('preview', `❌ Rebuild failed for tab ${tabId}:`, error);
389
+ return false;
390
+ }
391
+ if (!tab) return false;
392
+
393
+ await Promise.all([
394
+ this.consoleManager.setupConsoleLogging(tab.id, tab.page, tab),
395
+ this.navigationTracker.setupNavigationTracking(tab.id, tab.page, tab)
396
+ ]);
397
+
398
+ this.videoCapture.preInjectScripts(tab.id, tab).catch(() => {});
399
+
400
+ await this.captureHistoryBase(tab.id);
401
+ void this.refreshTabMeta(tab.id);
402
+
403
+ this.emit('preview:browser-navigation', {
404
+ sessionId: tabId,
405
+ type: 'recovery',
406
+ url: tab.url,
407
+ timestamp: Date.now()
408
+ });
409
+
410
+ debug.log('preview', `✅ Tab ${tabId} rebuilt at ${tab.url}`);
411
+
412
+ return true;
413
+ }
414
+
317
415
  /**
318
416
  * Navigate tab to a new URL
319
417
  */
@@ -1028,7 +1126,8 @@ export class BrowserPreviewService extends EventEmitter {
1028
1126
  this.interactionHandler.clearAllSessionCursors();
1029
1127
  // Release host-bridge scratch dirs and unblock any parked page promises
1030
1128
  await this.hostBridge.cleanup();
1031
- // Cleanup tabs (this will also cleanup all contexts/pages/browser pool)
1129
+ // Cleanup tabs (contexts and pages go with them). The shared browser
1130
+ // pool is deliberately left alone — it is one Chrome for every project.
1032
1131
  await this.tabManager.cleanup();
1033
1132
  }
1034
1133
 
@@ -1107,13 +1206,18 @@ class BrowserPreviewServiceManager {
1107
1206
  private setupWebSocketForwarding(service: BrowserPreviewService, projectId: string): void {
1108
1207
  debug.log('preview', `🔌 Setting up WebSocket forwarding for project: ${projectId}...`);
1109
1208
 
1209
+ // `projectId` is a workspace scope key: it separates a worktree's tabs from
1210
+ // the main tree's. Rooms are keyed by the real project, so events go there
1211
+ // and each client filters on the scope carried in the payload.
1212
+ const roomId = scopeProjectId(projectId);
1213
+
1110
1214
  // Forward WebCodecs events.
1111
1215
  //
1112
1216
  // The room is the whole project, so several viewers of the same tab all
1113
1217
  // receive these. `viewerId` is what lets each of them recognise the half
1114
1218
  // of the handshake that is theirs.
1115
1219
  service.on('preview:browser-webcodecs-ice-candidate', (data) => {
1116
- ws.emit.project(projectId, 'preview:browser-stream-ice', {
1220
+ ws.emit.project(roomId, 'preview:browser-stream-ice', {
1117
1221
  sessionId: data.sessionId,
1118
1222
  viewerId: data.viewerId,
1119
1223
  candidate: data.candidate,
@@ -1122,25 +1226,25 @@ class BrowserPreviewServiceManager {
1122
1226
  });
1123
1227
 
1124
1228
  service.on('preview:browser-webcodecs-connection-state', (data) => {
1125
- ws.emit.project(projectId, 'preview:browser-stream-state', data);
1229
+ ws.emit.project(roomId, 'preview:browser-stream-state', data);
1126
1230
  });
1127
1231
 
1128
1232
  service.on('preview:browser-cursor-change', (data) => {
1129
- ws.emit.project(projectId, 'preview:browser-cursor-change', data);
1233
+ ws.emit.project(roomId, 'preview:browser-cursor-change', data);
1130
1234
  });
1131
1235
 
1132
1236
  // Forward navigation events
1133
1237
  service.on('preview:browser-navigation-loading', (data) => {
1134
- ws.emit.project(projectId, 'preview:browser-navigation-loading', data);
1238
+ ws.emit.project(roomId, 'preview:browser-navigation-loading', data);
1135
1239
  });
1136
1240
 
1137
1241
  service.on('preview:browser-navigation', (data) => {
1138
- ws.emit.project(projectId, 'preview:browser-navigation', data);
1242
+ ws.emit.project(roomId, 'preview:browser-navigation', data);
1139
1243
  });
1140
1244
 
1141
1245
  // Forward SPA navigation events (pushState/replaceState — URL-only update)
1142
1246
  service.on('preview:browser-navigation-spa', (data) => {
1143
- ws.emit.project(projectId, 'preview:browser-navigation-spa', data);
1247
+ ws.emit.project(roomId, 'preview:browser-navigation-spa', data);
1144
1248
  });
1145
1249
 
1146
1250
  // Forward tab events. Each carries projectId so the frontend can drop
@@ -1149,113 +1253,113 @@ class BrowserPreviewServiceManager {
1149
1253
  // project the user is now viewing.
1150
1254
  service.on('preview:browser-tab-opened', (data) => {
1151
1255
  debug.log('preview', `🚀 Forwarding preview:browser-tab-opened to project ${projectId}:`, data);
1152
- ws.emit.project(projectId, 'preview:browser-tab-opened', { ...data, projectId });
1256
+ ws.emit.project(roomId, 'preview:browser-tab-opened', { ...data, projectId });
1153
1257
  });
1154
1258
 
1155
1259
  service.on('preview:browser-tab-closed', (data) => {
1156
- ws.emit.project(projectId, 'preview:browser-tab-closed', { ...data, projectId });
1260
+ ws.emit.project(roomId, 'preview:browser-tab-closed', { ...data, projectId });
1157
1261
  });
1158
1262
 
1159
1263
  service.on('preview:browser-tab-switched', (data) => {
1160
- ws.emit.project(projectId, 'preview:browser-tab-switched', { ...data, projectId });
1264
+ ws.emit.project(roomId, 'preview:browser-tab-switched', { ...data, projectId });
1161
1265
  });
1162
1266
 
1163
1267
  service.on('preview:browser-tab-navigated', (data) => {
1164
- ws.emit.project(projectId, 'preview:browser-tab-navigated', { ...data, projectId });
1268
+ ws.emit.project(roomId, 'preview:browser-tab-navigated', { ...data, projectId });
1165
1269
  });
1166
1270
 
1167
1271
  service.on('preview:browser-viewport-changed', (data) => {
1168
- ws.emit.project(projectId, 'preview:browser-viewport-changed', { ...data, projectId });
1272
+ ws.emit.project(roomId, 'preview:browser-viewport-changed', { ...data, projectId });
1169
1273
  });
1170
1274
 
1171
1275
  service.on('preview:browser-fullscreen-state', (data) => {
1172
- ws.emit.project(projectId, 'preview:browser-fullscreen-state', { ...data, projectId });
1276
+ ws.emit.project(roomId, 'preview:browser-fullscreen-state', { ...data, projectId });
1173
1277
  });
1174
1278
 
1175
1279
  // Forward live tab metadata (title, favicon, back/forward availability)
1176
1280
  service.on('preview:browser-tab-meta', (data) => {
1177
- ws.emit.project(projectId, 'preview:browser-tab-meta', { ...data, projectId });
1281
+ ws.emit.project(roomId, 'preview:browser-tab-meta', { ...data, projectId });
1178
1282
  });
1179
1283
 
1180
1284
  // Forward host-capability requests (geolocation, camera, clipboard, …)
1181
1285
  // and relayed downloads — both are answered by the viewer's own browser.
1182
1286
  service.on('preview:browser-host-request', (data) => {
1183
- ws.emit.project(projectId, 'preview:browser-host-request', data);
1287
+ ws.emit.project(roomId, 'preview:browser-host-request', data);
1184
1288
  });
1185
1289
 
1186
1290
  // Answered (or expired) — every viewer that was shown this prompt drops it.
1187
1291
  service.on('preview:browser-host-request-settled', (data) => {
1188
- ws.emit.project(projectId, 'preview:browser-host-request-settled', data);
1292
+ ws.emit.project(roomId, 'preview:browser-host-request-settled', data);
1189
1293
  });
1190
1294
 
1191
1295
  service.on('preview:browser-download', (data) => {
1192
- ws.emit.project(projectId, 'preview:browser-download', data);
1296
+ ws.emit.project(roomId, 'preview:browser-download', data);
1193
1297
  });
1194
1298
 
1195
1299
  // Forward console events
1196
1300
  service.on('preview:browser-console-message', (data) => {
1197
- ws.emit.project(projectId, 'preview:browser-console-message', data);
1301
+ ws.emit.project(roomId, 'preview:browser-console-message', data);
1198
1302
  });
1199
1303
 
1200
1304
  service.on('preview:browser-console-clear', (data) => {
1201
- ws.emit.project(projectId, 'preview:browser-console-clear', data);
1305
+ ws.emit.project(roomId, 'preview:browser-console-clear', data);
1202
1306
  });
1203
1307
 
1204
1308
  // Forward dialog events
1205
1309
  service.on('preview:browser-dialog', (data) => {
1206
- ws.emit.project(projectId, 'preview:browser-dialog', data);
1310
+ ws.emit.project(roomId, 'preview:browser-dialog', data);
1207
1311
  });
1208
1312
 
1209
1313
  // A dialog belongs to the page, not to whoever answered it: every viewer
1210
1314
  // was shown the same prompt, so all of them are told it is settled.
1211
1315
  service.on('preview:browser-dialog-closed', (data) => {
1212
- ws.emit.project(projectId, 'preview:browser-dialog-closed', data);
1316
+ ws.emit.project(roomId, 'preview:browser-dialog-closed', data);
1213
1317
  });
1214
1318
 
1215
1319
  service.on('preview:browser-print', (data) => {
1216
- ws.emit.project(projectId, 'preview:browser-print', data);
1320
+ ws.emit.project(roomId, 'preview:browser-print', data);
1217
1321
  });
1218
1322
 
1219
1323
  // Forward native UI events
1220
1324
  service.on('preview:browser-native-picker', (data) => {
1221
- ws.emit.project(projectId, 'preview:browser-native-picker', data);
1325
+ ws.emit.project(roomId, 'preview:browser-native-picker', data);
1222
1326
  });
1223
1327
 
1224
1328
  service.on('preview:browser-select', (data) => {
1225
- ws.emit.project(projectId, 'preview:browser-select', data);
1329
+ ws.emit.project(roomId, 'preview:browser-select', data);
1226
1330
  });
1227
1331
 
1228
1332
  service.on('preview:browser-context-menu', (data) => {
1229
- ws.emit.project(projectId, 'preview:browser-context-menu', data);
1333
+ ws.emit.project(roomId, 'preview:browser-context-menu', data);
1230
1334
  });
1231
1335
 
1232
1336
  service.on('preview:browser-copy-to-clipboard', (data) => {
1233
- ws.emit.project(projectId, 'preview:browser-copy-to-clipboard', data);
1337
+ ws.emit.project(roomId, 'preview:browser-copy-to-clipboard', data);
1234
1338
  });
1235
1339
 
1236
1340
  service.on('preview:browser-open-url-new-tab', (data) => {
1237
- ws.emit.project(projectId, 'preview:browser-open-url-new-tab', data);
1341
+ ws.emit.project(roomId, 'preview:browser-open-url-new-tab', data);
1238
1342
  });
1239
1343
 
1240
1344
  service.on('preview:browser-download-image', (data) => {
1241
- ws.emit.project(projectId, 'preview:browser-download-image', data);
1345
+ ws.emit.project(roomId, 'preview:browser-download-image', data);
1242
1346
  });
1243
1347
 
1244
1348
  service.on('preview:browser-open-url-host', (data) => {
1245
- ws.emit.project(projectId, 'preview:browser-open-url-host', data);
1349
+ ws.emit.project(roomId, 'preview:browser-open-url-host', data);
1246
1350
  });
1247
1351
 
1248
1352
  service.on('preview:browser-open-inspector', (data) => {
1249
- ws.emit.project(projectId, 'preview:browser-open-inspector', data);
1353
+ ws.emit.project(roomId, 'preview:browser-open-inspector', data);
1250
1354
  });
1251
1355
 
1252
1356
  service.on('preview:browser-copy-image-to-clipboard', (data) => {
1253
- ws.emit.project(projectId, 'preview:browser-copy-image-to-clipboard', data);
1357
+ ws.emit.project(roomId, 'preview:browser-copy-image-to-clipboard', data);
1254
1358
  });
1255
1359
 
1256
1360
  // Forward new window events
1257
1361
  service.on('preview:browser-new-window', (data) => {
1258
- ws.emit.project(projectId, 'preview:browser-new-window', data);
1362
+ ws.emit.project(roomId, 'preview:browser-new-window', data);
1259
1363
  });
1260
1364
 
1261
1365
  // MCP control events come from the singleton browserMcpControl, so their
@@ -1390,6 +1494,12 @@ class BrowserPreviewServiceManager {
1390
1494
 
1391
1495
  await Promise.all(cleanupPromises);
1392
1496
  this.services.clear();
1497
+
1498
+ // The only place the shared browser may be closed: this is every
1499
+ // project at once, i.e. the process going away. A single workspace's
1500
+ // teardown must never reach it — doing so took every other project's
1501
+ // preview tabs down with it.
1502
+ await browserPool.cleanup();
1393
1503
  }
1394
1504
 
1395
1505
  /**