Skip to content

fix(browser): cap and reclaim offscreen browser tabs on headless serve - #19628

Open
LesleyMurfin wants to merge 5 commits into
stablyai:mainfrom
LesleyMurfin:ai/14552-tab-cap
Open

LesleyMurfin wants to merge 5 commits into
stablyai:mainfrom
LesleyMurfin:ai/14552-tab-cap

Conversation

@LesleyMurfin

@LesleyMurfin LesleyMurfin commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Agent-opened headless browser tabs on a remote serve used 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

  • Default cap is 4 concurrent offscreen tabs, overridable via ORCA_MAX_OFFSCREEN_BROWSER_TABS (accepted range 1–64).
  • Creating a tab beyond the cap fails fast with browser_tab_capacity rather than queueing or silently spawning. The error names the fix: close a tab, or raise the env var.
  • tab close now always frees the slot, in this order:
    1. tracking removal happens first, so the slot is released even if everything downstream fails;
    2. retirement gets a 5s deadline instead of waiting unboundedly on the renderer;
    3. the window is destroyed regardless of whether retirement succeeded;
    4. the OS process is force-reclaimed — poll, then SIGKILL.
  • The force-reclaim step is skipped when a live BrowserWindow still 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:

  • Cap enforced: 6 creates → 4 succeeded, 2 refused with browser_tab_capacity.
  • Processes match the cap: ps showed exactly 4 renderer processes — the cap is real at the OS level, not just bookkeeping.
  • Wedged renderer still closes: a SIGSTOP'd renderer's tab was closed anyway in 1.297s (inside the 5s deadline), and the pid was confirmed gone, not zombied.
  • Slot genuinely returned: a fresh create after that close succeeded, proving the freed slot was usable and not merely decremented.

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 serve run above (create refusals, ps renderer count, the SIGSTOP close timing and pid reclamation), plus the regression tests.

Files touched

  • src/main/browser/offscreen-browser-backend.ts — cap check on create, reordered/deadlined close path
  • src/main/browser/offscreen-browser-tab-capacity.ts (new) — cap resolution and ORCA_MAX_OFFSCREEN_BROWSER_TABS parsing
  • src/main/browser/offscreen-renderer-process-reclaim.ts (new) — poll-then-SIGKILL reclaim with shared-renderer guard
  • src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts (new) — cap and reclaim regression coverage
  • src/main/browser/offscreen-browser-backend-lifecycle.test.ts — updated for the new close ordering
  • src/cli/specs/browser-basic.ts — surfaces the browser_tab_capacity failure

Linked Issue

Architectural Context (RFC #21556)

  • Roadmap Phase: Step 1: Launch & Bind
  • Severity / Priority: P2 (Medium)
  • Why It Ties into the Lifecycle: Automated subagents spawning headless browser tabs could allocate unbounded Chromium renderers without concurrency ceilings.
  • System Impact: Enforces a 4-tab concurrency cap and 5s SIGKILL watchdog on headless browser renderers, preventing memory exhaustion on headless servers.
  • Master Tracking RFC: Part of stablyai/orca#21556

@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

The offscreen browser backend enforces a default four-tab limit with an environment override and a browser_tab_capacity error. Tab closure tracks closing pages, bounds owner retirement and start-time probes, and attempts renderer reclamation while checking for shared or reused processes. Tests cover capacity handling, environment validation, stalled teardown, and renderer process outcomes. The CLI specification describes the limit and recovery options.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to df486

Tab closure can hang or report failure after closing the page, and an unavailable process-identity reading leaves a risk of killing an unrelated process. Resolve these paths before merging.

Security architecture risk: 🟡 Moderate · up to df486

The tab limit reduces uncontrolled resource use, but the new forced-cleanup path can lose its process-identity safeguard when a probe fails. Some cleanup failures can also leave a close unfinished or report success without confirming that the process exited.

Retained concerns

  • Medium · security · inferred: A failed or timed-out initial identity probe permits the new reclamation path to SIGKILL a live, non-shared PID without confirming it still belongs to the closed renderer. If that PID has been reused, another process could be killed.
  • Medium · reliability · inferred: After the grace period, reclamation can await a second start-time probe without a deadline. If it stalls, tab close remains pending after window teardown, delaying caller-visible completion and session-row retirement.
  • Medium · reliability · inferred: The default process control suppresses every SIGKILL error, after which reclamation reports the process killed and tab close can succeed. A genuine signaling failure can therefore leave a renderer running outside the active-tab count.
Security review details

Security Blast Radius

  • inferred — One accepted offscreen close can reach an OS-level kill for its captured renderer PID. Under failed identity probing and PID reuse, the possible effect extends to a different process signalable by the serving process; it is not an unrestricted caller-supplied PID.

Security Findings and Attack Paths

  • inferred — A caller able to close a registered offscreen page can trigger reclamation. If the initial probe fails and the captured PID is reused before signaling, the null-identity path can kill the replacement process. Probe failure and timely PID reuse have not been shown to occur together in production.

Trust Boundaries and Controls

  • observed — The offscreen runtime branch checks explicit pages against registered tabs for the resolved worktree. The RPC close handler passes parameters to the runtime without caller identity; whether the outer transport authenticates or further scopes callers was not established.

Resilience and Maintainability Implications

  • inferred — An unbounded later identity probe or suppressed kill error can break the intended relationship between completed close, session cleanup, and renderer exit. These are failure-path limits on the new resource-containment guarantee, not evidence that every close fails.

Hardening Proposals

  • proposed — Require verified process-instance identity before forced signaling, bound the post-grace probe, and make signaling failure distinguishable from confirmed exit so lifecycle owners can reconcile an incomplete close.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
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.

❤️ 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/main/browser/offscreen-browser-tab-capacity.ts (1)

42-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Localize 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.ts
  • src/main/browser/offscreen-browser-backend-lifecycle.test.ts
  • src/main/browser/offscreen-browser-backend.ts
  • src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
  • src/main/browser/offscreen-browser-tab-capacity.ts
  • src/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.

@pullfrog pullfrog 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.

ℹ️ No critical issues — two minor suggestions inline, and one shutdown-drain observation below.

Reviewed changes

  • Tab cap — createTab now refuses past maxTabs (default 4, ORCA_MAX_OFFSCREEN_BROWSER_TABS 1–64) with a browser_tab_capacity BrowserError, and the refusal happens before a BrowserWindow is constructed.
  • Bounded close + forced reclaim — closeTab removes 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) and offscreen-renderer-process-reclaim.ts (poll/kill + shared-renderer guard).
  • Coverage — new offscreen-browser-tab-cap-reclaim.test.ts plus a getOSProcessId mock and maxTabs: 6 bump in the lifecycle suite; tab create help 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

