Repository navigation
fix(browser): cap and reclaim offscreen browser tabs on headless serve - #19628
LesleyMurfin wants to merge 5 commits into
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:
📝 Walkthrough
Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to
|
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title clearly and concisely describes the main changes: limiting offscreen browser tabs and reclaiming renderer processes for headless serve. |
| Description check | ✅ Passed | The description is mostly complete and covers the user impact, implementation, rationale, linked issue, validation, and visual-proof exception. It uses equivalent headings for behavior and testing, bu… |
| Linked Issues check | ✅ Passed | The PR meets the coding objectives in issue #14552. OffscreenBrowserBackend enforces a default cap of 4 and accepts ORCA_MAX_OFFSCREEN_BROWSER_TABS values from 1 through 64. Capacity accounting in… |
| Out of Scope Changes check | ✅ Passed | The changed browser backend, capacity module, renderer reclamation module, lifecycle updates, CLI specification, and regression tests support issue #14552. No unrelated product-area or feature changes… |
| Docstring Coverage | ✅ Passed | Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 6 files. |
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 @coderabbitai help to get the list of available commands.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/main/browser/offscreen-browser-tab-capacity.ts (1)
42-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLocalize the new capacity text.
These new user-visible strings bypass the translation source. Add intent-named localization IDs with named placeholders.
src/main/browser/offscreen-browser-tab-capacity.ts#L42-L44: move the capacity message into the translation source.src/cli/specs/browser-basic.ts#L190-L191: move the capacity guidance into the translation source.Based on learnings: new user-facing TypeScript strings must use intent-named localization IDs with named interpolation placeholders.
Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b063209c-afd0-40e3-986c-77bebad283d6
📥 Commits
Reviewing files that changed from the base of the PR and between 4f0e380 and c65e6e73e36c03d1b1dac4aab5ffbb386169d961.
📒 Files selected for processing (6)
src/cli/specs/browser-basic.tssrc/main/browser/offscreen-browser-backend-lifecycle.test.tssrc/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-tab-cap-reclaim.test.tssrc/main/browser/offscreen-browser-tab-capacity.tssrc/main/browser/offscreen-renderer-process-reclaim.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — two minor suggestions inline, and one shutdown-drain observation below.
Reviewed changes
- Tab cap —
createTabnow refuses pastmaxTabs(default 4,ORCA_MAX_OFFSCREEN_BROWSER_TABS1–64) with abrowser_tab_capacityBrowserError, and the refusal happens before aBrowserWindowis constructed. - Bounded close + forced reclaim —
closeTabremoves tracking first, bounds owner retirement to 5s, destroys the window regardless, then polls-then-SIGKILLs the renderer process, skipping renderers still shared with a live window. - New modules —
offscreen-browser-tab-capacity.ts(env parsing) andoffscreen-renderer-process-reclaim.ts(poll/kill + shared-renderer guard). - Coverage — new
offscreen-browser-tab-cap-reclaim.test.tsplus agetOSProcessIdmock andmaxTabs: 6bump in the lifecycle suite;tab createhelp notes added.
I verified the cap/reclaim and lifecycle suites pass (18 tests) and confirmed the error surfaces correctly through mapBrowserError (browser error codes are passthrough) and that orca tab close --page <id> is a valid command via effectiveAllowedFlags.
ℹ️ Shutdown retirement drain is still unbounded
settleOwnerRetirement bounds the per-close wait, but destroyAll still ends in await Promise.all(this.pendingOwnerRetirements) with no deadline. A wedged page whose onPageClosed never settles — the exact #14552 failure mode — would keep the browser teardown pending until the outer settleTeardownWithinDeadline backstop in main-process-quit.ts fires. The forced reclaim will likely un-wedge the close (the SIGKILL drops the CDP socket session.proxy.stop() is waiting on), so this reads more as a redundant backstop than a regression, but it's worth confirming the drain join is meant to stay unbounded.
Technical details
# Shutdown retirement drain
## Affected sites
- src/main/browser/offscreen-browser-backend.ts:196 — `await Promise.all(this.pendingOwnerRetirements)` has no deadline; a still-pending `retirePageOwner` promise is not removed by the 5s settle, only by its own settlement.
- src/main/startup/main-process-quit.ts:231 — `browserShutdown` is wrapped in `settleTeardownWithinDeadline`, the current backstop.
## Required outcome
- Confirm whether `destroyAll` should bound this final drain (mirror `OWNER_RETIREMENT_TIMEOUT_MS`, or `allSettled` with a deadline) so a wedged owner retirement doesn't ride the quit deadline.
## Open questions for the human
- Does `session.proxy.stop()` reliably settle once `reclaimRendererProcess` SIGKILLs the wedged renderer? If yes, this drain simply resolves after the reclaim and needs no change.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…tream #19628) (#369) Port de stablyai/orca#19628. Cada tab offscreen es un BrowserWindow con su propio proceso renderer, y en un `orca serve` headless nada reclama el que un agente se olvido de cerrar — tampoco hay ventana donde se vea crecer. Upstream midio un dia de trabajo llegando a 9 tabs con 6 renderers de 220-480 MB en un host de 4 vCPU / 8 GB: load 6.85, 2.5 GB de swap, y un cliente que solo decia "Reconnecting to remote runtime". Nos aplica directo: contabo corre dos instancias en 11 GiB. Los dos modulos nuevos entran tal cual. El backend se adapta porque el nuestro es anterior al de upstream: - Nuestro constructor no tenia options bag; se agrega uno con `maxTabs` y `rendererProcessControl` solamente. El `getAgentBrowserBridge` de upstream no existe aca. - No tenemos `retirePageOwner`, asi que la parte de `settleOwnerRetirement` no aplica; queda el reclamo del renderer, que es lo que libera el puesto. - No tenemos taxonomia de errores de browser. En vez de inventarla para cargar un codigo, la refusal declara su propia clase con el MISMO codigo que usa upstream (`browser_tab_capacity`), asi un caller que ya lo maneja sigue andando. Queda fuera un caso de test de upstream: "does not spend a slot on a page the registry refused" afirma un camino que aca no existe — nuestro `registerOffscreenGuest` devuelve `void` y no puede rechazar. Hacerlo rechazable es cambiar el contrato de browser-manager, que es otra cosa. 654 tests de browser en verde.
c65e6e7 to
1953a47
Compare
There was a problem hiding this comment.
Important
The clamp change breaks the new cap test: '65' now resolves to 64 (clamped via Math.min), not the default 4, so offscreen-browser-tab-cap-reclaim.test.ts fails with expected 64 to be 4. CI is red on this branch — the test was not updated to match the new clamp behavior.
Reviewed changes
- Clamp high overrides —
resolveOffscreenBrowserTabCapnow clamps values above64to the ceiling instead of falling back to the default, per prior feedback. - Injectable retirement timeout —
ownerRetirementTimeoutMsthreads through the backend options, replacing the hardcodedOWNER_RETIREMENT_TIMEOUT_MS. - Closing tabs count toward the cap — a new
closingPageIdsset is folded intocreateTab's capacity check so a create can't slip in while a tab is mid-close. - Bounded shutdown drain — the 5s settle deadline moved into
retirePageOwner, sopendingOwnerRetirements(and thereforedestroyAll'sPromise.all) is now bounded rather than waiting on a wedged renderer. - PID-reuse guard —
reclaimRendererProcessre-reads the renderer's start time at the kill deadline and bails withpid_reusedif the PID was recycled, avoiding a SIGKILL on an unrelated process.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: f6933148-4939-4056-817c-2d1499cb8417
📥 Commits
Reviewing files that changed from the base of the PR and between c65e6e73e36c03d1b1dac4aab5ffbb386169d961 and 1953a47e02736dcc6936ef3ab82ef535a2268acc.
📒 Files selected for processing (3)
src/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-tab-capacity.tssrc/main/browser/offscreen-renderer-process-reclaim.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
1953a47 to
6b791eb
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Fixed the cap-resolution test — removed
'65'from the unusable-overrides loop and asserted'65'/'100'clamp to the64ceiling, matchingresolveOffscreenBrowserTabCap'sMath.minclamp. The previously failing assertion flagged in the prior review now passes.
Verified offscreen-browser-tab-cap-reclaim.test.ts (8 tests) and offscreen-browser-backend-lifecycle.test.ts (10 tests) both pass under config/vitest.config.ts.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
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 (2)
src/main/browser/offscreen-renderer-process-reclaim.ts (2)
75-75: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winFail closed when the renderer identity probe is unavailable.
OffscreenBrowserBackend.closeTabpassesexpectedStartTimeMs: nullwhenreadProcessStartTimeMsfails. At the deadline,reclaimRendererProcessthen skips the identity check and callscontrol.kill(osProcessId). If the PID was reused, this can sendSIGKILLto an unrelated process. Returnpid_reusedwhenexpectedStartTimeMsisnull, after the existing shared-renderer check so that outcome remainsshared.
88-88: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftRecheck shared renderers after the identity read
reclaimRendererProcesschecksisShared(osProcessId), then awaitsreadStartTime(osProcessId)before callingcontrol.kill. During this await, the productionbrowserTabCreateroute can create a same-partitionBrowserWindow. Chromium may assign that tab to the reclaimed renderer. The finalcontrol.killcan then sendSIGKILLto a live tab because no shared-renderer check runs after the await. Recheck sharing immediately beforecontrol.kill, or synchronize tab creation with this decision.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: bf82c281-4390-4bb8-b0e1-f41d934384d3
📥 Commits
Reviewing files that changed from the base of the PR and between 1953a47e02736dcc6936ef3ab82ef535a2268acc and 6b791eb1957fe1cb262975379404b13c43a84cb5.
📒 Files selected for processing (1)
src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Bounded the close-path start-time probe with
resolveWithTimeout(1s), so a probe that never answers can no longer holdcloseTabopen; a timed-out probe degrades toexpectedStartTimeMs: nulland reclaim still proceeds. - Re-checked the shared-renderer guard in
reclaimRendererProcessafter the deadline start-time read, closing the window where a same-site sibling could be co-hosted mid-await and then caught by theSIGKILL. - Added regression coverage for both: the probe-hang case now runs under fake timers and asserts teardown completes, plus
'shared'(shared during the probe) and'pid_reused'cases.
Both suites pass (21 tests) and pnpm run typecheck:node is clean.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Review Feedback Updates (
|
stablyai#14552) A headless `orca serve` backs every agent-opened tab with its own offscreen BrowserWindow, and nothing bounded that population: stablyai#14552 measured 9 open tabs behind 6 renderers of 220-480 MB each in one working day, taking a 4 vCPU / 8 GB host to a 6.85 load average and 2.5 GB of swap. With no window to reveal the growth, the only symptom reaching the paired client was "Reconnecting to remote runtime". Cap the offscreen backend at 4 concurrent tabs — any default of 6 or more still admits the renderer count that was already saturating that host — and refuse the create past it with `browser_tab_capacity`, naming the page to close. Refusing beats evicting: an open page is a measurement in progress whose state an agent cannot recover. `ORCA_MAX_OFFSCREEN_BROWSER_TABS` raises it on larger hosts. Closing is what makes the cap survivable, so it can no longer be blocked by the page it is closing. Owner retirement now settles against a 5s deadline instead of waiting on a renderer that has stopped answering, and once the window is destroyed the renderer's OS process is reclaimed: it is given a second to exit on its own, then SIGKILLed if it never does. A process still rendering another live window is left alone, since Chromium shares one renderer across same-site pages.
0f8104e to
df4862b
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b819999a-408c-4396-a00f-3fb575a9f049
📥 Commits
Reviewing files that changed from the base of the PR and between 0f8104eda925a07c095803479c704f00441aff46 and df4862b.
📒 Files selected for processing (4)
src/cli/specs/browser-basic.tssrc/main/browser/offscreen-browser-backend.tssrc/main/browser/offscreen-browser-tab-cap-reclaim.test.tssrc/main/browser/offscreen-renderer-process-reclaim.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/cli/specs/browser-basic.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| if (osProcessId > 0) { | ||
| await reclaimRendererProcess(osProcessId, { | ||
| control: this.rendererProcessControl, | ||
| expectedStartTimeMs | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '155,245p' src/main/browser/offscreen-browser-backend.ts
sed -n '20,110p' src/main/browser/offscreen-renderer-process-reclaim.ts
rg -n 'closeTab\(' src/main/browser src/cli | head -60Repository: stablyai/orca
Length of output: 7572
🏁 Script executed:
set -o pipefail
printf '%s\n' '--- closeTab references ---'
rg -n -C 4 'closeTab|\.closeTab' src --glob '!**/*.map'
printf '%s\n' '--- browser backend interface and implementations ---'
sed -n '1,120p' src/main/browser/browser-backend.ts
sed -n '1,260p' src/main/browser/offscreen-browser-backend.ts
printf '%s\n' '--- reclamation tests and lifecycle tests around close ---'
sed -n '1,360p' src/main/browser/offscreen-browser-backend-lifecycle.test.ts
sed -n '1,340p' src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
printf '%s\n' '--- dependency/version declarations ---'
rg -n -C 2 '"electron"|"@electron|electronVersion' package.json package-lock.json pnpm-lock.yaml yarn.lock .npmrc 2>/dev/null | head -100Repository: stablyai/orca
Length of output: 45339
🏁 Script executed:
set -o pipefail
printf '%s\n' '--- main closeTab bindings ---'
rg -n -C 8 'terminal\.closeTab|closeTab\s*[:=]|\.closeTab\(' src/main src/shared --glob '*.ts' --glob '!**/*.json'
printf '%s\n' '--- backend ownership and construction ---'
rg -n -C 6 'OffscreenBrowserBackend|BrowserBackend|offscreenBrowser' src/main --glob '*.ts'
printf '%s\n' '--- focused lifecycle reclaim/close tests ---'
rg -n -C 10 'reclaim|renderer|closeTab|throws|rejects' src/main/browser/offscreen-browser-backend-lifecycle.test.ts src/main/browser/offscreen-browser-tab-cap-reclaim.test.tsRepository: stablyai/orca
Length of output: 42773
🏁 Script executed:
set -o pipefail
printf '%s\n' '--- exact terminal close RPC references ---'
rg -n -C 12 'terminal\.closeTab' src --glob '*.ts'
printf '%s\n' '--- named browser-tab-close command ---'
fd -i 'runtime-browser-commands-browser-tab-close.ts' src
file=$(fd -i 'runtime-browser-commands-browser-tab-close.ts' src | head -1)
[ -n "$file" ] && sed -n '1,280p' "$file"
printf '%s\n' '--- offscreen backend setup and close callers ---'
rg -n -C 10 'setOffscreenBrowserBackend|new OffscreenBrowserBackend|offscreenBrowserBackend|\.closeTab\(' src/main/runtime src/main/browser src/main/orcad --glob '*.ts'
printf '%s\n' '--- reclaim symbol and default control references ---'
rg -n -C 10 'reclaimRendererProcess|rendererProcessControl|rendererProcessIsShared|BrowserWindow\.getAllWindows|getOSProcessId' src/main/browser --glob '*.ts' --glob '!*.test.ts'Repository: stablyai/orca
Length of output: 42880
🏁 Script executed:
set -o pipefail
printf '%s\n' '--- closeTerminalTab implementation ---'
rg -n -C 12 'closeTerminalTab' src/main/runtime src/main --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- exact browser offscreen close block ---'
file=$(fd -i 'runtime-browser-commands-browser-tab-close.ts' src | head -1)
[ -n "$file" ] && rg -n -C 18 'offscreen|closeTab|closed: true|retire' "$file"
printf '%s\n' '--- production backend construction ---'
rg -n -C 14 'new OffscreenBrowserBackend|rendererProcessControl' src --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- close attribution boundary ---'
sed -n '1,130p' src/main/runtime/rpc/terminal-close-attribution.ts
sed -n '145,180p' src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.tsRepository: stablyai/orca
Length of output: 42467
🌐 Web query:
official Electron 43 BrowserWindow getAllWindows isDestroyed webContents getOSProcessId behavior destroyed window exceptions
💡 Result:
For Electron 43, the documented behavior is:
- **`BrowserWindow.getAllWindows()`** returns an array of all open browser windows. ([electronjs.org](https://www.electronjs.org/docs/latest/api/browser-window?utm_source=openai))
- **`win.isDestroyed()`** returns whether that window has been destroyed. Check it before accessing properties that may throw. In particular, **reading `win.webContents` after the window is destroyed throws** `Object has been destroyed`. ([electronjs.org](https://www.electronjs.org/docs/latest/api/browser-window?utm_source=openai))
- **`win.webContents.isDestroyed()`** reports whether the `WebContents` is destroyed. After destruction, it is no longer usable; Electron documents a `destroyed` event. ([electronjs.org](https://www.electronjs.org/docs/latest/api/web-contents?utm_source=openai))
- **`webContents.getOSProcessId()`** returns the OS PID of the associated renderer process. The docs do not specify a special return value or guarantee for calling it after destruction, so check liveness first rather than relying on its behavior. ([electronjs.org](https://www.electronjs.org/docs/latest/api/web-contents?utm_source=openai))
```js
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
const contents = win.webContents;
if (contents.isDestroyed()) continue;
const pid = contents.getOSProcessId();
}
```
The separate checks matter if destruction can occur between operations.
Citations:
- 1: https://www.electronjs.org/docs/latest/api/browser-window?utm_source=openai
- 2: https://www.electronjs.org/docs/latest/api/browser-window?utm_source=openai
- 3: https://www.electronjs.org/docs/latest/api/web-contents?utm_source=openai
- 4: https://www.electronjs.org/docs/latest/api/web-contents?utm_source=openai
Do not let renderer reclamation failures reject closeTab after teardown.
closeTab destroys the window before it awaits reclaimRendererProcess. The default sharing check accesses window.webContents after only checking window.isDestroyed(), and Electron does not guarantee getOSProcessId() after WebContents destruction. A configured RendererProcessControl.isAlive can also throw.
The offscreen close command awaits this operation before retiring the session row. The terminal-close RPC records the failure and rethrows it, so callers can receive an error even though the page was removed. Catch and log reclamation failures.
Suggested fix
if (osProcessId > 0) {
- await reclaimRendererProcess(osProcessId, {
- control: this.rendererProcessControl,
- expectedStartTimeMs
- })
+ await reclaimRendererProcess(osProcessId, {
+ control: this.rendererProcessControl,
+ expectedStartTimeMs
+ }).catch((error) => {
+ console.warn(
+ '[offscreen-browser] renderer reclaim failed:',
+ error instanceof Error ? error.message : String(error)
+ )
+ })
}📝 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.
| if (osProcessId > 0) { | |
| await reclaimRendererProcess(osProcessId, { | |
| control: this.rendererProcessControl, | |
| expectedStartTimeMs | |
| }) | |
| if (osProcessId > 0) { | |
| await reclaimRendererProcess(osProcessId, { | |
| control: this.rendererProcessControl, | |
| expectedStartTimeMs | |
| }).catch((error) => { | |
| console.warn( | |
| '[offscreen-browser] renderer reclaim failed:', | |
| error instanceof Error ? error.message : String(error) | |
| ) | |
| }) |
| if (expectedStartTime !== null) { | ||
| const currentStartTime = await readStartTime(osProcessId).catch(() => null) | ||
| if ( | ||
| currentStartTime === null || | ||
| Math.abs(currentStartTime - expectedStartTime) > PROCESS_START_TIME_TOLERANCE_MS | ||
| ) { | ||
| // The original process exited and its PID was reused or is no longer verifiable. | ||
| return 'pid_reused' | ||
| } | ||
| } | ||
| if (isShared(osProcessId)) { | ||
| return 'shared' | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '60,112p' src/main/browser/offscreen-renderer-process-reclaim.ts
sed -n '165,210p' src/main/browser/offscreen-browser-backend.ts
sed -n '150,173p' src/main/runtime/agent-session-process-identity-probe.tsRepository: stablyai/orca
Length of output: 4323
🏁 Script executed:
set -eu
printf '%s\n' '--- reclaim file outline and relevant source ---'
ast-grep outline src/main/browser/offscreen-renderer-process-reclaim.ts
sed -n '1,150p' src/main/browser/offscreen-renderer-process-reclaim.ts
printf '%s\n' '--- identity probe outline and implementations ---'
ast-grep outline src/main/runtime/agent-session-process-identity-probe.ts
rg -n -A35 -B8 'function readLinuxProcessStartTimeMs|function readDarwinProcessStartTimeMs|function readWindowsProcessStartTimeMs|readProcessStartTimeMs|execFile|spawn' src/main/runtime/agent-session-process-identity-probe.ts
printf '%s\n' '--- timeout helper and constants ---'
rg -n -A25 -B10 'resolveWithTimeout|START_TIME_PROBE_TIMEOUT_MS|RENDERER_EXIT_(GRACE|POLL)_MS' src/main
printf '%s\n' '--- callers and tests ---'
rg -n -A30 -B12 'reclaimRendererProcess|closeTab|readStartTimeMs|expectedStartTimeMs' src test tests 2>/dev/null || true
printf '%s\n' '--- changed diff summary and focused diff ---'
git diff --stat d04b05b5c8f0b8074a7e316c8cd6ccdbbddf7e2c df4862bc0c7792aff1e34803b408456788678818
git diff --unified=20 d04b05b5c8f0b8074a7e316c8cd6ccdbbddf7e2c df4862bc0c7792aff1e34803b408456788678818 -- src/main/browser/offscreen-renderer-process-reclaim.ts src/main/browser/offscreen-browser-backend.tsRepository: stablyai/orca
Length of output: 45642
🏁 Script executed:
set -eu
printf '%s\n' '--- timeout helper ---'
rg -n -A45 -B10 'export function resolveWithTimeout|function resolveWithTimeout' src/main/browser/browser-manager-types.ts
printf '%s\n' '--- identity probe imports and process helpers ---'
sed -n '1,145p' src/main/runtime/agent-session-process-identity-probe.ts
rg -n -A35 -B15 'function runProcess|const runProcess|readWindowsProcessIdentityTableFresh|isWindowsProcessStartTimeAvailable' src/main/runtime
printf '%s\n' '--- backend close and retirement ---'
sed -n '160,220p' src/main/browser/offscreen-browser-backend.ts
sed -n '300,360p' src/main/browser/offscreen-browser-backend.ts
printf '%s\n' '--- focused tests ---'
fd -i 'offscreen.*(test|spec)|renderer.*reclaim' src
rg -n -A35 -B20 'reclaimRendererProcess|expectedStartTimeMs|START_TIME_PROBE_TIMEOUT_MS|closeTab|ownerRetirementTimeoutMs' src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts src/main/browser/offscreen-browser-backend-lifecycle.test.tsRepository: stablyai/orca
Length of output: 42064
🏁 Script executed:
set -eu
printf '%s\n' '--- focused reclaim test slices ---'
sed -n '1,45p' src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
sed -n '220,292p' src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
printf '%s\n' '--- Windows process table implementation ---'
rg -n -A80 -B20 'readWindowsProcessIdentityTableFresh|runProcess|timeoutMs|isWindowsProcessStartTimeAvailable' src/main/windows/windows-process-table.ts
printf '%s\n' '--- runProcess contract ---'
sed -n '1,180p' src/shared/child-process/run-process.tsRepository: stablyai/orca
Length of output: 14726
Bound the post-grace start-time probe.
When closeTab obtains a start time, reclaimRendererProcess can await a later readStartTime call indefinitely. The initial probe timeout and owner-retirement timeout do not cover this later call. Treat a timed-out probe as null so the existing pid_reused path returns.
Suggested fix
import { BrowserWindow } from 'electron'
+import { resolveWithTimeout } from './browser-manager-types'
import {
PROCESS_START_TIME_TOLERANCE_MS,
readProcessStartTimeMs
} from '../runtime/agent-session-process-identity-probe'
@@
const RENDERER_EXIT_GRACE_MS = 1_000
const RENDERER_EXIT_POLL_MS = 25
+const RENDERER_START_TIME_PROBE_TIMEOUT_MS = 1_000
@@
if (expectedStartTime !== null) {
- const currentStartTime = await readStartTime(osProcessId).catch(() => null)
+ const currentStartTime = (
+ await resolveWithTimeout(
+ readStartTime(osProcessId).catch(() => null),
+ RENDERER_START_TIME_PROBE_TIMEOUT_MS,
+ null
+ )
+ ).value
if (
currentStartTime === null ||Refuse SIGKILL when renderer start-time is unknown, reclaim on unexpected destroy, and hold the tab-cap slot through reclaim so close cannot oversubscribe headless serve mid-grace. Split identity and page-load helpers so the backend stays under the file line gate.
|
Thanks for working on this, @LesleyMurfin. We took #14552 in a different direction: #42686 frees idle serve tabs and brings them back under the same page id when they're used again, rather than refusing new tabs past a cap, and #42660 stops unwatched tabs from painting. I'm leaving this PR open for now. |

ELI5
Agent-opened headless browser tabs on a remote
serveused to pile up without limit — every tab a renderer process, none of them ever reclaimed. Now they stop at a small cap, and closing a tab actually kills its process even if the renderer has stopped answering.Previously a wedged renderer could hold its slot forever: the close path waited on the very process that was no longer responding, so the tab never went away and the slot never came back.
Closes #14552.
Behavior and implementation
ORCA_MAX_OFFSCREEN_BROWSER_TABS(accepted range 1–64).browser_tab_capacityrather than queueing or silently spawning. The error names the fix: close a tab, or raise the env var.tab closenow always frees the slot, in this order:SIGKILL.BrowserWindowstill shares that renderer process, so killing one tab can never take down a sibling that happens to be co-hosted.Validation
Verified against a real headless
serve, not mocks:browser_tab_capacity.psshowed exactly 4 renderer processes — the cap is real at the OS level, not just bookkeeping.SIGSTOP'd renderer's tab was closed anyway in 1.297s (inside the 5s deadline), and the pid was confirmed gone, not zombied.Unit/integration coverage lands in
offscreen-browser-tab-cap-reclaim.test.ts(new, 226 lines) plus updates to the existing lifecycle suite.No full-repository test run or release build is claimed. No merge performed.
Visual proof
N/A for rendered UI — this is headless browser backend and CLI behavior. Behavioral proof is the live headless
serverun above (create refusals,psrenderer count, theSIGSTOPclose timing and pid reclamation), plus the regression tests.Files touched
src/main/browser/offscreen-browser-backend.ts— cap check on create, reordered/deadlined close pathsrc/main/browser/offscreen-browser-tab-capacity.ts(new) — cap resolution andORCA_MAX_OFFSCREEN_BROWSER_TABSparsingsrc/main/browser/offscreen-renderer-process-reclaim.ts(new) — poll-then-SIGKILLreclaim with shared-renderer guardsrc/main/browser/offscreen-browser-tab-cap-reclaim.test.ts(new) — cap and reclaim regression coveragesrc/main/browser/offscreen-browser-backend-lifecycle.test.ts— updated for the new close orderingsrc/cli/specs/browser-basic.ts— surfaces thebrowser_tab_capacityfailureLinked Issue
Architectural Context (RFC #21556)