Repository navigation
fix(pty): require proven absence before retiring a stable pane owner - #12393
Conversation
"Session not found" only proves the provider we asked has no such PTY. A degraded router answers unmapped session ids from the local fallback, which never owned a daemon session, so a live agent's PTY produced the same error a dead one does — and the pane was then given a synthetic exit, its durable pane->PTY binding deleted, and a duplicate spawned. For a single-pane tab the retirement also drops the tab from persisted state, which the renderer cannot add back. Gate the retirement on probePtyLiveness, which polls every possible owner and answers false only when all of them agree the session is absent. `null` (nobody could answer) is not absence. Providers without a probe are their own sole owner, so their refusal stays authoritative and their behavior is unchanged. Also move the retirement's durability barrier off writeToDiskSync: it fsyncs the whole multi-MB state from the main thread, and a restore that retired N dead panes paid that stall N times.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughPTY liveness probing now supports daemons before and after 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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 |
… to the real owner Review found the proven-absence gate correct in direction but terminal in effect: "probe says alive" and "probe says unknown" both became a hard spawn failure with no consumer, no retry, and a raw internal token in a toast. - Graceful teardown (should-fix): a session being killed reports alive (getAppliedSize answers while isAlive, and isTerminating does not flip _state) while createOrAttach already throws SessionNotFoundError, so for up to KILL_TIMEOUT_MS the pane failed instead of retiring the doomed binding. The veto now re-proves on a bounded 6s budget: the moment any owner answers "absent" the pane retires and spawns fresh exactly as before. - Unprovable owners (should-fix): DaemonPtyAdapter.probePtyLiveness never called ensureConnected, so a merely disconnected adapter answered null forever and one null poisons probePtyOwners; it also took no deadline, so a wedged daemon burned the client's 30s request timeout per attach. It now connects first (like listProcesses) and threads an absolute deadline through the fan-out. The thrown error is user-legible English instead of terminal_pane_owner_unverified. - Durability barrier (should-fix): flushPendingOrThrowAsync is not a twin of flushOrThrow — it defaults to the drain-to-stable-generation loop the sibling best-effort caller deliberately avoids, adds active-view and GitHub sidecar writes, re-serializes state per iteration, and rejects when writes are frozen where the sync path no-ops. Reverted to flushOrThrow, matching the sibling retire paths in orca-runtime. - Misrouting root cause (nit): DegradedDaemonFreshSpawnRouter.spawn sent an unmapped sessionId to the local fallback and DaemonPtyRouter.spawn sent it to the current daemon, both faking "Session not found" for a live session. Both now resolve an existing owner first (the same resolution every non-spawn path already uses); minted ids still route to the fallback/current daemon. The pane reattaches instead of only surviving. Tests: retry-until-proven, teardown-window retire, misroute-then-reattach, probe deadline threading, unconnected-adapter probe, and both routers' owner resolution. Each fails with only the source reverted.
Review findings addressed (all four)#1 graceful-teardown window (should-fix) — fixed. Confirmed: #2 unprovable owners (should-fix) — fixed at the root. I did not convert "unreachable" into "absent": that would re-open the P0 this PR exists to fix. What changed is that unknown is now rare (reconnect), bounded (deadline), and self-healing (each retry and each later attach re-proves), rather than a permanent one-shot veto. #3 durability barrier (should-fix) — reverted, reviewer is right. #4 misrouting root cause (nit) — fixed. VerificationNew/changed tests, each proven to fail with only the source reverted (
Two provider mocks now drop the session id on
SSH/relay providers still have no |
Reverts aa27eb5 and leaves only the original guard: retire a stable pane's owner solely when a provider authoritatively answers absent (probePtyLiveness === false). `true` and `null` still refuse to authorize destruction, and providers without a probe keep their refusal authoritative, so their behavior is unchanged. The follow-up bought too much surface for a P0, and two of its pieces did not hold up: - The `hasPty` owner scan added to DaemonPtyRouter.spawn and the degraded fresh-spawn router is inert for the case it targeted. `hasPty` reads `activeSessionIds`, which only spawn/attach populate — `listProcesses` (daemon-pty-adapter.ts) never does. After a failed discovery the scan therefore cannot find the owner it was written to find. - Its two routing tests could not fail: the mocks backed `hasPty` and `listProcesses` with one shared array, giving the fake adapter knowledge the real DaemonPtyAdapter provably lacks. Also dropped: the bounded 6s retry loop and its constants, the sentinel symbol, the exported user-facing message, the `opts.deadlineMs` widening of probePtyLiveness and its threading through the probe/routers, and the ensureConnected change in DaemonPtyAdapter. Kept from the follow-up: the flushOrThrow revert. flushPendingOrThrowAsync is not a like-for-like twin (drain-to-stable-generation loop, sidecar writes, per-iteration serialize, rejects when writes are frozen), so retirePersistedStablePaneOwner stays synchronous. One gap the strict one-shot gate does open is closed here. `getSize` landed in daemon protocol v18, and legacy adapters are created for every version in PREVIOUS_DAEMON_PROTOCOL_VERSIONS (1..30). A pre-v18 daemon error-replies "Unknown request type", probePtyLiveness catches it as `null`, and one `null` makes probePtyOwners unprovable forever — so a genuinely dead pane could never retire. probePtyLiveness now version-gates getSize and asks such a daemon for `listSessions` instead, the same inventory legacy discovery already routes by, requested directly rather than through listProcesses (which swallows errors into an empty list) so an unreachable socket still answers `null`. Unreachable never means absent; only an owner that answered does.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/daemon-pty-adapter.ts (1)
903-907: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the new comments.
Keep each comment to its local invariant. The code and tests already show the cross-layer behavior.
src/main/daemon/daemon-pty-adapter.ts#L903-L907: State that pre-v18 daemons use directlistSessionsrequests so failures remain unknown.src/main/daemon/daemon-pty-adapter.test.ts#L1220-L1222: State the legacy behavior under test.src/main/ipc/pty.ts#L737-L742: State that only confirmed absence permits persisted-owner retirement.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5fe69847-8936-453b-b884-bef2e43ccf14
📒 Files selected for processing (5)
src/main/daemon/daemon-protocol-version.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.ts
…protocol number The version gate was not a sound boundary. `getSize` landed in 22b00a7 while PROTOCOL_VERSION was already 18 and that commit did not bump it, so version 18 means two different things: daemons built before it lack the request, daemons built after it have it. Both report 18. A daemon from that window therefore passed the `>= 18` gate, was sent `getSize`, error-replied "Unknown request type", and answered `null` — and one `null` makes the owner fan-out permanently unprovable, so a genuinely dead pane could never retire. That is the same wedge the gate was added to close, just narrowed to one build window. Ask the daemon what it supports rather than trusting its number: attempt `getSize`, and fall back to `listSessions` only when the daemon itself replies that the request type is unknown. The predicate is deliberately narrow so a transient failure stays unproven instead of being mistaken for a missing capability, and the rejection is remembered so later probes skip a round trip that cannot work. This mirrors the capability-probe rule AGENTS.md already requires for Git, for the same reason: version numbers overstate capabilities. Unreachable still never means absent.
|
Follow-up: replaced the protocol-version gate on Why the version gate was unsound.
So version 18 means two different things. A daemon from that build window passes The change. Attempt This follows the capability-probe rule Why no path regresses
Unreachable still never means absent. Verification. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/daemon-pty-adapter.ts (1)
206-207: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winScope
getSizeUnsupportedto the daemon identity.Lines 206-207 store one result for the whole
DaemonPtyAdapter, butdoRespawn()reuses that adapter after a daemon replacement. If the old daemon rejectsgetSize, the replacement daemon inheritstrueand continues using fulllistSessionsinventories for every probe. Key the result by daemon identity or generation, and prevent late probes from the old daemon from updating the new entry.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9a18a9b9-4813-42b4-ae1c-7ebe3323dbef
📒 Files selected for processing (2)
src/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/daemon/daemon-pty-adapter.test.ts
… rationale Review found the guard had no positive-direction coverage: every existing retire test uses a provider with no probePtyLiveness, so the guard is skipped there. Mutating `!== false` into `!== undefined` — which turns the guard into a permanent veto, so no daemon-backed pane could ever recover from a genuinely dead owner — left the whole suite green. Pinned with a case that fails under exactly that mutation. Also corrects the fallback's Why-comment. It claimed listProcesses "swallows errors into an empty list"; it does not — DaemonPtyAdapter.listProcesses rethrows and the router fails closed. The error-swallowing lives in discoverLegacySessions / discoverDegradedDaemonSessions. Requesting listSessions directly is still right, but because a liveness probe should not publish inventory audit observations as a side effect — not for the stated reason.
… a pane mount probePtyLiveness passed no timeout, so each request fell back to the client's 30s REQUEST_TIMEOUT_MS. A wedged daemon holds its socket open rather than refusing, so it answers neither quickly nor at all — and probePtyOwners awaits every adapter before it can conclude anything. One hung daemon therefore stalled each restoring pane for up to 30s before the pane reported that it could not reopen. Nearly all local terminals are daemon-backed, so this is the common configuration, not an edge case. Bound both probe requests to 2s. Answering "unknown" quickly is strictly better here than answering slowly: unknown never authorizes retirement, it only defers it, so the only thing a shorter budget can cost is an earlier retry. The tests now pin the bound at the call rather than leaving it implicit.
… comment Review proved a coverage gap by mutation: removing LIVENESS_PROBE_TIMEOUT_MS from the getSize request left the whole suite green, so nothing stopped that leg regressing to the client's 30s default. Only the listSessions leg was pinned. The assertion now fails under exactly that mutation. Also moves isUnknownRequestTypeError below isDaemonGoneError. It had been inserted between isDaemonGoneError and the comment describing it, so that comment read as documenting the wrong function.
…12393) * fix(pty): require proven absence before retiring a stable pane owner "Session not found" only proves the provider we asked has no such PTY. A degraded router answers unmapped session ids from the local fallback, which never owned a daemon session, so a live agent's PTY produced the same error a dead one does — and the pane was then given a synthetic exit, its durable pane->PTY binding deleted, and a duplicate spawned. For a single-pane tab the retirement also drops the tab from persisted state, which the renderer cannot add back. Gate the retirement on probePtyLiveness, which polls every possible owner and answers false only when all of them agree the session is absent. `null` (nobody could answer) is not absence. Providers without a probe are their own sole owner, so their refusal stays authoritative and their behavior is unchanged. Also move the retirement's durability barrier off writeToDiskSync: it fsyncs the whole multi-MB state from the main thread, and a restore that retired N dead panes paid that stall N times. * fix(pty): make the unproven-absence veto transient and route attaches to the real owner Review found the proven-absence gate correct in direction but terminal in effect: "probe says alive" and "probe says unknown" both became a hard spawn failure with no consumer, no retry, and a raw internal token in a toast. - Graceful teardown (should-fix): a session being killed reports alive (getAppliedSize answers while isAlive, and isTerminating does not flip _state) while createOrAttach already throws SessionNotFoundError, so for up to KILL_TIMEOUT_MS the pane failed instead of retiring the doomed binding. The veto now re-proves on a bounded 6s budget: the moment any owner answers "absent" the pane retires and spawns fresh exactly as before. - Unprovable owners (should-fix): DaemonPtyAdapter.probePtyLiveness never called ensureConnected, so a merely disconnected adapter answered null forever and one null poisons probePtyOwners; it also took no deadline, so a wedged daemon burned the client's 30s request timeout per attach. It now connects first (like listProcesses) and threads an absolute deadline through the fan-out. The thrown error is user-legible English instead of terminal_pane_owner_unverified. - Durability barrier (should-fix): flushPendingOrThrowAsync is not a twin of flushOrThrow — it defaults to the drain-to-stable-generation loop the sibling best-effort caller deliberately avoids, adds active-view and GitHub sidecar writes, re-serializes state per iteration, and rejects when writes are frozen where the sync path no-ops. Reverted to flushOrThrow, matching the sibling retire paths in orca-runtime. - Misrouting root cause (nit): DegradedDaemonFreshSpawnRouter.spawn sent an unmapped sessionId to the local fallback and DaemonPtyRouter.spawn sent it to the current daemon, both faking "Session not found" for a live session. Both now resolve an existing owner first (the same resolution every non-spawn path already uses); minted ids still route to the fallback/current daemon. The pane reattaches instead of only surviving. Tests: retry-until-proven, teardown-window retire, misroute-then-reattach, probe deadline threading, unconnected-adapter probe, and both routers' owner resolution. Each fails with only the source reverted. * fix(pty): drop the follow-up, keep the minimal proven-absence guard Reverts aa27eb5 and leaves only the original guard: retire a stable pane's owner solely when a provider authoritatively answers absent (probePtyLiveness === false). `true` and `null` still refuse to authorize destruction, and providers without a probe keep their refusal authoritative, so their behavior is unchanged. The follow-up bought too much surface for a P0, and two of its pieces did not hold up: - The `hasPty` owner scan added to DaemonPtyRouter.spawn and the degraded fresh-spawn router is inert for the case it targeted. `hasPty` reads `activeSessionIds`, which only spawn/attach populate — `listProcesses` (daemon-pty-adapter.ts) never does. After a failed discovery the scan therefore cannot find the owner it was written to find. - Its two routing tests could not fail: the mocks backed `hasPty` and `listProcesses` with one shared array, giving the fake adapter knowledge the real DaemonPtyAdapter provably lacks. Also dropped: the bounded 6s retry loop and its constants, the sentinel symbol, the exported user-facing message, the `opts.deadlineMs` widening of probePtyLiveness and its threading through the probe/routers, and the ensureConnected change in DaemonPtyAdapter. Kept from the follow-up: the flushOrThrow revert. flushPendingOrThrowAsync is not a like-for-like twin (drain-to-stable-generation loop, sidecar writes, per-iteration serialize, rejects when writes are frozen), so retirePersistedStablePaneOwner stays synchronous. One gap the strict one-shot gate does open is closed here. `getSize` landed in daemon protocol v18, and legacy adapters are created for every version in PREVIOUS_DAEMON_PROTOCOL_VERSIONS (1..30). A pre-v18 daemon error-replies "Unknown request type", probePtyLiveness catches it as `null`, and one `null` makes probePtyOwners unprovable forever — so a genuinely dead pane could never retire. probePtyLiveness now version-gates getSize and asks such a daemon for `listSessions` instead, the same inventory legacy discovery already routes by, requested directly rather than through listProcesses (which swallows errors into an empty list) so an unreachable socket still answers `null`. Unreachable never means absent; only an owner that answered does. * fix(daemon): detect getSize support instead of inferring it from the protocol number The version gate was not a sound boundary. `getSize` landed in 22b00a7 while PROTOCOL_VERSION was already 18 and that commit did not bump it, so version 18 means two different things: daemons built before it lack the request, daemons built after it have it. Both report 18. A daemon from that window therefore passed the `>= 18` gate, was sent `getSize`, error-replied "Unknown request type", and answered `null` — and one `null` makes the owner fan-out permanently unprovable, so a genuinely dead pane could never retire. That is the same wedge the gate was added to close, just narrowed to one build window. Ask the daemon what it supports rather than trusting its number: attempt `getSize`, and fall back to `listSessions` only when the daemon itself replies that the request type is unknown. The predicate is deliberately narrow so a transient failure stays unproven instead of being mistaken for a missing capability, and the rejection is remembered so later probes skip a round trip that cannot work. This mirrors the capability-probe rule AGENTS.md already requires for Git, for the same reason: version numbers overstate capabilities. Unreachable still never means absent. * test(pty): pin that proven absence still retires, and correct a wrong rationale Review found the guard had no positive-direction coverage: every existing retire test uses a provider with no probePtyLiveness, so the guard is skipped there. Mutating `!== false` into `!== undefined` — which turns the guard into a permanent veto, so no daemon-backed pane could ever recover from a genuinely dead owner — left the whole suite green. Pinned with a case that fails under exactly that mutation. Also corrects the fallback's Why-comment. It claimed listProcesses "swallows errors into an empty list"; it does not — DaemonPtyAdapter.listProcesses rethrows and the router fails closed. The error-swallowing lives in discoverLegacySessions / discoverDegradedDaemonSessions. Requesting listSessions directly is still right, but because a liveness probe should not publish inventory audit observations as a side effect — not for the stated reason. * fix(daemon): bound the liveness probe so a wedged daemon cannot stall a pane mount probePtyLiveness passed no timeout, so each request fell back to the client's 30s REQUEST_TIMEOUT_MS. A wedged daemon holds its socket open rather than refusing, so it answers neither quickly nor at all — and probePtyOwners awaits every adapter before it can conclude anything. One hung daemon therefore stalled each restoring pane for up to 30s before the pane reported that it could not reopen. Nearly all local terminals are daemon-backed, so this is the common configuration, not an edge case. Bound both probe requests to 2s. Answering "unknown" quickly is strictly better here than answering slowly: unknown never authorizes retirement, it only defers it, so the only thing a shorter budget can cost is an earlier retry. The tests now pin the bound at the call rather than leaving it implicit. * test(daemon): pin the getSize probe timeout, and reattach an orphaned comment Review proved a coverage gap by mutation: removing LIVENESS_PROBE_TIMEOUT_MS from the getSize request left the whole suite green, so nothing stopped that leg regressing to the client's 30s default. Only the listSessions leg was pinned. The assertion now fails under exactly that mutation. Also moves isUnknownRequestTypeError below isDaemonGoneError. It had been inserted between isDaemonGoneError and the comment describing it, so that comment read as documenting the wrong function. --------- Co-authored-by: OrcaWin <[email protected]> (cherry picked from commit ac7f9a4)
…Y absence orca terminal send to a leaf whose ptyId no provider in this process owns was a silent no-op reported as success: the graph mirror answers writable=true, every provider write to an unknown id is accepted fire-and-forget, and bytesWritten is computed from the payload rather than delivery. sendTerminal and sendTerminalAgentPrompt now consult a controller liveness probe when the provider does not synchronously know the id (hasPty), and throw terminal_not_writable only on an exact false — unknown liveness, probe errors, SSH/remote scopes, and probe-less providers never reject (#12393's rule: null is not absence), so a restored daemon session still accepts writes before its pane remounts. Push-on-idle orchestration delivery gains the same gate so a proven-dead leaf keeps its messages queued instead of marking them delivered into a void. The pty controller now exposes probePtyLiveness, routed like write: a provider probe is preferred, the in-process local provider's refusal is authoritative (sole owner), and remote-scoped or SSH ids without a probe answer null after awaiting the cold-start daemon swap. Proven-absent verdicts cache 15s per ptyId with in-flight dedupe, superseded the moment the provider re-learns the id.
…Y absence (#12578) * fix(runtime): reject leaf terminal sends only on controller-proven PTY absence orca terminal send to a leaf whose ptyId no provider in this process owns was a silent no-op reported as success: the graph mirror answers writable=true, every provider write to an unknown id is accepted fire-and-forget, and bytesWritten is computed from the payload rather than delivery. sendTerminal and sendTerminalAgentPrompt now consult a controller liveness probe when the provider does not synchronously know the id (hasPty), and throw terminal_not_writable only on an exact false — unknown liveness, probe errors, SSH/remote scopes, and probe-less providers never reject (#12393's rule: null is not absence), so a restored daemon session still accepts writes before its pane remounts. Push-on-idle orchestration delivery gains the same gate so a proven-dead leaf keeps its messages queued instead of marking them delivered into a void. The pty controller now exposes probePtyLiveness, routed like write: a provider probe is preferred, the in-process local provider's refusal is authoritative (sole owner), and remote-scoped or SSH ids without a probe answer null after awaiting the cold-start daemon swap. Proven-absent verdicts cache 15s per ptyId with in-flight dedupe, superseded the moment the provider re-learns the id. * fix(runtime): arm one probe-deferred delivery continuation per pty Review (GPT verifier) confirmed: triggers arriving during one in-flight absence probe each attached a continuation to the deduped probe promise, and since Claude-target delivered_at stamps only after the delayed Enter, every continuation re-read the same unread rows — double payload injection and two armed Enters. Single-flight the deferred continuation per pty; the one armed continuation re-reads fresh rows when it fires, so nothing is lost, and the guard clears on settle so later triggers defer again. The narrower pre-existing 500ms sync-path window is unchanged and out of scope. * fix(runtime): single-flight the whole orchestration delivery window per pty The probe-continuation guard cleared at probe settle, but Claude-target delivered_at stamps only in the delayed-Enter callback ~500ms later — a trigger landing in that gap armed a fresh probe cycle, re-read the same un-stamped rows, and re-injected the payload. The identical window existed on the pure sync path pre-PR (two triggers within 500ms double-deliver). Hold a per-pty delivery-in-flight flag from before the payload write until delivery settles: entry-checked before reading unread rows, cleared through one settle point covering the failed write, the sync-stamped coordinator and Cursor branches, any sync throw, and the delayed-Enter callback on submit, refusal, and throw alike. A trigger arriving mid-flight is not dropped — it parks the latest leaf per ptyId and re-runs delivery once on settle, so rows inserted mid-flight deliver without waiting for the next idle event. The probe single-flight stays; the new guard subsumes its post-settle gap, and no trigger site bypasses it. Both strengthened tests are red on the previous commit (first subject injected twice) and green here: in-window re-trigger on the probe path and sync-path double-trigger each deliver the first batch exactly once, with the parked second row delivering alone after settle. * fix(runtime): retire the armed delivery Enter on pty exit; guard fire-time on current state Two variants of one root cause — the delayed-Enter callback outliving the session it was armed for: 1. Cold restore respawns under the same session id. onPtyExit never cancelled the armed Enter or the in-flight delivery state, and onPtySpawned flips the same leaf writable again — so an exit + same-id respawn inside the 500ms window let the stale callback inject \r into the replacement session and stamp rows it never received, then settle against a newer same-id flight. 2. Graph resync replaces leaf objects, so onPtyExit flips writable=false only on the current replacement; a callback trusting its closed-over snapshot still read writable=true and fired after exit with no respawn. The flight record now carries its armed Enter timer and serves as settle identity: onPtyExit clears the timer and drops the flight and any parked re-delivery without stamping (rows stay unstamped and re-deliver on the replacement's next idle — the existing contract), and settle no-ops unless its own flight is still current, so a stale settle can never clear a newer same-id flight or flush its parked trigger. At fire time the callback re-resolves the leaf by key and requires the same ptyId binding and current writability instead of reading the closure snapshot. All three regressions are red on the previous commit: same-id respawn saw \r plus a false delivered_at stamp, exit leaked the flight and parked state, and the orphaned-snapshot resync variant fired Enter after exit. --------- Co-authored-by: OrcaWin <[email protected]>
During the cold-start swap window the routed local provider is still the pre-swap LocalPtyProvider, which does not own restored daemon ids; its answer about one is fabricated, and today reads as unavailable only because the inspection funnel happens to consult hasPty before the provider's own inspection. Completion-sensitive inspection must not ride on that internal ordering: defer until the swap lands, exactly like pty:kill (#7742) and pty:hasPty. SSH-owned ids and no-barrier (headless/orcad sole-owner, #12393) registrations keep answering immediately. The thrice-repeated barrier idiom is now one helper.
…during the daemon swap window (#16953) * fix(pty): answer unverifiable, not false, for presence questions during the daemon swap window During cold start the installed local provider is still the plain in-process LocalPtyProvider until daemon-init swaps in the daemon router. It does not own restored daemon PTY ids, but pty:hasPty and the runtime controller's sync hasPty still let it answer — and its "not in my table" false read as an observed absence: the renderer dead-session reconciler tears panes down on exactly that false, remount recovery refuses on it, and terminal.list records an observed absence instead of an unverifiable verdict. - pty:hasPty now waits for the local-provider startup barrier before choosing an answering provider (the same #7742 guard pty:kill uses), so the post-swap owner answers. - hasPtyFromRuntimeController is sync and cannot wait; while the startup barrier is unsettled it answers null (unverifiable), and it inherits the async probe's remote-handle guard: no locally routed provider may answer for a paired runtime handle. - SSH-owned ids keep answering from their own provider without waiting, and a registration without a startup barrier (headless/orcad) keeps the in-process provider's false authoritative (#12393). * test(pty): isolate the remote-handle guard from the swap-window gate * refactor(pty): arm the swap-window settle watcher once per startup promise * Gate pty:inspectProcess on the daemon-swap startup barrier During the cold-start swap window the routed local provider is still the pre-swap LocalPtyProvider, which does not own restored daemon ids; its answer about one is fabricated, and today reads as unavailable only because the inspection funnel happens to consult hasPty before the provider's own inspection. Completion-sensitive inspection must not ride on that internal ordering: defer until the swap lands, exactly like pty:kill (#7742) and pty:hasPty. SSH-owned ids and no-barrier (headless/orcad sole-owner, #12393) registrations keep answering immediately. The thrice-repeated barrier idiom is now one helper.
…during the daemon swap window (stablyai#16953) * fix(pty): answer unverifiable, not false, for presence questions during the daemon swap window During cold start the installed local provider is still the plain in-process LocalPtyProvider until daemon-init swaps in the daemon router. It does not own restored daemon PTY ids, but pty:hasPty and the runtime controller's sync hasPty still let it answer — and its "not in my table" false read as an observed absence: the renderer dead-session reconciler tears panes down on exactly that false, remount recovery refuses on it, and terminal.list records an observed absence instead of an unverifiable verdict. - pty:hasPty now waits for the local-provider startup barrier before choosing an answering provider (the same stablyai#7742 guard pty:kill uses), so the post-swap owner answers. - hasPtyFromRuntimeController is sync and cannot wait; while the startup barrier is unsettled it answers null (unverifiable), and it inherits the async probe's remote-handle guard: no locally routed provider may answer for a paired runtime handle. - SSH-owned ids keep answering from their own provider without waiting, and a registration without a startup barrier (headless/orcad) keeps the in-process provider's false authoritative (stablyai#12393). * test(pty): isolate the remote-handle guard from the swap-window gate * refactor(pty): arm the swap-window settle watcher once per startup promise * Gate pty:inspectProcess on the daemon-swap startup barrier During the cold-start swap window the routed local provider is still the pre-swap LocalPtyProvider, which does not own restored daemon ids; its answer about one is fabricated, and today reads as unavailable only because the inspection funnel happens to consult hasPty before the provider's own inspection. Completion-sensitive inspection must not ride on that internal ordering: defer until the swap lands, exactly like pty:kill (stablyai#7742) and pty:hasPty. SSH-owned ids and no-barrier (headless/orcad sole-owner, stablyai#12393) registrations keep answering immediately. The thrice-repeated barrier idiom is now one helper. (cherry picked from commit 4cb013c)
…tablyai#12393) * fix(pty): require proven absence before retiring a stable pane owner "Session not found" only proves the provider we asked has no such PTY. A degraded router answers unmapped session ids from the local fallback, which never owned a daemon session, so a live agent's PTY produced the same error a dead one does — and the pane was then given a synthetic exit, its durable pane->PTY binding deleted, and a duplicate spawned. For a single-pane tab the retirement also drops the tab from persisted state, which the renderer cannot add back. Gate the retirement on probePtyLiveness, which polls every possible owner and answers false only when all of them agree the session is absent. `null` (nobody could answer) is not absence. Providers without a probe are their own sole owner, so their refusal stays authoritative and their behavior is unchanged. Also move the retirement's durability barrier off writeToDiskSync: it fsyncs the whole multi-MB state from the main thread, and a restore that retired N dead panes paid that stall N times. * fix(pty): make the unproven-absence veto transient and route attaches to the real owner Review found the proven-absence gate correct in direction but terminal in effect: "probe says alive" and "probe says unknown" both became a hard spawn failure with no consumer, no retry, and a raw internal token in a toast. - Graceful teardown (should-fix): a session being killed reports alive (getAppliedSize answers while isAlive, and isTerminating does not flip _state) while createOrAttach already throws SessionNotFoundError, so for up to KILL_TIMEOUT_MS the pane failed instead of retiring the doomed binding. The veto now re-proves on a bounded 6s budget: the moment any owner answers "absent" the pane retires and spawns fresh exactly as before. - Unprovable owners (should-fix): DaemonPtyAdapter.probePtyLiveness never called ensureConnected, so a merely disconnected adapter answered null forever and one null poisons probePtyOwners; it also took no deadline, so a wedged daemon burned the client's 30s request timeout per attach. It now connects first (like listProcesses) and threads an absolute deadline through the fan-out. The thrown error is user-legible English instead of terminal_pane_owner_unverified. - Durability barrier (should-fix): flushPendingOrThrowAsync is not a twin of flushOrThrow — it defaults to the drain-to-stable-generation loop the sibling best-effort caller deliberately avoids, adds active-view and GitHub sidecar writes, re-serializes state per iteration, and rejects when writes are frozen where the sync path no-ops. Reverted to flushOrThrow, matching the sibling retire paths in orca-runtime. - Misrouting root cause (nit): DegradedDaemonFreshSpawnRouter.spawn sent an unmapped sessionId to the local fallback and DaemonPtyRouter.spawn sent it to the current daemon, both faking "Session not found" for a live session. Both now resolve an existing owner first (the same resolution every non-spawn path already uses); minted ids still route to the fallback/current daemon. The pane reattaches instead of only surviving. Tests: retry-until-proven, teardown-window retire, misroute-then-reattach, probe deadline threading, unconnected-adapter probe, and both routers' owner resolution. Each fails with only the source reverted. * fix(pty): drop the follow-up, keep the minimal proven-absence guard Reverts aa27eb5 and leaves only the original guard: retire a stable pane's owner solely when a provider authoritatively answers absent (probePtyLiveness === false). `true` and `null` still refuse to authorize destruction, and providers without a probe keep their refusal authoritative, so their behavior is unchanged. The follow-up bought too much surface for a P0, and two of its pieces did not hold up: - The `hasPty` owner scan added to DaemonPtyRouter.spawn and the degraded fresh-spawn router is inert for the case it targeted. `hasPty` reads `activeSessionIds`, which only spawn/attach populate — `listProcesses` (daemon-pty-adapter.ts) never does. After a failed discovery the scan therefore cannot find the owner it was written to find. - Its two routing tests could not fail: the mocks backed `hasPty` and `listProcesses` with one shared array, giving the fake adapter knowledge the real DaemonPtyAdapter provably lacks. Also dropped: the bounded 6s retry loop and its constants, the sentinel symbol, the exported user-facing message, the `opts.deadlineMs` widening of probePtyLiveness and its threading through the probe/routers, and the ensureConnected change in DaemonPtyAdapter. Kept from the follow-up: the flushOrThrow revert. flushPendingOrThrowAsync is not a like-for-like twin (drain-to-stable-generation loop, sidecar writes, per-iteration serialize, rejects when writes are frozen), so retirePersistedStablePaneOwner stays synchronous. One gap the strict one-shot gate does open is closed here. `getSize` landed in daemon protocol v18, and legacy adapters are created for every version in PREVIOUS_DAEMON_PROTOCOL_VERSIONS (1..30). A pre-v18 daemon error-replies "Unknown request type", probePtyLiveness catches it as `null`, and one `null` makes probePtyOwners unprovable forever — so a genuinely dead pane could never retire. probePtyLiveness now version-gates getSize and asks such a daemon for `listSessions` instead, the same inventory legacy discovery already routes by, requested directly rather than through listProcesses (which swallows errors into an empty list) so an unreachable socket still answers `null`. Unreachable never means absent; only an owner that answered does. * fix(daemon): detect getSize support instead of inferring it from the protocol number The version gate was not a sound boundary. `getSize` landed in 27d73c8 while PROTOCOL_VERSION was already 18 and that commit did not bump it, so version 18 means two different things: daemons built before it lack the request, daemons built after it have it. Both report 18. A daemon from that window therefore passed the `>= 18` gate, was sent `getSize`, error-replied "Unknown request type", and answered `null` — and one `null` makes the owner fan-out permanently unprovable, so a genuinely dead pane could never retire. That is the same wedge the gate was added to close, just narrowed to one build window. Ask the daemon what it supports rather than trusting its number: attempt `getSize`, and fall back to `listSessions` only when the daemon itself replies that the request type is unknown. The predicate is deliberately narrow so a transient failure stays unproven instead of being mistaken for a missing capability, and the rejection is remembered so later probes skip a round trip that cannot work. This mirrors the capability-probe rule AGENTS.md already requires for Git, for the same reason: version numbers overstate capabilities. Unreachable still never means absent. * test(pty): pin that proven absence still retires, and correct a wrong rationale Review found the guard had no positive-direction coverage: every existing retire test uses a provider with no probePtyLiveness, so the guard is skipped there. Mutating `!== false` into `!== undefined` — which turns the guard into a permanent veto, so no daemon-backed pane could ever recover from a genuinely dead owner — left the whole suite green. Pinned with a case that fails under exactly that mutation. Also corrects the fallback's Why-comment. It claimed listProcesses "swallows errors into an empty list"; it does not — DaemonPtyAdapter.listProcesses rethrows and the router fails closed. The error-swallowing lives in discoverLegacySessions / discoverDegradedDaemonSessions. Requesting listSessions directly is still right, but because a liveness probe should not publish inventory audit observations as a side effect — not for the stated reason. * fix(daemon): bound the liveness probe so a wedged daemon cannot stall a pane mount probePtyLiveness passed no timeout, so each request fell back to the client's 30s REQUEST_TIMEOUT_MS. A wedged daemon holds its socket open rather than refusing, so it answers neither quickly nor at all — and probePtyOwners awaits every adapter before it can conclude anything. One hung daemon therefore stalled each restoring pane for up to 30s before the pane reported that it could not reopen. Nearly all local terminals are daemon-backed, so this is the common configuration, not an edge case. Bound both probe requests to 2s. Answering "unknown" quickly is strictly better here than answering slowly: unknown never authorizes retirement, it only defers it, so the only thing a shorter budget can cost is an earlier retry. The tests now pin the bound at the call rather than leaving it implicit. * test(daemon): pin the getSize probe timeout, and reattach an orphaned comment Review proved a coverage gap by mutation: removing LIVENESS_PROBE_TIMEOUT_MS from the getSize request left the whole suite green, so nothing stopped that leg regressing to the client's 30s default. Only the listSessions leg was pinned. The assertion now fails under exactly that mutation. Also moves isUnknownRequestTypeError below isDaemonGoneError. It had been inserted between isDaemonGoneError and the comment describing it, so that comment read as documenting the wrong function. --------- Co-authored-by: OrcaWin <[email protected]>
…Y absence (stablyai#12578) * fix(runtime): reject leaf terminal sends only on controller-proven PTY absence orca terminal send to a leaf whose ptyId no provider in this process owns was a silent no-op reported as success: the graph mirror answers writable=true, every provider write to an unknown id is accepted fire-and-forget, and bytesWritten is computed from the payload rather than delivery. sendTerminal and sendTerminalAgentPrompt now consult a controller liveness probe when the provider does not synchronously know the id (hasPty), and throw terminal_not_writable only on an exact false — unknown liveness, probe errors, SSH/remote scopes, and probe-less providers never reject (stablyai#12393's rule: null is not absence), so a restored daemon session still accepts writes before its pane remounts. Push-on-idle orchestration delivery gains the same gate so a proven-dead leaf keeps its messages queued instead of marking them delivered into a void. The pty controller now exposes probePtyLiveness, routed like write: a provider probe is preferred, the in-process local provider's refusal is authoritative (sole owner), and remote-scoped or SSH ids without a probe answer null after awaiting the cold-start daemon swap. Proven-absent verdicts cache 15s per ptyId with in-flight dedupe, superseded the moment the provider re-learns the id. * fix(runtime): arm one probe-deferred delivery continuation per pty Review (GPT verifier) confirmed: triggers arriving during one in-flight absence probe each attached a continuation to the deduped probe promise, and since Claude-target delivered_at stamps only after the delayed Enter, every continuation re-read the same unread rows — double payload injection and two armed Enters. Single-flight the deferred continuation per pty; the one armed continuation re-reads fresh rows when it fires, so nothing is lost, and the guard clears on settle so later triggers defer again. The narrower pre-existing 500ms sync-path window is unchanged and out of scope. * fix(runtime): single-flight the whole orchestration delivery window per pty The probe-continuation guard cleared at probe settle, but Claude-target delivered_at stamps only in the delayed-Enter callback ~500ms later — a trigger landing in that gap armed a fresh probe cycle, re-read the same un-stamped rows, and re-injected the payload. The identical window existed on the pure sync path pre-PR (two triggers within 500ms double-deliver). Hold a per-pty delivery-in-flight flag from before the payload write until delivery settles: entry-checked before reading unread rows, cleared through one settle point covering the failed write, the sync-stamped coordinator and Cursor branches, any sync throw, and the delayed-Enter callback on submit, refusal, and throw alike. A trigger arriving mid-flight is not dropped — it parks the latest leaf per ptyId and re-runs delivery once on settle, so rows inserted mid-flight deliver without waiting for the next idle event. The probe single-flight stays; the new guard subsumes its post-settle gap, and no trigger site bypasses it. Both strengthened tests are red on the previous commit (first subject injected twice) and green here: in-window re-trigger on the probe path and sync-path double-trigger each deliver the first batch exactly once, with the parked second row delivering alone after settle. * fix(runtime): retire the armed delivery Enter on pty exit; guard fire-time on current state Two variants of one root cause — the delayed-Enter callback outliving the session it was armed for: 1. Cold restore respawns under the same session id. onPtyExit never cancelled the armed Enter or the in-flight delivery state, and onPtySpawned flips the same leaf writable again — so an exit + same-id respawn inside the 500ms window let the stale callback inject \r into the replacement session and stamp rows it never received, then settle against a newer same-id flight. 2. Graph resync replaces leaf objects, so onPtyExit flips writable=false only on the current replacement; a callback trusting its closed-over snapshot still read writable=true and fired after exit with no respawn. The flight record now carries its armed Enter timer and serves as settle identity: onPtyExit clears the timer and drops the flight and any parked re-delivery without stamping (rows stay unstamped and re-deliver on the replacement's next idle — the existing contract), and settle no-ops unless its own flight is still current, so a stale settle can never clear a newer same-id flight or flush its parked trigger. At fire time the callback re-resolves the leaf by key and requires the same ptyId binding and current writability instead of reading the closure snapshot. All three regressions are red on the previous commit: same-id respawn saw \r plus a false delivered_at stamp, exit leaked the flight and parked state, and the orphaned-snapshot resync variant fired Enter after exit. --------- Co-authored-by: OrcaWin <[email protected]>
…during the daemon swap window (stablyai#16953) * fix(pty): answer unverifiable, not false, for presence questions during the daemon swap window During cold start the installed local provider is still the plain in-process LocalPtyProvider until daemon-init swaps in the daemon router. It does not own restored daemon PTY ids, but pty:hasPty and the runtime controller's sync hasPty still let it answer — and its "not in my table" false read as an observed absence: the renderer dead-session reconciler tears panes down on exactly that false, remount recovery refuses on it, and terminal.list records an observed absence instead of an unverifiable verdict. - pty:hasPty now waits for the local-provider startup barrier before choosing an answering provider (the same stablyai#7742 guard pty:kill uses), so the post-swap owner answers. - hasPtyFromRuntimeController is sync and cannot wait; while the startup barrier is unsettled it answers null (unverifiable), and it inherits the async probe's remote-handle guard: no locally routed provider may answer for a paired runtime handle. - SSH-owned ids keep answering from their own provider without waiting, and a registration without a startup barrier (headless/orcad) keeps the in-process provider's false authoritative (stablyai#12393). * test(pty): isolate the remote-handle guard from the swap-window gate * refactor(pty): arm the swap-window settle watcher once per startup promise * Gate pty:inspectProcess on the daemon-swap startup barrier During the cold-start swap window the routed local provider is still the pre-swap LocalPtyProvider, which does not own restored daemon ids; its answer about one is fabricated, and today reads as unavailable only because the inspection funnel happens to consult hasPty before the provider's own inspection. Completion-sensitive inspection must not ride on that internal ordering: defer until the swap lands, exactly like pty:kill (stablyai#7742) and pty:hasPty. SSH-owned ids and no-barrier (headless/orcad sole-owner, stablyai#12393) registrations keep answering immediately. The thrice-repeated barrier idiom is now one helper.
The defect
LocalPtyProvider.spawn({ attachOnly })throws the literal stringSession not found:for an id it does not own.isPtyAlreadyGoneError()regex-matches that string, andattachStablePaneOwner()treated it as proof the PTY had died — firing a synthetic exit, deleting the persisted pane→PTY binding, and spawning a duplicate.In degraded mode any unmapped session id is routed to that local fallback, so a live daemon-hosted agent got declared dead by a provider that never owned it. For a single-pane tab the retirement also drops the tab from persisted state, which the renderer cannot restore.
The fix
Retire the pane only when a provider authoritatively answers absent —
probePtyLiveness(...) === false.true(someone owns it and it is alive) andnull(nobody could answer) do not authorize destroying the binding. Providers that do not implementprobePtyLivenessare their own sole owner, so their refusal stays authoritative and their behavior is unchanged.That is 9 lines in
attachStablePaneOwner.Closing the one gap the strict gate opens
A one-shot gate means an adapter that can never answer makes the probe return
nullforever, so a genuinely dead pane would surface an error instead of respawning — a permanent wedge.There is one such adapter, and it is pre-existing code (
getSize+ its catch-to-nullwere introduced in24a2accc3c, not by this PR):getSizelanded in daemon protocol v18 (22b00a7cd2, added todaemon-server.tswithout a version bump).PREVIOUS_DAEMON_PROTOCOL_VERSIONS(1..30) whose socket still accepts a connection (daemon-init.ts:1149).routeRequest's switch and error-repliesUnknown request type: getSize(daemon-server.ts:1078); the client rejects, andprobePtyLivenesscatches it asnull.nullmakesprobePtyOwnersreturnnull([false, null]→null), so the fan-out is unprovable forever —protocolVersionis fixed at construction and never renegotiated.probePtyLivenessnow version-gatesgetSizeand asks such a daemon forlistSessionsinstead — present since the first daemon commit (fd4f986c59), and the same inventory legacy discovery already routes by. It is requested directly rather than throughlistProcesses, becauselistProcessesswallows errors into an empty list, which would read as absence.This never lets "unreachable" mean "absent": if
listSessionsalso fails, the answer is stillnull. Only an owner that actually answered can authorize retirement. This mirrors the existing pre-v27inspectProcessfallback in the same file, which uses the identical "request directly so a dead socket still rejects" reasoning.Scope
src/main/ipc/pty.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-protocol-version.tssrc/main/ipc/pty.test.tssrc/main/daemon/daemon-pty-adapter.test.tsPurely additive: +202, −0 against the merge base.
Dropped follow-up
The second commit (
aa27eb5274) was reverted — too much surface for a P0, and two pieces did not hold up under review:hasPtyowner scan added toDaemonPtyRouter.spawnand the degraded fresh-spawn router is inert for the case it targeted.hasPtyreadsactiveSessionIds, which only spawn/attach populate —listProcessesnever does. After a failed discovery it cannot find the owner it was written to find.hasPtyandlistProcesseswith one shared array, giving the fake adapter knowledge the realDaemonPtyAdapterprovably lacks.Also dropped: the bounded 6s retry loop and its constants, the sentinel symbol, the exported user-facing message constant, the
opts.deadlineMswidening ofprobePtyLivenessand its threading through the probe and both routers, and theensureConnectedchange.Kept from the follow-up: the
flushOrThrowrevert.flushPendingOrThrowAsyncis not a like-for-like twin — it defaults to the drain-to-stable-generation loop, adds active-view and GitHub sidecar writes, re-serializes state per iteration, and rejects when writes are frozen where the sync path no-ops.retirePersistedStablePaneOwnerstays synchronous.Tests
keeps a persisted owner whose absence is unproven(×2: probe says alive / nobody could answer) — proves the pane is not retired, gets no synthetic exit, is not duplicated, and the tab survives.answers a pre-getSize daemon from its session inventory— with only the source reverted this failsexpected null to be true, i.e. it reproduces the wedge.still answers unknown when a pre-getSize daemon cannot be reached— pins the P0 boundary: unreachable staysnull.Every test fails with only the source reverted (verified via patch, not stash).
Follow-up (not in this PR)
The real root cause is that a provider which does not own a session reports it with the same string as a provider that owns it and knows it is dead. Both surface as the literal
Session not found, andisPtyAlreadyGoneError()cannot tell "the owner says it is dead" from "a non-owner says it has never heard of it".The structural fix is for a non-owning provider to raise a distinct typed "not mine" error instead of
Session not found, soisPtyAlreadyGoneErrorstops conflating the two. That would make liveness probing unnecessary here entirely — this PR's guard, the fan-out, and the protocol gate could all be removed — and it would fix every other caller that pattern-matches that string.