Skip to content

fix: preserve terminal retirement proof across renderer publications - #19002

Merged
nwparker merged 8 commits into
mainfrom
nwparker/preserve-terminal-retirement-publication
Sep 8, 2026
Merged

nwparker merged 8 commits into
mainfrom
nwparker/preserve-terminal-retirement-publication

Conversation

@nwparker

@nwparker nwparker commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​579 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​578
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​267 $\color{#cf222e}{\Huge{\mathbf{−}}}$​51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​216

ELI5

When you close a terminal, the app's host process writes down a receipt that says "this exact terminal really did shut down." Other devices looking at the same workspace — a phone, a browser tab, a laptop connected over SSH — use that receipt to know the terminal is gone for good. The problem: the moment the main window sent its next routine update about which tabs are open, that update didn't include the receipt, so the receipt got thrown away. A device that hadn't already seen it never found out the terminal had closed, so it kept showing the dead tab — and in some cases actively re-adopted it, making a terminal you just closed pop back up. Now the host keeps the receipt across those routine updates, and only tears it up when that slot genuinely gets a new terminal in it.

What changed

After a durable terminal close publishes an exact retirement proof, a later renderer snapshot dropped that proof. A paired client that missed the first publication could then retain the closed terminal as an unverifiable orphan, or re-claim it via terminal.adoptOrphans.

storeMobileSessionSnapshot is the single host writer for mobile session snapshots, so preservation is applied there: carry the host-owned bounded proof history into subsequent snapshots, drop a proof once its surface is published again, and do not carry proofs across a workspace identity change.

The live-surface filter is shared with the publication projection in runtime-mobile-session-result-finalization.ts, which already applied the same predicate inline — one helper (dropRetirementProofsForLiveSurfaces) now serves both, so the two cannot drift.

Tradeoffs

  • Proofs are retained for the worktree's process lifetime, but no longer re-sent. The host still pins up to 64 proofs per worktree in memory. On the wire, a client that advertises session-tabs.retirement-proof-delta.v1 (the Electron renderer and paired web client) receives each proof once per stream and retains it in a bounded client ledger; a title tick that used to carry ~17 KB of repeated proofs now carries none. Measured in session-tabs-retirement-proof-delta.test.ts against the real session.tabs.subscribe handler: 18,694 -> 1,450 bytes per tick on a 3-tab frame with 64 pinned proofs. Clients that do not advertise the capability (CLI, mobile, older desktops) receive the full list on every frame exactly as before this PR, so their behavior is unchanged.
  • Scope is wider than the title implies. Four host-authored paths that build a snapshot from scratch previously wiped the proof list as a side effect and now retain it, and the three that emitted the pre-store object now emit the stored one.
  • Workspace identity is inherited onto host writes. Host-authored writes never set worktreeInstanceId; the stored entry now keeps the last known identity so a host write between two renderer occupants cannot launder one occupant's proofs into the next. A frame from a different occupant starts with only its own proofs.
  • Reused surfaces lose their old evidence. A proof is dropped as soon as any terminal reoccupies the same (parentTabId, leafId), on the host and in the client ledger alike (one shared rule in src/shared/terminal-retirement-proof-ledger.ts). This matches the pre-existing projection semantics.
  • No user-visible capability is removed. One optional runtime client capability is added; no wire field, opcode, or protocol version changes.

Reliability

Terminal retirement needs host-owned positive evidence; absence or disconnection never proves process exit, and the live / unverifiable / exited vocabulary is unchanged. No wire fields or opcodes are added; existing optional retirement proofs remain readable by mixed versions, and the projection could already emit an empty retiredTerminalSurfaces array before this change.

The oracle is preservation of the exact retired handle/leaf after a later publication, plus removal of superseded proofs. Local/daemon and SSH partition contracts are unit-covered; native Windows/WSL and live paired/mobile coverage remain gaps.

Validation: the new runtime regression test fails on the parent commit (retiredTerminalSurfaces is undefined after a renderer publication) and passes with the fix. Full src/main/runtime suite: 6483 tests pass. Node typecheck, oxlint, and oxfmt pass.

Visual proof: not applicable. This is main-process snapshot bookkeeping with no rendered surface of its own; the observable effect requires two coordinated clients (host + paired client) and is covered by the runtime regression test. Local Electron launches are paused for this task, so paired Electron close validation remains pending.

Application fix: leave open for user review.

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: d675c940-7be0-4a1b-8277-b1c8880d5236

📥 Commits

Reviewing files that changed from the base of the PR and between 2e248d9 and 99c745b.

📒 Files selected for processing (1)
  • src/renderer/src/runtime/web-session-terminal-retirement-proof-ledger.test.ts

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


📝 Walkthrough

Walkthrough

The change adds shared retirement-proof ledger helpers and preserves proofs across compatible mobile session snapshots. Runtime storage and publication paths now return or emit the stored snapshot. Session-tab streams send capability-gated proof deltas. The renderer merges, resets, and consumes retained proofs during orphan recovery. Tests cover snapshot preservation, proof publication, streaming deltas, capability negotiation, and renderer retention.

Merge Risk: ⚪ Minimal · up to 99c74

This change preserves terminal closure proofs across session snapshots and delivers them safely to compatible and legacy clients. Current coverage supports the intended proof-retention and cleanup behavior with no concrete merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides detailed context, implementation scope, rationale, tradeoffs, and testing results. However, it omits the required Linked Issue and several template sections, including the che… Add the required template sections and content. Include a real issue reference after Fixes #, add the ## Why, ## Visual Proof, ## Testing, ## AI Disclosure, ## Review, ## Agent skill upstream boundary, ## Notes, and `## Chec…
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 19 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 and concisely describes the primary change: preserving terminal retirement proofs across renderer publications.
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 provides detailed context, implementation scope, rationale, tradeoffs, and testing results. However, it omits the required Linked Issue and several template sections, including the checklist and agent-skill boundary declaration.

Resolution

Add the required template sections and content. Include a real issue reference after Fixes #, add the ## Why, ## Visual Proof, ## Testing, ## AI Disclosure, ## Review, ## Agent skill upstream boundary, ## Notes, and ## Checklist sections, and complete the applicable checkboxes. Use N/A with a reason for visual proof if no visual change exists.

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

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

Important

preserveTerminalRetirementProofs drops a host-owned proof whenever the incoming snapshot still lists the just-retired surface, which happens during the async kill() window where the retirement fence fails to strip that surface. That is the exact "client missed the first publication" case this PR targets, and the added test only exercises the benign tabs: [] path.

Reviewed changes

  • Preserve proofs across renderer publications — storeMobileSessionSnapshot now re-merges retiredTerminalSurfaces from the stored snapshot before stamping, via the new preserveTerminalRetirementProofs.
  • Drop superseded proofs — a proof is filtered out when its parentTabId+leafId reappears as a live terminal surface.
  • Workspace-identity isolation — proofs are not carried when the worktree path or worktreeInstanceId is known to differ.
  • Tests — pure-function unit tests plus a runtime regression test (headless close → later renderer publication).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

const retiredTerminalSurfaces = appendRetiredTerminalSurfaceProofs(
existing.retiredTerminalSurfaces,
snapshot.retiredTerminalSurfaces ?? []
).filter((surface) => !liveSurfaces.has(`${surface.parentTabId}\0${surface.leafId}`))

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.

This filter drops a host-owned proof whenever the incoming snapshot still lists the retired surface, but the fence meant to strip that surface (applyMobileSessionRetirementFences) only removes it when isMobileSessionSurfaceMembershipAllowed returns false — and that predicate returns true while the PTY is still connected. closeHeadlessMobileTerminalTab (orca-runtime-close-headless-mobile-terminal-tab.ts:77) calls kill() without awaiting and never clears connected; only the async onPtyExit (orca-runtime-on-pty-exit.ts:203) does. A stale renderer frame landing in that window keeps the surface in tabs, so this filter drops the proof and resurrects the closed terminal — the exact missed-publication case this PR is meant to fix.

Technical details
# Preserve proofs for host-retired surfaces even while their PTY is still connected

## Affected sites
- src/main/runtime/mobile-session-terminal-retirement-proof.ts:21-29 — `liveSurfaces` is built from the incoming `snapshot.tabs`; the `.filter` drops any proof whose `parentTabId\0leafId` is still present.
- src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts:109-136 — `applyMobileSessionRetirementFences` leaves a surface in place when `isMobileSessionSurfaceMembershipAllowed` returns true (connected-PTY branch at 86-93).
- src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts:77-81 — `kill()` is fire-and-forget; `connected` is only cleared by the async exit.

## Required outcome
- A host-retired surface must keep its proof even when a later renderer frame still lists that surface (stale frame), while a genuinely re-created surface should still drop its proof. Distinguish these two, or stop filtering against raw `snapshot.tabs`.

## Suggested approach (optional)
- Base the drop decision on the host's own live-surface membership (e.g. `isMobileSessionSurfaceMembershipAllowed` / pty-connected plus host-authoritative retirement state) rather than the incoming renderer's `tabs`, or apply the fence first and only drop proofs for surfaces the fence did not itself retire.

## Open questions for the human (optional)
- Add a regression test that closes a terminal and then publishes a renderer frame still containing the closed surface, asserting the proof survives.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This window self-heals on the same path that mints the proof, so a stale renderer frame cannot resurrect the terminal.

Sequence: closeHeadlessMobileTerminalTab appends proof P for (tab, leaf) and fires kill(). A stale renderer frame that still lists (tab, leaf) arrives before onPtyExit; dropRetirementProofsForLiveSurfaces drops P because the surface is in tabs, and the surface is stored as live again. Then onPtyExit fires: it collects exactSurfaces from the pty's own leaves and pane key (orca-runtime-on-pty-exit.ts:87-100) and calls retireMobileSessionSurfacesForPty, which retires exactly those surfaces from the stored snapshot and appends a fresh proof P' (same tab/leaf/handle, since the handle is not invalidated before line 229). So the stored snapshot ends with the surface gone and P' present; the intermediate state is only visible to clients between the two host publications, and a client sees the retired surface plus P' on the next frame.

The alternative — keeping P while the renderer still lists the surface — is what this PR must not do: a genuinely recreated pane at the same (tab, leaf) would then carry a proof naming a live handle, and the client consumer (hasExactTerminalRetirementProof) would retire a live terminal. Dropping on "published live again" errs toward keeping panes, which is the correct direction under the SSH boundary rule (absence never proves exit; a proof is the only thing that does).

If you want it pinned: orca-runtime-terminal-close-continuity.test.ts already exercises close then republish, and terminal-retirement-proof-publication.test.ts covers proof survival across a renderer frame that omits the surface. I have not added a test for the exact interleaving because it asserts an intermediate stored state rather than a client-visible outcome.

…ervation and projection

The publication projection already dropped proofs whose surface is live;
reuse that as one helper instead of a second inline scan.
Three callers built a snapshot, stored it, then emitted the pre-store object. Storing grafts on the preserved proofs, so those frames carried the stored snapshotVersion without the proofs; subscribers dedupe on version and never saw them.

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

Important

The delta itself is clean and complete — no new issues in this commit. I'm withholding approval because the prior review's open thread remains unaddressed: dropRetirementProofsForLiveSurfaces still drops a freshly-created proof when a stale renderer frame lists the just-retired surface during the async kill() window. This commit changes only the emission sites, not that filter.

Reviewed changes

  • Emit the stored snapshot from host-authored writes — createRuntimeOwnedMobileSessionTerminal and both publishStructuredAgentSessionTab paths now build their emitted frame from storeMobileSessionSnapshot's return value, so subscribers receive grafted retirement proofs on the exact frame where they land instead of waiting for an unrelated later version bump.
  • Regression test for the create path — terminal-retirement-proof-emitted-frame.test.ts seeds a stored proof and asserts the frame a runtime-owned create publishes carries it and the stored version; it fails on the parent commit.

The fix is correctly scoped: the other host-authored writers that build a snapshot from scratch (publishPtyBackedMobileSessionTerminal, hydrateHeadlessMobileSessionTabsFromWorkspaceSession) emit via notifyMobileSessionTabsChanged, which reads the latest stored snapshot, and the close path already appends proofs to the object it emits — so only the two changed sites stranded proofs.

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

…y occupant

Proofs are pinned per worktree for the host's lifetime, so every snapshot publication — including a 50ms title tick — re-shipped up to 64 proofs (~17 KB on realistic ids) to every paired client.

Negotiate session-tabs.retirement-proof-delta.v1: the host projects each session-tabs stream to send a proof only the first time that stream carries it, and a capable renderer keeps the union in a ledger keyed by (environment, worktree) with the same 64-entry bound and the same live-surface drop rule as the host, reset on removed frames and on a new connection generation. Legacy clients keep receiving the full list; CLI and mobile do not advertise the capability.

Also inherit worktreeInstanceId onto identity-less host writes so a host write between two renderer occupants can no longer launder one occupant's proofs into the next.

@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: Team

Run ID: 5f42566c-2883-4958-b096-ddf6497f6ed7

📥 Commits

Reviewing files that changed from the base of the PR and between 84d42df and b141791.

📒 Files selected for processing (13)
  • src/main/runtime/mobile-session-terminal-retirement-proof.test.ts
  • src/main/runtime/mobile-session-terminal-retirement-proof.ts
  • src/main/runtime/rpc/methods/session-tabs-inventory.ts
  • src/main/runtime/rpc/methods/session-tabs-retirement-proof-delta.test.ts
  • src/main/runtime/rpc/methods/session-tabs-retirement-proof-delta.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/renderer/src/runtime/web-session-terminal-orphan-recovery.ts
  • src/renderer/src/runtime/web-session-terminal-retirement-proof-ledger.test.ts
  • src/renderer/src/runtime/web-session-terminal-retirement-proof-ledger.ts
  • src/renderer/src/web/web-runtime-client.test.ts
  • src/renderer/src/web/web-runtime-connection-frame-router.ts
  • src/shared/protocol-version.ts
  • src/shared/terminal-retirement-proof-ledger.ts

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

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

Important

The capability-gated proof delta is clean and well-tested — no new issues in this commit. I'm withholding approval because the prior review's async-kill() window thread remains open and unchanged: dropRetirementProofsForLiveSurfaces still drops a freshly-minted proof when a stale renderer frame lists the just-retired surface before onPtyExit clears connected. This commit moves that filter into the shared ledger but does not alter its behavior.

Reviewed changes

  • Shared the proof ledger — appendRetiredTerminalSurfaceProofs and dropRetirementProofsForLiveSurfaces moved to src/shared/terminal-retirement-proof-ledger.ts and are now reused by both the preservation path and the projection path, so the two cannot drift.
  • Added a per-stream proof delta — createSessionTabsRetirementProofDelta gates on a new session-tabs.retirement-proof-delta.v1 capability and sends each proof once per stream; negotiated clients (Electron renderer + paired web client) no longer re-ship up to 64 proofs on every title tick, while legacy CLI/mobile clients keep full lists.
  • Added the client-side retention ledger — mergeRetainedTerminalRetirementProofs keeps the union of sent proofs, drops them when their surface is published live again, and keys retention on the runtime connection generation so a host restart never matches stale handles.
  • Inherited worktreeInstanceId onto host writes — identity-less snapshots now adopt the stored occupant identity, closing the renderer(A) → host write → renderer(B) proof-laundering hole raised in the prior review.
  • Added coverage — byte-size regression against the real session.tabs.subscribe handler, the delta projection, the client ledger, and the occupant-fencing inheritance.

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

A negotiated stream now sends retiredTerminalSurfaces: [] when nothing is new instead of omitting the field. Absence is the host's "I hold no proofs" signal — which is also what a recreated worktree's fresh host entry publishes — so the client ledger forgets on absence and a successor occupant never inherits its predecessor's proofs, even when the removed frame was missed.
An old host sends the full proof list whenever it holds any and omits the field when it holds none. Prove the new client ledger shows exactly what a legacy client would see across that sequence, so forgetting on absence is verified not to regress the mixed-version case.

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

Important

This commit is clean — no new issues. I'm still withholding approval because the async-kill() window thread from the initial review remains open: dropRetirementProofsForLiveSurfaces still drops a freshly-minted proof when a stale renderer frame lists the just-retired surface before onPtyExit clears connected. This commit changes the proof delta's wire semantics, not that filter.

Reviewed changes

  • Kept an empty proof delta distinguishable from a proof-less host — createSessionTabsRetirementProofDelta now emits retiredTerminalSurfaces: [] when nothing is new instead of omitting the field, and mergeRetainedTerminalRetirementProofs now forgets on an absent field but keeps retained proofs on an empty delta. This closes the hole where a recreated worktree's fresh host entry (which omits the field) inherited its predecessor's retained proofs.
  • Extended coverage — a new ledger test for the absent-vs-empty distinction, updated delta-projection expectations, and a tightened byte-size assertion (proofBytes - 2) against the real session.tabs.subscribe handler.

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

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

Important

Test-only follow-up; no new issues. Approval is still withheld pending the async-kill() window thread from the initial review, which this commit does not touch.

Reviewed changes

  • Pinned ledger visibility against a legacy full-list host — a new test asserts mergeRetainedTerminalRetirementProofs reproduces, frame by frame, exactly what a non-negotiating host sent (full list when it holds proofs, omitted field when it holds none), confirming the "forget on absence" rule does not diverge from legacy behavior.

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

@nwparker
nwparker merged commit da836fa into main Sep 8, 2026
33 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