@myrialabs/clopen 0.4.35 → 0.4.37

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 (91) 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/git/conflict-state.test.ts +396 -0
  13. package/backend/git/git-executor.ts +6 -0
  14. package/backend/git/git-parser.ts +144 -48
  15. package/backend/git/git-service.ts +727 -57
  16. package/backend/git/push-target.test.ts +264 -0
  17. package/backend/host/metrics.test.ts +110 -0
  18. package/backend/host/metrics.ts +235 -0
  19. package/backend/index.ts +5 -2
  20. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  21. package/backend/ports/attribute.test.ts +3 -2
  22. package/backend/ports/attribute.ts +5 -44
  23. package/backend/preview/browser/browser-pool.ts +81 -0
  24. package/backend/preview/browser/browser-preview-service.ts +142 -32
  25. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  26. package/backend/preview/browser/types.ts +9 -0
  27. package/backend/project/status-manager.ts +20 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  29. package/backend/projects/project-cleanup.ts +7 -1
  30. package/backend/projects/shell-ownership.ts +65 -0
  31. package/backend/snapshot/snapshot-service.ts +6 -2
  32. package/backend/terminal/ptykit.ts +35 -6
  33. package/backend/utils/ws.ts +21 -1
  34. package/backend/worktrees/clone.ts +222 -0
  35. package/backend/worktrees/index.ts +29 -0
  36. package/backend/worktrees/merge.test.ts +93 -0
  37. package/backend/worktrees/merge.ts +232 -0
  38. package/backend/worktrees/paths.test.ts +60 -0
  39. package/backend/worktrees/paths.ts +60 -0
  40. package/backend/worktrees/resolve.ts +67 -0
  41. package/backend/worktrees/service.ts +315 -0
  42. package/backend/worktrees/tree.ts +59 -0
  43. package/backend/ws/access.ts +18 -0
  44. package/backend/ws/artifacts/generate.ts +2 -2
  45. package/backend/ws/chat/stream.ts +9 -2
  46. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  47. package/backend/ws/files/path-access.test.ts +93 -1
  48. package/backend/ws/files/path-access.ts +54 -5
  49. package/backend/ws/files/read.ts +15 -10
  50. package/backend/ws/files/search.ts +7 -7
  51. package/backend/ws/files/state.ts +70 -8
  52. package/backend/ws/files/watch.ts +16 -14
  53. package/backend/ws/git/branch-name.ts +9 -8
  54. package/backend/ws/git/branch.ts +58 -16
  55. package/backend/ws/git/commit-message.ts +16 -13
  56. package/backend/ws/git/commit.ts +17 -17
  57. package/backend/ws/git/conflict.ts +116 -13
  58. package/backend/ws/git/diff-budget.test.ts +125 -0
  59. package/backend/ws/git/diff-budget.ts +220 -0
  60. package/backend/ws/git/diff.ts +9 -9
  61. package/backend/ws/git/ignored.ts +9 -9
  62. package/backend/ws/git/log.ts +28 -3
  63. package/backend/ws/git/remote.ts +118 -44
  64. package/backend/ws/git/staging.ts +16 -16
  65. package/backend/ws/git/status.ts +13 -13
  66. package/backend/ws/index.ts +4 -0
  67. package/backend/ws/preview/access.ts +11 -3
  68. package/backend/ws/projects/index.ts +5 -1
  69. package/backend/ws/projects/info.test.ts +54 -0
  70. package/backend/ws/projects/info.ts +398 -0
  71. package/backend/ws/sessions/crud.ts +21 -6
  72. package/backend/ws/snapshot/restore.ts +11 -14
  73. package/backend/ws/system/device-info.ts +62 -144
  74. package/backend/ws/worktrees/crud.ts +187 -0
  75. package/backend/ws/worktrees/index.ts +33 -0
  76. package/backend/ws/worktrees/transfer.ts +88 -0
  77. package/dist/assets/{index-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
  78. package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
  79. package/dist/assets/main-DLqolBI2.css +1 -0
  80. package/dist/assets/main-Df1I3hnw.js +1096 -0
  81. package/dist/index.html +2 -2
  82. package/package.json +1 -1
  83. package/shared/types/database/schema.ts +26 -0
  84. package/shared/types/git.ts +123 -0
  85. package/shared/utils/logger.ts +1 -0
  86. package/shared/utils/workspace-scope.test.ts +80 -0
  87. package/shared/utils/workspace-scope.ts +57 -0
  88. package/shared/utils/ws-client.ts +25 -5
  89. package/shared/utils/ws-server.ts +19 -3
  90. package/dist/assets/main-Buko4D0t.css +0 -1
  91. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -1,18 +1,38 @@
1
- import type { Browser, BrowserContext, Page } from 'puppeteer';
1
+ import type { Browser, BrowserContext, Page, Target } from 'puppeteer';
2
2
  import { EventEmitter } from 'events';
3
3
  import { getViewportDimensions } from '$shared/constants/preview.js';
4
4
  import type { BrowserTab, BrowserTabInfo, DeviceSize, Rotation } from './types';
5
5
  import { DEFAULT_STREAMING_CONFIG } from './types';
6
- import { browserPool } from './browser-pool';
6
+ import { browserPool, type PooledSession } from './browser-pool';
7
7
  import { BrowserAudioCapture } from './browser-audio-capture';
8
8
  import { cursorTrackingScript } from './scripts/cursor-tracking';
9
9
  import { browserMcpControl } from './browser-mcp-control';
10
10
  import { debug } from '$shared/utils/logger';
11
+ import { scopeSlug } from '$shared/utils/workspace-scope';
11
12
 
12
13
  // Tab cleanup configuration
13
14
  const INACTIVE_TIMEOUT = 5 * 60 * 1000; // 5 minutes
14
15
  const CLEANUP_INTERVAL = 60 * 1000; // Check every minute
15
16
 
17
+ /**
18
+ * Shortest gap between two rebuild requests for the same tab.
19
+ *
20
+ * The health check runs from read paths that fire many times a second (the
21
+ * stream's per-frame guard, the tab list, an MCP action's pre-check), so
22
+ * without this a single dead page would ask for a rebuild on every one of
23
+ * them. Long enough that a failed rebuild backs off, short enough that the
24
+ * page is back before anyone reaches for reload.
25
+ */
26
+ const RECOVERY_REQUEST_INTERVAL = 5 * 1000;
27
+
28
+ /**
29
+ * Why a tab's underlying page cannot be driven right now.
30
+ *
31
+ * All three are recoverable: the tab keeps its identity and the page is
32
+ * rebuilt underneath it. None of them is a reason to delete the tab.
33
+ */
34
+ export type TabAilment = 'browser-gone' | 'session-gone' | 'page-gone';
35
+
16
36
  /**
17
37
  * Browser Tab Manager
18
38
  *
@@ -46,6 +66,43 @@ export class BrowserTabManager extends EventEmitter {
46
66
  private cleanupInterval: NodeJS.Timeout | null = null;
47
67
  private signalHandlers: { sigterm: () => void; sigint: () => void } | null = null;
48
68
 
69
+ /** Tabs whose close is already running, so closeTab is idempotent. */
70
+ private closingTabs = new Set<string>();
71
+
72
+ /**
73
+ * Set once the process is on its way out, and while a workspace teardown is
74
+ * running. Both close every page on purpose, and without this each one would
75
+ * read as a crash worth relaunching Chrome for.
76
+ */
77
+ private shuttingDown = false;
78
+
79
+ /** When a rebuild was last asked for, per tab — see RECOVERY_REQUEST_INTERVAL. */
80
+ private recoveryRequestedAt = new Map<string, number>();
81
+
82
+ /**
83
+ * Per-tab page setup that has to run again on every page the tab gets.
84
+ * Dialog interception and the host-capability shims must be installed
85
+ * before the first navigation, so a rebuilt page needs them re-applied
86
+ * exactly as the original one did.
87
+ */
88
+ private tabSetupHooks = new Map<string, (page: Page, tabId: string) => Promise<void>>();
89
+
90
+ /**
91
+ * The listeners a tab holds on objects that outlive its page — the shared
92
+ * browser and its own context. A rebuild has to take these off before it
93
+ * fits new ones: left attached, the old popup watcher would see the tab's
94
+ * replacement page as a popup and close it on sight.
95
+ */
96
+ private tabListeners = new Map<
97
+ string,
98
+ {
99
+ browser: Browser;
100
+ onDisconnected: () => void;
101
+ context: BrowserContext;
102
+ onTargetCreated: (target: Target) => void;
103
+ }
104
+ >();
105
+
49
106
  // Audio capture manager
50
107
  private audioCapture = new BrowserAudioCapture();
51
108
 
@@ -83,7 +140,9 @@ export class BrowserTabManager extends EventEmitter {
83
140
  preNavigationSetup?: (page: Page, tabId: string) => Promise<void>;
84
141
  }
85
142
  ): Promise<BrowserTab> {
86
- const tabId = `tab-${this.nextTabNumber++}`;
143
+ // The counter restarts per workspace, so the scope token is what stops a
144
+ // worktree's `tab-1` from being matched as the main tree's on the client.
145
+ const tabId = `tab-${scopeSlug(this.projectId)}-${this.nextTabNumber++}`;
87
146
  const finalUrl = url || 'about:blank';
88
147
 
89
148
  debug.log('preview', `🟡🟡🟡 Creating new tab: ${tabId} for project: ${this.projectId} 🟡🟡🟡`);
@@ -177,6 +236,11 @@ export class BrowserTabManager extends EventEmitter {
177
236
  };
178
237
 
179
238
  this.tabs.set(tabId, tab);
239
+ // Kept for the life of the tab: a rebuilt page needs the same setup the
240
+ // original one got, before it navigates anywhere.
241
+ if (options?.preNavigationSetup) {
242
+ this.tabSetupHooks.set(tabId, options.preNavigationSetup);
243
+ }
180
244
  this.setupBrowserHandlers(tabId, browser, context, page);
181
245
 
182
246
  // Mark tab as active immediately
@@ -269,66 +333,82 @@ export class BrowserTabManager extends EventEmitter {
269
333
  return { success: false, newActiveTabId: null };
270
334
  }
271
335
 
272
- debug.log('preview', `🗑️ Closing tab: ${tabId}`);
273
-
274
- const wasActive = tab.isActive;
336
+ // Closing is reachable from several places at once (the user, an MCP
337
+ // batch, the idle sweep). Running it twice destroys the pool session
338
+ // under the half that is still working.
339
+ if (this.closingTabs.has(tabId)) {
340
+ debug.log('preview', `⏭️ Tab ${tabId} is already closing`);
341
+ return { success: false, newActiveTabId: null };
342
+ }
343
+ this.closingTabs.add(tabId);
275
344
 
276
- // Auto-release MCP control if this tab is being controlled
277
- browserMcpControl.autoReleaseForTab(tabId, this.projectId);
345
+ try {
346
+ debug.log('preview', `🗑️ Closing tab: ${tabId}`);
278
347
 
279
- // IMMEDIATELY set destroyed flag and stop streaming
280
- tab.isDestroyed = true;
281
- tab.isStreaming = false;
348
+ const wasActive = tab.isActive;
282
349
 
283
- // Clear all intervals immediately
284
- if (tab.screenshotInterval) {
285
- clearInterval(tab.screenshotInterval);
286
- tab.screenshotInterval = undefined;
287
- }
288
- if (tab.streamingInterval) {
289
- clearInterval(tab.streamingInterval);
290
- tab.streamingInterval = undefined;
291
- }
292
-
293
- // Wait a moment for streaming loop to detect the flags and stop
294
- await new Promise(resolve => setTimeout(resolve, 500));
350
+ // Auto-release MCP control if this tab is being controlled
351
+ browserMcpControl.autoReleaseForTab(tabId, this.projectId);
295
352
 
296
- // Clean up the isolated context
297
- await this.cleanupContext(tab);
353
+ // IMMEDIATELY set destroyed flag and stop streaming
354
+ tab.isDestroyed = true;
355
+ tab.isStreaming = false;
298
356
 
299
- // Remove from map
300
- this.tabs.delete(tabId);
301
- this.tabActivity.delete(tabId);
357
+ // Clear all intervals immediately
358
+ if (tab.screenshotInterval) {
359
+ clearInterval(tab.screenshotInterval);
360
+ tab.screenshotInterval = undefined;
361
+ }
362
+ if (tab.streamingInterval) {
363
+ clearInterval(tab.streamingInterval);
364
+ tab.streamingInterval = undefined;
365
+ }
302
366
 
303
- // If closing active tab, switch to another tab
304
- let newActiveTabId: string | null = null;
305
- if (wasActive && this.tabs.size > 0) {
306
- // Get the first available tab
307
- const nextTab = Array.from(this.tabs.values())[0];
308
- if (nextTab) {
309
- this.setActiveTab(nextTab.id);
310
- newActiveTabId = nextTab.id;
311
- } else {
367
+ // Wait a moment for streaming loop to detect the flags and stop
368
+ await new Promise(resolve => setTimeout(resolve, 500));
369
+
370
+ // Clean up the isolated context
371
+ await this.cleanupContext(tab);
372
+
373
+ // Remove from map
374
+ this.detachTabListeners(tabId);
375
+ this.tabs.delete(tabId);
376
+ this.tabActivity.delete(tabId);
377
+ this.tabSetupHooks.delete(tabId);
378
+ this.recoveryRequestedAt.delete(tabId);
379
+
380
+ // If closing active tab, switch to another tab
381
+ let newActiveTabId: string | null = null;
382
+ if (wasActive && this.tabs.size > 0) {
383
+ // Get the first available tab
384
+ const nextTab = Array.from(this.tabs.values())[0];
385
+ if (nextTab) {
386
+ this.setActiveTab(nextTab.id);
387
+ newActiveTabId = nextTab.id;
388
+ } else {
389
+ this.activeTabId = null;
390
+ }
391
+ } else if (this.tabs.size === 0) {
312
392
  this.activeTabId = null;
313
393
  }
314
- } else if (this.tabs.size === 0) {
315
- this.activeTabId = null;
316
- }
317
394
 
318
- // Emit tab closed event
319
- this.emit('preview:browser-tab-closed', {
320
- tabId,
321
- newActiveTabId,
322
- timestamp: Date.now()
323
- });
395
+ // Emit tab closed event
396
+ this.emit('preview:browser-tab-closed', {
397
+ tabId,
398
+ newActiveTabId,
399
+ timestamp: Date.now()
400
+ });
324
401
 
325
- debug.log('preview', `✅ Tab closed: ${tabId} (new active: ${newActiveTabId || 'none'})`);
402
+ debug.log('preview', `✅ Tab closed: ${tabId} (new active: ${newActiveTabId || 'none'})`);
326
403
 
327
- // Log pool stats after cleanup
328
- const stats = browserPool.getStats();
329
- debug.log('preview', `📊 Pool stats after cleanup: ${stats.activeSessions}/${stats.maxConcurrency} tabs active`);
404
+ // Log pool stats after cleanup
405
+ const stats = browserPool.getStats();
406
+ debug.log('preview', `📊 Pool stats after cleanup: ${stats.activeSessions}/${stats.maxConcurrency} tabs active`);
330
407
 
331
- return { success: true, newActiveTabId };
408
+ return { success: true, newActiveTabId };
409
+ } finally {
410
+ this.closingTabs.delete(tabId);
411
+ }
332
412
  }
333
413
 
334
414
  /**
@@ -390,6 +470,16 @@ export class BrowserTabManager extends EventEmitter {
390
470
  return tab;
391
471
  }
392
472
 
473
+ /**
474
+ * Get a tab without validating its page.
475
+ *
476
+ * The counterpart to `getTab`: used by the rebuild path, which needs the
477
+ * record of a tab precisely when its page is the thing that is broken.
478
+ */
479
+ peekTab(tabId: string): BrowserTab | null {
480
+ return this.tabs.get(tabId) ?? null;
481
+ }
482
+
393
483
  /**
394
484
  * Get the active tab
395
485
  */
@@ -521,21 +611,31 @@ export class BrowserTabManager extends EventEmitter {
521
611
  isStreaming: tab.isStreaming,
522
612
  isDestroyed: tab.isDestroyed || false,
523
613
  browserConnected: tab.browser?.connected || false,
524
- pageClosed: tab.page?.isClosed() || true,
614
+ // `tab.page?.isClosed() || true` — the shape this used to have — is
615
+ // always true, which reported every tab as a dead one.
616
+ pageClosed: tab.page ? tab.page.isClosed() : true,
525
617
  deviceSize: tab.deviceSize,
526
618
  rotation: tab.rotation,
527
619
  consoleLogs: tab.consoleLogs.length,
528
620
  lastInteractionTime: tab.lastInteractionTime,
529
621
  duplicateFrameCount: tab.duplicateFrameCount || 0,
530
622
  isActive: tab.isActive,
623
+ isRecovering: tab.isRecovering || false,
531
624
  createdAt: tab.createdAt,
532
625
  lastAccessedAt: tab.lastAccessedAt
533
626
  }));
534
627
 
628
+ // "Alive" is about the page, not about whether anyone is watching it:
629
+ // a tab whose panel is closed is not streaming and is perfectly fine.
630
+ // The inactive-mode cleanup uses the same definition, so what this
631
+ // reports is what that mode would actually remove.
632
+ const isDead = (t: (typeof tabs)[number]) =>
633
+ t.isDestroyed || (!t.isRecovering && (!t.browserConnected || t.pageClosed));
634
+
535
635
  return {
536
636
  totalTabs: tabs.length,
537
- activeTabs: tabs.filter(t => t.isStreaming && t.browserConnected && !t.pageClosed && !t.isDestroyed).length,
538
- inactiveTabs: tabs.filter(t => t.isDestroyed || !t.browserConnected || t.pageClosed || !t.isStreaming).length,
637
+ activeTabs: tabs.filter(t => !isDead(t)).length,
638
+ inactiveTabs: tabs.filter(isDead).length,
539
639
  tabs
540
640
  };
541
641
  }
@@ -568,44 +668,159 @@ export class BrowserTabManager extends EventEmitter {
568
668
  }
569
669
 
570
670
  /**
571
- * Validate tab
671
+ * What, if anything, is wrong with a tab's page. Pure — it only looks.
672
+ *
673
+ * Deliberately side-effect free: this is called from read paths (the tab
674
+ * list, the stream's per-frame guard, an MCP action's pre-check), and it
675
+ * used to close the tab from all of them. A page that dies for a moment is
676
+ * not a request to throw the tab away, and answering one that way is what
677
+ * made previews disappear with nobody having closed anything.
678
+ */
679
+ diagnoseTab(tabId: string): TabAilment | null {
680
+ const tab = this.tabs.get(tabId);
681
+ if (!tab) return null;
682
+
683
+ if (!tab.browser || !tab.browser.connected) return 'browser-gone';
684
+ if (!browserPool.isSessionValid(this.getSessionId(tabId))) return 'session-gone';
685
+ if (!tab.page || tab.page.isClosed()) return 'page-gone';
686
+
687
+ return null;
688
+ }
689
+
690
+ /**
691
+ * Ask for a tab's page to be rebuilt.
692
+ *
693
+ * The tab manager cannot do it alone — console logging, navigation
694
+ * tracking and the streaming scripts are all owned a layer up — so this
695
+ * only reports the ailment. `BrowserPreviewService` listens and calls
696
+ * `respawnPage` as part of a full rebuild.
697
+ */
698
+ private requestRecovery(tabId: string, ailment: TabAilment): void {
699
+ if (this.shuttingDown) return;
700
+
701
+ const tab = this.tabs.get(tabId);
702
+ if (!tab || tab.isDestroyed || tab.isRecovering) return;
703
+ if (this.closingTabs.has(tabId)) return;
704
+
705
+ const now = Date.now();
706
+ const last = this.recoveryRequestedAt.get(tabId) ?? 0;
707
+ if (now - last < RECOVERY_REQUEST_INTERVAL) return;
708
+ this.recoveryRequestedAt.set(tabId, now);
709
+
710
+ debug.warn('preview', `⚠️ Tab ${tabId}: ${ailment} — requesting a page rebuild`);
711
+ this.emit('preview:browser-tab-unhealthy', { tabId, reason: ailment, timestamp: now });
712
+ }
713
+
714
+ /**
715
+ * Whether the tab can be driven right now. An unusable page schedules a
716
+ * rebuild rather than a close.
572
717
  */
