Repository navigation
fix(terminal): bound a pane's wait on a spawn that never settles - #19318
brennanb2025 wants to merge 13 commits into
Conversation
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.
📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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 Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
⚔️ Resolve merge conflicts 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 8cdfdb3d-0289-4f57-9b43-5dd1820cb0fa
📒 Files selected for processing (5)
src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.tssrc/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.
| // 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>>() |
There was a problem hiding this comment.
🩺 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-connectionRepository: 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-connectionRepository: 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-connectionRepository: 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.tsRepository: 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.tsRepository: 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.
There was a problem hiding this comment.
ℹ️ One subtle edge case in the watchdog's recovery decision is worth tightening — nothing blocking.
Reviewed changes
- Watchdog for never-settling spawns —
armSpawnSettlementWatchdogarms a 60s (TRANSPORT_CONNECT_SETTLE_GRACE_MS) timer that unpins the pane key and remounts an unbound pane under a newspawn-never-settledreason, with a module-levelWeakSetdeduping 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--resumeon the same transcript. - Consolidated spawn outcomes —
observeSpawnSettlementnow owns both the settled-without-PTY-id recovery and the never-settled watchdog;fresh-spawn-start.tsanddeferred-session-reattach-choice.tsroute 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.
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.
There was a problem hiding this comment.
ℹ️ 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.tsnow treats a spawn as resume-shaped whencoldRestoreOverrideorsession.transportOptions?.resumeProviderSessionis set, closing the sidebar "resume a sleeping agent" gap where the pane mounts into a plainstartFreshSpawn()(no cold-restore override) yet still re-issues--resumeoff the transport options. - Promise-keyed resume exclusion — the resume marker moved from an arming-call option to a
resumeShapedSpawnsWeakSetkeyed 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 indeferred-session-reattach-choice.tsand addedleafIdto the "resume spawn never settled" breadcrumb for consistency withremountUnboundPane. - Tests — new
fresh-spawn-start.test.tscovers resume classification;unbound-pane-spawn-recovery.test.tsgained a red-green case proving a disposed-pane-adopted resume spawn is never remounted.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…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.
|
PASS — healthy spawn and idle regression recheck at Idle check re-confirmed at this head: 188.768 seconds idle, same pane and PTY, retained output, and successful input afterward. Earlier four-scenario evidence below was captured at Healthy shell spawn displays Two tabs hold three live terminal sessions; both split panes display output and prompts. After 160 seconds idle (beyond the current 140-second watchdog), the same terminal elements retain output and accept new input. Closed tab reopened through the terminal reopen action; its shell accepts input and displays Console findings: zero occurrences of |
There was a problem hiding this comment.
ℹ️ 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_MSmoved intopty-connect-limits.tsand is now derived (60_000gate ceiling +20_000 + 30_000daemon settle +30_000headroom, ~140s) instead of the earlier flat 60s, so a slow cold start — wherepty:spawnsequentially 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.tsimportsLOCAL_PTY_STARTUP_FAIL_OPEN_TIMEOUT_MSfromsrc/mainand 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.jsonnow includes the purefirst-window-startup-services.tsleaf so the parity test typechecks.
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.
There was a problem hiding this comment.
ℹ️ 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 onspawn-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) inpty-connect-limits.ts, witharmSpawnSettlementWatchdogchoosing the deadline bysession.runtimeEnvironmentId— a discriminator that mirrors the transport factory inpty-input-recovery.ts:140(truthyruntimeEnvironmentId⇔createRemoteRuntimePtyTransport, whose create runs theREMOTE_RUNTIME_AUTO_RECOVERY_TIMEOUT_MSretry 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.tsgains a red-green case proving a remote pane does not remount at the local deadline but does at the remote one.
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.
There was a problem hiding this comment.
ℹ️ 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 onspawn-settlement-watchdog-budget.test.ts), plus one new latent nit inline.
Reviewed changes
- Introduced a producer-declared resume flag — added
resumesAgentSession?: booleanacrossPtyPaneStartup,WorktreeStartupPayload, and the terminal store types, set unconditionally bylaunchAiVaultSessionInNewTab(sidebar Resume and the drag-dropAiVaultSessionDropLayer, including OMP/antigravity/pi whose resume rides--resume <id|path>alone) and bylaunchSleepingAgentSession, and read in theobserveSpawnSettlementclassification before thetransportOptions.resumeProviderSessionfallback so a hung vault resume can no longer remount into a second--resume. - Added a classification test —
fresh-spawn-start.test.tscovers a producer-flagged resume with no provider session.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| // only the producer's own flag identifies it. | ||
| resumesProviderSession: Boolean( | ||
| coldRestoreOverride ?? | ||
| session.paneStartup?.resumesAgentSession ?? |
There was a problem hiding this comment.
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.
Review status: fixes landed, ready for another lookReviewed 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. Fixed1. The resume exclusion missed the main resume path — 2. The exclusion could be lost when a remount adopted the spawn — 3. 60s was unsafe — 4. Remote-runtime panes needed their own deadline — 5. A resume can be carried by the command alone — 6. The budget test now actually pins what it claims — Verification
Kept as-is, deliberately
Follow-ups (not this PR)
Note on scopeFix 5 reaches slightly outside CI was still running when this was written; no failures at that point. |
There was a problem hiding this comment.
ℹ️ No new issues in this delta — extracting the daemon timeouts into an import-free
rpc-timeouts.tsand 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 onunbound-pane-spawn-recovery.ts, and theresumesAgentSession??-ordering nit onfresh-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 exportingCONNECT_TIMEOUT_MS/CONNECTION_ATTEMPT_WAIT_MS/REQUEST_TIMEOUT_MS), pointeddaemon/client.tsat it, and updatedspawn-settlement-watchdog-budget.test.tsto import the realCONNECTION_ATTEMPT_WAIT_MS/REQUEST_TIMEOUT_MSinstead of hand-copied5_000 * 4/30_000mirrors, allowlisting the leaf inconfig/tsconfig.tc.web.jsonso it typechecks under the web project.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
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. |
|
Heads-up on a textual conflict, not a disagreement: #20025 ( #20025 moves the terminal recovery budget off module-level Maps onto the void trackedPromise.then((spawnedPtyId) => {
if (spawnedPtyId) {
session.settlePaneAttachAttempt?.(undefined, 'success')
return
}
queueMicrotask(() => { /* ... settleSpawnThatLeftPaneUnbound(session) */ })
})The reason it is there: a This PR rewrites Whichever lands second: please keep the |
|
Review status update
The branch is pushed at commit |
There was a problem hiding this comment.
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 liftTransfer watchdog ownership when adopting a pending spawn.
armSpawnSettlementWatchdogreturns 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 ordirectSshRetryAttempt; 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
📒 Files selected for processing (39)
config/tsconfig.tc.web.jsonsrc/main/ipc/pty/ipc/spawn-begin-reservation.test.tssrc/main/ipc/pty/ipc/spawn-begin.tssrc/main/ipc/pty/ipc/spawn-run-preparation-deadline.test.tssrc/main/ipc/pty/ipc/spawn-run.tssrc/main/ipc/pty/pty-spawn-preparation-deadline.test.tssrc/main/ipc/pty/pty-spawn-preparation-deadline.tssrc/main/ipc/pty/runtime/spawn.tssrc/main/runtime/orca-runtime-create-mobile-session-terminal.tssrc/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.tssrc/main/runtime/orca-runtime-create-terminal-desktop.tssrc/main/runtime/orca-runtime-run-create-mobile-session-terminal.tssrc/main/runtime/rpc/methods/session-tabs-schemas.tssrc/main/runtime/rpc/methods/session-tabs.tssrc/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.tssrc/main/runtime/rpc/methods/terminal/unary-schemas.tssrc/main/runtime/runtime-terminal-contracts.tssrc/preload/api/ui-bridge-terminal-and-session-tabs.tssrc/preload/api/ui-command-event-api.tssrc/renderer/src/components/terminal-pane/ipc-pty-connect.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-connect-limits.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership-tracker.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership.test.tssrc/renderer/src/components/terminal-pane/pty-connection/pty-spawn-ownership.tssrc/renderer/src/components/terminal-pane/pty-connection/spawn-watchdog-recovery-ownership.test.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.tssrc/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/hooks/direct-ssh-runtime-wake-isolation.test.tsxsrc/renderer/src/hooks/ipc-events/terminal-presentation-ipc-bridge.tssrc/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge.tssrc/renderer/src/lib/launch-ai-vault-session.test.tssrc/renderer/src/lib/launch-ai-vault-session.tssrc/renderer/src/runtime/web-runtime-session-terminal-legacy-create.test.tssrc/renderer/src/runtime/web-runtime-session-types.tssrc/renderer/src/runtime/web-runtime-terminal-create-operation.tssrc/shared/runtime-terminal-contracts.tssrc/shared/worktree/launch-types.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| onTimeout: () => | ||
| rejectPaneSpawnReservation( | ||
| ctx.paneSpawnReservationKey, | ||
| ctx.paneSpawnReservation, | ||
| new Error('PTY spawn preparation timed out before provider spawn') | ||
| ) |
There was a problem hiding this comment.
🩺 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() |
There was a problem hiding this comment.
🎯 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.
| preparationDeadline.assertPreparing() | |
| try { | |
| preparationDeadline.assertPreparing() | |
| } catch (error) { | |
| restoreProvisionalPtySize(ctx) | |
| throw error | |
| } |
| done: false, | ||
| retentionTimer: setTimeout(() => { | ||
| if (!record.result && !record.done) { | ||
| removeAttemptRecord(record) |
There was a problem hiding this comment.
🚀 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.
There was a problem hiding this comment.
ℹ️ 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) racesrunPtyIpcSpawnandspawnPtyFromRuntimeController, rejecting the pane reservation and throwing past every preflight/env/options step viaassertPreparing, 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 plussuccessorOwnsPtySpawnResult) lets a rejected fresh spawn defer itspty.killuntil a concurrent sibling proves it adopted the same id, closing the detach/reattach handoff races; wired throughpty-transport.tsandipc-pty-connect.ts. - Identity-guarded the watchdog recovery decision —
armSpawnSettlementWatchdognow 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 —
resumesAgentSessionnow flows through the mobile/runtime RPC schemas, preload bridges, shared contracts, and runtime terminal create methods.
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 = |
There was a problem hiding this comment.
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.






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:spawnis a bareipcRenderer.invokewith no timeout. Infresh-spawn-start.tsboth the pane-key unpin (.finally) and #19223's recovery hook (.then) hang off the same promise, so a main handler that never resolves:pendingSpawnByPaneKeyforever — a real leak, and any later remount that adopts the stranded pin freezes with itThe 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
--resumeagainst 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;
retireFreshSpawnskipscoldRestoreresults; 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.tsrather than being split across the caller. That was needed to keepfresh-spawn-start.tsunder its 300-line cap without a lint disable, and it leaves the caller smaller.Verification
Number of calls: 0; restoring is green and byte-identical to HEAD. The wiring test deliberately goes throughobserveSpawnSettlementrather 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.terminal-panesuite: 441 files / 4233 tests pass.tc:webclean.Note for anyone running a full typecheck
pnpm tcis red on main independently of this branch: duplicatelastActivityAtproperties cause TS1117 insrc/main/agent-hooks/first-work-branch-rename.test.ts.