Repository navigation
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR adds headless browser renderer reclamation. Pages retain identity, URL, title, profile data, and worktree data after parking. Configurable policies select idle and least-recently-used pages while excluding pinned pages. Parked pages can wake on targeted commands and remain visible in tab listings. Runtime tab switching and closing support parked pages. Tests cover policy behavior, lifecycle races, renderer limits, and end-to-end headless operation. Documentation describes parking behavior and environment variables. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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.
Actionable comments posted: 8
🧹 Nitpick comments (1)
src/main/browser/offscreen-browser-window.ts (1)
34-95: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winHandle WebContents and renderer termination during URL loading.
Register handlers for both
destroyedandrender-process-gone. A renderer crash emitsrender-process-goneand does not necessarily destroy theWebContents; otherwise,wakeTabcan still wait forLOAD_TIMEOUT_MS. KeepisMainFrameas the fifthdid-fail-loadparameter for Electron 43.1.0.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c591f31b-46de-49ed-9b85-54f709f8cd45
📒 Files selected for processing (16)
docs/reference/headless-linux-server.mdsrc/cli/browser-format.tssrc/main/browser/agent-browser-bridge.tssrc/main/browser/browser-backend.tssrc/main/browser/offscreen-browser-backend-reclaim.test.tssrc/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-page-reclaim.test.tssrc/main/browser/offscreen-browser-page-reclaim.tssrc/main/browser/offscreen-browser-window.tssrc/main/browser/offscreen-browser-window.web-preferences.test.tssrc/main/index.tssrc/main/runtime/orca-runtime-browser.tssrc/main/runtime/orca-runtime.tssrc/shared/runtime-types.tstests/e2e/headless-serve-browser-tab-reclaim.spec.tstests/e2e/helpers/headless-paired-runtime-host.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 2 remain after this review.
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| nextWebContentsId = 100 | ||
| process.env.ORCA_HEADLESS_BROWSER_RESIDENT_LIMIT = '2' | ||
| process.env.ORCA_HEADLESS_BROWSER_PARK_IDLE_MS = '60000' | ||
| process.env.ORCA_HEADLESS_BROWSER_PARK_GRACE_MS = '5000' | ||
| process.env.ORCA_HEADLESS_BROWSER_PARK_SWEEP_MS = '100000' | ||
| }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Vitest vi.stubEnv vi.unstubAllEnvs API
💡 Result:
In Vitest, vi.stubEnv and vi.unstubAllEnvs are utilities used to mock and restore environment variables [1][2]. vi.stubEnv(name, value) This function changes the value of an environment variable on both process.env and import.meta.env [1][3]. When called, Vitest remembers the original value of the variable, allowing it to be restored later [1][2]. vi.unstubAllEnvs This function restores all environment variables that were modified using vi.stubEnv to their original values [1][2]. Automated Cleanup By default, these stubs are not automatically reset between tests [4][5]. To automate the restoration process, you can enable the unstubEnvs configuration option in your vitest.config.ts file [4][6]: export default defineConfig({ test: { unstubEnvs: true, }, }) When unstubEnvs is set to true, Vitest automatically calls vi.unstubAllEnvs before each test [6]. Note that this can cause issues with concurrent tests, as restoring variables globally may affect other tests currently in progress [6]. Alternatively, you can manually call vi.unstubAllEnvs in a beforeEach or afterEach hook to manage lifecycle cleanup per test [4][5][7].
Citations:
- 1: https://vitest.dev/api/vi
- 2: https://github.com/vitest-dev/vitest/blob/206e8cff/docs/api/vi.md
- 3: https://v0.vitest.dev/api/vi
- 4: https://vitest.dev/guide/mocking
- 5: https://github.com/vitest-dev/vitest/blob/main/docs/guide/mocking.md
- 6: https://vitest.dev/config/unstubenvs
- 7: https://stackoverflow.com/questions/76768119/mocking-env-variables-with-vitest
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- test file outline ---'
ast-grep outline src/main/browser/offscreen-browser-backend-reclaim.test.ts
printf '%s\n' '--- relevant test file sections ---'
cat -n src/main/browser/offscreen-browser-backend-reclaim.test.ts | sed -n '1,155p'
printf '%s\n' '--- Vitest version/config references ---'
rg -n --hidden --glob '!node_modules' '"vitest"|"vitest":|unstubEnvs|setupFiles|clearMocks|restoreMocks' package.json package-lock.json pnpm-lock.yaml yarn.lock vitest.config.* vite.config.* . 2>/dev/null | head -200
printf '%s\n' '--- environment policy implementation and test isolation references ---'
rg -n --glob '*.{ts,tsx,js,jsx}' 'readOffscreenBrowserReclaimPolicy|ORCA_HEADLESS_BROWSER_(RESIDENT_LIMIT|PARK_IDLE_MS|PARK_GRACE_MS|PARK_SWEEP_MS)|stubEnv|unstubAllEnvs' src tests . 2>/dev/null | head -240Repository: stablyai/orca
Length of output: 29063
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- reclaim policy implementation ---'
cat -n src/main/browser/offscreen-browser-page-reclaim.ts | sed -n '1,90p'
printf '%s\n' '--- Vitest configuration and resolved package version ---'
cat -n config/vitest.config.ts | sed -n '1,100p'
python3 - <<'PY'
import json
from pathlib import Path
for name in ('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock'):
p = Path(name)
if p.exists():
print(f'--- {name} ---')
text = p.read_text(errors='replace')
for needle in ('vitest@', 'node_modules/vitest:', 'vitest:'):
for i, line in enumerate(text.splitlines(), 1):
if needle in line:
print(f'{i}: {line}')
if i > 30:
break
PY
printf '%s\n' '--- test command/config references ---'
rg -n --hidden --glob '!node_modules' 'config/vitest.config|vitest run|pool|fileParallelism|singleThread|isolate' package.json config .github 2>/dev/null | head -160Repository: stablyai/orca
Length of output: 49058
🌐 Web query:
Vitest 4.1.5 vi.stubEnv vi.unstubAllEnvs API
💡 Result:
In Vitest 4.1.5, the vi.stubEnv and vi.unstubAllEnvs APIs are used to manage environment variables during tests [1][2]. vi.stubEnv(name, value) This function modifies the value of an environment variable on both process.env and import.meta.env [1][3]. When called, Vitest remembers the original value of the variable, allowing you to restore it later [1][2]. vi.unstubAllEnvs This function restores all environment variables changed via vi.stubEnv to their original values [1][2]. Vitest caches the initial state when the first stubEnv call is made and uses this to perform the restoration [1][3]. Additional Configuration You can automate the restoration of environment variables by enabling the unstubEnvs option in your Vitest configuration [4][5]. When set to true, Vitest will automatically call vi.unstubAllEnvs before each test [6]. Example Configuration: // vitest.config.ts export default defineConfig({ test: { unstubEnvs: true, }, }) Warning: Enabling unstubEnvs can cause issues with concurrent tests, as one test completing may restore values currently in use by other tests running in parallel [6].
Citations:
- 1: https://vitest.dev/api/vi
- 2: https://github.com/vitest-dev/vitest/blob/v4.1.7/docs/api/vi.md
- 3: https://github.com/vitest-dev/vitest/blob/206e8cff/docs/api/vi.md
- 4: https://vitest.dev/guide/mocking
- 5: https://github.com/vitest-dev/vitest/blob/main/docs/guide/mocking.md
- 6: https://tangled.org/vitest.dev/vitest/blob/b7902bcb409882a445aa5f9a8675cb1a71696ad2/docs/config/unstubenvs.md
Restore the reclaim environment variables after this suite.
Use vi.stubEnv for the four overrides and call vi.unstubAllEnvs() in afterEach. Otherwise, later tests in the same worker can inherit this suite’s reclaim policy.
| // Why (STA-4341): on a headless `orca serve` host every agent-opened browser | ||
| // page is backed by its own hidden BrowserWindow, i.e. its own renderer | ||
| // process. Nothing owned those renderers, so a long agent session accumulated | ||
| // them until the host saturated. This module is the policy half of that owner: | ||
| // given the resident pages it decides which ones to park (drop the renderer, | ||
| // keep the page). It mirrors terminal hidden-view parking — the cap is the | ||
| // primary evictor, the idle clock is the tail — and is pure so the decision is | ||
| // testable without Electron. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Keep explanatory comments concise and focused on non-obvious invariants. Move detailed incident background and test rationale to documentation or the issue.
📍 Affects 2 files
src/main/browser/offscreen-browser-page-reclaim.ts#L1-L8(this comment)src/cli/browser-format.ts#L37-L39
Source: Coding guidelines
| const host = await launchHeadlessPairedRuntimeHost({ extraEnv: FAST_RECLAIM_ENV }) | ||
| const pageServer = await startAnimatedPageServer() | ||
| try { | ||
| const worktreeId = await resolveSeededWorktreeId(host, testRepoPath) | ||
| expect(await countOffscreenRenderers(host)).toBe(0) | ||
|
|
||
| const pageIds = await createTabs(host, worktreeId, pageServer.url, 6) | ||
| expect(await countOffscreenRenderers(host)).toBe(6) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Isolate the idle-timeout assertion from the resident cap.
FAST_RECLAIM_ENV sets the resident cap to 2. createTabs creates six tabs sequentially. After the 400 ms grace period, a sweep can park early tabs before Line 118 runs. The assertion can then observe fewer than six renderers.
Override ORCA_HEADLESS_BROWSER_RESIDENT_LIMIT to 6 for this test.
Proposed fix
- const host = await launchHeadlessPairedRuntimeHost({ extraEnv: FAST_RECLAIM_ENV })
+ const host = await launchHeadlessPairedRuntimeHost({
+ extraEnv: { ...FAST_RECLAIM_ENV, ORCA_HEADLESS_BROWSER_RESIDENT_LIMIT: '6' }
+ })📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const host = await launchHeadlessPairedRuntimeHost({ extraEnv: FAST_RECLAIM_ENV }) | |
| const pageServer = await startAnimatedPageServer() | |
| try { | |
| const worktreeId = await resolveSeededWorktreeId(host, testRepoPath) | |
| expect(await countOffscreenRenderers(host)).toBe(0) | |
| const pageIds = await createTabs(host, worktreeId, pageServer.url, 6) | |
| expect(await countOffscreenRenderers(host)).toBe(6) | |
| const host = await launchHeadlessPairedRuntimeHost({ | |
| extraEnv: { ...FAST_RECLAIM_ENV, ORCA_HEADLESS_BROWSER_RESIDENT_LIMIT: '6' } | |
| }) | |
| const pageServer = await startAnimatedPageServer() | |
| try { | |
| const worktreeId = await resolveSeededWorktreeId(host, testRepoPath) | |
| expect(await countOffscreenRenderers(host)).toBe(0) | |
| const pageIds = await createTabs(host, worktreeId, pageServer.url, 6) | |
| expect(await countOffscreenRenderers(host)).toBe(6) |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (3)
src/main/browser/offscreen-browser-backend.ts (3)
86-90: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRemove the page record if
materializefails.
this.pages.set()completes before synchronous window creation. Ifmaterialize()throws,createTab()rejects but the backend retains a parked record that has no renderer.Delete the record in a
catch, then rethrow.
310-318: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRun local teardown when bridge cleanup fails.
If
bridge.onTabClosed()rejects, this method skips guest unregistration and window destruction.closeTab()has already removed the page record, so the renderer becomes unreachable.Use
finallyfor local teardown.
282-283: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winKeep a renderer created by a concurrent wake.
wakeTab()waits on the inner release promise and can materialize a new window beforereleaseRenderer()resolves toparkPage(). Line 283 then clears the new window reference. The backend reports a live renderer as parked and cannot later destroy it.Capture the released window. Clear
page.windowonly if it still references that window.
🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.ts (1)
33134-33175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUpdate the stale comment on browser tab resolution.
liveBrowserTabsByPageIdis built fromgetOpenBrowserTabsByPageId, which now returns both live and parked pages. The comment at line 33166, "only surface pages the browser bridge can still route to," and the local variable nameliveTabno longer match this behavior: a parked page has no renderer and the bridge cannot route to it directly until the runtime wakes it.Update the comment and consider renaming
liveTabto something likeopenTab, so a future reader does not assume every entry here is bridge-routable.Suggested comment/name update
if (tab.type === 'browser') { - const liveTab = tab.browserPageId + const openTab = tab.browserPageId ? liveBrowserTabsByPageId.get(tab.browserPageId) : undefined - if (!liveTab) { + if (!openTab) { continue } - // Why: renderer snapshots lag BrowserView teardown/process swaps; only surface pages the browser bridge can still route to. + // Why: renderer snapshots lag BrowserView teardown/process swaps; only surface pages + // still open (live or parked), since a closed page must not linger in the tab bar. tabs.push({ ...tab, - title: liveTab.title || tab.title, - url: liveTab.url || tab.url, + title: openTab.title || tab.title, + url: openTab.url || tab.url, isActive: tab.isActive }) continue }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 548e448a-bc32-4f18-aeba-6a50f1c498cb
📒 Files selected for processing (14)
docs/reference/headless-linux-server.mdsrc/main/browser/agent-browser-bridge-in-flight-pin.test.tssrc/main/browser/agent-browser-bridge.tssrc/main/browser/browser-backend.tssrc/main/browser/cdp-ws-proxy.tssrc/main/browser/headless-browser-tab-listing.test.tssrc/main/browser/headless-browser-tab-listing.tssrc/main/browser/offscreen-browser-backend-reclaim.test.tssrc/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-page-reclaim.test.tssrc/main/browser/offscreen-browser-page-reclaim.tssrc/main/runtime/orca-runtime-browser-parked-targeting.test.tssrc/main/runtime/orca-runtime-browser.tssrc/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/browser/browser-backend.ts
- docs/reference/headless-linux-server.md
- src/main/runtime/orca-runtime-browser.ts
- src/main/browser/offscreen-browser-backend-reclaim.test.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 2 remain after this review.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/browser/offscreen-browser-backend.ts (1)
159-169: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRoute resident pages through bridge cleanup during shutdown.
destroyAllunregisters and destroys resident pages without callingbridge.onTabClosed, leaving helper sessions and CDP resources active. Reuse the renderer-release cleanup path before clearing the page registry.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7bb79ddc-bbc0-4a52-ac54-06f893e7c615
📒 Files selected for processing (3)
src/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-open-pages.tssrc/main/runtime/orca-runtime-browser.test.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 2 remain after this review.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/main/browser/offscreen-browser-backend.ts (3)
140-150: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftHandle
onProcessSwapfailure duringwakeTab.If
bridge.onProcessSwaprejects aftermaterialize(page), the live window and guest registration remain. A laterwakeTabreturnstruebefore retrying the bridge reset orloadPage. Clean up the new renderer and registration, or retain a retryable wake state before propagating the error.
329-342: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftRetain failed renderer cleanup for retry.
If
CdpWsProxy.stop()rejects,destroySessionhas already removed the session and clears its pending-destruction entry. RetryingonTabClosedcannot recover the proxy. Preserve the teardown handle and retry cleanup before discarding it.
100-103: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftSerialize close with an in-flight wake.
closeTabremovesthis.wakingwithout awaiting the wake. After ID reuse, the old wake can passthis.pages.has(browserPageId)while still using the deleted page object. It can then update the new ID mapping and delete a newer wake entry in itsfinallyblock. Track page identity or closing state, and serialize close with wake completion.
♻️ Duplicate comments (3)
src/main/browser/offscreen-browser-backend.ts (3)
186-228: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftRevalidate eligibility before each park or retained close.
reclaimIdlePagessnapshotsloadingand pin state, then awaits each destructive action. A page can become pinned, start loading, or be closed before its turn. The loops still callparkPageorcloseTabwithout checking current state. Recheck page existence,loading, pin state,releasing, and the current renderer immediately before each action. The same race remains in this revision.
247-248: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winDo not clear a renderer created by a concurrent wake.
If
wakeTabwaits on the same release, it can materialize a new window afterreleaseRenderercompletes and beforeparkPageresumes. Line 248 then clears the newpage.windowreference.browserManagerstill owns the new guest, butdestroyAllcannot reach the window. Capture the released window and clear the reference only when it is still the same window. The same race remains in this revision.Proposed fix
+ const releasedWindow = page.window await this.releaseRenderer(page, browserPageId) - page.window = null + if (page.window === releasedWindow) { + page.window = null + }
279-292: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAlways finish local teardown when bridge cleanup fails.
If
bridge.onTabClosedrejects,runReleaseRendererexits beforeunregisterGuestandwindow.destroy.closeTabhas already removed the persistent page, so the renderer and guest mapping remain unreachable. Move local cleanup intofinallyand propagate the bridge error after cleanup. The same teardown gap remains in this revision.Proposed fix
- if (bridge && webContentsId != null) { - await bridge.onTabClosed(webContentsId) + try { + if (bridge && webContentsId != null) { + await bridge.onTabClosed(webContentsId) + } + } finally { + this.browserManager.unregisterGuest(browserPageId) + if (page?.window && !page.window.isDestroyed()) { + page.window.destroy() + } } - this.browserManager.unregisterGuest(browserPageId) - if (page?.window && !page.window.isDestroyed()) { - page.window.destroy() - }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f93fed6d-13d2-4c73-bb3c-11811a0f081f
📒 Files selected for processing (4)
src/main/browser/offscreen-browser-backend-reclaim.test.tssrc/main/browser/offscreen-browser-backend.tssrc/main/runtime/orca-runtime-browser-parked-targeting.test.tssrc/main/runtime/orca-runtime-browser.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/runtime/orca-runtime-browser-parked-targeting.test.ts
- src/main/browser/offscreen-browser-backend-reclaim.test.ts
- src/main/runtime/orca-runtime-browser.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 2 remain after this review.
2b3aa4c to
5a80b74
Compare
On a headless `orca serve` host every agent-created browser page is backed by
its own hidden BrowserWindow, i.e. its own renderer process, held in a map that
only ever shrank on an explicit `tab close` or process exit. Agents open pages
per measurement and rarely close them, so a long session accumulated renderers
until the host saturated: a reporter measured 9 tabs / 6 renderers at 220-480MB
each, the oldest at 1.3GB after 15h, load 6.85 on 4 cores. A hidden guest also
runs with background throttling disabled, so an animated page kept painting
where nothing could see it.
Reproduced on a real serve process (tests/e2e/headless-serve-browser-tab-reclaim
.spec.ts): 6 tabs -> 6 renderers, still 6 after 20s fully idle, and 2405 rAF
frames in ~25s on a window that is never shown.
Give the offscreen backend a lifecycle owner. It now keeps the page identity an
agent holds — id, address, worktree, profile — and treats the renderer as a
reclaimable resource. An idle page is parked (renderer destroyed, record kept)
and woken by the next command that targets it. Eviction mirrors terminal
hidden-view parking: a resident cap of 4 is the primary evictor, a 5 minute idle
window is the tail, and a page a client streams or that has a command in flight
is never parked. `tab list` keeps listing parked pages so an agent does not read
a reclaimed tab as gone and open yet another one.
Two related defects fall out of the same teardown path. The headless close path
never notified the agent-browser bridge, so every closed page left its helper
session, CDP proxy and listening port behind; park and close now both route
through the bridge before the mapping and the window go away. And because the
listing now spans resident and parked pages, `--index` resolves against that
same listing, so `tab close --index` can no longer address a different tab than
the one the caller read.
Parking discards in-page JavaScript state; cookies and local storage live in the
profile partition and survive. The thresholds are settable via
ORCA_HEADLESS_BROWSER_{RESIDENT_LIMIT,PARK_IDLE_MS,PARK_GRACE_MS,PARK_SWEEP_MS}.
Desktop is untouched — it has no offscreen backend.
Self-review found the first fix only taught the CLI's `browser.tabList` about parked pages. The paired-client session snapshot enumerated headless browser tabs straight off the bridge, which lists live WebContents only, so a parked page vanished from the client's tab bar and the next snapshot pruned it — the exact failure the file's own comment says the synthesis exists to prevent. Worktree teardown had the same shape and leaked parked page records. Route all three through one merge (headless-browser-tab-listing.ts): session publication, worktree teardown and `tab list` now agree on what is open. Parking also records whether the page was its worktree's active tab, because tearing the renderer down moves the bridge's active pointer — without that a park silently deselected the tab a user had open. A parked page only claims active when nothing live does, so a listing can never report two. Also guard the reclaim sweep against re-entry: a park waits on the helper session's own bounded teardown, which can outlast the sweep interval.
Three fresh gpt-5.6-luna reviewers took lifecycle, resources and compatibility. Two of their high findings were the ones the previous commit already fixed (session snapshot, worktree teardown), which is a useful cross-check. Four were real and new: - `tab switch --index` resolved the index *after* target resolution had already woken the most recently used parked page. Waking makes that page live, which moves it to the front of the listing, so index 0 selected a different tab than the caller had just read. Indices are now resolved before any wake. - An in-flight command was only pinned while the queue was executing it. `enqueueTargetedCommand` awaits `ensureSession` first, and that can spend up to EXEC_TIMEOUT_MS (90s) closing a stale helper session — far past the 30s grace — so a sweep could destroy the renderer mid-setup. A page is now claimed from target resolution through completion. - A renderer lost on its own never told the bridge, so a crash loop leaked one helper session, CDP proxy and listening port per page. It now routes through the same teardown as park and close, and stops the sweep when the last page goes. Reading `win.webContents` in that handler throws once the contents are destroyed, which wedged the whole main process — the id is captured up front. `CdpWsProxy.stop()` also closes its socket even when detaching the debugger throws, which is exactly the case a crashed renderer produces. - Parking a page mid-navigation snapshotted the uncommitted `about:blank` address over the URL the agent asked for, so the wake loaded the wrong page. A loading page is no longer parkable and an uncommitted address is ignored. Also bounds the last unbounded thing: parking caps renderer processes but not the page records behind them, so past a generous retention limit the oldest parked pages are closed outright and logged. Each fix has a regression test that was mutation-checked against the exact defect. The `tab switch` case is covered at the runtime layer rather than e2e because driving a real switch needs the agent-browser binary, which cannot run in the sandboxed e2e HOME.
…backend The backend crossed the 300-line cap, and a max-lines suppression is not an option here. The split follows the distinction the fix is built on: a headless page and the renderer behind it have different lifetimes. OffscreenBrowserOpenPages is the book of open pages; the backend owns renderers. "Parked" is exactly a record in the book with no window attached, so the queries the runtime needs — which pages are parked, which is most recently used — belong with the records rather than threaded through renderer bookkeeping. Also fixes an existing spec my first commit broke: the implicit-target activity touch calls getActivePageId, which that test's partial bridge stub did not have. Caught here because a background full-suite run launched mid-edit had raced the files it was reading — the pass it reported was not of this tree.
…-less command means Round-two review of the merged listing. Four defects, all in what parking projects rather than in the reclamation itself: - A page-less command picked the most recently used parked page. Recency is not activeness: an explicit `--page b` makes b the most recently used while a is still the active tab, and a page-less command has always meant "the active tab". The retained active page now wins, with recency only breaking the tie. - Parking the active page promotes another live tab to active, which then parks claiming the flag too, so a listing could report two active tabs. Only the newest claim holds it, and the merge enforces at most one either way. - A parked page reported no load failure, showing a page that could not load as healthy at its address. The failure becomes unreadable once the guest is unregistered, so it is captured onto the record. Certificate failures are deliberately not carried: their challenge id dies with the renderer, so surfacing one would offer an action that cannot work. - Parking sniffed the committed address, which cannot tell an intentional navigation to about:blank from the blank page a failed load left behind. The record now follows did-navigate, so waking returns the page to where it actually is; chrome-error addresses are the failure, not a destination, and never replace the address that produced them. Each has a mutation-checked regression test.
…x from waking Round two, resources. Two defects: - createTab added the page record before materializing it, so a window that failed to construct or register left the record behind — occupying the retention budget, listed as parked, and making a retry with the same id fail as "already exists" — without ever installing the crash handler that would have cleaned it up. The handler lives inside materialize, after the operations that can throw, so nothing else would have. materialize now destroys a window it cannot finish attaching rather than orphaning a hidden renderer, and createTab drops the record. - `tab close --index` on a parked page went through the shared index resolver, which wakes unconditionally so that switching counts as using a page. For a close that is pure churn: it rebuilds a renderer, tears down and recreates the helper session, starts a navigation, and then destroys all of it — and a wake that failed would turn a reclaimable page into an unclosable one. The resolver takes a no-wake mode and close uses it. Both mutation-checked.
… in use Round two, lifecycle. The sweep picks its victims once and then parks them one at a time, awaiting each helper-session teardown. That await is long enough for a page later in the list to be woken and driven, and the selection was being treated as a licence rather than a proposal: - A page used while an earlier park was in flight was parked anyway, destroying the renderer and session underneath a running command. - The retention close had the same shape and was worse: it ignored pins entirely, so a page woken mid-sweep could be deleted outright. - A wake is resident but not yet loading while it awaits the process swap, so it was neither pinned nor loading — a concurrent sweep could park a page in the middle of rebuilding it. Each page is now re-checked against live state immediately before its renderer goes, and a wake in progress pins the page for its duration. Also makes `tab current` count as using the page it names. Every other page-targeting command refreshes the reclaim clock; this one resolved the active id directly and skipped it, so an agent polling `tab current` could have that very page reclaimed under it. All four mutation-checked.
- Reusing a page id while its close was still tearing down let the new renderer register and the old close then unregister it, leaving a page the runtime owned but no command could resolve. A create now waits out an in-flight release for that id, which orders the whole reuse. - Closing a parked page told nobody: it has no WebContents teardown for the session-tabs publication to piggyback on, so a paired client kept showing a ghost tab until an operation against it failed. - A page waiting on a certificate decision was parkable. Its challenge id dies with the renderer, so parking discarded both the warning and the ability to approve it. Such a page is work waiting on an answer and stays resident. - The load helper resolves on its own 30s timeout, so `loading` stopped covering a navigation that was merely slow. The renderer is asked directly. - An iframe changing its own hash fires did-navigate-in-page too, and its address was being recorded as the tab's — waking would have landed the page on the iframe's document. Only main-frame navigations move the record. - `tab switch --index` reported the position the wake had renumbered the target to, which described neither the request nor the listing the caller read. Each mutation-checked. An ownership guard added alongside the reuse fix turned out to be unreachable once creates are ordered, so it is not here.
A wake materializes the window before it swaps the helper session and reloads the retained address, so the page reads as resident well before it is usable. The coalescing promise was consulted after that resident check, so a second command targeting the same page returned immediately and ran against a blank renderer whose session was still being torn down underneath it. Join the in-flight wake first. Mutation-checked: restoring the old order turns the new test red.
Round four. Compatibility came back clean; two real findings remain, and the first is a regression the round-three fix introduced. Pinning a page while `webContents.isLoading()` was meant to protect a slow navigation past the load helper's timeout. But a navigation can stay running forever — a server that accepts the request and never finishes it — so that pin had no bound: one stalled page per create would hold a renderer indefinitely, which is exactly the failure this reclaimer exists to prevent. The pin is gone. `loading` still covers the load helper's own bounded window, so a page is never parked mid-create; past that timeout it is deliberately reclaimable, and waking retries the address. The test now asserts that directly, so the cap cannot be quietly re-broken. A wake also validated a page that had been closed and replaced underneath it: `createTab` waits for an in-flight release but not for an in-flight wake, so the stale wake resolved true and handed the original command a different page under the name it had asked for. The wake now checks record identity, not presence, after every await. Both mutation-checked.
…'s lock Round five. Lifecycle came back clean; one finding left. A wake cleared its entry from the waking map unconditionally. An abandoned wake can outlive a close and the replacement page's own wake, so that cleanup could drop the replacement's lock — and the next command would then see a live window with no wake in flight and drive a renderer still being rebuilt, defeating the coalescing fix from the round-three pass. Clear the entry only when it is still the one this wake installed, matching how releases already do it. Mutation-checked.
…weep out CI was red on one thing: offscreen-browser-backend.ts had grown past the 300-line cap. The bare `oxlint` CI runs enforces it; the changed-code gate and the max-lines ratchet I had been running locally do not — the ratchet only catches new suppressions, not new overruns. The sweep is now its own module, which is the right seam anyway: deciding which pages keep a renderer is a separate job from owning the renderers. Comparing against the desktop guest budget also turned up a real defect. That budget vetoes evicting a worktree whose pages are still writing a download, because browser-manager cancels a page's in-flight downloads when its guest unregisters. The headless reclaimer unregisters guests the same way and had no such veto, so parking a page mid-download silently cancelled it — reachable through `orca download` on any headless host. Mirrored the veto, with a mutation-checked regression test. The two mechanisms now reference each other so the next person finds both.
The focused code-quality plugin audit runs with --deny-warnings across the whole repo, so a single import(no-duplicates) warning in the new file failed CI. The changed-code gate did not surface it, so re-run `pnpm lint` rather than the changed gate alone before pushing.
…n order CI on Linux caught a flaw in my own test. It assumed the pages created first are the least recently used, but a page's reclaim clock restarts when its load completes, and load completion does not have to follow creation order — under Xvfb it did not, so a different page was resident than the spec named. Touching two pages once up front had the same hole: a page finishing its load after the touch overtakes it. The spec now keeps two pages genuinely in use across the convergence poll, which is what its name claims and what makes the most-recently-used set unambiguous. It asserts those two are the residents, which proves recency is what decides — something creation order never showed.
…ancel one Round seven, from three fresh reviewers. Compatibility came back clean; two of the three findings were real, and both are on the download veto added last commit. The veto was unbounded, which is the same shape as the load-pin bug found in round four: a download whose response never completes keeps its DownloadItem active forever, so the page stayed pinned forever, and one stalled download per page would defeat the resident cap outright. BrowserManager now reports when a page's downloads last advanced rather than a bare boolean, and the reclaimer vetoes only while that progress is recent — the bound lives with the other reclaim thresholds instead of inside the manager. The veto also only covered the sweep's decision. Teardown then awaits the helper session while the page keeps running, and the unregister that follows cancels the page's downloads — so a download started inside that window was cancelled despite the veto. Park now gives up if that happens, leaving the page resident; the helper session is already gone but the next command recreates it. The third finding — `tab current` failing against an all-parked worktree — does not reproduce: resolveActiveTab falls back to activating the first live tab when parking cleared the active pointers. Kept a test for it. Moving the pin predicate onto the reclaimer, where the other reclaim thresholds already live, also puts the backend back under the line cap.
Round eight. Both reviewers independently found the same defect in the abort I added last commit, and chasing it showed the abort was the wrong trade. releaseRenderer's pending branch discarded the boolean, so a `tab close` that joined an aborted park reported success while the renderer was deliberately left alive — orphaning the window, its guest mapping and its download, and arming a stale destroyed-handler that could unregister a page reusing the id. Two more followed from aborting after a destructive step: onTabClosed has already destroyed the helper session (losing the page's intercept patterns) and already moved the worktree's active pointer to a fallback, and the abort restored neither. So an aborted park left a resident page with reset automation state that implicit commands no longer routed to. All three exist only because the abort backs out halfway through a teardown that is not reversible. The veto is re-checked immediately before teardown starts; what remains is the narrow window during the helper-session await, where a download that begins is cancelled exactly as it would be if the tab were closed at that instant. That is the same decision-time-only guarantee the desktop guest budget gives, and it is now stated in the code. The bounded progress veto — the actual round-seven fix — stays.
…g policy Headless reclamation now has exactly the policy surface the desktop guest budget has, and nothing more. Dropped the retained-page limit and its outright close. Desktop destroys guests but never removes a tab, so closing a page past a count had no precedent here and was the one genuinely novel product decision in this change — it permanently destroyed a page id an agent still held. Parked records are ~200 bytes against the 220-480 MB renderers being reclaimed, so retaining them indefinitely is the right trade and matches what desktop already does. Dropped the download veto's progress window with it. Desktop treats an active download as work in progress for as long as it stays active, and headless now does the same. That accepts the same unbounded-veto shape desktop has: a download that never completes keeps its page resident. Deliberate, and the alternative was a threshold desktop does not have. What stays is the part with precedent: a resident cap of 4 (the desktop limit), LRU eviction, and the idle clock headless needs because it has no notion of a visible worktree.
…ed it Design review found the one thing that made the "wake transparently" contract untrue in production. A wake awaited the full 30s page-load budget, but a wake happens inside browser.tabShow, which the paired client caps at 15s (remote-browser-page-session.ts, remote-browser-screencast-subscription.ts). So revealing a parked page whose site is slow reported the browser unreachable — the same "flaky remote" symptom the original ticket is about, reintroduced by the fix for it. The asymmetry was mine: createTab deliberately never waits for its load, and returns a tab that is operable and still navigating. A wake now does the same, with a budget comfortably inside the client's, and the load continues after it returns. Fast pages are still fully loaded when the wake resolves, which is what an agent expects; slow ones no longer stall the caller. Also drops the reclaimer's `close` dependency, dead since the retained-page close was removed. Reviewers were unanimous that park-and-wake is the right mechanism, the main process the right owner, and command activity the right signal; both other lenses returned no merge blocker.
The sweep only stopped when the last page was closed, so a host whose pages had all been parked kept waking every interval to find nothing to reclaim — on a headless server that is meant to sit idle cheaply. It now stops as soon as nothing is resident, and a wake reschedules it, because a woken page has to become reclaimable again. The timer only ever served the idle evictor. The cap is inherently event-driven — residency changes only on create and wake — but a page going idle produces no event by definition, so something has to look. Polling is the cheaper form of looking here rather than the lazier one: activity is recorded on every command, so per-page deadlines would be rescheduled far more often than the interval fires.
Both hosts already bounded live browser renderers, but with two separate implementations: the desktop app evicted hidden worktrees' webview guests on a visibility change, and the headless page reclaimer re-evaluated residency every 15 seconds. The rule they were each expressing turned out to be the same one — keep the most recently used, never evict something in use, optionally shed what has gone stale — so it now lives in src/shared/browser-retention-budget.ts and each host supplies its own configuration and its own trigger. The desktop keeps its exact behaviour: rank-only, no clock (idleMs Infinity, graceMs 0), the active worktree left out of the budget entirely, and isEvictable still consulted lazily. Its 13 tests pass unchanged. Headless drops the recurring sweep. A repeating heartbeat was never needed: the limit can only be crossed when a page is created, woken or closed, and every one of those already re-arms. Only the idle window needs a clock, so the reclaimer now computes the earliest moment its own answer could change and arms one timer for it. A host with nothing resident holds no timer at all, and one pinned by a download or a streamed client re-asks on a bounded cadence because releasing those pins raises no event the backend can observe. Two guards fell out of building it. The deadline and the selector are separate functions, so a fuzz test asserts nothing can become evictable before its deadline — it catches an off-by-one in the rank branch. And a sweep that frees nothing now backs off, measured by observed residency rather than by trusting park(), which no-ops for a window that is already gone; without it a deadline that lands early re-arms at 0ms and spins. Headless semantics change in one case: a stale pinned page no longer forces fresher unpinned pages to be evicted in its place. That is the desktop rule, and the limit was already documented as exceedable by pinned work. Removes ORCA_HEADLESS_BROWSER_PARK_SWEEP_MS, which no longer has a meaning.
e5ee913 to
2c479aa
Compare
…tarts then Streaming pins a page but frames are not activity, so a client that only watched for longer than the idle window had the page parked on the next 30s recheck after closing the pane — not 5 minutes later. Restamp the page's activity when the stream pin lifts (clearPageGate), the same markHeadlessBrowserPageUsed the subscribe path already routes through. At that instant the page is guaranteed resident (the pin vetoed any park, and pin-delete -> touch is synchronous), so the wake is a pure timestamp; a page closed or crashed mid-stream has no record left and the call no-ops. Download and certificate pins deliberately do not get the same treatment: a finished download implies no viewer to come back, and a resolved challenge is always followed by commands that stamp activity themselves.
…ebuilt Fourth external review round (2 Opus + 2 Antigravity reviewers), three fixes and four coverage seams: P0 — parkPage resumed after releaseRenderer with a continuation that runs AFTER a wake awaiting the same release promise. The wake re-materializes the window first, so the park's unconditional 'page.window = null' dropped the fresh renderer off the record on every wake-during-park overlap: leaked BrowserWindow (close/destroyAll walk page.window), the page listed parked and live at once, and the wake reporting success against a blank page whose load no-oped on the nulled field. The park now owns only the window it destroyed: it leaves the record alone when the field changed under it. The existing race test drove exactly this interleaving but asserted window identity, not residency; it now asserts both and was red before the fix. P1 — a park that rejected skipped the backoff assignment, so the next reschedule saw a deadline in the past with zero backoff: an instant re-sweep failing the same way forever. Rejections now continue to the backoff like a no-progress sweep. P2 — stop() was not terminal: it cleared sweepInFlight, so a still-running sweep's own re-arm no longer saw itself in flight and scheduled a check after shutdown (destroyAll's window teardown could do the same through the 'destroyed' handler). stop() now sets a terminal flag reschedule honors. Coverage seams the review found (each seam's mutation previously left the whole suite green): the real bridge isActiveBrowserPage (tests only ever stubbed it), the runtime isBrowserPagePinned composition the backend's pin option is wired to, explicit-page close of a parked page not waking it, and the CLI '(parked)' suffix.
Compat-lens findings from the fourth review round (1 P1, 4 P2): P1 — the merged listing ordered resident tabs before parked ones, so a background park renumbered indices that pre-reclaim moved only on create/close: an index the agent read minutes ago could close a different tab, and a paired client's tab bar reordered whenever a tab parked or woke. Listings now sort by the page book's creation order, which parking cannot change. P2 — closing the page that carried the scope's only active claim (the parked-active holder, or the last live tab) left a worktree whose every open page reported inactive, breaking the one-selected-tab assumption paired clients render on. closeTab now promotes the most recently used parked page when nothing live claims active. P2 — claimParkedActive treated an undefined worktree as 'every worktree', so a worktree-less page (a remote 'tab create' without --worktree) parking while active wiped every other worktree's parked-active flag host-wide. The claim now scopes strictly, undefined matching only undefined. P2 — readPositiveIntEnv used parseInt, which reads '1e9' as 1: an operator following the docs' 'set the idle window very high' advice silently got a 1ms window. Number() consumes the whole string, and trailing garbage now falls back instead of truncating. P2 — the docs' closed enumeration of park vetoes omitted the download and in-flight-wake vetoes; the download one is the guarantee an operator most needs stated, since parking cancels a download. Renderer construction moved to offscreen-browser-renderer-attachment.ts — the backend crossed the max-lines budget, and building + wiring a renderer to its record was a coherent seam to split.
Test-adequacy findings from the fifth review round — no production
changes. The real backend's listOpenPageIds order across park/wake was
only exercised through a test fake; the e2e index spec never asserted the
creation order end to end; nothing pinned that a live active tab
suppresses parked-active promotion on close; blank env knobs relied on an
untested guard (Number('') is 0); and stale ids in a creation order had
no case. Each new test was mutation-checked where a named mutant existed:
listOpenPageIds returning [] and the promotion condition dropped both go
red against exactly their test.
…ive claim Round-five Opus findings (both reviewers converged independently): P1 — 'tab show', 'tab current' and 'tab switch --page' reported the bridge's registration index, which any park+wake permutes (unregister deletes the map key, re-register appends). The listing speaks creation order, so the reported number named a different tab than the listing — and chaining it into '--index' closed the wrong tab. Every index a headless caller sees now comes from the same creation-ordered listing. P1 — the strict parked-active claim let one flag exist per scope, but the scope-less implicit target still scanned broadly and returned the FIRST flagged page in creation order — the oldest scope's page, not the page that actually held the most recent active claim. It now prefers the most recently used flagged page, matching the bridge's global-pointer semantics; scoped queries see at most one flag and are unchanged. P2 — closeTab's promotion gate called getActivePageId, which resolves through resolveActiveTab and reassigns the bridge's active pointers as a side effect (the exact mutation this PR's own comment warns against), and its undefined scope meant 'anywhere' while the promotion is strict. The gate now reads the page book: promote only when the closed page's scope holds no resident page. P2 — an idle/grace window past 2^31-1ms (reachable via the documented 'set it very high' advice, e.g. 1e10) overflowed setTimeout, which Node clamps to 1ms — a permanent spin. The armed delay is now capped at the setTimeout ceiling; re-checking at the horizon is harmless. Invalid knob values also warn instead of falling back silently. P2 — the docs sold the download veto as a guarantee; reworded to what ships: a decision-time veto, with downloads that begin during teardown still cancelled, exactly as if the tab had been closed at that instant.
Fixes STA-4341.
The problem
On a headless
orca servehost, every browser page an agent opens is backed by its own hiddenBrowserWindow— its own renderer process — held inOffscreenBrowserBackend's map. That map only ever shrank on an explicittab closeor on process exit. Agents open a page per measurement and rarely close them, so nothing reclaimed the renderers. The reporter measured 9 tabs / 6 renderers at 220–480 MB each, the oldest at 1 328 MB after 15h41, load average 6.85 on 4 cores, 2.5 GB of swap. From the paired client the only symptom isReconnecting to remote runtime, which reads as a network problem while the host is actually saturated.Reproduced on latest main
tests/e2e/headless-serve-browser-tab-reclaim.spec.tsdrives the exact RPCsorca tab …sends against a realorca serveprocess. On unmodifiedmain(640e8a4):Six agent tabs, six renderers, still six after 20 s of complete idleness.
window.__frames= 2405 in ~25 s is ~96 fps ofrequestAnimationFramein a window that is never shown — guest policies disable background throttling, which is the CPU half of the report.Red/green is clean: every spec fails on unmodified main and passes with this change, verified by stashing
src/and rebuilding.Root cause
Offscreen browser pages had no lifecycle owner. On desktop a page is owned by the pane that hosts it and a human can see it. A page created by
orca tab createon a headless host is not even in the workspace session — it exists only inOffscreenBrowserBackend's map andBrowserManager's maps, with no cap, no idle tracking, and nothing that would ever release it.The fix
Make the offscreen backend that owner. It keeps the page identity an agent holds —
browserPageId, address, worktree, profile — for as long as the page is open, and treats the renderer behind it as a reclaimable resource:onProcessSwappath, which already exists for "same page, new renderer".terminal-hidden-view-parking.ts: a resident cap of 4 is the primary evictor (LRU), a 5 minute idle window is the tail, and a 30 s grace floor keeps a just-used page resident.Deliberately not an arbitrary cap on how many tabs an agent may open: the number of open pages is unbounded, only the number of resident renderers is bounded, and an agent that keeps working on a page never loses it.
tab listkeeps listing parked pages ((parked)in text,parked: truein--json) so an agent does not read a reclaimed tab as gone and open yet another one — which is the loop that produced the leak. The same merge feeds the paired-client session snapshot and worktree teardown, so all three surfaces agree on what is open.Related defects fixed on the same paths
onTabClosed— which destroys the agent-browser helper session, itsCdpWsProxyHTTP/WebSocket server and its attached debugger — was only wired to the renderer'sbrowser:unregisterGuestIPC. The headless close path calledbrowserManager.unregisterGuestdirectly and never told the bridge, so every closed page left a session and a listening port behind. Park, close and renderer-crash teardown now all route through the bridge before the mapping and the window go away.--indexcould address the wrong tab. Because the listing now spans resident and parked pages, index-addressed commands resolve against that same listing, before any implicit wake can reorder it.What this does not fix
attachGuestPoliciescallssetBackgroundThrottling(false)on every guest, including offscreen ones that are never visible — that is why a hidden animated page paints at ~96 fps. Parking removes the cost for idle pages (a parked page has no renderer, so zero CPU), but a page resident under the cap still runs unthrottled. Re-enabling throttling for offscreen guests needs the capture paths to lift it around a screenshot, and theagent-browserbinary does not run in this e2e environment, so I could not prove that change safe here. Filed as follow-up rather than shipped unvalidated.Trade-off
Parking discards in-page JavaScript state. Cookies and local storage live in the profile partition and survive a wake; an unsubmitted form or an SPA's in-memory state does not. This is the same trade Orca already ships for terminal pane parking, at the same 5-minute hot-retain window. Mitigated by never parking a streamed, in-flight or loading page, by the LRU cap keeping the most recently used pages resident, and by surfacing
parkedso an agent can tell.Thresholds are operator-settable:
ORCA_HEADLESS_BROWSER_RESIDENT_LIMIT,..._PARK_IDLE_MS,..._PARK_GRACE_MS. Documented indocs/reference/headless-linux-server.md.One budget, two hosts
The rule is shared with the desktop app rather than reimplemented.
src/shared/browser-retention-budget.tsholds it: keep the most recently used, never evict something in use, optionally shed what has gone stale. Each host supplies a configuration and a trigger.browser-guest-worktree-retention.ts)idleMsInfinity,graceMs0)Desktop behaviour is unchanged; its 13 retention tests pass untouched.
No recurring sweep
There is no periodic reclaim. The limit can only be crossed when a page is created, woken or closed, and each of those re-arms directly; only the idle window needs a clock, so the reclaimer computes the earliest moment its own answer could change and arms one timer for it. A host with nothing resident holds no timer at all. A page pinned by a download, a streamed client or a certificate prompt is re-asked on a bounded cadence, because releasing those pins raises no event the backend observes.
Two guards came out of building it: a fuzz test asserting nothing can become evictable before its deadline (it caught an off-by-one in the rank branch), and a backoff after any sweep that frees nothing — measured by observed residency rather than by trusting
park(), which no-ops for a window that is already gone. Without it, a deadline landing early re-arms at 0 ms and spins.One deliberate headless semantics change: a stale pinned page no longer forces fresher unpinned pages to be evicted in its place. That is the desktop rule, and the limit was already documented as exceedable by pinned work.
Compatibility
parked?: booleanis a new optional field onbrowser.tabListresults (Rule 1 — old readers ignore it). Under Rule 3 the host now publishes tabs with no live renderer; an old client can still act on one, because acting on it wakes it host-side.resolveBrowserCommandTarget; and a parked page stays in the session snapshot with its active flag preserved.Review
Three fresh
gpt-5.6-lunareviewers (Codex CLI, spawned in this worktree) took lifecycle, resources and compatibility independently, over nine rounds against the evolving diff (fresh sessions from round seven). They found 23 real defects; every one is fixed here with a regression test that was mutation-checked — the guard is reverted and the test confirmed red before being kept.Two of their round-one findings were ones self-review had already caught (session-snapshot pruning of parked pages, worktree teardown missing them), which is a useful cross-check on the rest. The high-value ones:
tab switch --indexresolved after an implicit wake had already reordered the listing, so index 0 selected a different tab than the caller read.ensureSessionruns first and can spend up toEXEC_TIMEOUT_MS(90 s) closing a stale helper session — far past the 30 s grace.win.webContentsin adestroyedhandler throws and wedged the whole main process.about:blankfrom the blank page a failed load left behind. The record now followsdid-navigate.createTableft an unreachable record occupying the retention budget and could orphan a hidden renderer.webContents.isLoading()had no bound, so one never-finishing navigation per create could hold a renderer forever and defeat the resident cap outright. Removed; the test now asserts a stalled page is parked.wakingentry unconditionally and could drop a replacement page's lock.Round seven used three fresh reviewers with no memory of the earlier rounds. They cleared compatibility and found the download veto I had just added was unbounded — a stalled download could pin a renderer forever, the same cap-defeating shape as the round-four bug. Round eight then showed the abort I added to close the remaining race was itself the wrong trade: it backed out halfway through an irreversible teardown, orphaning the renderer on a concurrent close and leaving a resident page with a destroyed helper session and a moved active pointer. It was reverted; the veto is decision-time only, as stated in the code and as the desktop budget also is. Round nine returned clean from both. One finding was verified as pre-existing on
mainand deliberately left alone:destroyAllSessions()at app quit is fire-and-forget and not joined into the quit barrier — that line is untouched by this PR and fixing it means changing quit sequencing.Two pieces of code were deleted rather than kept: an ownership guard that became unreachable once creates are ordered (no mutation could fail a test without it), and the park abort above. Both times the review converged by removing code rather than adding it.
Comparing against the desktop guest budget (
browser-guest-worktree-retention.ts, #12137) also found a real defect independently: that budget vetoes evicting a worktree still writing a download, becauseunregisterGuestcancels in-flight downloads. The headless reclaimer unregisters guests the same way and had no such veto, so parking mid-download silently cancelled it.Testing## Testing
tab switchis covered at the runtime layer rather than e2e: driving a real switch needs theagent-browserbinary, which cannot run in the sandboxed e2e HOME, so an e2e assertion there would be environment-dependent.src/relay/pty-handler-spawn-environment.test.ts(Windows relay → WSL history isolation) and were verified to reproduce on unmodifiedorigin/main. The browser e2e regression set —browser-tab,browser-guest-crash-recovery,browser-embedded-owner-routing,paired-remote-browser-*,paired-remote-html-browser-focus,headless-serve-*— is 28/28 green.pnpm lint,check:code-quality:changed,check:react-doctor:changed,typecheck:nodeclean.