Repository navigation
fix(browser): bound retained webview guests across worktree switches - #12194
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughBrowser guest worktrees track activation recency and retain up to four eligible hidden worktrees with live guests. Older eligible worktrees are evicted unless protected by active, automation, mobile, or download activity. Worktree-level cleanup destroys page-backed and legacy browser guests while restoring explicit zoom levels. Terminal preserves mounted worktree surfaces during eviction. Tests cover retention, download tracking, cleanup, overlay remounting, and viewport rebuilding. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/Terminal.tsx (1)
1159-1234: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a settings toggle to disable the browser-guest retention budget.
This eviction effect runs unconditionally whenever
renderedActiveWorktreeIdis set; there is no equivalent ofterminalHiddenViewParkingorterminalHiddenWorktreeRetentionBudgetto disable it. Given the eviction path fully unmounts a hidden worktree's surface and destroys its browser guests, add a settings flag (mirroring the existing pattern) so this feature can be disabled quickly if a regression surfaces in production, without requiring a full release.♻️ Proposed direction
+ const browserGuestRetentionBudgetEnabled = useAppStore( + (s) => s.settings?.browserGuestHiddenWorktreeRetentionBudget !== false + ) useEffect(() => { - if (!renderedActiveWorktreeId) { + if (!renderedActiveWorktreeId || !browserGuestRetentionBudgetEnabled) { return }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 54e77a12-cd11-4d07-b545-498047ffba63
📒 Files selected for processing (8)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/components/browser-pane/BrowserPaneOverlayLayer.test.tsxsrc/renderer/src/components/browser-pane/browser-guest-worktree-retention.test.tssrc/renderer/src/components/browser-pane/browser-guest-worktree-retention.tssrc/renderer/src/components/browser-pane/browser-page-viewport.test.tssrc/renderer/src/components/browser-pane/webview-registry.tssrc/renderer/src/store/slices/browser-webview-cleanup.test.tssrc/renderer/src/store/slices/browser-webview-cleanup.ts
Greptile SummaryThis PR introduces an LRU-based retention budget for Electron webview guests across worktree switches, capping hidden-worktree guest retention at 4 (
Confidence Score: 5/5Safe to merge; the eviction path destroys guests before unmounting their surface, preserving the invariant from #12137 that no live webview is ever detached without being destroyed first. The change is well-scoped to a single new effect and three small helpers, all backed by comprehensive unit tests. Eviction guards cover every documented exemption (active worktree, automation/mobile visibility, measure windows, background mounts, portals, exempt ptys, pending spawns), and the destroy-then-unmount ordering prevents the blank-forever regression. No new IPC channels, no auth/secret surface, and the cleanup paths for explicit close, sleep, and removal are untouched. Files Needing Attention: No files require special attention. The eviction effect in Terminal.tsx is the most complex change and was reviewed for ordering correctness, idempotency under StrictMode double-invoke, and interaction with the terminal retention system — all check out.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/Terminal.tsx | Adds browser-guest retention budget effect: LRU recency tracking, eviction selection, guest destruction, and revision bump to trigger surface unmount. Logic is correct; eviction guards cover all documented exemptions. |
| src/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts | New pure-utility module: eviction selection, live-guest detection, visibility page-id derivation, and recency touch. All functions are side-effect-free and well-tested. |
| src/renderer/src/store/slices/browser-webview-cleanup.ts | Adds destroyWorktreeBrowserGuests delegating to the existing destroyWorkspaceWebviews per tab; correctly handles legacy tab-id-keyed sessions through the existing fallback path. |
| src/renderer/src/components/browser-pane/webview-registry.ts | Exports thin hasLiveBrowserGuest predicate backed by the existing webviewRegistry map; no behavioral change to existing functions. |
| src/renderer/src/components/browser-pane/browser-guest-worktree-retention.test.ts | New unit tests covering eviction selection (budget boundary, active exemption, live-guest filter, non-evictable guard, duplicates, custom limit), worktreeHoldsLiveBrowserGuests, browserTabVisibilityPageIds, and touchBrowserGuestWorktreeRecency. |
| src/renderer/src/components/browser-pane/BrowserPaneOverlayLayer.test.tsx | Adds test verifying that eviction unmount and remount resets the hasCommittedMount latch so a revisit correctly defers until eligible again. |
| src/renderer/src/store/slices/browser-webview-cleanup.test.ts | Extends test suite with two cases for destroyWorktreeBrowserGuests: cross-worktree isolation and no-op for a worktree with no tabs. |
| src/renderer/src/components/browser-pane/browser-page-viewport.test.ts | Adds test for the post-eviction revisit path: verifies a fresh viewport is built after removeBrowserPageViewport and slot deregistration. |
Sequence Diagram
sequenceDiagram
participant User as User activates worktree
participant Effect as Eviction Effect
participant Recency as browserGuestWorktreeRecencyRef
participant Selector as selectBrowserGuestEvictionWorktreeIds
participant Cleanup as destroyWorktreeBrowserGuests
participant Registry as webviewRegistry
participant Mounted as mountedWorktreeIdsRef
participant React as React re-render
User->>Effect: renderedActiveWorktreeId changes
Effect->>Recency: touchBrowserGuestWorktreeRecency
Effect->>Recency: prune IDs absent from workspaceSurfaces
Effect->>Selector: orderedWorktreeIds and predicates
Selector-->>Effect: evictedWorktreeIds (LRU beyond budget)
loop for each evicted worktree
Effect->>Cleanup: destroyWorktreeBrowserGuests
Cleanup->>Registry: destroyPersistentWebview per page
Effect->>Mounted: delete evicted worktree
end
Effect->>React: setBrowserGuestEvictionRevision
React-->>User: evicted surface unmounts
Reviews (2): Last reviewed commit: "fix(browser): merge duplicate imports fl..." | Re-trigger Greptile
| export const BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT = 4 | ||
|
|
||
| /** | ||
| * Hidden worktrees whose retained guests fall beyond the budget, LRU-first. |
There was a problem hiding this comment.
Docstring says "LRU-first" but returned order is MRU-among-evictees
The JSDoc says the function returns evicted IDs "LRU-first", but because the loop iterates orderedWorktreeIds in MRU-to-LRU order and appends each eviction as it is found, the returned array is ordered MRU-first among the evictees (e.g., with six worktrees and limit 4, the result is ['wt-5', 'wt-6'] — wt-5 is more-recently-used than wt-6). The calling code processes all evicted IDs in one pass so the order has no functional consequence, but the description may mislead future readers about iteration semantics.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Unmounting the surface disposed every parked terminal byte watcher for the evicted worktree (bell/title/agent-completion facts dropped for good after the 15s handoff TTL) and skipped the force-park scrollback capture remote panes rely on. Destroy the guests only: hidden slots mount no BrowserPane, so nothing resurrects a destroyed guest before the next visit, and no slot ever unmount-detaches a live guest (STA-3228). Terminal-state vetoes and the eviction re-render bump are no longer needed; the only veto left is a guest an automation/mobile controller is actively driving.
…l switch Main cancels a page's active downloads when its guest unregisters (tab-close semantics), so eviction now vetoes worktrees with a page still writing a download, tracked app-wide because download state was pane-local and hidden panes are unmounted. Eviction is not a user close: re-remember explicit zoom past the destroy-path forget so a revisit reasserts the user's zoom instead of resetting same-host siblings through Chromium's partition-wide HostZoomMap. browserGuestWorktreeRetentionBudget mirrors the terminal budget kill switch.
|
Live Electron QA on this head (dev build of the composed branch with #12191, isolated instance, identity-verified):
Also observed earlier in the session: the guest rebuilds and renders correctly even across a full renderer reload — the revisit-rebuild path works. Review loop caught and folded in two real fixes (eviction without surface unmount; download veto + kill switch); remaining pass-3 polish (LRU order across kill-switch toggle, interrupted-download veto release) fails toward extra retention only and follows in a small separate PR. |
…nload veto on interrupt (#12232) Two robustness follow-ups from the #12194 safety-review loop (pass 3), staged by the reviewer before its session ended; both fail toward extra retention only: - recency bookkeeping now runs while the retention kill switch is off, so re-enabling evicts in true LRU order instead of worktree-list order - interrupted downloads release the eviction veto instead of pinning the worktree as downloading forever
…tablyai#12194) * fix(browser): bound retained webview guests across worktree switches * fix(browser): merge duplicate imports flagged by import/no-duplicates * fix(browser): evict guests without unmounting the worktree surface Unmounting the surface disposed every parked terminal byte watcher for the evicted worktree (bell/title/agent-completion facts dropped for good after the 15s handoff TTL) and skipped the force-park scrollback capture remote panes rely on. Destroy the guests only: hidden slots mount no BrowserPane, so nothing resurrects a destroyed guest before the next visit, and no slot ever unmount-detaches a live guest (STA-3228). Terminal-state vetoes and the eviction re-render bump are no longer needed; the only veto left is a guest an automation/mobile controller is actively driving. * fix(browser): veto eviction for downloading pages; keep zoom; add kill switch Main cancels a page's active downloads when its guest unregisters (tab-close semantics), so eviction now vetoes worktrees with a page still writing a download, tracked app-wide because download state was pane-local and hidden panes are unmounted. Eviction is not a user close: re-remember explicit zoom past the destroy-path forget so a revisit reasserts the user's zoom instead of resetting same-host siblings through Chromium's partition-wide HostZoomMap. browserGuestWorktreeRetentionBudget mirrors the terminal budget kill switch.
…nload veto on interrupt (stablyai#12232) Two robustness follow-ups from the stablyai#12194 safety-review loop (pass 3), staged by the reviewer before its session ended; both fail toward extra retention only: - recency bookkeeping now runs while the retention kill switch is off, so re-enabling evicts in true LRU order instead of worktree-list order - interrupted downloads release the eviction veto instead of pinning the worktree as downloading forever

Summary
After #12137 (STA-3228), every worktree visited with browser pages kept its Electron webview guests alive for the rest of the session, so guest-process memory grew linearly with worktrees visited. This adds a retention budget: hidden worktrees keep their live browser guests for instant revisits, but only the 4 most recently activated (
BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT). Beyond that, the least-recently-activated worktree's guests are fully destroyed through the sanctioned cleanup path (destroyPersistentWebview, via the newdestroyWorktreeBrowserGuests) and the worktree is dropped frommountedWorktreeIdsRef, so its overlay surface unmounts cleanly and a revisit rebuilds from persisted tab state — a fresh mount and page load, not a blank pane.Key properties:
Screenshots
No visual change. The only observable behavior difference is that revisiting an evicted worktree reloads its browser pages once instead of resuming instantly. This change was authored by an agent worker that did not run the packaged app; validation was via the unit suites and static gates below.
Testing
pnpm lintpnpm typecheckpnpm test— full suite left to CI (local host runs Node 26 vs the repo's pinned Node 24, a known source of false reds). Targeted + adjacent suites pass locally: the wholebrowser-panedirectory (35 files / 230 tests) including the newbrowser-guest-worktree-retention.test.tsand the extendedBrowserPaneOverlayLayer.test.tsx,browser-page-viewport.test.ts,browser-webview-cleanup.test.ts, plusterminal-hidden-worktree-retention.test.ts.pnpm build— not run locally; renderer-only change, CI covers packaging.New/extended coverage: over-budget eviction targets the LRU worktrees only; active worktree never evicted (even when it ranks past the budget); under-budget is a no-op; non-evictable worktrees stay retained over budget; only live-guest holders count; revisit rebuilds a fresh viewport instead of reattaching the stale shell; eviction unmount resets the
hasCommittedMountlatch;destroyWorktreeBrowserGuestsdestroys every page (including legacy tab-id-keyed guests) and leaves other worktrees alone.AI Review Report
Authored and reviewed agentically (Claude). Main risks checked:
destroyPersistentWebviewfirst, then removes the worktree frommountedWorktreeIdsRefand bumps a revision so the next render unmounts an already-empty surface. No live webview is ever detached. The revisit path was traced throughensureBrowserPageWebview(created: true→ initial navigation from the store-persisted URL).mountedWorktreeIdsRefalso unmounts its terminal surface, so eviction is vetoed for worktrees with Activity portals, targeted background mounts, active measure windows, pending spawn work, or eviction-exempt ptys (a remount would respawn and orphan those live shells). Ordinary hidden worktrees are already cold-parked/watcher-covered; eviction returns them to the fully supported "not yet visited this session" state.webviewRegistry,registeredWebContentsIds, page viewports, live-URL cache, and explicit zoom clear viadestroyPersistentWebview; slot viewport roots clear via the slot's unmount ref callback; thehasCommittedMountlatch dies with the unmounted layer;backgroundMountTabIdsByWorktreeRef/activationDeferredMountTabIdsByWorktreeRefentries are deleted alongside the mounted-set entry (mirroring the existing removed-worktree pruning).Flagged during review and fixed:
recency.includesinside a filter (React Doctor performance warning on the new lines) → Set lookup. Both CI changed-lines gates (check-changed-code-quality.mjs,check-react-doctor-changed.mjs) were run locally against the merge base and pass with 0 blocking findings.Security Audit
No new input handling, command execution, path handling, auth, secrets, or dependency surface. The only IPC involved is the existing sanctioned
window.api.browser.unregisterGuestcall insidedestroyPersistentWebview, now reachable from the eviction path with the same page-id arguments explicit close already sends — no new channels or payload shapes. Eviction strictly reduces lingering guest processes and clears their registry entries, so no destroyed guest remains reachable through stale renderer state.Notes
BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT = 4insrc/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts.