Repository navigation
fix(runtime): retire an exited terminal before its stream end - #23492
Conversation
An exit's durable retirement became asynchronous, so onPtyExit released the terminal stream before the retirement landed. A paired client answers a stream end by re-activating its pane; that activation still found the exited leaf, materialized it under the same session id, and registerPty dropped the pending retirement. The exited split pane came back as a fresh shell. The exit now stages the retirement into the in-memory session and publishes it synchronously, then notifies exit listeners, and only then makes it durable. A failed durable write is logged and left in memory for the next profile write instead of being rolled back, since the process is gone either way. This removes the pending-retirement latch and its post-await incarnation fence: there is no longer a window for them to guard.
Pins the no-rollback contract through a real Store and SQLite authority: when the retirement's own durable write fails, the in-memory retirement is carried by the next unrelated profile write, and by the app-quit flush when no other write happens. The delayed authority fixture can now fail its next write, and the acknowledged-retirement fixture reads the database a relaunch would load and models the quit flush.
…ished The re-activation check alone passes with the listener ordering reverted, because activation awaits before its lookup. Record the session binding and publication count at the moment the exit listener fires so the ordering itself is pinned.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughPTY exit handling now stages terminal-surface removals before notifying exit listeners. It publishes removals without waiting for durable persistence, and a failed write does not restore the staged session state. Tests cover publication timing, failed writes, later persistence through another profile write or the final quit flush, and attempted reactivation of an exited terminal leaf. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to An exited terminal pane is now removed in memory before its stream ends, and the change is saved to disk afterward. This prevents clients from reviving the pane with a fresh shell. If the save fails, the removal is written by a later save or at quit. No blocking issues remain. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to Normal exits now remove the pane before clients can reactivate it. If saving fails, however, the pane can be absent from the live session while an older saved session still contains it, allowing it to reappear after a restart. No new privilege gain is established. Retained concerns
Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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 3 functions across 10 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b17770a6-d158-48b9-8274-a063bacf98d7
📒 Files selected for processing (14)
config/reliability-gates.jsoncsrc/main/persistence-host-admitted-terminal-membership.test.tssrc/main/persistence/loading-store/profile-state-delayed-authority-fixture.tssrc/main/persistence/loading-store/pty-retirement-publication-during-read.test.tssrc/main/runtime/acknowledged-terminal-tab-retirement-fixture.tssrc/main/runtime/orca-runtime-fit-override-listeners.tssrc/main/runtime/orca-runtime-invalidate-all-handles-for-pty.tssrc/main/runtime/orca-runtime-on-pty-exit.tssrc/main/runtime/orca-runtime-persist-terminal-surface-retirements.tssrc/main/runtime/orca-runtime-register-pty.tssrc/main/runtime/orca-runtime-terminal-retirement.test.tssrc/main/runtime/orca-runtime-tests/exit-retirement-activation.spec.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/terminal-retirement-async-durability.test.ts
💤 Files with no reviewable changes (3)
- src/main/runtime/orca-runtime-fit-override-listeners.ts
- src/main/runtime/orca-runtime-invalidate-all-handles-for-pty.ts
- src/main/runtime/orca-runtime-register-pty.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| unpersisted.push(surface) | ||
| continue | ||
| } | ||
| const next = retireTerminalSurfaceFromPersistence(current, surface) | ||
| if (next === current) { | ||
| continue | ||
| } | ||
| try { | ||
| this.store.setWorkspaceSession(next, hostId) | ||
| accepted.push(surface) | ||
| } catch (error) { | ||
| // Why: the process is gone whether or not the profile admits the write (quit, maintenance). | ||
| console.error('[runtime] could not stage terminal retirement:', error) | ||
| unpersisted.push(surface) | ||
| } | ||
| } | ||
| return { accepted, unpersisted } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '1,160p' src/main/runtime/orca-runtime-persist-terminal-surface-retirements.ts
sed -n '85,160p' src/main/runtime/orca-runtime-perform-mobile-session-pty-records-refresh.tsRepository: stablyai/orca
Length of output: 10833
🏁 Script executed:
set -e
printf '%s\n' '--- changed diff ---'
git diff fb51e6cb4c15e340b29d142a46c22e8059dcbe26 7fd30aac299115675fe6c6f09b75e9d9d138997d -- src/main/runtime/orca-runtime-persist-terminal-surface-retirements.ts
printf '%s\n' '--- relevant symbols ---'
rg -n -S "hydrateHeadlessMobileSessionTabsFromWorkspaceSession|setWorkspaceSession|getWorkspaceSession|stageTerminalSurfaceRetirements|retireMobileSessionSurfacesForPty|stream.*end|activateMobileSessionTab|on.*Exit|exit.*activate" src/main src/shared
printf '%s\n' '--- candidate files ---'
git ls-files | rg 'workspace|session|terminal.*retire|pty|runtime' | head -120Repository: stablyai/orca
Length of output: 45663
🏁 Script executed:
rg -n -S "hydrateHeadlessMobileSessionTabsFromWorkspaceSession|setWorkspaceSession|getWorkspaceSession|retireMobileSessionSurfacesForPty|activateMobileSessionTab" .Repository: stablyai/orca
Length of output: 41551
🏁 Script executed:
set -e
printf '%s\n' '--- hydration ---'
cat -n src/main/runtime/orca-runtime-hydrate-headless-mobile-session-tabs-from-workspace-session.ts
printf '%s\n' '--- pty exit ---'
sed -n '180,260p' src/main/runtime/orca-runtime-on-pty-exit.ts | cat -n
printf '%s\n' '--- activation ---'
sed -n '85,190p' src/main/runtime/orca-runtime-perform-mobile-session-pty-records-refresh.ts | cat -n
printf '%s\n' '--- focused retirement test ---'
sed -n '1,240p' tests/e2e/remote-terminal-tab-retirement.unit.test.ts | cat -nRepository: stablyai/orca
Length of output: 32473
🏁 Script executed:
set -e
printf '%s\n' '--- pty-exit listener bindings ---'
rg -n -S "onPtyExit|notifyPtyExitListeners|onPtyExitListener|activateMobileSessionTab\\(" src mobile tests/e2e \
-g '*.ts' -g '*.tsx' -g '*.js' -g '*.mjs'
printf '%s\n' '--- runtime activation API bindings ---'
rg -n -S "activateMobileSessionTab.*runtime|runtime\\.activateMobileSessionTab|activateMobileSessionTab\\(" src/main mobile/src \
-g '*.ts' -g '*.tsx'Repository: stablyai/orca
Length of output: 41580
🏁 Script executed:
set -e
cat -n src/main/runtime/orca-runtime-tests/exit-retirement-activation.spec.tsRepository: stablyai/orca
Length of output: 5117
Publish only successfully staged retirements.
When setWorkspaceSession rejects before applying the update, the surface remains in the workspace session but is added to unpersisted. The current code then removes it from the published snapshot. Stream-end reactivation can hydrate that stale leaf and create another PTY.
Suggested fix
- const removableRetiredSurfaces = [...persisted.accepted, ...persisted.unpersisted]
+ const removableRetiredSurfaces = persisted.acceptedThere was a problem hiding this comment.
ℹ️ No critical issues — one test-coverage rough edge worth a look.
Reviewed changes
- Synchronous in-memory retirement —
retireMobileSessionSurfacesForPtynow stages the removal in the host-owned session and publishes it in the same tick, returning only the durable disk write;persistTerminalSurfaceRetirementsis split intostageTerminalSurfaceRetirements(sync, no rollback) andpersistStagedTerminalSurfaceRetirements(the awaited write). - Exit ordering —
onPtyExitretires beforenotifyPtyExitListeners, so the stream end can no longer cue a re-attach that finds a listed-but-dead pane and respawns it. - Fence removal —
pendingPtySurfaceRetirementsByPtyIdand its deletes inonPtySpawned/registerPty/invalidateAllHandlesForPtyare gone. - Tests / durability — new
exit-retirement-activation.spec.ts; failed-retirement tests against a real SQLite store showing the next write (or the final quit flush) carries the removal; three contracts intentionally flipped to "publish before durable".
ℹ️ Test coverage no longer matches the new synchronous contract
Two tests in the touched retirement suites now describe coverage they no longer provide. Neither is a production defect, but both should be reconciled before merge so the suites keep pinning the behavior they name.
terminal-retirement-async-durability.test.ts — does not publish a delayed exit over a newly admitted incarnation (lines 58-72) passes vacuously now. onPtyExit publishes synchronously (retireMobileSessionSurfacesForPty → storeMobileSessionSnapshot + notifyMobileSessionTabsChanged, and notifyMobileSessionTabsChangedNow calls listeners synchronously), so by the time await gate.started.promise resolves the call has already happened. published.mockClear() at line 67 then erases the only call, and expect(published).not.toHaveBeenCalled() at line 70 cannot fail regardless of the fence. The neighboring renamed test (publishes physical-exit retirement before its durable write completes) already proves the synchronous publish, so this one should be deleted or rewritten to assert one-shot publication without clearing the spy.
pty-retirement-publication-during-read.test.ts — the replacement / legacy-replacement branches (lines 88-92) now end with expect(runtime.snapshot()?.tabs).toHaveLength(0) (line 97), which is the intended behavior, but each branch only calls onPtySpawned with a new incarnation. onPtySpawned / registerPty do not themselves re-mint mobileSessionTabsByWorktree; a fully-admitted same-id replacement is only restored through a pending mobile create, a renderer republish (isMobileSessionSurfaceMembershipAllowed), or hydration from a re-persisted binding. The old fence kept the pane only by never removing it, so the new "surface survives an admitted replacement" path has no coverage that I could find.
Technical details
# Stale/weak retirement tests after the synchronous-retirement reorder
## Affected sites
- `src/main/runtime/terminal-retirement-async-durability.test.ts:58-72` — clears the spy after the
only (now-synchronous) publication, so the final assertion is unfalsifiable.
- `src/main/persistence/loading-store/pty-retirement-publication-during-read.test.ts:73-99` — the
`replacement`/`legacy-replacement` cases assert 0 tabs but never complete admission, so they do
not distinguish "exit wins over a raw spawn" from "an admitted replacement recovers."
## Evidence
- `src/main/runtime/orca-runtime-on-pty-exit.ts:224-231` — retirement call has no `await`;
`notifyPtyExitListeners` runs after it.
- `src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts:153-191` and
`orca-runtime-schedule-mobile-session-tabs-changed.ts:36-52` — `notifyMobileSessionTabsChanged`
reaches listeners synchronously.
- `src/main/runtime/orca-runtime-invalidate-all-handles-for-pty.ts:137-180` and
`orca-runtime-register-pty.ts` — `onPtySpawned` never touches `mobileSessionTabsByWorktree`;
`registerPty` only restores a surface via `ensurePtyBackedMobileSurfaceForRendererTab`, which
returns null without a pending mobile create.
## Required outcome
- Remove or rewrite the vacuous test so its assertion can fail if synchronous one-shot publication
regresses.
- Either exercise a fully-admitted same-id replacement end to end, or rename/re-scope the
`replacement` cases so they are documented as "a raw spawn does not resurrect the pane."
## Open questions for the human
- Is a provider replacement that reuses the pty id after an exit expected to keep the pane visible
without a renderer republish? If so, the removal needs a test proving that recovery path.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…cepted The retirement result is staged in memory before any write, and the removable-surface comment and the replacement-admission test name still described the old publish-after-durable rule.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The two test-coverage rough edges the prior review flagged are untouched by these commits, so this is not an approval.
Reviewed changes
- Moved the whole pty-exit cleanup body into a
try/finally, sonotifyPtyExitListenersalways runs — a cleanup fault such asdisposeHeadlessTerminalthrowing still ends the stream, while the retirement still precedes it. - Switched the durable retirement write to
persist: 'if-dirty', so several exits retired in one tick share the first profile save instead of each forcing their own. - Extracted the split-host setup in
exit-retirement-activation.spec.tsintostartSplitHost()and added cases for a refused staging write and for a cleanup fault still ending the stream. - Added a durability test asserting two same-tick exits produce exactly one profile write.
I traced the 'if-dirty' optimization against the persistence layer: staging goes through setWorkspaceSession → scheduleSave, which bumps writeGeneration, and selective writes carry the staged domain (or fall back to a full snapshot when the dirty set is empty), so a skipped write can only mean the retirement is already durable.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Review status: ready to land at
|
| Arm | Result |
|---|---|
| Merge base + 1.5 s delay before the retirement save | 3/3 fail: "host never retired the exited split leaf" |
| This PR + the same delay inside its save | 3/3 pass |
| This PR, no delay | 8/8 pass |
| Neighbouring split/exit specs | pass (close-layout consistency 7/7, shortcuts, split-pane paste ownership) |
golden-shell-after-agent-exit fails identically on the merge base on that machine (its stub agent never starts); not related.
The deliberate rule reversal (publishing an exit retirement before it is saved, reversing #9687) is described in the body, with the crash window and the five tests whose contract changes.
Composition: works with #22953 (one computed set feeds the in-memory and saved retirement; expect a whitespace-only conflict at the onPtyExit call site) and with the planned stable-pane replacement work (activation of a retired pane returns "tab not found" before it could be adopted).
There was a problem hiding this comment.
ℹ️ No new issues in the merge delta — but this is not an approval: the two test-coverage rough edges the prior review flagged are still open.
Reviewed changes
- Merge of
origin/maininto the branch. The only PR-authored delta is the conflict resolution inonPtyExit: the branch'sintentionalHandlelessPtyStops.get/hascheck was replaced by main'sintentionalPtyStops.claimExit(ptyId, exitIncarnationId ?? pty?.incarnationId).length > 0(renamed topreservesIntentionallyStoppedSurface). The merged line is byte-identical to main's own, so the fix itself — the synchronous in-memory retirement, its ordering before the stream end in thefinally, and thependingPtySurfaceRetirementsByPtyIdfence removal — is unchanged by the merge. - No other PR-authored file changed in the delta. The
origin/mainmerge otherwise only pulled upstream churn; no dangling references topendingPtySurfaceRetirementsByPtyIdorintentionalHandlelessPtyStopsremain.
I ran the touched suites at the merged head: 42 tests across terminal-intentional-stop-exit (main's claimExit path), orca-runtime-terminal-retirement, pty-retirement-publication-during-read, terminal-intentional-stops, and terminal-retirement-async-durability, plus orca-runtime.test.ts (1316 pass, including the new exit-retirement-activation.spec). All green.
Because the previously reported test-coverage gaps are untouched by this merge and remain unresolved, this review is intentionally not an approval.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Status update: ready at
|

ELI5
When you type
exitin one pane of a split terminal that the host keeps for every connected device (the kind a phone or paired desktop also sees), that pane should close. Sometimes it came back instead: the host started a fresh shell in the exited pane under the same session. This makes the host take the exited pane out of the session the moment the process exits, before anyone can ask for it again, so it can't be brought back by accident.What Changed
Before: when a terminal process exited, the host told subscribers the stream had ended first. It then removed the pane from the session only after the removal had been saved to disk, which since #22612 happens in a background writer. In that gap the pane was still listed. The client that owned the stream reacts to the stream end by re-attaching, and asked the host to activate the pane. The host saw a listed pane with no live process, so it started a new shell under the same session id. Registering that new shell cancelled the pending removal, and the pane survived with a fresh shell. The e2e
paired-remote-split-pane-host-retired-ghost.spec.tscaught it intermittently (1 in 12 runs on main before #22810, and 3 in 3 with a 1.5 s delay injected before the save).After:
Mechanism (
src/main/runtime):retireMobileSessionSurfacesForPtyis now synchronous. It computes the set of panes to retire once, stages the retirement in memory (stageTerminalSurfaceRetirements), publishes it, and returns only the disk write (persistStagedTerminalSurfaceRetirements, which never rolls back).onPtyExit, the synchronous retirement now comes beforenotifyPtyExitListenersin the same handler, with no await between them: the pane is retired and published, then the stream is ended. That is the natural order for the exit tick, not an extra check. The stream end is sent from afinally, so a throw anywhere in the exit cleanup can never leave a stream open.persist: 'if-dirty'), instead of one full save each.pendingPtySurfaceRetirementsByPtyIdbookkeeping is deleted. Nothing waits before the removal is shown any more, so there is nothing left for it to guard.Why
Every reader decides whether a pane exists from the host's session snapshot: activating a pane, listing tabs, and the updates pushed to other devices. Keeping an exited pane in that snapshot until the disk write landed let the host say "this pane exists" for a dead process, so a re-attach started a new shell in it. Retiring it in memory first leaves one source of truth and deletes the pending-retirement bookkeeping, instead of adding a second check that overrules the snapshot.
This deliberately reverses a rule. Since #9687, an exited pane was removed from what devices see only after the removal was saved to disk (#22612 kept that rule but made the save run in the background, which opened this window). The rule protected against two things:
Tests whose contract changes on purpose:
terminal-retirement-async-durability.test.ts: "publishes physical-exit retirement only after durability" becomes "publishes physical-exit retirement before its durable write completes".orca-runtime-terminal-retirement.test.ts: "does not publish absence when the durable retirement flush fails" becomes "publishes absence and reports when the durable retirement flush fails".orca-runtime-terminal-retirement.test.ts: "rolls back an in-memory retirement when the durable flush fails" becomes "keeps the in-memory retirement when the durable flush fails".pty-retirement-publication-during-read.test.ts: a replacement spawned while the save was pending used to keep the pane; the exit now retires it before any of those actions run, so each case ends with no pane.terminal-retirement-async-durability.test.ts: "does not publish a delayed exit over a newly admitted incarnation" becomes "publishes nothing when the exit write lands after a replacement is admitted". Publication now happens in the exit tick, so the save that lands later must add no second publication.Alternatives considered:
Differences from the common pattern
The common pattern for sessions that several devices share is that the host process owns the session's state in memory, applies a change there first, and persists it as a separate step, so every reader sees the change the moment it happens.
Known weakness. If the host crashes after the pane is removed in memory but before the removal is saved (from the exit until the first successful profile save after it; normally one write of 3 to 7 ms, longer if other writes are queued, and until the next good save if a save fails), the pane comes back after restart as an empty pane with no process behind it, until the user closes it. The process had already exited, so nothing is lost.
Linked Issue
Found while investigating e2e
paired-remote-split-pane-host-retired-ghost.spec.tsfailures on main. They were first attributed to #22810, but the race reproduces on main before #22810 and comes from the asynchronous retirement save.Visual Proof
Manual test on a second Mac: a real paired setup, with an Orca host in serve mode and a second Orca desktop paired to it as the client, both built from the same commit. Each try: the host opens a terminal, the client splits it with the keyboard shortcut and types
exitin the new pane, then the client restarts. Both apps were background-launched and captured over the debugging protocol.Before (main
0de5e4d84d, with a QA-only 1.5 s delay added before the retirement save to make the race reliable): the split beforeexit,then after
exitthe pane comes back with a new shell (the shell id changes from 24746 to 24805),and it is still there after the client restarts.
After (this PR,
df12a9b01e): with the same 1.5 s delay inside its save, the split beforeexit,then after
exitthe pane closes and the terminal is a single pane again,and it stays closed after the client restarts (also shown without any delay, after 20 tries).
Manual test counts (the same paired setup, same machine):
Main's natural race did not reproduce in 50 tries on this machine; it is timing-dependent (it showed in 1 of 12 e2e runs earlier), so the delay is what makes the before and after comparable. The built bundle was checked in every arm: main had the old save path and no new one, this PR had the new one and not the old, and the delay marker was present only in the delay arms. The delay edits were removed afterwards. A phone client was not included. SSH is not covered by a separate shot: the fix is on the host and does not depend on how the client connects.
Testing
New host-level test (
exit-retirement-activation.spec.ts): with the save held open, an exit followed by an automatic activation of that pane. The pane stays gone, the activation getstab_not_found, no new shell is created, and the exit listener observes the retirement already published. It fails if the retirement is deferred behind the save or if the stream end goes first.New durability tests, using a real SQLite-backed store: a failed retirement save is carried to disk by the next unrelated profile write, and by the final quit flush when nothing else is written. Both fail if the retirement is rolled back or not staged in memory.
e2e on a second Mac at
cdb29282ca(the final code; spec only, background launch, production e2e build verified in the built bundle): the merge base with a 1.5 s delay before the retirement save failed 3 of 3 ("host never retired the exited split leaf"); this PR with the same delay inside its save passed 3 of 3, and passed 8 of 8 with no delay. Neighbouring split/exit specs passed (close-layout consistency 7/7, shortcuts, split-pane paste ownership);golden-shell-after-agent-exitfails identically on the merge base on that machine (its stub agent never starts).New tests: the stream still ends when exit cleanup throws before the retirement; exits retired in the same tick are written once; when the profile refuses the write (during quit or maintenance), the pane is still retired and the stream still ends.
Retirement, durability and runtime suites are green.
pnpm tc:node,oxlint,check:code-quality:changedandcheck:reliability-gatesare clean. The cross-version session-tabs retirement proof passes.I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Written with Claude.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
onPtyExitcall site.Author X handle: @BrennanKB5
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)