Skip to content

fix(browser): bound retained webview guests across worktree switches - #12194

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-browser-guest-budget
Aug 3, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/fix-browser-guest-budget

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

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 new destroyWorktreeBrowserGuests) and the worktree is dropped from mountedWorktreeIdsRef, 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:

  • LRU order = worktree activation order; re-activating a worktree refreshes its recency.
  • Only worktrees that actually hold live guests count toward the budget.
  • Never evicted: the active worktree; worktrees whose browser is currently visible to a remote controller (automation-visible / mobile-driven); background measure windows and targeted background mounts; Activity-portal worktrees; and worktrees with eviction-exempt terminal ptys or pending spawn work (a surface unmount would orphan live shells). These stay retained even over budget.
  • Eviction destroys-then-recreates; it never detaches a live guest (the STA-3228 blank-forever state).
  • Explicit close, worktree sleep, and worktree removal cleanup paths are untouched.

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 lint
  • pnpm typecheck
  • pnpm 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 whole browser-pane directory (35 files / 230 tests) including the new browser-guest-worktree-retention.test.ts and the extended BrowserPaneOverlayLayer.test.tsx, browser-page-viewport.test.ts, browser-webview-cleanup.test.ts, plus terminal-hidden-worktree-retention.test.ts.
  • pnpm build — not run locally; renderer-only change, CI covers packaging.
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

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 hasCommittedMount latch; destroyWorktreeBrowserGuests destroys every page (including legacy tab-id-keyed guests) and leaves other worktrees alone.

AI Review Report

Authored and reviewed agentically (Claude). Main risks checked:

  • STA-3228 regression (detached-but-alive guest): the eviction effect destroys guests via destroyPersistentWebview first, then removes the worktree from mountedWorktreeIdsRef and bumps a revision so the next render unmounts an already-empty surface. No live webview is ever detached. The revisit path was traced through ensureBrowserPageWebview (created: true → initial navigation from the store-persisted URL).
  • Terminal interplay: dropping a worktree from mountedWorktreeIdsRef also 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.
  • Loop/thrash safety: the effect runs on activation/surface-set/portal changes; the revision bump is not in its deps, and re-runs treat evicted worktrees as unretained, so it is idempotent (including StrictMode double-invoke).
  • Per-worktree state reset on eviction: webviewRegistry, registeredWebContentsIds, page viewports, live-URL cache, and explicit zoom clear via destroyPersistentWebview; slot viewport roots clear via the slot's unmount ref callback; the hasCommittedMount latch dies with the unmounted layer; backgroundMountTabIdsByWorktreeRef / activationDeferredMountTabIdsByWorktreeRef entries are deleted alongside the mounted-set entry (mirroring the existing removed-worktree pruning).
  • Cross-platform (macOS/Linux/Windows): no shortcuts, labels, file paths, or shell behavior touched; the logic is id-based and identical on all platforms, and applies unchanged to SSH-hosted workspaces and folder workspaces (webview guests are always local Electron processes regardless of workspace host).

Flagged during review and fixed: recency.includes inside 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.unregisterGuest call inside destroyPersistentWebview, 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

  • Cherry-pick target: v1.4.165 release — this bounds a memory regression introduced by fix(browser): keep browser tabs rendering across worktree switches (STA-3228) #12137, which shipped in the RC (relevant given the chronic renderer heap growth reports on 1.4.162–164).
  • The budget is defined in exactly one place, with its rationale: BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT = 4 in src/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts.
  • Intended behavior change: a worktree evicted from the budget reloads its browser pages on the next visit (URLs and tab structure come from the store) instead of resuming instantly.
  • Follow-up candidate: worktrees protected from eviction (e.g. automation-pinned) can hold guests over budget indefinitely; if that shows up in the field, a TTL like the terminal retention budget's could be layered on top of the count bound.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 605d7dec-75d8-450f-bd97-bef1638c65ef

📥 Commits

Reviewing files that changed from the base of the PR and between 402c19e and 6bf0942.

📒 Files selected for processing (8)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts
  • src/renderer/src/components/browser-pane/browser-page-download-activity.test.ts
  • src/renderer/src/components/browser-pane/browser-page-download-activity.ts
  • src/renderer/src/store/slices/browser-webview-cleanup.test.ts
  • src/renderer/src/store/slices/browser-webview-cleanup.ts
  • src/shared/constants.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/store/slices/browser-webview-cleanup.ts
  • src/renderer/src/store/slices/browser-webview-cleanup.test.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts

📝 Walkthrough

Walkthrough

Browser 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes bounding retained webview guests across worktree switches.
Description check ✅ Passed The description covers the required sections, behavior, testing, AI review, security audit, and platform considerations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/components/Terminal.tsx (1)

1159-1234: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a settings toggle to disable the browser-guest retention budget.

This eviction effect runs unconditionally whenever renderedActiveWorktreeId is set; there is no equivalent of terminalHiddenViewParking or terminalHiddenWorktreeRetentionBudget to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4481b9b and 136f826.

📒 Files selected for processing (8)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/browser-pane/BrowserPaneOverlayLayer.test.tsx
  • src/renderer/src/components/browser-pane/browser-guest-worktree-retention.test.ts
  • src/renderer/src/components/browser-pane/browser-guest-worktree-retention.ts
  • src/renderer/src/components/browser-pane/browser-page-viewport.test.ts
  • src/renderer/src/components/browser-pane/webview-registry.ts
  • src/renderer/src/store/slices/browser-webview-cleanup.test.ts
  • src/renderer/src/store/slices/browser-webview-cleanup.ts

@greptile-apps

greptile-apps Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR introduces an LRU-based retention budget for Electron webview guests across worktree switches, capping hidden-worktree guest retention at 4 (BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT). Beyond the budget, the least-recently-activated worktrees have their guests fully destroyed via destroyWorktreeBrowserGuests and their surfaces unmounted cleanly, so a revisit rebuilds from persisted tab state rather than reattaching a stale (blank) guest.

  • New eviction effect in Terminal.tsx: tracks activation recency in a ref array, selects over-budget evictable worktrees via selectBrowserGuestEvictionWorktreeIds, destroys their guests, removes them from mountedWorktreeIdsRef, and bumps a revision counter to trigger an unmount render.
  • Eviction guards: active worktree, automation-visible pages, mobile-driven pages, measure windows, targeted background mounts, Activity-portal worktrees, eviction-exempt terminal ptys, and pending spawn work are all excluded from eviction.
  • New helpers: destroyWorktreeBrowserGuests in browser-webview-cleanup.ts, hasLiveBrowserGuest in webview-registry.ts, and the pure utility functions in browser-guest-worktree-retention.ts are well-scoped and thoroughly tested.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live Electron QA on this head (dev build of the composed branch with #12191, isolated instance, identity-verified):

  • Opened a browser guest (example.com) in one worktree, switched to another worktree, switched back.
  • While away: guest stayed in DOM parked at 0×0 (retained, under budget — correct, not destroyed).
  • After return: same guest connected and rendering at full size. Zero renderer window errors during the cycle.

qa12194-switch-return.png

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.

@brennanb2025
brennanb2025 merged commit 93a2ad8 into main Aug 3, 2026
42 checks passed
brennanb2025 added a commit that referenced this pull request Aug 4, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant