Skip to content

fix(runtime): retire an exited terminal before its stream end - #23492

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/exit-retirement-before-stream-end
Sep 28, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/exit-retirement-before-stream-end

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​224 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​205
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​248 $\color{#cf222e}{\Huge{\mathbf{−}}}$​252 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4

ELI5

When you type exit in 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.ts caught 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:

  • The host removes the exited pane from its in-memory session and publishes that immediately, in the same tick as the exit. Only the save to disk happens later.
  • In the same tick, the stream end is sent after the removal, so a client learns about the exit only once the pane is already gone.
  • Any later activation of that pane gets "tab not found" instead of a new shell. That covers this client's re-attach, a phone opening the session, another client's attach loop, and a re-attach after a network blip.
  • If the save fails, the failure is logged and the pane stays removed. The next successful profile save, or the final save when the app quits, writes it to disk.

Mechanism (src/main/runtime):

  • retireMobileSessionSurfacesForPty is 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).
  • In onPtyExit, the synchronous retirement now comes before notifyPtyExitListeners in 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 a finally, so a throw anywhere in the exit cleanup can never leave a stream open.
  • Several exits in the same tick share one profile save (persist: 'if-dirty'), instead of one full save each.
  • The pendingPtySurfaceRetirementsByPtyId bookkeeping 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:

  • A stale copy of the session sent later by the desktop window bringing the pane back. That stays protected without the disk: the session's change counter moves forward in memory at the same moment, and an older copy arriving afterwards is merged against it rather than accepted.
  • A host crash before the removal is saved. That is the accepted cost, described under Known weakness below.

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:

  • Check for a pending retirement when a pane is activated. Keeps the old rule, but it is a second decider next to the snapshot, and the tab list and pushed updates would keep showing the pane until the save lands.
  • Delay the stream end until the save lands. Keeps the old rule, but it only closes this client's re-attach (a phone or another client can still activate the pane). It would also tie every exit signal to disk latency, with no upper bound under load.
  • Stop the client from re-attaching after an exit. Older desktops and phones would still trigger it, and it moves a lifecycle decision into a reader.

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.

  • What matches: the host now applies the pane's removal in memory and publishes it immediately, and the disk write is a separate, later step that never undoes the in-memory state.
  • What differs: Orca had a rule (fix(terminal): make remote agent sessions host-authoritative #9687) that removals are shown to devices only after they are saved. This PR drops that rule for panes whose process exited, and keeps it everywhere else.

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.ts failures 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 exit in 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 before exit,

Before: the paired client's split terminal, both panes live, before typing exit

then after exit the pane comes back with a new shell (the shell id changes from 24746 to 24805),

Before: after exit, the pane comes back in the split with a new shell

and it is still there after the client restarts.

Before: after the client restarts, the resurrected pane is still in the split

After (this PR, df12a9b01e): with the same 1.5 s delay inside its save, the split before exit,

After: the paired client's split terminal, both panes live, before typing exit

then after exit the pane closes and the terminal is a single pane again,

After: after exit, the exited pane closes and the tab is back to one pane

and it stays closed after the client restarts (also shown without any delay, after 20 tries).

After: after the client restarts, the exited pane stays closed

After, no delay: after 20 tries and a client restart, the exited pane stays closed

Manual test counts (the same paired setup, same machine):

Build Save delay Tries Pane came back After client restart
main none 50 0 gone every time
main 1.5 s (QA-only) 5 5 still there, 5 of 5
this PR none 20 0 gone, 20 of 20
this PR 1.5 s (QA-only) 5 0 gone, 5 of 5

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 gets tab_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-exit fails 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:changed and check:reliability-gates are 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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Mixed versions: host-side only. Older clients benefit too, because the host now answers "tab not found" instead of starting a new shell.
  • SSH / remote: sessions the host keeps behave the same on any host; loss of contact is unaffected (this is about a proven process exit).
  • Interaction with feat(terminal): main's exit record for a kept pane, its capability-gated publication and one restart #22953: that PR passes a narrower "retirable" set into the same function; the one computed set feeds both the in-memory and the saved retirement, so a pane it keeps is never retired. Expect a small textual conflict at the onPtyExit call site.

Author X handle: @BrennanKB5

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

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

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b39aff3b-9983-4665-92fc-4793a411840a

📥 Commits

Reviewing files that changed from the base of the PR and between cdb2928 and df12a9b.

📒 Files selected for processing (3)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime-on-pty-exit.ts
  • src/main/runtime/orca-runtime.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/reliability-gates.jsonc

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


📝 Walkthrough

Walkthrough

PTY 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 df12a

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 Review

Security architecture risk: 🟡 Moderate · up to df12a

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

  • Medium · reliability · inferred: After a failed durable write, clients can see a retired pane even though the saved session still contains its binding; a restart before a successful follow-up save can restore the exited pane.
Security review details

Security Blast Radius

  • inferred — The relevant exposure is an already addressable host terminal pane and clients attached to its session. The examined change does not establish a new remote entrypoint, cross-session retirement authority, or broader privilege.

Trust Boundaries and Controls

  • observed — In the tested pending-write race, a stream-end consumer cannot use automatic activation to adopt or spawn the retired pane; incarnation and exact-binding checks also constrain retirement of replacements.

Resilience and Maintainability Implications

  • inferred — Failed persistence limits the non-resurrection guarantee across restart; synchronous staging refusal has an additional, unverified browser-backed hydration path. Neither establishes a new privilege escalation, but both matter to containment of unintended shell reactivation.

Hardening Proposals

  • proposed — Preserve a recoverable retirement intent when staging or durability fails, and check restart and browser-backed publication against that intent before permitting activation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
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 3 functions across 10 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main runtime change: retiring an exited terminal before its stream-end notification.
Description check ✅ Passed The description is detailed and covers the required explanation, behavior change, rationale, testing, visual proof, review notes, compatibility considerations, and checklist. The Linked Issue section …
Full details: Docstring Coverage

Explanation

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

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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

Run ID: b17770a6-d158-48b9-8274-a063bacf98d7

📥 Commits

Reviewing files that changed from the base of the PR and between b61797d and 7fd30aa.

📒 Files selected for processing (14)
  • config/reliability-gates.jsonc
  • src/main/persistence-host-admitted-terminal-membership.test.ts
  • src/main/persistence/loading-store/profile-state-delayed-authority-fixture.ts
  • src/main/persistence/loading-store/pty-retirement-publication-during-read.test.ts
  • src/main/runtime/acknowledged-terminal-tab-retirement-fixture.ts
  • 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-on-pty-exit.ts
  • src/main/runtime/orca-runtime-persist-terminal-surface-retirements.ts
  • src/main/runtime/orca-runtime-register-pty.ts
  • src/main/runtime/orca-runtime-terminal-retirement.test.ts
  • src/main/runtime/orca-runtime-tests/exit-retirement-activation.spec.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/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.

Comment on lines +29 to +46
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 }
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 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.ts

Repository: 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 -120

Repository: 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 -n

Repository: 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.ts

Repository: 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.accepted

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one test-coverage rough edge worth a look.

Reviewed changes

  • Synchronous in-memory retirement — retireMobileSessionSurfacesForPty now stages the removal in the host-owned session and publishes it in the same tick, returning only the durable disk write; persistTerminalSurfaceRetirements is split into stageTerminalSurfaceRetirements (sync, no rollback) and persistStagedTerminalSurfaceRetirements (the awaited write).
  • Exit ordering — onPtyExit retires before notifyPtyExitListeners, so the stream end can no longer cue a re-attach that finds a listed-but-dead pane and respawns it.
  • Fence removal — pendingPtySurfaceRetirementsByPtyId and its deletes in onPtySpawned / registerPty / invalidateAllHandlesForPty are 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta. The 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, so notifyPtyExitListeners always runs — a cleanup fault such as disposeHeadlessTerminal throwing 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.ts into startSplitHost() 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.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to land at cdb29282ca

Summary: three review rounds (the last clean), e2e QA on a second Mac, and CI fully green (27/27).

Review rounds

  • Round 1:
    • Fixed a regression the change itself introduced: moving the stream end after the exit cleanup meant a throw in that cleanup would leave the stream open. The stream end is now sent from a finally, exactly once, with a test.
    • Made same-tick exits share one profile save (persist: 'if-dirty'), with a test.
    • Added a test that a refused staging write (quit, profile maintenance) still retires the pane and ends the stream.
  • Round 2: proved at source that the stream end is sent exactly once on every path, and that staging a retirement always marks the store dirty, so 'if-dirty' can never skip it. Corrected stale wording that still described the reversed rule.
  • Round 3: clean. No references to the deleted pending-retirement bookkeeping remain. Quit does not trigger a flood of retirements. Each key behaviour is covered by a test that goes red when it is removed.

e2e QA (second Mac, production e2e build, the built bundle checked for the new code), spec paired-remote-split-pane-host-retired-ghost:

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in 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/main into the branch. The only PR-authored delta is the conflict resolution in onPtyExit: the branch's intentionalHandlelessPtyStops.get/has check was replaced by main's intentionalPtyStops.claimExit(ptyId, exitIncarnationId ?? pty?.incarnationId).length > 0 (renamed to preservesIntentionallyStoppedSurface). 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 the finally, and the pendingPtySurfaceRetirementsByPtyId fence removal — is unchanged by the merge.
  • No other PR-authored file changed in the delta. The origin/main merge otherwise only pulled upstream churn; no dangling references to pendingPtySurfaceRetirementsByPtyId or intentionalHandlelessPtyStops remain.

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.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status update: ready at df12a9b01e

  • Merged with main (merge commit, no rebase). One conflict at the onPtyExit call site, resolved to keep main's new behavior and this PR's order: the exited pane is retired in memory and published, then the stream is ended, in the same synchronous call. CI is green on this head (30/30).
  • Manual test added to the description. It uses a real paired setup: an Orca host plus a second Orca desktop paired to it, on a second Mac.
    • Main with a QA-only save delay: the exited pane came back with a new shell in 5 of 5 tries.
    • This PR, with and without that delay: the pane closed and stayed closed after a client restart, 0 of 25 came back.
    • Main without the delay didn't reproduce in 50 tries on that machine (the race is timing-dependent), and the description says so.
  • Before/after screenshots are embedded in the description.

@brennanb2025
brennanb2025 merged commit d68eee3 into main Sep 28, 2026
42 checks passed
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