fabolivark added a commit to ab2webco/orca-oss that referenced this pull request Sep 9, 2026
…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.
@svc-orca
svc-orca Bot force-pushed the ai/14552-tab-cap branch from c65e6e7 to 1953a47 Compare September 11, 2026 06:39

@pullfrog pullfrog 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.

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 — resolveOffscreenBrowserTabCap now clamps values above 64 to the ceiling instead of falling back to the default, per prior feedback.
  • Injectable retirement timeout — ownerRetirementTimeoutMs threads through the backend options, replacing the hardcoded OWNER_RETIREMENT_TIMEOUT_MS.
  • Closing tabs count toward the cap — a new closingPageIds set is folded into createTab'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, so pendingOwnerRetirements (and therefore destroyAll's Promise.all) is now bounded rather than waiting on a wedged renderer.
  • PID-reuse guard — reclaimRendererProcess re-reads the renderer's start time at the kill deadline and bails with pid_reused if the PID was recycled, avoiding a SIGKILL on an unrelated process.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

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.ts
  • src/main/browser/offscreen-browser-tab-capacity.ts
  • src/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.

@svc-orca
svc-orca Bot force-pushed the ai/14552-tab-cap branch from 1953a47 to 6b791eb Compare September 11, 2026 06:50

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Fixed the cap-resolution test — removed '65' from the unusable-overrides loop and asserted '65'/'100' clamp to the 64 ceiling, matching resolveOffscreenBrowserTabCap's Math.min clamp. 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

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 win

Fail closed when the renderer identity probe is unavailable. OffscreenBrowserBackend.closeTab passes expectedStartTimeMs: null when readProcessStartTimeMs fails. At the deadline, reclaimRendererProcess then skips the identity check and calls control.kill(osProcessId). If the PID was reused, this can send SIGKILL to an unrelated process. Return pid_reused when expectedStartTimeMs is null, after the existing shared-renderer check so that outcome remains shared.


88-88: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Recheck shared renderers after the identity read

reclaimRendererProcess checks isShared(osProcessId), then awaits readStartTime(osProcessId) before calling control.kill. During this await, the production browserTabCreate route can create a same-partition BrowserWindow. Chromium may assign that tab to the reclaimed renderer. The final control.kill can then send SIGKILL to a live tab because no shared-renderer check runs after the await. Recheck sharing immediately before control.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.

@pullfrog pullfrog 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.

✅ 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 hold closeTab open; a timed-out probe degrades to expectedStartTimeMs: null and reclaim still proceeds.
  • Re-checked the shared-renderer guard in reclaimRendererProcess after the deadline start-time read, closing the window where a same-site sibling could be co-hosted mid-await and then caught by the SIGKILL.
  • 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@LesleyMurfin

Copy link
Copy Markdown
Contributor Author

Review Feedback Updates (6b791eb & 0f8104e)

All reviewer comments from CodeRabbit and Pullfrog have been addressed:

  1. Capacity Accounting: In-flight closing tabs are now tracked in closingPageIds so capacity reservations remain held until destruction completes (windowsByPageId.size + closingPageIds.size).
  2. Bounded Shutdown: Owner retirement is bounded by retirementTimeoutMs via a settled timer promise, preventing shutdown hangs on wedged renderers.
  3. PID Reuse Guard: Renderer reclamation verifies process start-time identity before issuing SIGKILL, returning pid_reused on mismatch.
  4. Bounded Start-Time Probe: Wrapped start-time probe in closeTab with resolveWithTimeout (1,000ms timeout, fallback null) so slow /proc reads never stall teardown.
  5. Shared Renderer Race Guard: Added an immediate isShared recheck after the start-time probe yield directly before control.kill to protect co-hosted sibling windows.

All 38 browser unit and lifecycle tests pass cleanly.

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.

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

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.ts
  • src/main/browser/offscreen-browser-backend.ts
  • src/main/browser/offscreen-browser-tab-cap-reclaim.test.ts
  • src/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.

Comment on lines +194 to +198
if (osProcessId > 0) {
await reclaimRendererProcess(osProcessId, {
control: this.rendererProcessControl,
expectedStartTimeMs
})

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.

🩺 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 -60

Repository: 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 -100

Repository: 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.ts

Repository: 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.ts

Repository: 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.

Suggested change
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)
)
})

Comment on lines +89 to +101
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'
}

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.

🩺 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.ts

Repository: 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.ts

Repository: 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.ts

Repository: 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.ts

Repository: 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.
@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

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.

This branch has not been deployed

No deployments
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.

[Bug]: Agent-driven built-in browser tabs are never reclaimed on headless serve — one renderer per tab, no cap

2 participants