573
718
  private isValidTab(tabId: string): boolean {
574
719
  const tab = this.tabs.get(tabId);
575
- if (!tab) {
576
- return false;
577
- }
720
+ if (!tab) return false;
578
721
 
579
- // Check if tab is already destroyed
580
722
  if (tab.isDestroyed) {
581
723
  debug.warn('preview', `⚠️ Tab ${tabId}: already destroyed`);
582
724
  return false;
583
725
  }
584
726
 
585
- // Check if browser is still connected (shared browser)
586
- if (!tab.browser || !tab.browser.connected) {
587
- debug.warn('preview', `⚠️ Tab ${tabId}: shared browser disconnected`);
588
- this.closeTab(tabId).catch(console.error);
589
- return false;
590
- }
727
+ const ailment = this.diagnoseTab(tabId);
728
+ if (!ailment) return true;
591
729
 
592
- // Check if session is still valid in the pool (use project-scoped sessionId)
593
- const sessionId = this.getSessionId(tabId);
594
- const isPoolValid = browserPool.isSessionValid(sessionId);
595
- if (!isPoolValid) {
596
- debug.warn('preview', `⚠️ Tab ${tabId}: session no longer valid in pool`);
597
- this.closeTab(tabId).catch(console.error);
598
- return false;
599
- }
730
+ this.requestRecovery(tabId, ailment);
731
+ return false;
732
+ }
600
733
 
