Skip to content

fix(terminal): bound a pane's wait on a spawn that never settles - #19318

Open
brennanb2025 wants to merge 13 commits into
mainfrom
brennanb2025/fix-hung-spawn-pane-pin
Open

brennanb2025 wants to merge 13 commits into
mainfrom
brennanb2025/fix-hung-spawn-pane-pin

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​374 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​371
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​244 $\color{#cf222e}{\Huge{\mathbf{−}}}$​32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​212

Follow-up to #19223, which fixed a pane left unbound by a spawn that settled without a PTY id. This covers the other half: a spawn that never settles at all.

The gap

pty:spawn is a bare ipcRenderer.invoke with no timeout. In fresh-spawn-start.ts both the pane-key unpin (.finally) and #19223's recovery hook (.then) hang off the same promise, so a main handler that never resolves:

The pane ends up mounted and unbound, its output accumulating in the pre-handler buffer, with the same invisible freeze #19223 was written to stop.

Why not a timeout on the invoke

A reject in the renderer cannot cancel main's spawn. Racing the invoke would respawn a slow-but-alive shell and orphan the late PTY, with nobody left to retire it. This times out the pane's waiting instead; the existing spawn-retirement path already handles a late settlement.

On fire the watchdog unpins under an identity guard, defers to the direct-SSH retry ledger, and routes to the same remount seam under its own reason (spawn-never-settled) so field triage can tell a hung spawn from a settled one. A disposed arming pane recovers by tab, since an adopter may still be waiting on the pin.

The resume exclusion — deliberate freeze-over-corruption trade

Resume spawns are excluded from the timer-triggered remount, and this is the important part of the PR.

A cold-restore spawn clears its sleeping record only once it settles, and a late one is deliberately not retired (it may own a recycled id). So remounting a hung resume would start a second --resume against the same transcript with the first process still live — two agents writing one conversation.

Nothing existing bounds that. The sleeping record survives an unsettled spawn; retireFreshSpawn skips coldRestore results; spawn-preflight has no duplicate-resume admission gate; and the renderer's provider-session claim is pane-scoped, so same-pane re-entry across a remount passes it. A wedged invoke can also occur after main launched the child, so "hung means nothing started" is false here.

Those spawns therefore get pin GC and an anomaly breadcrumb, but never a remount. A stuck pane is recoverable by hand; a duplicated agent session is not. Lifting this needs a main-side duplicate-resume admission gate keyed on provider session id — noted, not attempted here.

Also in this PR

Both outcomes of a spawn now live together in unbound-pane-spawn-recovery.ts rather than being split across the caller. That was needed to keep fresh-spawn-start.ts under its 300-line cap without a lint disable, and it leaves the caller smaller.

Verification

  • Red-green, run locally: ablating the arming fails the wiring test with Number of calls: 0; restoring is green and byte-identical to HEAD. The wiring test deliberately goes through observeSpawnSettlement rather than calling the watchdog directly — an earlier draft's unit tests passed under ablation because they proved the function worked without proving anything armed it.
  • Tests cover: hang → remount, pin GC, a newer spawn's pin left alone, transport bound meanwhile, SSH-ledger deference, disposed-pane tab-keyed recovery, cancel on settle, and both resume cases.
  • terminal-pane suite: 441 files / 4233 tests pass. tc:web clean.

Note for anyone running a full typecheck

pnpm tc is red on main independently of this branch: duplicate lastActivityAt properties cause TS1117 in src/main/agent-hooks/first-work-branch-rename.test.ts.

Merge Sim added 2 commits September 7, 2026 10:28
pty:spawn is a bare ipcRenderer.invoke with no timeout, and both the pane-key
unpin (.finally) and the settled-spawn recovery hook (.then) hang off the same
promise. A main handler that never resolves therefore pins pendingSpawnByPaneKey
forever AND starves the recovery added in #19223 — the pane stays mounted and
unbound, its output accumulates in the pre-handler buffer, and any remount that
adopts the stranded pin freezes with it.

Time out the pane's waiting rather than the invoke. A reject in the renderer
cannot cancel main's spawn, so racing the invoke would respawn a slow-but-alive
shell and orphan the late PTY; the existing spawn-retirement path already cleans
up a late settlement. On fire the watchdog unpins under an identity guard, defers
to the direct-SSH ledger, and routes to the same remount seam under its own
reason so field triage can tell a hung spawn from a settled one. A disposed
arming pane recovers by tab, since an adopter may still be waiting on the pin.

Both outcomes of a spawn - settles with no id, never settles - now live together
in unbound-pane-spawn-recovery.ts instead of being split across the caller.
A cold-restore spawn clears its sleeping record only once it settles, and a
late one is deliberately not retired because it may own a recycled id. So
remounting a hung resume would start a SECOND --resume against the same
transcript with the first process still live - two agents writing one
conversation.

Nothing existing bounds that: the sleeping record survives an unsettled spawn,
retireFreshSpawn skips coldRestore results, spawn-preflight has no
duplicate-resume admission gate, and the renderer's provider-session claim is
pane-scoped so same-pane re-entry across a remount passes it.

Withhold the remount for those spawns and record the anomaly instead. The pin
GC still runs, since that leak is safe to collect either way. A stuck pane is
recoverable by hand; a duplicated agent session is not. Lifting this needs a
main-side duplicate-resume admission gate keyed on provider session id.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds PTY preparation deadlines, concurrent spawn ownership tracking, and settlement watchdog recovery. Watchdogs clean stranded pending-spawn state and request pane or tab recovery. Resume-session metadata now flows through terminal creation contracts and startup commands. Tests cover timeout fencing, ownership handoff, watchdog behavior, resume classification, and runtime timing.

Priority: ➖ Normal

Merge Risk: 🟠 High · up to 19e3d

Timeout and adoption paths can leave terminal panes hidden or permanently unbound, so these lifecycle issues should be fixed before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives a detailed and relevant explanation of the problem, design, resume behavior, and verification. However, it does not follow the required template structure and omits required sect… Add the missing template sections and complete them. Add an explicit ELI5, What Changed, Why, Linked Issue with Fixes #19223``, and Visual Proof with N/A plus a reason if there is no UI change. Complete Testing with manual test status, pl…
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 45 functions across 52 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: bounding a pane's wait when a PTY spawn never settles. It is concise and specific.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description gives a detailed and relevant explanation of the problem, design, resume behavior, and verification. However, it does not follow the required template structure and omits required sections such as Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist. The linked issue is referenced as a follow-up but not in the required Fixes format.

Resolution

Add the missing template sections and complete them. Add an explicit ELI5, What Changed, Why, Linked Issue with Fixes #19223``, and Visual Proof with N/A plus a reason if there is no UI change. Complete Testing with manual test status, platforms tested, and automation status. Complete AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist entries. Retain the existing verification details and document the known full-typecheck failure separately if needed.

Full details: Docstring Coverage

Explanation

Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 45 functions across 52 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch brennanb2025/fix-hung-spawn-pane-pin

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 8cdfdb3d-0289-4f57-9b43-5dd1820cb0fa

📥 Commits

Reviewing files that changed from the base of the PR and between 83b1558 and de12668.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +14 to +16
// Why a module-level set: a promise is already a unique identity, so arming from
// both the fresh spawn and a remount's pending-spawn adoption cannot double-time it.
const spawnSettlementTimedPromises = new WeakSet<Promise<unknown>>()

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:

#!/bin/bash
set -e
printf '%s\n' '--- target file ---'
sed -n '1,260p' src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
printf '%s\n' '--- adoption caller ---'
sed -n '130,215p' src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
printf '%s\n' '--- related symbols ---'
rg -n -C 3 'armSpawnSettlementWatchdog|spawnSettlementTimedPromises|retry lease|retryLease|direct.*SSH|bound' src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 50369


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 37154


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,260p' src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
sed -n '130,215p' src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
rg -n -C 4 'armSpawnSettlementWatchdog|spawnSettlementTimedPromises|retryLease|direct.*SSH|bound' src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target file ---'
sed -n '1,260p' src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
printf '%s\n' '--- adoption caller ---'
sed -n '130,215p' src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts
printf '%s\n' '--- related definitions and callers ---'
rg -n -C 4 'armSpawnSettlementWatchdog|spawnSettlementTimedPromises|retryLease|direct.*SSH|bound' src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- direct SSH lease implementation ---'
rg -n -C 12 'armDirectSshPaneRetryTimeout|directSshRetryAttempt' src/renderer/src/components/terminal-pane/pty-connection --glob '*.ts' | head -n 220
printf '%s\n' '--- watchdog tests ---'
sed -n '104,232p' src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.ts

Repository: stablyai/orca

Length of output: 33119


🏁 Script executed:

#!/bin/bash
set -e
rg -n 'armDirectSshPaneRetryTimeout' src/renderer/src/components/terminal-pane --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 964


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,110p' src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-retry-status.ts

Repository: stablyai/orca

Length of output: 5882


🏁 Script executed:

#!/bin/bash
set -e
cat -n src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-retry-status.ts | sed -n '1,100p'

Repository: stablyai/orca

Length of output: 6040


Track watchdog arming per session, not only per promise.

The adopting session’s armDirectSshPaneRetryTimeout call returns when it has no retry lease. The WeakSet also rejects its armSpawnSettlementWatchdog call when the original session already armed the promise. The original watchdog can then return because the original session has a direct-SSH retry lease, while no timer evaluates the adopting session. A never-settling spawn can leave the adopter unbound. Track each (trackedPromise, session) pair and add a regression test with a shared never-settling promise, an original retry lease, and no lease on the adopting session.

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

ℹ️ One subtle edge case in the watchdog's recovery decision is worth tightening — nothing blocking.

Reviewed changes

  • Watchdog for never-settling spawns — armSpawnSettlementWatchdog arms a 60s (TRANSPORT_CONNECT_SETTLE_GRACE_MS) timer that unpins the pane key and remounts an unbound pane under a new spawn-never-settled reason, with a module-level WeakSet deduping arming across the fresh-spawn and remount-adoption call sites.
  • Resume-exclusion — cold-restore resume spawns (resumesProviderSession) are frozen (pin GC + anomaly breadcrumb, no remount) to avoid a second --resume on the same transcript.
  • Consolidated spawn outcomes — observeSpawnSettlement now owns both the settled-without-PTY-id recovery and the never-settled watchdog; fresh-spawn-start.ts and deferred-session-reattach-choice.ts route through it.
  • Tests — red-green coverage for hang→remount, pin GC, newer-spawn pin preservation, transport-bound, SSH-ledger deference, disposed-pane tab recovery, settle-cancel, and both resume cases.

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

…e spawn

The watchdog's resume exclusion keyed on the cold-restore override alone, but
spawnIpcPty falls back to the transport options for resumeProviderSession. The
sidebar 'resume a sleeping agent' flow clears its sleeping record at tab
creation, so the pane mounts into a plain startFreshSpawn() with no override
while main still re-issues --resume. A hung spawn there was remounted into a
second --resume on one transcript.

Carry the exclusion on the spawn promise rather than the arming call, so a
remount that adopts a pending spawn cannot lose it.

@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 in this delta — the classification widening and the promise-keyed resume exclusion are correct and well-tested. One minor item from the prior review (the recovery decision not being identity-guarded when a newer spawn claims the pane key) is unchanged by these commits and remains tracked in the existing open thread on unbound-pane-spawn-recovery.ts; nothing blocking here.

Reviewed changes

  • Widened resume-spawn classification — fresh-spawn-start.ts now treats a spawn as resume-shaped when coldRestoreOverride or session.transportOptions?.resumeProviderSession is set, closing the sidebar "resume a sleeping agent" gap where the pane mounts into a plain startFreshSpawn() (no cold-restore override) yet still re-issues --resume off the transport options.
  • Promise-keyed resume exclusion — the resume marker moved from an arming-call option to a resumeShapedSpawns WeakSet keyed on the tracked promise, so the exclusion survives a disposed arming pane whose spawn is later adopted and re-armed by a remount (the one path that previously lost the flag).
  • Adoption-site comment and anomaly leafId — updated the re-arm rationale in deferred-session-reattach-choice.ts and added leafId to the "resume spawn never settled" breadcrumb for consistency with remountUnboundPane.
  • Tests — new fresh-spawn-start.test.ts covers resume classification; unbound-pane-spawn-recovery.test.ts gained a red-green case proving a disposed-pane-adopted resume spawn is never remounted.

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

Merge Sim added 3 commits September 7, 2026 12:05
…keyed record

Two module-level weak collections keyed on the same promise had to stay in
sync by hand. Collapse them into one WeakMap record carrying both facts, so
'everything armed carries a classification' is structural rather than
coincidental, and the fire path reads the classification off the spawn.

The deadline was borrowed from TRANSPORT_CONNECT_SETTLE_GRACE_MS, whose
comment documents an unrelated input-recovery policy. Same value, own name,
so tuning one cannot silently move the other.
pty:spawn awaits the first-window startup gate before the handler runs, and
only then does the daemon client spend its connection-attempt wait plus a
request timeout. Those are sequential, so a local cold start can legitimately
take ~110s to settle. At 60s the watchdog fired while main was still inside
the gate and remounted a spawn that was about to succeed — on exactly the
cold start where every restored pane is spawning at once.

Derive the deadline from those budgets with a request timeout of headroom,
and pin it against main's own constant so the two cannot drift apart.
A remote-runtime create does not fail fast. On the first recoverable connection
error it arms REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS and keeps retrying inside
the create call, so the connect promise legitimately pends well past the local
deadline on a flapping link. Timing out under it remounts a pane whose create is
still running and can orphan a host terminal.

Pick the deadline by transport and pin the remote one against the ladder it must
outlast.
@brennanb2025

brennanb2025 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor Author

PASS — healthy spawn and idle regression recheck at 60c4daff14856325264ab71c54cbe4965e0d049c.

Idle check re-confirmed at this head: 188.768 seconds idle, same pane and PTY, retained output, and successful input afterward.

03-idle.png

Earlier four-scenario evidence below was captured at db4f82c9996b2b8cf831ef139fb6f539aa8e3d42; those screenshots are preserved.

Healthy shell spawn displays orca-qa-19318 and a prompt.

01-shell.png

Two tabs hold three live terminal sessions; both split panes display output and prompts.

02-split.png

After 160 seconds idle (beyond the current 140-second watchdog), the same terminal elements retain output and accept new input.

03-idle.png

Closed tab reopened through the terminal reopen action; its shell accepts input and displays reopened-tab-working.

04-reopened.png

Console findings: zero occurrences of spawn-never-settled, spawn-left-pane-unbound, [terminal-lifecycle], and terminal_pane_recovery_remount.

@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 blocking issues — one minor observation on the parity guard, inline.

Reviewed changes

  • Raised the spawn watchdog above the cold-start budget — SPAWN_SETTLEMENT_WATCHDOG_MS moved into pty-connect-limits.ts and is now derived (60_000 gate ceiling + 20_000 + 30_000 daemon settle + 30_000 headroom, ~140s) instead of the earlier flat 60s, so a slow cold start — where pty:spawn sequentially awaits the fail-open gate before the daemon client — no longer trips a remount of a spawn that was about to settle.
  • Added a parity ratchet — spawn-settlement-watchdog-budget.test.ts imports LOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MS from src/main and asserts the watchdog outlasts the worst legitimate local settle with ≥30s headroom, failing when the gate grows past its ceiling.
  • Widened the web typecheck allowlist — config/tsconfig.tc.web.json now includes the pure first-window-startup-services.ts leaf so the parity test typechecks.

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

An AI-vault resume for an agent Orca has no provider-session model for emits
'<agent> --resume <id>' as the command and carries no resumeProviderSession:
getAiVaultAgentProviderSession returns null purely on !isResumableTuiAgent, so
the metadata is absent while the resume is real. Inferring resume-ness from that
metadata classified those spawns as fresh, and the watchdog would remount a hung
one into a second live transcript — the exact outcome the exclusion exists to
prevent.

Have the producers that know they are resuming say so, and read that.

@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 in this delta — the remote-runtime deadline is correct and well-tested. Not approving because two prior minor threads remain open (the recovery-decision identity guard on unbound-pane-spawn-recovery.ts, and the daemon-budget parity gap flagged on spawn-settlement-watchdog-budget.test.ts), both non-blocking.

Reviewed changes

  • Added a remote-runtime watchdog deadline — REMOTE_RUNTIME_SPAWN_SETTLEMENT_WATCHDOG_MS (REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS + 30_000, ~210s) in pty-connect-limits.ts, with armSpawnSettlementWatchdog choosing the deadline by session.runtimeEnvironmentId — a discriminator that mirrors the transport factory in pty-input-recovery.ts:140 (truthy runtimeEnvironmentId ⇔ createRemoteRuntimePtyTransport, whose create runs the REMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MS retry ladder inside the call), so a flapping remote link is no longer timed out into a remount that orphans the host terminal.
  • Added parity + behavioral coverage — the budget test asserts the remote deadline outlasts the ladder and that a local pane stays on the shorter deadline; unbound-pane-spawn-recovery.test.ts gains a red-green case proving a remote pane does not remount at the local deadline but does at the remote one.

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

…eouts

The budget test imported the startup gate but hand-copied the daemon client's
connect and request timeouts, because those were module-private. Raising
REQUEST_TIMEOUT_MS in main would then leave the watchdog silently short and the
test still green — the drift it exists to catch.

Move the three to an import-free module both sides can read, and note in each
pinned file that it is typechecked under the web config so it stays that way.

@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 blocking issues in this delta — the producer-declared resume flag is correct and complete against the launch paths (cold-restore, sleeping-agent, vault sidebar + drag-drop, and the remote-open IPC fallback all classify as resume). Not approving because two prior minor threads remain open (the recovery-decision identity guard on unbound-pane-spawn-recovery.ts, and the daemon-budget parity gap on spawn-settlement-watchdog-budget.test.ts), plus one new latent nit inline.

Reviewed changes

  • Introduced a producer-declared resume flag — added resumesAgentSession?: boolean across PtyPaneStartup, WorktreeStartupPayload, and the terminal store types, set unconditionally by launchAiVaultSessionInNewTab (sidebar Resume and the drag-drop AiVaultSessionDropLayer, including OMP/antigravity/pi whose resume rides --resume <id|path> alone) and by launchSleepingAgentSession, and read in the observeSpawnSettlement classification before the transportOptions.resumeProviderSession fallback so a hung vault resume can no longer remount into a second --resume.
  • Added a classification test — fresh-spawn-start.test.ts covers a producer-flagged resume with no provider session.

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

// only the producer's own flag identifies it.
resumesProviderSession: Boolean(
coldRestoreOverride ??
session.paneStartup?.resumesAgentSession ??

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.

resumesAgentSession is an optional boolean, but ?? treats an explicit false as definitive — if a producer ever sets resumesAgentSession: false to mark a non-resume while transportOptions.resumeProviderSession is still present, this collapses to false and the spawn is remounted into a duplicate --resume. Latent today (only true/undefined are ever written), but coldRestoreOverride || session.paneStartup?.resumesAgentSession === true || session.transportOptions?.resumeProviderSession drops the trap.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: fixes landed, ready for another look

Reviewed across parallel lanes (correctness, prior-art/precedent, performance, release readiness) plus background Electron QA. The core design is right and I kept it: bound the pane's wait, not the invoke, and withhold the remount from resume spawns. What the review found is that the mechanism was correct in shape but under-covered in three places and mistuned in two — all now fixed on this branch.

Every fix below was verified in-tree and carries a red-green ablation: reverting it fails only its own test.

Fixed

1. The resume exclusion missed the main resume path — ffdb2e9900
Boolean(coldRestoreOverride) only sees a launchConfig-bearing startupOverride. The sidebar "resume a sleeping agent" flow clears its sleeping record at tab creation, so the pane mounts into a plain startFreshSpawn() with no override — while spawnIpcPty still replays resumeProviderSession off the transport options (ipc-pty-spawn-request.ts:57-58) and main prepares the resume (spawn-preflight.ts:124). A hung spawn there was remounted into a second --resume on one transcript: exactly the outcome this PR exists to prevent. The queued startup is only spent once a PTY binds, so the remounted pane re-read it and re-fired, and the recovery budget allows up to three.

2. The exclusion could be lost when a remount adopted the spawn — f7c10e35d7
armSpawnSettlementWatchdog returned early without recording the promise when the arming pane was disposed, and the adoption site armed with no options — so the single case where the adopter's arming actually runs was the case where the resume flag had already been lost. The classification now rides the spawn promise in one keyed record with an explicit armed field (the flag is written before arming, so a has()-style dedup would have deduped away every arming, including the adopter's).

3. 60s was unsafe — db4f82c999
pty:spawn awaits the first-window startup gate before the handler runs (spawn.ts:9-13, local-only per register-handlers.ts:92-97), where the fail-open is 60s; only then does the daemon client spend its 20s connection-attempt wait plus a 30s request timeout. Those are sequential, so a legitimate local cold start reaches ~110s. At 60s the watchdog fired while main was still inside the gate and remounted spawns that were about to succeed — on precisely the cold start where every restored pane is spawning at once. The deadline is now derived from the budgets it must outlast, with headroom.

4. Remote-runtime panes needed their own deadline — a9e467c3f4
A remote create does not fail fast: on the first recoverable connection error it arms the auto-recovery ladder and keeps retrying inside the create call, so the connect promise legitimately pends past the local deadline on a flapping link. Cutting it short remounts a pane whose create is still running — and the replacement can neither reconcile nor adopt the orphaned host terminal, since that state is per-transport and pane resolution needs a sessionId a fresh spawn lacks. The deadline is now chosen by transport.

5. A resume can be carried by the command alone — 60c4daff14
getAiVaultAgentProviderSession returns null purely on !isResumableTuiAgent, so for vault-resumable agents Orca has no session model for, the metadata is absent while the resume is real — the emitted command is <agent> --resume <id>. Those spawns classified as fresh, so a hung one would have been remounted into a second live transcript. The producers that know they are resuming now declare it explicitly rather than it being inferred from metadata that may not exist.

6. The budget test now actually pins what it claims — b437e185e6
It imported the startup gate but hand-copied the daemon client's timeouts, which were module-private — so raising REQUEST_TIMEOUT_MS in main would leave the watchdog silently short with the test still green. All three are now read from one import-free module.

Verification

  • terminal-pane suite green; tc:web and tc:node clean; changed-code quality gate 0 findings; max-lines-ratchet, reliability-gates, zustand-selector-fanout all pass. No lint suppressions added.
  • Electron QA in a background window over CDP (hidden renderer, no focus stealing): healthy spawn, concurrent split panes, and tab close/reopen. The key false-positive check — a pane left idle past the watchdog deadline — was run twice: 160s on the four-scenario pass, then re-confirmed at 188.8s on the current head. In both the pane kept its output, kept its PTY, and still accepted input, with zero occurrences of spawn-never-settled, spawn-left-pane-unbound, [terminal-lifecycle], or terminal_pane_recovery_remount. Screenshots are in a separate comment on this PR.
  • QA ran against 60c4daff14; the only commit after it (b437e185e6) moves three constants and strengthens a test, with no behaviour change.

Kept as-is, deliberately

  • The freeze-over-corruption trade. It is the right call and matches how mature terminal/editor codebases handle a spawn whose outcome is unknown. Worth noting the honest limitation: refusing to retry on the client is an interim measure, not the cure — established practice pairs the timeout with the host owning and reclaiming the spawn generation. Today a spawn-never-settled resume pane is a dead end with a log line, so I'd suggest filing the main-side duplicate-resume admission gate as a tracked ticket rather than leaving it as a note in the PR body.
  • The pin GC identity guard is safe. A recovery remount bumps the tab generation, which is part of pendingSpawnKey, so it mints a different key and cannot adopt the old pin whether or not the watchdog collected it — the GC is genuine leak cleanup.

Follow-ups (not this PR)

  • The STALE PENDING SPAWN branch in deferred-session-reattach-choice.ts is unreachable, because tabGeneration is already inside the key it compares. Inert today, but it encodes a different policy than the live no-pin path, so it is a trap if the key composition ever changes.
  • session.directSshRetryAttempt is captured at mount and never cleared, so the watchdog's SSH bail-out is permanent for those panes.

Note on scope

Fix 5 reaches slightly outside terminal-pane: an optional resumesAgentSession flag on the pane-startup types plus a stamp at the two launch producers. I judged it in scope because the watchdog introduces the double-resume for those agents, so leaving it would ship a mechanism that is unsafe for part of the resume surface — but it is cleanly separable if you'd rather it be its own PR.

CI was still running when this was written; no failures at that point.

@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 in this delta — extracting the daemon timeouts into an import-free rpc-timeouts.ts and having the parity test import the real values cleanly closes the earlier by-value-mirror gap. Not approving because two minor threads remain open (the recovery-decision identity guard on unbound-pane-spawn-recovery.ts, and the resumesAgentSession ??-ordering nit on fresh-spawn-start.ts).

Reviewed changes

  • Linked the parity test to main's real daemon timeouts — introduced src/main/daemon/rpc-timeouts.ts (an import-free leaf exporting CONNECT_TIMEOUT_MS/CONNECTION_ATTEMPT_WAIT_MS/REQUEST_TIMEOUT_MS), pointed daemon/client.ts at it, and updated spawn-settlement-watchdog-budget.test.ts to import the real CONNECTION_ATTEMPT_WAIT_MS/REQUEST_TIMEOUT_MS instead of hand-copied 5_000 * 4/30_000 mirrors, allowlisting the leaf in config/tsconfig.tc.web.json so it typechecks under the web project.

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

@coderabbitai

coderabbitai Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker

Copy link
Copy Markdown
Contributor

Heads-up on a textual conflict, not a disagreement: #20025 (fix/terminal-recovery-row-ledger) touches the same two files as this PR.

#20025 moves the terminal recovery budget off module-level Maps onto the TerminalTab row and replaces the counting cap with an observation gate — a remount cannot be requested until the previous one settles success | failed | timed-out | superseded. While closing the last gap in that gate it adds three lines to fresh-spawn-start.ts, in the same void trackedPromise.then((spawnedPtyId) => { ... }) block this PR edits:

void trackedPromise.then((spawnedPtyId) => {
  if (spawnedPtyId) {
    session.settlePaneAttachAttempt?.(undefined, 'success')
    return
  }
  queueMicrotask(() => { /* ... settleSpawnThatLeftPaneUnbound(session) */ })
})

The reason it is there: a spawn-left-pane-unbound remount heals by spawning, not reattaching, so it never reaches handleReattachResult — the only place success was settled. The failure half already reported (settleSpawnThatLeftPaneUnbound settles 'failed' before requesting the remount), but a spawn that succeeded left the attempt pending for the full 31s settlement bound, blocking the tab's next recovery for any other reason.

This PR rewrites unbound-pane-spawn-recovery.ts 40 → 119 lines and pulls both outcomes into it, so the two changes overlap directly. They look complementary to me — you bound a pty:spawn invoke that never resolves at all, #20025 reports the outcome when it does resolve — so this is purely about not losing one in the merge.

Whichever lands second: please keep the success settle on the bound-PTY arm. If it is dropped, the 31s pending window silently reopens for every fresh-spawn recovery and nothing outside pty-connection-spawn-left-pane-unbound.test.ts will fail. Happy to do the rebase on the #20025 side if this one lands first — just ping me.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status update

  • Fixed the staggered PTY handoff race: ownership claims are generation-fenced, observe later siblings, preserve rejected predecessor records through teardown, and release claims on reconnect/exit/disconnect/destroy.
  • Added bounded ownership-record cleanup with immediate retention-timer cancellation; the transport bookkeeping is isolated in a pane ownership tracker.
  • Propagated the additive optional resumesAgentSession marker through runtime RPC/preload/desktop/mobile/web paths, with AI-vault resume producers setting it explicitly.
  • Validation: final readiness checklist clean; focused ownership/spawn/runtime suite 9 files / 62 tests passed; pnpm tc:node; pnpm tc:web; changed-code quality (0 new findings across 51 files); git diff --check.
  • Electron QA: the requested Grok orchestration worker was blocked by the weekly credit limit after the prescribed retry. No Electron screenshots were produced or attached, so rendered-app evidence remains a documented gap.

The branch is pushed at commit 19e3dd43e2; no unrelated lockfile or planning-file changes are included.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts (1)

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

Transfer watchdog ownership when adopting a pending spawn. armSpawnSettlementWatchdog returns for an already-armed promise, so its timer keeps the original session. On expiry, it deletes the shared pending entry before checking that session’s transport or directSshRetryAttempt; the timer can then return while the adopting session remains unbound. Store the current watchdog owner with the settlement record and update it on adoption, or evaluate expiry against that owner.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 39e73775-0faf-4b7a-ad87-abe64cbb26d6

📥 Commits

Reviewing files that changed from the base of the PR and between c345da4 and 19e3dd4.

📒 Files selected for processing (39)
  • config/tsconfig.tc.web.json
  • src/main/ipc/pty/ipc/spawn-begin-reservation.test.ts
  • src/main/ipc/pty/ipc/spawn-begin.ts
  • src/main/ipc/pty/ipc/spawn-run-preparation-deadline.test.ts
  • src/main/ipc/pty/ipc/spawn-run.ts
  • src/main/ipc/pty/pty-spawn-preparation-deadline.test.ts
  • src/main/ipc/pty/pty-spawn-preparation-deadline.ts
  • src/main/ipc/pty/runtime/spawn.ts
  • src/main/runtime/orca-runtime-create-mobile-session-terminal.ts
  • src/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.ts
  • src/main/runtime/orca-runtime-create-terminal-desktop.ts
  • src/main/runtime/orca-runtime-run-create-mobile-session-terminal.ts
  • src/main/runtime/rpc/methods/session-tabs-schemas.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts
  • src/main/runtime/rpc/methods/terminal/unary-schemas.ts
  • src/main/runtime/runtime-terminal-contracts.ts
  • src/preload/api/ui-bridge-terminal-and-session-tabs.ts
  • src/preload/api/ui-command-event-api.ts
  • src/renderer/src/components/terminal-pane/ipc-pty-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership-tracker.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership.ts
  • src/renderer/src/components/terminal-pane/pty-connection/spawn-watchdog-recovery-ownership.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
  • src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/hooks/direct-ssh-runtime-wake-isolation.test.tsx
  • src/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.ts
  • src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge.ts
  • src/renderer/src/lib/launch-ai-vault-session.test.ts
  • src/renderer/src/lib/launch-ai-vault-session.ts
  • src/renderer/src/runtime/web-runtime-session-terminal-legacy-create.test.ts
  • src/renderer/src/runtime/web-runtime-session-types.ts
  • src/renderer/src/runtime/web-runtime-terminal-create-operation.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/shared/worktree/launch-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +38 to +43
onTimeout: () =>
rejectPaneSpawnReservation(
ctx.paneSpawnReservationKey,
ctx.paneSpawnReservation,
new Error('PTY spawn preparation timed out before provider spawn')
)

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

Run full preparation cleanup when the deadline expires.

The deadline rejects only the pane reservation. It does not cancel the active operation.

preparePtyIpcSpawnPreflight can set preSpawnHiddenMarkId before an await. If that await never settles, the operation never reaches the cleanup at Lines 53-65. Renderer PTY delivery then remains hidden after the caller receives the timeout.

Move the idempotent abandonment cleanup into a shared function. Call that function from both onTimeout and the operation catch. Add a test that sets a hidden mark before a permanently pending preparation step.

restoreProvisionalPtySize(ctx)
throw error
})
preparationDeadline.assertPreparing()

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Restore provisional PTY size when the deadline fence throws.

If buildRuntimePtySpawnOptions() updates ptySizes and then waits past the deadline, Line 114 throws after the options promise resolves. The existing rejection handler restores the provisional size only when option building rejects. The outer catch does not restore it. A later spawn can then use dimensions for a PTY that was never created.

Restore the provisional size before rethrowing a deadline-fence failure.

Proposed fix
-    preparationDeadline.assertPreparing()
+    try {
+      preparationDeadline.assertPreparing()
+    } catch (error) {
+      restoreProvisionalPtySize(ctx)
+      throw 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
preparationDeadline.assertPreparing()
try {
preparationDeadline.assertPreparing()
} catch (error) {
restoreProvisionalPtySize(ctx)
throw error
}

done: false,
retentionTimer: setTimeout(() => {
if (!record.result && !record.done) {
removeAttemptRecord(record)

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Clean completed siblings when the last pending record expires.

When the retention callback removes the last pending record, completed records and accepted claims can remain in attemptsByPaneKey and acceptedClaimsByPaneKey. Repeated overlapping attempts can accumulate this state and make later ownership scans grow. Reuse the all-complete cleanup used by finishPtySpawnOwnership after retention removal, and add a fake-timer regression test.

@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 — one minor observation on the parity test, inline.

Reviewed changes

  • Fenced hung spawn preparation on the main side — new pty-spawn-preparation-deadline.ts (60s) races runPtyIpcSpawn and spawnPtyFromRuntimeController, rejecting the pane reservation and throwing past every preflight/env/options step via assertPreparing, so a provider process is never issued after the deadline; the renderer watchdog links this constant and both deadlines grew accordingly.
  • Introduced a PTY spawn ownership registry — pty-spawn-ownership.ts (begin/publish/finish/release plus successorOwnsPtySpawnResult) lets a rejected fresh spawn defer its pty.kill until a concurrent sibling proves it adopted the same id, closing the detach/reattach handoff races; wired through pty-transport.ts and ipc-pty-connect.ts.
  • Identity-guarded the watchdog recovery decision — armSpawnSettlementWatchdog now early-returns when the pane pin was superseded, and the disposed-pane branch uses the session's captured recovery generation instead of a fresh capture, so a stale watchdog can't remount a tab that already recovered.
  • Propagated the resume flag across the runtime surface — resumesAgentSession now flows through the mobile/runtime RPC schemas, preload bridges, shared contracts, and runtime terminal create methods.

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

describe('spawn settlement watchdog budget', () => {
// Sequential, not overlapping: pty:spawn awaits the startup gate, and only then
// does the daemon client spend its connection-attempt wait plus one request timeout.
const worstLegitimateLocalSettleMs =

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.

worstLegitimateLocalSettleMs omits the PTY_SPAWN_PREPARATION_DEADLINE_MS term that SPAWN_SETTLEMENT_WATCHDOG_MS now adds, so the "slowest legitimate settle" this test models is 60s short and the headroom assertion computes ~90s when the true headroom is 30s. PTY_SPAWN_PREPARATION_DEADLINE_MS is an import-free leaf, so import it and add it to the formula to keep the "keeps real headroom" claim accurate.

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.

2 participants