Skip to content

Never let a non-owning provider answer a PTY presence question false during the daemon swap window - #16953

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/coercion-swap-window-r1
Aug 28, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/coercion-swap-window-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​268 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​268
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​51 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​43

Summary

  • during the cold-start daemon provider swap, presence questions about daemon-restored PTY ids are no longer answered by the pre-swap in-process provider, which does not own them
  • pty:hasPty now waits out the same local-provider startup barrier pty:kill already waits on (Renderer crash+restart orphans open terminal PTYs, crashing shells (PowerShell FailFast on broken console pipe) #7742) and lets the post-swap owner answer
  • the runtime controller's sync hasPty answers null (unverifiable) while that barrier is unsettled, and inherits the async probe's paired-runtime-handle guard: a remote: id is never answered from the local registry

Author: @BrennanKB5

ELI5

When Orca starts up, terminals that survived the last quit live inside a background daemon, and for a moment Orca is still "plugging in" the connector to that daemon. During that moment, if anything asked "is this terminal still alive?", the question went to the old, empty connector — which confidently said "no" about terminals it had never heard of. A confident "no" from something that was never in charge is not evidence. Now Orca either waits for the real owner to answer, or says "I can't check right now" — and only the owner's "no" can ever be treated as a death certificate.

User-facing before / after

When you'd hit this: you restart Orca (or it relaunches after an update) with terminals kept alive by the daemon — agents still running in them — and within the startup window (normally sub-second, up to 60s on a slow daemon start) you switch worktree tabs, type into a restored pane, or run orca terminal list. The renderer and CLI are live during exactly this window by design.

Before: a liveness probe about a restored pane was answered false by the pre-swap local provider. Switching back to a hidden worktree could tear the pane down as "Process exited" while the agent inside was alive; typing into a restored pane whose input wasn't deliverable yet triggered a recovery probe that read the same false and refused to remount ("a dead PTY is the reconciler's job"); terminal.list recorded the pane as an observed absence, so worker-observation surfaces read a live worker as exited.

After: the same probe waits for the swap to land and reports the daemon's real answer (true for a live restored pane), and the synchronous listing path reports unverifiable with a reason until the swap settles. Panes stay up, recovery remounts proceed, and observation surfaces say unverifiable, never exited, until the owner has answered. A post-swap confirmed "no" demotes exactly as before, and headless/relay registrations (daemon installed before the IPC layer, no barrier) keep the installed provider's false fully authoritative.

Reliability contract

  • Invariant: only a provider that owns a PTY id may produce a confident false for it. During the swap window no local provider owns daemon-restored ids, so the answer is deferred (async) or unverifiable (sync) — exited requires positive evidence from the owner (docs/reference/ssh-execution-boundary.md, rule 2; rule 1's no-silent-substitution is the same reason a remote: handle is never answered locally).
  • Failure source: pty:hasPty (src/main/ipc/pty/ipc/inspect.ts) resolved its provider without the startup barrier every sibling destructive/authoritative handler already awaits, and hasPtyFromRuntimeController (src/main/ipc/pty/runtime/operations.ts) had no gate at all — both routed a daemon-restored id to the pre-swap LocalPtyProvider, whose ptyProcesses.has(id) is membership in a table that never contained the id.
  • Vocabulary carry: no new type. boolean | null is the controller's documented presence answer (null = "the query could not be answered"); consumers already resolve null to the shipped live | unverifiable | exited verdicts (markPtyLivenessUnverifiable with NO_OBSERVING_PROVIDER_REASON), and the renderer reconciler's isLive !== false guard already treats null as non-evidence (pinned at terminal-dead-session-reconcile.test.ts).
  • Oracle: pre-fix, three of the six new tests fail against origin/main production files — pty:hasPty resolves false during the window, the sync controller answers false during the window, and a remote: handle is answered false from the local registry. The SSH-exemption and no-barrier-authority tests pass pre- and post-fix, pinning that neither surface over-gates.
  • Ablation: each production hunk reverted individually goes red — IPC startup gate (1 test), sync swap-window gate (1), remote-handle guard (1), controller deps threading (3 tests; a plain revert is also a compile error).
  • Sync gate mechanics: a sync call cannot await, so settlement of the startup promise is tracked by identity in module-level WeakSets (armed once per promise; no strong retention, no timers). The one-microtask lag after settlement yields at most one extra unverifiable answer, in the conservative direction.

Consumers checked (derived, all readers of both surfaces)

Renderer, via pty:hasPty (answer type Promise<boolean | null> unchanged):

  • shouldReconcileMissingSession → session.onExit pane teardown (use-terminal-pane-lifecycle.ts visibility resume → session-reconcile-dispose.ts): reconciles only on false; the deferred answer is guarded against staleness by livenessRequestedAt/ptyBoundAt, pty-rebind, and disposed checks — a late real false still tears down.
  • requestTerminalPaneRecovery (terminal-pane-recovery.ts): refuses remount only on false; already re-checks its budget across the await.
  • web preload stub (web-terminal-api.ts) answers a constant null — unchanged.
  • mobile/ has no hasPty consumer (grepped).

Runtime, via ptyController.hasPty (type boolean | null unchanged — every site compiles unchanged; per-site behavior with null where false used to arrive):

  • orca-runtime.ts:19330 (controllerKnowsPtyIsLive, === true): decision-identical.
  • orca-runtime.ts:33751 (inventory sweep): null takes the existing markPtyLivenessUnverifiable arm instead of forgetPtyLivenessVerdict — the sweep's own comment says only false is an observed absence; this is the intended verdict correction.
  • orca-runtime.ts:33844 (refreshFloatingWorkspacePtyLiveness): null aborts the targeted fast-path, falling back to the full inventory sweep — previously the fast-path demoted floating panes on the fabricated false with no verdict at all.
  • orca-runtime.ts:34057 (buildTerminalSummary provenAbsent rescue, !== true): decision-identical on main — deliberately untouched; the unverifiable-vs-demote refinement of that gate is Never read an unanswerable hasPty probe as proven PTY absence #16932's, and this change composes with it (the provider seam stops fabricating the false that gate must trust).
  • orca-runtime.ts:9389: method-presence check only.

Direct provider.hasPty callers not routed through these seams, each still owner-scoped or out of scope: SSH provider/relay session tables (own their ids), daemon router/degraded/owner-resolution internals (post-swap authorities), writePtyInputAccepted (a delivery refusal, not a liveness fact — true during the window), and pty-process-inspection.ts:17 (foreground/child inspection lane, in flight separately — listed under residual risk).

Remote wire

No RPC params, stream frames, or opcodes change; pty:hasPty is same-binary Electron IPC. Value-level: the only delta a paired peer can see is observation.status: 'unverifiable' with NO_OBSERVING_PROVIDER_REASON occurring in a window that previously published an observed absence. Verified against the shipped release tag v1.4.190 (6e4f817101da): the unverifiable union member with reason, the NO_OBSERVING_PROVIDER_REASON constant, and CLI formatting for unverifiable rows/verdicts (src/cli/terminal-format.ts) all ship there, so old clients parse and render this value today. No capability gating needed.

Performance

Steady-state sync path adds one ptyOwnership lookup, an SSH-id parse only for unowned ids, one thunk call, and one WeakSet membership test — O(1), no polling, timers, or subprocesses; no new spawns (child-process allowlists and ratchet baselines untouched). The IPC path adds one await on an almost-always-settled promise. During the window, null short-circuits provider work entirely; the deferred IPC answer is bounded by the existing 60s startup fail-open cap, the same bound pty:kill accepts.

Verification

  • pnpm test src/main/ipc/pty-startup-swap-window-presence.test.ts — 6/6 post-fix; 3 fail against origin/main production files
  • pnpm test src/main/ipc ... (333 files): all pty/ipc/liveness/reconcile suites pass; the only failures (4 files / 10 tests, spawn-env ZDOTDIR/agent-overlay expectations) reproduce identically with origin/main production code on this machine — pre-existing, unrelated
  • pnpm test src/main/runtime/orca-runtime.test.ts (1213 passed), stale-leaf + partial-relay liveness, terminal-dead-session-reconcile.test.ts
  • pnpm tc (gate proven live with a type-error canary), oxlint (gate proven live with a canary), oxfmt --check, changed-code quality gate: 0 new findings

Residual risk

  • Process-activity questions during the same window (pty:inspectProcess, pty:hasChildProcesses, pty:getForegroundProcess, and pty-process-inspection.ts:17's hasPty === false short-circuit) still answer from the pre-swap provider as idle/no-children. That is the foreground/child-inspection coercion family, owned by the in-flight sibling lane — deliberately not touched here.
  • DegradedDaemonPtyProvider.hasPty answers false post-swap for a session its init-time discovery missed; post-swap the degraded provider fronts every local backend, so this is a discovery-completeness question, not a non-owner answer — noted, not changed.

…ng 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).
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Push verified: git ls-remote origin refs/heads/brennanb2025/coercion-swap-window-r1 returns exactly b3008b63192392430ea40443c3e6b11637407cb2, matching local HEAD. Commits on this PR: 77b9796 (fix + failing-first repro suite), 2167243 (isolate the remote-handle guard from the swap-window gate so its ablation is independently red), b3008b6 (arm the settle watcher once per startup promise).

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6b8e448d-9793-41b0-8185-d175aefe6834

📥 Commits

Reviewing files that changed from the base of the PR and between fef6388 and c90e2df.

📒 Files selected for processing (1)
  • src/main/ipc/pty/ipc/inspect.ts

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


📝 Walkthrough

Walkthrough

PTY presence and process inspection now wait for the relevant local or SSH provider during startup transitions. The runtime controller returns null for remote PTYs and unresolved local provider startup, then probes providers after startup settles. SSH-owned PTYs remain routed directly to the SSH provider. The pty:kill handler and its related cleanup dependencies were removed. Tests cover daemon restoration, remote PTYs, SSH ownership, startup barriers, process inspection, and no-barrier behavior.

Merge Risk: ⚪ Minimal · up to c90e2

The change narrows PTY presence answers to the owning provider during daemon startup and preserves an unverifiable state until ownership is settled; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives detailed context, behavior changes, testing, performance, compatibility, and residual risk. However, it omits several template sections, including the required Linked Issue, Visu… Add the missing template sections. Include a linked issue after “Fixes #”. For this behavior-only change, add “N/A” with a brief reason under Visual Proof. Complete or explicitly mark the remaining sections as applicable or not applicable, …
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. 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 primary change: preventing non-owning providers from reporting PTYs as absent during the daemon swap window.
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 detailed context, behavior changes, testing, performance, compatibility, and residual risk. However, it omits several template sections, including the required Linked Issue, Visual Proof or an explicit N/A statement, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist.

Resolution

Add the missing template sections. Include a linked issue after “Fixes #”. For this behavior-only change, add “N/A” with a brief reason under Visual Proof. Complete or explicitly mark the remaining sections as applicable or not applicable, and include the required checklist items and validation status.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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: Pro Plus

Run ID: 9e84c62a-85ac-435f-b068-0b07091b34ff

📥 Commits

Reviewing files that changed from the base of the PR and between 25fa6a9 and b3008b6.

📒 Files selected for processing (4)
  • src/main/ipc/pty-startup-swap-window-presence.test.ts
  • src/main/ipc/pty/ipc/inspect.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/runtime/operations.ts

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

Comment thread src/main/ipc/pty/ipc/inspect.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

CI state on b3008b63192392430ea40443c3e6b11637407cb2: everything green except three main-side failures inherited through the merge ref — none caused by this PR.

  1. tests node 24 8/8 + node 26 8/8 — src/renderer/src/web/web-preload-api-runtime-calls.test.ts ("unwraps domain failures…") is broken on current main by Add parent worktree selection when creating workspace #15420, which changed web-runtime-calls.ts to attach code to unwrapped errors without updating this test. Proof: git checkout origin/main -- src/renderer/src/web/ && pnpm test …runtime-calls.test.ts reproduces the exact CI assertion locally; this branch's own tree passes 4/4. Deterministic across reruns and both node versions.
  2. e2e / ssh docker watcher isolation — tests/e2e/ssh-lost-kill-tab-resurrection.spec.ts (killed-relay-daemon variant, added yesterday by fix(terminal): a close the host never heard must survive the reconnect #16752; the spec does not exist on this branch's base) fails with "Active terminal pane did not receive a PTY binding" (60s waitForActivePanePtyId timeout in the cycle's create step). Proven main-side by a local Docker A/B on the merged tree: identical failure with and without this PR's three production hunks; the sibling "host is disconnected" variant passes both ways. This job only selects the spec for PRs touching pty/SSH code, so main itself never runs it.
  3. verify — aggregator over the two above. package (windows) failed once on an EPERM temp-dir teardown in config/scripts/rebuild-native-deps.test.mjs and passed on rerun (flake).

Both main-side breakages need fixes on main (a one-line expectation update for #15420's test; a look at #16752's new spec), and they will hit every open PR's merge ref until then.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent adversarial review — head b3008b63192392430ea40443c3e6b11637407cb2

Sole reviewer; nothing below is taken from the author's report. Every claim re-derived or re-run in a clean worktree at this exact SHA.

Verdict: MERGE-READY (P2 notes only)


1. Pre-fix repro, re-run

Production files (inspect.ts, controller.ts, operations.ts) restored to merge-base 4f14d6d757c0, PR test suite kept: 3/6 fail, exactly the three claimed seams — pty:hasPty answers a pre-swap false instead of deferring; sync controller answers false instead of null; sync path answers a remote: handle from the local registry. The three exemption tests (SSH IPC, SSH sync, no-barrier sole owner) pass on main, i.e. they pin behavior that must not change.

2. Ablation table (each applied alone against head, my own edits)

Ablation Removed Result
A1 pty:hasPty barrier await (inspect.ts) 1 red — IPC defer test
A2 remote: guard (operations.ts) 1 red — remote-handle test (isolated: that test runs with no barrier, so the outer gate cannot mask it)
A3 sync swap-window null gate 1 red — sync-null test
A4 settle watcher (arm-once .then) 1 red — post-settle recovery times out (gate never reopens): the watcher is load-bearing, not decoration

6/6 green at head. Every functional hunk is individually pinned.

3. Attacks on the new waiting behavior

(a) Latency / who waits. Renderer callers of pty:hasPty are exactly two production sites plus a stub (derived, below); both are fire-and-forget liveness probes (visibility-resume reconcile, input-undeliverable recovery) — nothing paint-blocking awaits it. Worst case bound, proven from first-window-startup-services.ts: the barrier is Promise.race([daemon.ready, failOpen(60s)]); failOpenTimeout is cleared only after both services settle, so the race settles ≤60s after services start. On win32-packaged the window opens before services start, adding shell-path hydration bounded at 10s per probed shell (hydrate-shell-path.ts:25 SIGKILL timeout). This is the same wait class pty:kill (#7742) and pty:spawn already carry on this exact path; in practice it's daemon-adoption time (seconds).

(b) Can it hang / reject? No hang: startService wraps startDaemonPtyProvider in .catch(onError) — daemon.ready never rejects and always settles, including daemon crash mid-swap (crash → catch → resolve → race settles → post-swap registry answers; a degraded/local provider is then the legitimate owner). The 60s fail-open timer backstops a wedged start. Rejection is possible only if the outer services promise rejects (win32 shellPathReady.then(startServices)): then pty:hasPty rejects across IPC — both renderer callers catch (terminal-pane-recovery.ts try/catch, session-reconcile-dispose.ts .catch(() => {})), and the sync path's two-arg .then(markSettled, markSettled) treats rejection as settled and falls through to the provider (sole owner after a failed swap — correct). Same exposure pty:kill has had since #7742.

(c) Null-vs-false caller audit (the most likely failure mode — absent). Derived myself, not read from the PR. The controller installed by installPtyRuntimeController is consumed only in orca-runtime.ts; renderer consumers derived from the preload bridge (pty.hasPty → invoke('pty:hasPty'), typed boolean | null).

Sync (5 sites):

  • orca-runtime.ts:9389 — capability presence check only, no call.
  • :19330 controllerKnowsPtyIsLive (=== true) — null merely skips the live shortcut; absence is then decided by async probePtyLiveness, which awaits the same barrier; isLeafPtyProvenAbsent treats null/error as doubt and doubt never gates a write.
  • :33751 inventory sweep — explicit three-way: true rescues, false → forgetPtyLivenessVerdict (observed absence), null → markPtyLivenessUnverifiable(NO_OBSERVING_PROVIDER_REASON). This is the claimed terminal.list improvement, and it exists in production code, not just tests.
  • :33844 refreshFloatingWorkspacePtyLiveness — live === null aborts the targeted fast path (returns null; caller at :33518 falls back to the full inventory path) instead of demoting.
  • :34052 buildTerminalSummary leaf provenAbsent (!== true) — null lands like false here, but that is decision-identical to main's false (both ≠ true), guarded by provenLivePtyIds !== null plus remote/SSH exclusions, and composes with Never read an unanswerable hasPty probe as proven PTY absence #16932's confirmed-absence gate. No regression; see P2-2.

Renderer (3 consumers):

  • terminal-pane-recovery.ts:227 — explicit live === false early-return; null proceeds to remount unless requireAuthoritativeLiveness; rejection caught.
  • session-reconcile-dispose.ts:64 → shouldReconcileMissingSession — first line is if (args.isLive !== false) return false: null can never tear down a pane (pinned by terminal-dead-session-reconcile.test.ts).
  • web-terminal-api.ts:46 — paired-web stub already returns null.

No if (!hasPty)-style collapse exists anywhere in the consumer set.

(d) Exemptions can't reach the old confident-false. SSH exemption requires a non-null ptyOwnership entry or a strict ssh:<conn>@@<id> parse (src/shared/ssh-pty-id.ts); local ids listed by the local provider get ptyOwnership = null, which still gates (if (connectionId) is falsy for null). A retained-ownership id whose SSH provider is gone routes to getProvider → throw → null, never a local false (parity rows A.sync.owned-provider-gone, A.ipc.ssh-no-provider). The no-barrier exemption is reachable in production only via register-headless-runtime.ts (headless serve: daemon installed before registration, sole owner per #12393); the desktop path always threads the accessor (index.ts:1633 → attach-main-window-services.ts:137, the only production caller). Barrier identity is a module-level let bound once per launch (index.ts:3286/3289 → :1148), so the WeakSet-by-identity gate is sound; a hypothetical rebind degrades to one extra conservative null, and ablation A4 proves the suite catches a gate that fails to reopen.

4. Legacy byte-parity — mechanical differential harness

Built a 22-probe scratch harness (5 phases: no-barrier local, SSH registered, unsettled barrier, settled barrier + daemon owner, headless re-registration; sync + IPC probes each) writing one JSON row per probe; ran it against merge-base production code and head production code and diffed the outputs.

18/22 rows byte-identical. The only 4 diffs are the fix itself:

  • C.sync.daemon-restored: false → null (swap window)
  • C.ipc.daemon-restored: false → PENDING (deferred, lands true from the post-swap owner)
  • A/D.sync.remote-handle: false → null — the seam-2 guard, deliberately unconditional (matches the async probe's existing remote: handling on main); all five sync consumers audited above handle it (three-way, !== true decision-identical, or abort-to-full-sweep).

All exemption rows (SSH live/dead, provider-gone, headless sole-owner false, post-settle known/unknown) are byte-identical.

5. Wire claim vs shipped v1.4.190

Verified against the tag, not the vocabulary's existence on main: local and remote v1.4.190 peel to the same commit 6e4f817101da. At that tag: src/shared/pty-liveness-verdict.ts ships the full live | unverifiable | exited union and NO_OBSERVING_PROVIDER_REASON; src/cli/terminal-format.ts formats ptyStopVerdict === 'unverifiable' (:218), host=unverifiable (:28), and unverifiable scope (:43), with shipped tests asserting each. This PR adds no wire field, opcode, or frame — pty:hasPty is same-binary Electron IPC — and the only value that can newly reach a paired v1.4.190 client is an unverifiable verdict it already decodes and prints. Rule 1/2/3 of docs/reference/remote-wire-compatibility.md: clean.

6. Overlap with sibling PRs

File-disjoint from all four: #16932 (orca-runtime.ts, pty-liveness-verdict.ts), #16955 (providers/* inspection), #16926 (relay/pty-handler*, preload), #16924 (daemon pid publish). Composition with #16932 verified in code: this PR stops the provider fabricating false; #16932 stops the summary over-trusting it; #16932's terminal-list-stale-leaf-liveness.test.ts passes at this head. The residual foreground/child-process window (pty:inspectProcess etc.) is #16955's site-5 lane, untouched here.

7. Tests / typecheck / CI (honest attribution)

  • Head: new suite 6/6; terminal-dead-session-reconcile, terminal-pane-recovery, terminal-list-stale-leaf-liveness + new suite = 60/60; tc:node clean.
  • Full src/main/ipc/: 3235 passed; 10 failures confined to 4 spawn-env suites (login-shell, serializer-settlement, agent-overlays, codex-home-routing) that fail identically with merge-base production code on this machine — machine-env-dependent, pre-existing, not this PR's.
  • CI at this SHA: shard 8/8 red on both Node versions on web-preload-api-runtime-calls.test.ts ("unwraps domain failures…") — main-red since Add parent worktree selection when creating workspace #15420, inherited; e2e / ssh docker watcher isolation + the verify aggregate are the main-side lane being handled separately. All 14 other test shards, both packages, static analysis, changed-e2e: green. None of the failures are attributable to this change.

8. Performance (hand review; the $perf skill is disable-model-invocation for workers, so this is the documented substitute)

Sync path adds O(1) per call: one startsWith, ≤2 map lookups + a prefix parse, one accessor call, 1–2 WeakSet lookups; no steady-state allocation. Called per leaf per terminal.list build and per send gate — negligible. IPC path adds one microtask (await of a resolved promise) after startup. No new timers or listeners; the settle watcher arms once per barrier identity; WeakSets can't grow (at most a handful of barrier identities per app lifetime). The only real cost is the intended one: presence answers defer during the cold-start swap, bounded per (3a).

9. Superseding bar

This is substantially what I'd write from scratch, with one design difference: from scratch, the barrier owner would publish settledness (e.g. a sync isLocalPtyProviderStartupSettled() set in a .finally beside localPtyProviderReady) instead of consumers inferring it via WeakSet promise-identity bookkeeping — simpler, no arm-once watcher, no one-microtask lag. The current form is contained in one function, correct, and pinned by A4; not worth blocking or widening the diff now. Non-blocking.

P2 notes (none blocking)

  1. P2 Consumer-side settledness inference (above) — consider migrating to an owner-published sync flag if a third sync consumer of the barrier ever appears.
  2. P2 buildTerminalSummary's leaf arm (orca-runtime.ts:34052) still reports connected:false during the swap window when the aggregate inventory misses a daemon-restored id — decision-identical to main, now at least accompanied by an unverifiable verdict instead of an observed absence. This is the acknowledged discovery-completeness residual, not a regression.
  3. Observation: reconcileDeadSessions (the listSessions-based teardown in terminal-dead-session-reconcile.ts:107) has no production callers — the missed-exit path is per-PTY hasPty only, so no ungated listSessions teardown seam remains. Consider deleting it in a cleanup PR before someone rewires it.

Reviewed at b3008b63192392430ea40443c3e6b11637407cb2; findings apply to that SHA only.

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

Copy link
Copy Markdown
Contributor Author

Cross-PR audit follow-up @ exact SHA 9738182cf13eec015ddbe9e33d450293e1751aa9

(git ls-remote verified: refs/heads/brennanb2025/coercion-swap-window-r1 = 9738182cf13eec015ddbe9e33d450293e1751aa9)

Closes the residual seam this PR and #16955 both recorded: pty:inspectProcess was ungated during the daemon swap window. Placement rationale: it belongs here, not on #16955 — this PR owns the startup-barrier gating pattern, the swap-window test rig, and inspect.ts; #16955 owns local-pty-provider.ts and is file-disjoint, so the two still compose cleanly.

Empirical correction to the audit's harm shape (probed on the real swap path): the pre-swap route does NOT currently answer positive-exited evidence for an unowned id — inspectPtyProviderProcess consults provider.hasPty first, so the non-owning LocalPtyProvider's answer collapses to unavailable: true (probe: pre-barrier resolution of {foregroundProcess: null, hasChildProcesses: false, unavailable: true}), which the completion monitor treats as a failed inspection. That safety is incidental: it rides on the funnel's internal check ordering, and #16955's provider-level inspection ("a missing entry is a reaped PTY" → children exited) makes any future reordering or direct provider consult a live completion-coercion hole — the same closed-only-incidentally shape the monitor finding on #16926 had. The gate makes it structural: during the window the answer now comes from the post-swap owner.

Change (inspect.ts only): pty:inspectProcess awaits the local-provider startup barrier exactly like pty:kill (#7742) and pty:hasPty, via a small awaitSwapWindow helper now shared with pty:hasPty. pty:kill keeps its inline form untouched — its listener teardown is ordering-sensitive and must not gain even a no-barrier microtask (a first draft that unified it turned pty-listener-teardown-and-orphans red; reverted).

Exemptions preserved exactly: SSH-scoped ids resolve no barrier and answer their own provider immediately (new test); no-barrier headless/orcad registrations keep sole-owner authority — pty:inspectProcess answers immediately (#12393 test extended); remote: ids stay unavailable.

Tests (in pty-startup-swap-window-presence.test.ts): failing-first defer test — pre-fix the call resolves from the non-owning route before the barrier; post-fix it defers and lands the daemon owner's answer. Ablations at this SHA: new inspectProcess gate red (1), and this PR's four existing ablations re-run individually red (hasPty gate / sync controller gate / remote: guard / settle watcher — 1 failure each); baseline 8/8 green, nothing weakened.

Gates: full pnpm tc exit 0 (twice); oxlint clean; 10 pty IPC suites green (93 tests) including pty-runtime-kill-and-exit, pty-startup-barrier-and-listing, pty-listener-teardown-and-orphans, controller routing/inventory/recovery, daemon teardown.

Inherited CI note: tests shard 8/8 (web-preload runtime-calls, #15420) and e2e ssh docker watcher isolation are red main-side, owned by a separate lane — not caused here.

@coderabbitai

coderabbitai Bot commented Aug 28, 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.

Resolve inspect.ts: #17011 moved pty:kill into renderer-kill.ts, which keeps
its inline barrier await. The swap-window helper and both gates stay.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review round — rebased onto current main, re-verified at c90e2df0c3

Verdict: no P0/P1. Two P2s, neither blocking. The gate does what it says: after this change I could not construct a path where a non-owning provider produces an answer a caller reads as proven absence during the swap window.

Base was stale, and CI was dark

The PR was CONFLICTING when I picked it up, which means it had stopped producing CI runs entirely — the green shown against fef638858f predated that. #17011 landed on main and moved pty:kill out of inspect.ts into renderer-kill.ts, colliding with this PR's helper.

Resolved by merging current main (c90e2df0c3) and keeping main's slimmed inspect.ts, re-applying awaitSwapWindow and both gates on top. renderer-kill.ts:49 keeps pty:kill's inline barrier await, so the ordering-sensitivity note in the helper comment still holds — I updated the comment to name the file it now lives in. pty-listener-teardown-and-orphans (the suite that goes red if pty:kill is routed through an async helper) is green: 43/43 across the ordering-sensitive neighbours.

Failing-first proof

All three production files reverted to origin/main, PR test file kept:

Tests  4 failed | 4 passed (8)

The 4 red are exactly the behaviour-changing tests. The 4 green are preservation tests (SSH-owned ids don't wait ×3, no-barrier sole-owner authoritative ×1) — they guard against over-gating, so they correctly cannot fail pre-fix. Post-fix: 8/8.

Per-gate ablation — each gate individually red

Ablated one at a time, not just per-hunk:

# Gate Test that goes red
A1 inspect.ts — pty:hasPty barrier await pty:hasPty defers a restored daemon id…
A2 inspect.ts — pty:inspectProcess await + reordered routing guard pty:inspectProcess defers a restored daemon id…
A3 operations.ts — remote: early null runtime controller hasPty never answers a paired-runtime handle…
A4 operations.ts — sync swap-window gate runtime controller hasPty answers null, not false…
A5 operations.ts — settle watcher arming runtime controller hasPty answers null, not false…

No two gates are only jointly pinned. A1/A2/A3/A4 each go red alone on a distinct test; A5 is red alone as a post-settle timeout (without it the answer never returns to authoritative). controller.ts deps threading is type-pinned — reverting it fails tc.

Composes with #16932

File-disjoint. I built the composed tree and ran both suites: 48/48 green. Then ablated each PR's gate on the composed tree:

So neither makes the other's gate redundant.

Safety of the barrier itself

A gate that can hang is worse than the bug, so I verified rather than assumed. startService builds ready as .then(start).catch(onError).finally(…) — the .catch swallows, so daemon.ready never rejects; failOpenReady is resolve-only at 60s. So Promise.race([daemon.ready, failOpenReady]) cannot reject and cannot outlast the cap: no stuck-null, and no rejection escaping awaitSwapWindow. The sync watcher uses .then(markSettled, markSettled), settling on both arms. localPtyProviderStartupReady is a single module-level promise object, so the WeakSet identity check is stable.

Consumers of the changed value

pty:hasPty was already declared Promise<boolean | null> in preload — no type or wire change, value-level only. Both decision sites are strictly three-valued: shouldReconcileMissingSession reconciles only on isLive === false, and terminal-pane-recovery blocks only on live === false. No !hasPty collapse anywhere, and unhandled values fall to the safe branch — the opposite direction from the sibling defects.

No new type or union is introduced; the existing boolean | null shape is reused.

P2s (non-blocking, no change requested here)

  1. pty:hasChildProcesses / pty:getForegroundProcess remain ungated. hasPtyProviderForInspection passes daemon-restored ids through, and LocalPtyProvider.hasChildProcesses returns false for an id not in its table, so during the window these still answer a fabricated false. Its only consumer is the window-close confirmation (Terminal.tsx:560), where false skips the "processes are running" prompt — a lost confirmation, not a pane teardown, and daemon sessions survive. Deliberately left to the in-flight foreground/child lane; noting it so it isn't lost.
  2. Sync settle-detection. Inferring "startup settled" by attaching a .then watcher and recording promise identity in a WeakSet works and is GC-bounded, but an owner-published settled flag would express it directly. Behaviour-identical — better as a follow-up than as churn in a chain that ships together.

Gates

tc:node and tc:web clean · oxlint clean (verified live with a canary) · changed-code quality gate 0/0/0 new findings across 4 files since 94e7586665 · oxfmt --check clean · git diff --check clean · no node:child_process imports added · inspect.ts 277 lines, no max-lines suppression.

CI on c90e2df0c3: 19 success / 8 skipped, with e2e / ssh docker watcher isolation still running at time of writing — a long lane unrelated to these files.

Not verified

No Electron UI validation: this diff has no rendered surface to assert on, and the swap window is a sub-second cold-start race that dev-mode CDP cannot deterministically hit. No Windows host validation, and no packaged-build coverage.

@brennanb2025
brennanb2025 merged commit 4cb013c into main Aug 28, 2026
28 checks passed
brennanb2025 added a commit that referenced this pull request Aug 29, 2026
Reconcile the daemon-swap barrier (#16953) with the unverifiable absence
return in pty:inspectProcess: main split one guard into two around
awaitSwapWindow, so the unverifiable return lands at both halves rather
than one. Neither invariant is relaxed — the barrier still runs before
the routing check, and neither absence answer can read as a confirmed exit.

The sole-owner swap-window assertion now expects the published
`unverifiable` evidence: immediate is not observed, and a never-spawned id
was never watched exiting.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…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)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

1 participant