601
- // Check if page is still open
602
- if (!tab.page || tab.page.isClosed()) {
603
- debug.warn('preview', `⚠️ Tab ${tabId}: page closed`);
604
- this.closeTab(tabId).catch(console.error);
605
- return false;
734
+ /**
735
+ * Rebuild the page behind an existing tab, keeping the tab itself.
736
+ *
737
+ * The id, the slot in the tab strip, the device size and the URL all
738
+ * survive; only `browser`/`context`/`page` are replaced. The pool relaunches
739
+ * Chrome on demand, so this covers a crashed renderer and a browser that
740
+ * went away entirely. Callers own the per-page state layered on top (console,
741
+ * navigation tracking, streaming scripts) and must re-apply it afterwards.
742
+ *
743
+ * Returns the tab, or null if it is gone / already being rebuilt.
744
+ */
745
+ async respawnPage(tabId: string): Promise<BrowserTab | null> {
746
+ const tab = this.tabs.get(tabId);
747
+ if (!tab || tab.isDestroyed || tab.isRecovering) return null;
748
+ if (this.closingTabs.has(tabId)) return null;
749
+
750
+ tab.isRecovering = true;
751
+ let pooled: PooledSession | null = null;
752
+
753
+ try {
754
+ const sessionId = this.getSessionId(tabId);
755
+
756
+ // Before anything is asked of the context: its popup watcher closes
757
+ // every page in it that is not the one this tab was built around,
758
+ // which would include the replacement page it is about to open.
759
+ this.detachTabListeners(tabId);
760
+
761
+ // Keeps the context — and so the cookies and storage the tab has
762
+ // built up — whenever the context itself survived.
763
+ pooled = await browserPool.renewSessionPage(sessionId);
764
+ const browser = await browserPool.getBrowser();
765
+
766
+ tab.browser = browser;
767
+ tab.context = pooled.context;
768
+ tab.page = pooled.page;
769
+ tab.isStreaming = false;
770
+ tab.isCapturing = false;
771
+ tab.lastFrameHash = undefined;
772
+ tab.duplicateFrameCount = 0;
773
+ // History belongs to the page that died; the new one starts over.
774
+ tab.historyBaseIndex = undefined;
775
+ tab.canGoBack = false;
776
+ tab.canGoForward = false;
777
+
778
+ await this.setupPage(pooled.page, tab.deviceSize, tab.rotation);
779
+
780
+ const setupHook = this.tabSetupHooks.get(tabId);
781
+ if (setupHook) {
782
+ await setupHook(pooled.page, tabId);
783
+ }
784
+
785
+ this.setupBrowserHandlers(tabId, browser, pooled.context, pooled.page);
786
+
787
+ // `url` over `currentUrl`: the navigation tracker keeps the former
788
+ // current through redirects and SPA pushState, while the latter only
789
+ // moves on an explicit navigate. Rebuilding from `currentUrl` would
790
+ // drop a single-page app back to the route it was first opened at.
791
+ const target = tab.url || tab.currentUrl || 'about:blank';
792
+ const actualUrl = await this.navigateWithRetry(pooled.page, target);
793
+ tab.url = actualUrl;
794
+ tab.currentUrl = actualUrl;
795
+ tab.isLoading = false;
796
+
797
+ this.markTabActivity(tabId);
798
+ this.recoveryRequestedAt.delete(tabId);
799
+
800
+ debug.log('preview', `♻️ Tab ${tabId}: page rebuilt at ${actualUrl}`);
801
+
802
+ return tab;
803
+ } catch (error) {
804
+ // Drop a half-built page rather than leave it in place: it would
805
+ // have none of the instrumentation the tab needs, while reading as
806
+ // perfectly healthy — so nothing would ever try again.
807
+ if (pooled && !pooled.page.isClosed()) {
808
+ await pooled.page.close().catch(() => {});
809
+ }
810
+ throw error;
811
+ } finally {
812
+ tab.isRecovering = false;
606
813
  }
814
+ }
607
815
 
608
- return true;
816
+ /** Take a tab's browser- and context-level listeners back off. */
817
+ private detachTabListeners(tabId: string): void {
818
+ const entry = this.tabListeners.get(tabId);
819
+ if (!entry) return;
820
+
821
+ entry.browser.off('disconnected', entry.onDisconnected);
822
+ entry.context.off('targetcreated', entry.onTargetCreated);
823
+ this.tabListeners.delete(tabId);
609
824
  }
610
825
 
611
826
  /**
@@ -966,34 +1181,31 @@ export class BrowserTabManager extends EventEmitter {
966
1181
  * Setup browser event handlers
967
1182
  */
968
1183
  private setupBrowserHandlers(tabId: string, browser: Browser, context: BrowserContext, page: Page) {
969
- // Add error handlers for browser disconnection
970
- // Note: With shared browser, we only clean up THIS tab, not close the browser
971
- browser.on('disconnected', () => {
972
- const tab = this.tabs.get(tabId);
973
- if (tab && !tab.isDestroyed) {
974
- debug.warn('preview', `⚠️ Shared browser disconnected, cleaning up tab ${tabId}`);
975
- tab.isDestroyed = true;
976
- this.closeTab(tabId).catch(console.error);
977
- }
978
- });
1184
+ // Chrome went away — a crash, an OOM kill, a machine that slept. The tab
1185
+ // is not: the pool launches a new browser on demand, so ask for a rebuild
1186
+ // instead of deleting a tab the user never closed.
1187
+ const onDisconnected = () => {
1188
+ this.requestRecovery(tabId, 'browser-gone');
1189
+ };
979
1190
 
980
- // Handle page errors
1191
+ // Puppeteer raises this when the renderer crashes. Long-running previews
1192
+ // hit it on low-memory hosts, and it used to be terminal for the tab.
981
1193
  page.on('error', (error) => {
982
- const tab = this.tabs.get(tabId);
983
- if (tab && !tab.isDestroyed) {
984
- debug.error('preview', `💥 Page error for tab ${tabId}: ${error.message}, cleaning up`);
985
- tab.isDestroyed = true;
986
- this.closeTab(tabId).catch(console.error);
987
- }
1194
+ debug.error('preview', `💥 Page crashed for tab ${tabId}: ${error.message}`);
1195
+ this.requestRecovery(tabId, 'page-gone');
988
1196
  });
989
1197
 
990
- // Track page close event
1198
+ // The page can also go away without an error — a site calling
1199
+ // window.close(), a target Chrome dropped. Same answer: rebuild it.
1200
+ // Our own teardown paths hold the closing/recovering flags that
1201
+ // requestRecovery checks, so this never fights them.
991
1202
  page.on('close', () => {
992
1203
  debug.warn('preview', `⚠️ Page close event for tab ${tabId}`);
1204
+ this.requestRecovery(tabId, 'page-gone');
993
1205
  });
994
1206
 
995
1207
  // Handle popup/new window events within this context
996
- context.on('targetcreated', async (target) => {
1208
+ const onTargetCreated = async (target: Target) => {
997
1209
  if (target.type() === 'page') {
998
1210
  const newPage = await target.page();
999
1211
  if (newPage && newPage !== page) {
@@ -1014,7 +1226,14 @@ export class BrowserTabManager extends EventEmitter {
1014
1226
  }
1015
1227
  }
1016
1228
  }
1017
- });
1229
+ };
1230
+
1231
+ // Registered together so a rebuild can lift both at once, before the
1232
+ // context is asked for the page that replaces this one.
1233
+ this.detachTabListeners(tabId);
1234
+ browser.on('disconnected', onDisconnected);
1235
+ context.on('targetcreated', onTargetCreated);
1236
+ this.tabListeners.set(tabId, { browser, onDisconnected, context, onTargetCreated });
1018
1237
  }
1019
1238
 
1020
1239
  /**
@@ -1067,6 +1286,7 @@ export class BrowserTabManager extends EventEmitter {
1067
1286
  // and prevent duplicate listeners if multiple BrowserTabManager
1068
1287
  // instances are created.
1069
1288
  const cleanup = () => {
1289
+ this.shuttingDown = true;
1070
1290
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
1071
1291
  this.cleanupInterval = null;
1072
1292
  this.tabActivity.clear();
@@ -1090,7 +1310,12 @@ export class BrowserTabManager extends EventEmitter {
1090
1310
  }
1091
1311
 
1092
1312
  /**
1093
- * Perform cleanup of inactive tabs
1313
+ * Reap bookkeeping left behind by a close that did not finish.
1314
+ *
1315
+ * The only thing this may remove is a tab already marked destroyed with no
1316
+ * close in flight — i.e. an entry whose teardown threw halfway. A tab whose
1317
+ * page merely died is NOT reaped: it is rebuilt on next use, and closing it
1318
+ * here is exactly the silent disappearance this sweep used to cause.
1094
1319
  */
1095
1320
  private performCleanup(): void {
1096
1321
  const now = Date.now();
@@ -1111,11 +1336,8 @@ export class BrowserTabManager extends EventEmitter {
1111
1336
  continue;
1112
1337
  }
1113
1338
 
1114
- // Only cleanup if tab is truly orphaned
1115
- if (tab.isDestroyed || (tab.page?.isClosed() && !tab.browser?.connected)) {
1116
- debug.log('preview', `🧹 Auto-cleaning up inactive tab: ${tabId} (inactive for ${Math.round(inactiveTime / 1000)}s)`);
1117
-
1118
- // Close tab
1339
+ if (tab.isDestroyed && !this.closingTabs.has(tabId)) {
1340
+ debug.log('preview', `🧹 Reaping half-closed tab: ${tabId} (idle for ${Math.round(inactiveTime / 1000)}s)`);
1119
1341
  this.closeTab(tabId).catch(console.error);
1120
1342
  }
1121
1343
  }
@@ -1137,12 +1359,11 @@ export class BrowserTabManager extends EventEmitter {
1137
1359
  continue;
1138
1360
  }
1139
1361
 
1140
- // Check if tab is truly inactive
1141
- const isInactive =
1142
- tab.isDestroyed ||
1143
- !tab.browser?.connected ||
1144
- tab.page?.isClosed() ||
1145
- !tab.isStreaming;
1362
+ // Truly inactive means the page is gone, not that nobody is
1363
+ // watching: a tab whose panel is closed or minimized is not
1364
+ // streaming and is perfectly alive. Treating that as a zombie is
1365
+ // what let the "SAFE" mode take out tabs it promised to preserve.
1366
+ const isInactive = tab.isDestroyed || (!tab.isRecovering && this.diagnoseTab(tabId) !== null);
1146
1367
 
1147
1368
  if (isInactive) {
1148
1369
  inactiveTabs.push(tabId);
@@ -1183,6 +1404,13 @@ export class BrowserTabManager extends EventEmitter {
1183
1404
  async cleanup(): Promise<void> {
1184
1405
  debug.log('preview', `🧹 Cleaning up ${this.tabs.size} tabs...`);
1185
1406
 
1407
+ // Every page below is about to be closed on purpose; none of them is a
1408
+ // crash to rebuild from. Restored at the end: an admin "clean up all"
1409
+ // leaves the manager in service, and the tabs opened after it must be
1410
+ // able to recover like any other.
1411
+ const wasShuttingDown = this.shuttingDown;
1412
+ this.shuttingDown = true;
1413
+
1186
1414
  // Stop cleanup interval
1187
1415
  if (this.cleanupInterval) {
1188
1416
  clearInterval(this.cleanupInterval);
@@ -1213,12 +1441,21 @@ export class BrowserTabManager extends EventEmitter {
1213
1441
  }
1214
1442
 
1215
1443
  // Force clear tabs map
1444
+ for (const tabId of this.tabs.keys()) this.detachTabListeners(tabId);
1216
1445
  this.tabs.clear();
1217
1446
  this.activeTabId = null;
1218
1447
  this.tabActivity.clear();
1448
+ this.tabSetupHooks.clear();
1449
+ this.recoveryRequestedAt.clear();
1450
+
1451
+ this.shuttingDown = wasShuttingDown;
1219
1452
 
1220
- // Clean up the browser pool (closes all contexts and the shared browser)
1221
- await browserPool.cleanup();
1453
+ // Deliberately NOT browserPool.cleanup(): the pool holds one Chrome and
1454
+ // every project's contexts. Closing it from one workspace's teardown —
1455
+ // deleting a worktree, an admin "clean up all" — took every other
1456
+ // project's preview tabs down with it. Our own sessions are already gone
1457
+ // with the tabs above; the pool closes its browser when the last session
1458
+ // goes, and on process shutdown.
1222
1459
 
1223
1460
  debug.log('preview', '✅ All tabs cleaned up');
1224
1461
  }
@@ -123,6 +123,15 @@ export interface BrowserTab {
123
123
 
124
124
  // Internal
125
125
  isDestroyed?: boolean;
126
+ /**
127
+ * Whether the tab's page is being rebuilt right now.
128
+ *
129
+ * A crashed renderer or a Chrome that went away leaves the tab itself
130
+ * intact — it keeps its id, its slot in the strip and its URL — while
131
+ * `browser`/`context`/`page` are replaced underneath. Anything that would
132
+ * otherwise treat the dead page as a reason to reap the tab checks this.
133
+ */
134
+ isRecovering?: boolean;
126
135
  }
127
136
 
128
137
  /**