Repository navigation
fix(terminal): main records every tab close, and seeding reads the records - #22955
Conversation
… transaction A renderer save cannot shrink terminal membership once main owns a repo's topology, so desktop tab and pane closes, CLI split-pane closes and mobile split-pane closes only became durable when the killed process's exit retired the surface. A close whose kill failed or threw, or whose exit was never certified, came back after a reload. Every close now reaches closeTerminalSurface: the renderer sends an explicit intent for user and cleanup closes, the CLI and mobile split-pane closes commit the pane after their stop, and the headless and relayed mobile closes reuse the same commit. A failed flush keeps the in-memory removal and no longer cancels the kill. Exit retirement is unchanged.
…osed A CLI or mobile close of one pane in a split commits the pane in main, but the desktop kept showing it until reload when no exit arrived to remove it. The close now sends a leaf-addressed notice: a mounted pane closes by leaf id, and a parked tab collapses its stored layout. Addressing by leaf makes the notice and the renderer's exit handling no-ops after each other, which replaces the numeric pane-id notice that could close the whole tab when the exit won.
A leaf-addressed close fell through to the whole-tab close whenever main's layout no longer held that leaf as one of several. Main's exit handling retires an exited split pane from the saved layout, so closing that pane afterwards (the exited-pane overlay's Close, or a CLI close whose stop delivers the exit first) removed the whole tab, live sibling included, and the next renderer save could not restore it. A pane close is now a no-op unless its leaf is in a multi-pane layout. Also updates two mobile split-close assertions to expect the leaf-addressed notice, and adds a test that a relayed mobile close of a renderer-listed tab still reaches the renderer's pin guard.
The existing CLI split test resolves its handle through the renderer graph, so the branch that closes a runtime-owned pane by its PTY handle had no test failing without its commit.
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/main/runtime/terminal-surface-close.ts
…ll, and main's record writes against later saves
There was a problem hiding this comment.
Important
The PR's "main records every close, including pty-exit" invariant holds only for mobile/headless closes. A desktop-local pty-exit writes no record, so the same event reseeds a workspace on desktop and leaves it empty on mobile/headless. Details inline.
Reviewed changes
- Main owns the close records —
closeTerminalSurfaceInWorkspaceSessionnow records every tab close with areasoninto the owning host's partition; the renderer drops the field from its save payload (andSESSION_RELEVANT_FIELDS), mirrors it in memory only, and no longer acknowledges records away. - Seeding reads records —
isTerminalWorkspaceEmptiedOnPurposereplaces the bare empty-row check in both seeding paths, so a legacy empty row with no record gets a terminal back, while a recorded close keeps the workspace empty. - Resurrection fences —
pty-binding-refusals, relayisRetiredReattachedPtySurface, and orphan adoption all consult the records before re-creating or adopting a tab. - SSH owed kill —
pty2:ids may carry a pending kill with no incarnation (the id is the fence);normalizeSshPendingPtyKill/decideSshPendingPtyKillreplay those, andprior && prior.incarnationId === …fixes a latentprior-undefined crash for unfenced intents. - Tests — 26 files added/updated; the runtime close-record suite, per-partition pruning, legacy/TTL/cap seeding, the renderer mirror, and the SSH pending-kill/replay paths are all pinned.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| return ( | ||
| Object.hasOwn(state.tabsByWorktree, worktreeId) && | ||
| (state.tabsByWorktree[worktreeId]?.length ?? 0) === 0 && | ||
| Object.values(state.closedTerminalTabTombstonesByTabId ?? {}).some( |
There was a problem hiding this comment.
This .some counts a pty-exit record as "emptied on purpose", but a process exit is not an intentional emptying — and only mobile/headless closes actually write one. For the same event a desktop-local workspace seeds a fresh terminal (no record) while a mobile/headless workspace stays empty (a pty-exit record). Please confirm that platform split is intended, or exclude reason === 'pty-exit' here.
Technical details
# `pty-exit` suppresses the startup seed on mobile/headless but not on desktop
## Affected sites
- `src/shared/closed-terminal-tab-tombstones.ts:89` — `Object.values(...).some(...)` admits every reason, including `pty-exit`.
- `src/renderer/src/store/terminals/terminal-tab-close.ts:29,76,249` — `intentReason` is `null` for `pty-exit`, so the desktop renderer sends no close intent and mirrors nothing.
- `src/main/runtime/orca-runtime-on-pty-exit.ts:225` — `retireMobileSessionSurfacesForPty` never enters `closeTerminalSurface`, so main writes no record for a desktop process exit.
- `src/main/runtime/orca-runtime-close-mobile-session-tab.ts:173` — the mobile/headless lifecycle close does reach `closeTerminalSurface` and records `{ reason: 'pty-exit' }`.
- `src/main/runtime/orca-runtime-close-mobile-session-tab.ts:234,244` — sibling / renderer-ack branches forward no `reason`, so those closes record `user`.
- `src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts:130` — a local parked exit passes `hostCloseReason: 'pty-exit'` but no `reason`; `src/renderer/src/components/terminal/terminal-tab-actions.ts:223` forwards only `options.reason`, so it records a `user` close too.
## Required outcome
- One of: every `pty-exit` close writes a `pty-exit` record (desktop included), or this predicate ignores `pty-exit` so process-exit empty rows heal on every platform.
## Open questions for the human (optional)
- Is keeping a headless/mobile workspace empty after its process exits the intended end state, or an accident of which path owns the close?…that pane `orca terminal close <handle>` on one pane of a split used to close the whole tab, live sibling included, whenever that pane's stop could not be confirmed (for example an unreachable SSH host). An unconfirmed stop is unverifiable, not a reason to drop siblings: the close now commits only that leaf, tells the renderer to drop that leaf, and leaves the owed kill to the controller's existing SSH pending-kill path. On a host where no renderer lists the tab, main now also removes the closed pane from the paired-client snapshot (with its retirement proof), since no exit may arrive to do it.
…nts' into brennanb2025/terminal-close-records
The mirror is written by closeTab before main commits, so the claim that only a main-committed close writes a record was inaccurate; also reflow a split comment.
… a tab close
Every explicit close now states its target as `{kind:'tab'}` or `{kind:'pane', leafId}`; no
optional leaf id silently means the whole tab. Main resolves a close it started in exactly one
place, reading the copy of the tab's panes its layout owner holds (the renderer-published layout
for tabs the desktop renderer lists, main's session layout otherwise). Only `last-pane` escalates,
through the existing tab path so the renderer's pin guard still runs; an unknown pane never widens.
- The CLI and phone paths drop their per-site sibling counts for the resolver.
- The notifier splits into a tab-only close and a leaf-addressed pane close.
- The headless tab closer takes a parent tab id, so a pane row cannot reach it.
- A phone close of one pane on a host with no desktop window now stops and closes only that pane.
- A phone close of one pane with no live process record closes that pane, not its tab.
`orca terminal close` still exits 1 when the process stop cannot be verified, but its message now says the terminal was closed and names the host's reason, instead of "close failed". It promises that the kill retries on reconnect only when the SSH relay itself never answered the stop, the one case a recorded kill order backs.
A paired client's close of one pane threw `terminal_close_failed` before committing anything when the controller reported the kill failed, so the pane stayed. The kill is now best-effort, as it is for a whole-tab close: the pane's removal always commits and the failure stays on the PTY's liveness verdict.
…ast pane The close resolver read an owner copy that records no panes as "the tab has one pane", so a CLI close of one pane of a split, addressed while the renderer listed the tab before publishing its panes, closed the whole tab. Every copy now counts only if it records at least one pane, read in the owner's order with the published rows as the last fallback, and a pane close widens only when a copy lists that pane as the tab's only one. An unsplit tab whose saved layout predates its pane still closes: its published row names the pane.
|
Review status at This head merges current
|
The close receipt inferred "the kill retries when the host reconnects" from the stop reason's text, which a new transport message or a reworded error would silently break. An explicit close now records the replayable kill order when its stop goes unconfirmed, before sending the follow-up kill (whose own failure is recorded only once its RPC settles), and reports that on the receipt as an optional `pendingKillRecorded`. The CLI promises the retry only from that field, so an older host, which never sends it, gets no promise.
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/main/ipc/pty-ssh-undelivered-kill.test.ts # src/main/ipc/pty/runtime/undelivered-ssh-kill.ts # src/main/ipc/session.ts # src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts # src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts # src/main/runtime/terminal-surface-close.ts # src/preload/api/workspace-session-api.ts # src/renderer/src/store/terminals/terminal-surface-close-intent.ts # src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts # src/renderer/src/store/terminals/terminal-tab-close.ts
The low-evidence lint gate rejects Reflect.get and broad object parameters, which failed static analysis. Narrow with 'in' checks instead and cover the boundary parser's accept and reject cases.
…nts' into brennanb2025/terminal-close-records
… durable writes Main moved terminal-tab retirement onto awaited background writes (runDurableMutation) with an owner-identity fence. The close transaction now commits through that path instead of a synchronous flush, which the live background writer refuses: - closeTerminalSurface is async over runDurableMutation, keeps main's tab owner fence, and fences a pane close by the pane's own incarnation. - A failed durable write never undoes a user's close or skips its kill: the mutation carries no rollback, the removal stays dirty for the next write. - Every main-side caller awaits the transaction; the renderer's IPC promise is only awaited to report a failure, so its removal and kill stay immediate. - closeHeadlessMobileTerminalTab takes main's tab-row signature.
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/main/ipc/session.ts # src/main/persistence/loading-store/pty-binding-persistence.ts # src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts # src/main/runtime/terminal-surface-close.ts # src/renderer/src/hooks/remote-workspace-session-merge.ts # src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
…nd while it waited The renderer has already removed and killed a tab it closes, so its close intent now skips the owner fence phone and CLI closes use. Before, a split pane whose binding was admitted between the close request and its durable write made main refuse the close, and the tab came back on the next launch whenever its processes did not exit.
…ns the terminal layout
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts
…ofile store Main now requires a SQLite profile-state authority for a writable Store, so the save-and-reload close tests build and reopen their store through the shared SQLite test harness.
…nts' into brennanb2025/terminal-close-records # Conflicts: # src/renderer/src/components/terminal/initial-terminal-wiring.test.ts # src/renderer/src/components/use-terminal-watcher-effects.ts
There was a problem hiding this comment.
ℹ️ No new issues in this delta — no inline suggestions. The one PR-own production change is a faithful reconciliation of the seeding read with the base branch; the previously-flagged
pty-exitplatform divergence is unchanged and its thread remains open.
Reviewed changes
- Base branch absorbed —
0e97e856mergesbrennanb2025/terminal-close-intents. Intersecting the PR's 59-file diff with the merge's changes leaves three seeding files, base content inssh-relay-session.ts(the PR-ownclosedByRecordlines are untouched), and two runtime tests switched tocreateSqliteTestStore/closeTestStores. - Close records read at decision time —
use-terminal-watcher-effects.tsnow derives the seeding verdict fromisTerminalWorkspaceEmptiedOnPurpose(useAppStore.getState(), activeWorktreeId)inside the activation-gate callback, replacing the base branch'sObject.hasOwn(getState().tabsByWorktree, …)read; the render-captured selector and its effect dependency are gone. - Tests reconciled — the wiring test asserts the new predicate, and the structured-launch test pins an empty row with a record (stays empty) versus a legacy empty row with none (seeds) through the decision-time read.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…-close-records # Conflicts: # src/main/ipc/pty-ssh-undelivered-kill.test.ts # src/main/ipc/pty/runtime/undelivered-ssh-kill.ts # src/main/ipc/session.ts # src/main/persistence/loading-store/terminal-close-async-durability.test.ts # src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts # src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts # src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts # src/main/runtime/orca-runtime-terminal-surface-close.test.ts # src/main/runtime/terminal-surface-close.ts # src/preload/api/workspace-session-api.ts # src/renderer/src/store/terminals/terminal-surface-close-intent.ts # src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts # src/renderer/src/store/terminals/terminal-tab-close.ts
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
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 (5)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe changes add close reasons to terminal close requests and record tab-close tombstones. Runtime persistence, renderer merging and hydration, and terminal lifecycle checks now handle those records. Renderer workspace-session snapshots and patches no longer persist the tombstone map. SSH pending kill intents without an incarnation are accepted and replayed for epoch-scoped PTY IDs, but not for legacy IDs. Priority: ➖ Normal Merge Risk: 🔵 Low · up to Long-running sessions can accumulate close records in renderer memory and make tab closes progressively more expensive. This is a bounded merge risk that should be fixed or explicitly accepted. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The new close and remote-stop paths retain important identity checks. One client-side copy of close records can grow without the retention limit applied to the durable records, creating a limited availability concern during prolonged use. 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)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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: a9918b2d-5782-4e5b-86b7-fba186cd27ce
📒 Files selected for processing (95)
src/cli/handlers/terminal-close.tssrc/cli/handlers/terminal.test.tssrc/cli/terminal-format.test.tssrc/cli/terminal-format.tssrc/main/ipc/pty-ssh-undelivered-kill.test.tssrc/main/ipc/pty/runtime/controller.tssrc/main/ipc/pty/runtime/undelivered-ssh-kill.tssrc/main/ipc/register-core-handlers/register-core-handlers.test.tssrc/main/ipc/register-core-handlers/register-core-handlers.tssrc/main/ipc/session.tssrc/main/persistence-ssh-pending-pty-kill.test.tssrc/main/persistence/leasing-ssh-ptys/ssh-normalization.tssrc/main/persistence/leasing-ssh-ptys/ssh-pty-kill-intent-operations.tssrc/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/loading-store/pty-binding-refusals.tssrc/main/persistence/loading-store/terminal-close-async-durability.test.tssrc/main/persistence/runtime-authored-workspace-session-fields.tssrc/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.tssrc/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.tssrc/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.tssrc/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.tssrc/main/runtime/orca-runtime-close-mobile-session-tab.tssrc/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.tssrc/main/runtime/orca-runtime-terminal-close-continuity.test.tssrc/main/runtime/orca-runtime-terminal-close-no-widening.test.tssrc/main/runtime/orca-runtime-terminal-close-records.test.tssrc/main/runtime/orca-runtime-terminal-surface-close.test.tssrc/main/runtime/orca-runtime-test-scenario-builders.spec.tssrc/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.tssrc/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.tssrc/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.tssrc/main/runtime/orca-runtime-wait-for-leaf-pty-id.tssrc/main/runtime/runtime-notifier-contract.tssrc/main/runtime/runtime-pty-controller-contract.tssrc/main/runtime/runtime-terminal-orphan-adoption.tssrc/main/runtime/terminal-close-observed-exit-test-fixture.tssrc/main/runtime/terminal-surface-close.test.tssrc/main/runtime/terminal-surface-close.tssrc/main/ssh/ssh-pending-pty-kill-replay.test.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session.tssrc/main/window/runtime-window-lifecycle.tssrc/preload/api/session-bridge.tssrc/preload/api/ui-bridge-clipboard-and-window-controls.tssrc/preload/api/ui-command-event-api.tssrc/preload/api/workspace-session-api.tssrc/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.tssrc/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.tssrc/renderer/src/components/terminal-pane/pending-split-close.test.tssrc/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.tssrc/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsxsrc/renderer/src/components/terminal/initial-terminal-wiring.test.tssrc/renderer/src/components/terminal/initial-terminal.tssrc/renderer/src/components/use-terminal-watcher-effects.tssrc/renderer/src/hooks/ipc-events-close-routing-test-harness.tssrc/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.tssrc/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.tssrc/renderer/src/hooks/remote-workspace-session-merge-closed-terminal-tombstone.test.tssrc/renderer/src/hooks/remote-workspace-session-merge.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply-deferred-session-write.test.tssrc/renderer/src/hooks/remote-workspace-snapshot-apply.tssrc/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.tssrc/renderer/src/lib/session-write-subscriber-deferred-persist.test.tssrc/renderer/src/lib/workspace-session-browser-history.test.tssrc/renderer/src/lib/workspace-session-closed-tab-tombstones.test.tssrc/renderer/src/lib/workspace-session-closed-tab-tombstones.tssrc/renderer/src/lib/workspace-session-editor-drafts.test.tssrc/renderer/src/lib/workspace-session-liveness.test.tssrc/renderer/src/lib/workspace-session-patch.tssrc/renderer/src/lib/workspace-session-relevant-fields.test.tssrc/renderer/src/lib/workspace-session-ssh-partition-round-trip.test.tssrc/renderer/src/lib/workspace-session.tssrc/renderer/src/lib/worktree-activation-default-tabs.test.tssrc/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.tssrc/renderer/src/lib/worktree-activation-store-contract.tssrc/renderer/src/lib/worktree-initial-terminal-close-records.test.tssrc/renderer/src/lib/worktree-initial-terminal-seeding.tssrc/renderer/src/store/slices/worktrees/session/worktree-identity-rename-row-worktree-ids.test.tssrc/renderer/src/store/terminals/terminal-surface-close-intent.tssrc/renderer/src/store/terminals/terminal-tab-close-intent.test.tssrc/renderer/src/store/terminals/terminal-tab-close-tombstone.test.tssrc/renderer/src/store/terminals/terminal-tab-close.tssrc/renderer/src/store/terminals/workspace-terminal-hydration-patch.tssrc/renderer/src/store/terminals/workspace-terminal-hydration.tssrc/renderer/src/web/preload-api/web-workspace-session-api.tssrc/shared/closed-terminal-tab-tombstones.test.tssrc/shared/closed-terminal-tab-tombstones.tssrc/shared/pty-liveness-verdict.tssrc/shared/runtime-terminal-contracts.tssrc/shared/ssh-pending-pty-kill.test.tssrc/shared/ssh-pending-pty-kill.tssrc/shared/terminal-surface-close-target.test.tssrc/shared/terminal-surface-close-target.tssrc/shared/workspace-session-schema-field-coverage.test.ts
💤 Files with no reviewable changes (8)
- src/renderer/src/lib/workspace-session-patch.ts
- src/renderer/src/lib/workspace-session-closed-tab-tombstones.test.ts
- src/renderer/src/lib/workspace-session-closed-tab-tombstones.ts
- src/renderer/src/lib/workspace-session-editor-drafts.test.ts
- src/renderer/src/lib/workspace-session-liveness.test.ts
- src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts
- src/renderer/src/lib/workspace-session-relevant-fields.test.ts
- src/renderer/src/lib/workspace-session.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| const nextClosedTombstones = | ||
| closeReason === 'user' && | ||
| closedWorktreeId && | ||
| getConnectionIdFromState(s, closedWorktreeId) !== null | ||
| ? recordClosedTerminalTabTombstone( | ||
| s.closedTerminalTabTombstonesByTabId, | ||
| tabId, | ||
| closedWorktreeId, | ||
| Date.now() | ||
| ) | ||
| intentReason && closedWorktreeId && opts?.remoteCloseOwnedByHost !== true | ||
| ? { | ||
| ...s.closedTerminalTabTombstonesByTabId, | ||
| [tabId]: { | ||
| closedAt: Date.now(), | ||
| worktreeId: closedWorktreeId, | ||
| reason: intentReason | ||
| } | ||
| } | ||
| : s.closedTerminalTabTombstonesByTabId |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
Prune the renderer mirror with the shared recorder.
The old code called recordClosedTerminalTabTombstone, which applied the TTL and the 500-record cap. The new inline spread applies neither. The mirror now records every renderer close, including local tabs. Within one renderer session, only a full hydration from main's session replaces the map. A direct-SSH pull keeps the store's map (workspace-terminal-hydration.ts Lines 196-197).
The effect: the map grows without bound on long-running sessions. Each closeTab copies the whole map. isTerminalWorkspaceEmptiedOnPurpose scans all values. The mirror also stops matching the retention rules that main applies. Use the shared recorder again.
♻️ Proposed fix
const nextClosedTombstones =
intentReason && closedWorktreeId && opts?.remoteCloseOwnedByHost !== true
- ? {
- ...s.closedTerminalTabTombstonesByTabId,
- [tabId]: {
- closedAt: Date.now(),
- worktreeId: closedWorktreeId,
- reason: intentReason
- }
- }
+ ? recordClosedTerminalTabTombstone(
+ s.closedTerminalTabTombstonesByTabId,
+ tabId,
+ { worktreeId: closedWorktreeId, reason: intentReason },
+ Date.now()
+ )
: s.closedTerminalTabTombstonesByTabIdimport { recordClosedTerminalTabTombstone } from '../../../../shared/closed-terminal-tab-tombstones'There was a problem hiding this comment.
ℹ️ No new issues in this delta — no inline suggestions. The two new commits are merges of
origin/mainwhose conflict resolutions were audited and preserve the PR's semantics; the previously-flaggedpty-exitdivergence is unchanged and its thread remains open.
Reviewed changes
- Merged
origin/maintwice —f67ace981fanddbaacdc908absorb 108 files of unrelated main work (terminal subscription refactor, agent-launch caller selection, usage/telemetry, settings panes, tab-create search). Nothing in the merged content touches the close-record flow. - Resolved 13 PR-own conflicts faithfully —
terminal-surface-close.ts,session.ts,orca-runtime-build-headless-mobile-session-browser-tabs.ts,orca-runtime-close-headless-mobile-terminal-tab.ts,orca-runtime-close-mobile-session-tab.ts,undelivered-ssh-kill.ts,terminal-surface-close-intent.ts,terminal-tab-close.ts,workspace-session-api.ts, and four tests. Main's simpler two-argcloseTerminalSurfaceFromRenderer(worktreeId, target)was re-expanded to the PR's object form carryingreason; the tombstone write, theintentReasonnarrowing, the all-partition binding fence, and the epoch-scoped SSH kill recorder all survive. - Tests adapted to the resolved signatures — the close-durability, no-widening, and surface-close suites call the object form;
pty-ssh-undelivered-kill.test.tskeeps the epoch-scoped-id coverage. Mechanical, no assertion weakened.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
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: ad96c400-7fb5-4eea-a8ae-eb291700cd8c
📒 Files selected for processing (14)
src/main/ipc/pty-ssh-undelivered-kill.test.tssrc/main/ipc/pty/runtime/undelivered-ssh-kill.tssrc/main/ipc/session.tssrc/main/persistence/loading-store/terminal-close-async-durability.test.tssrc/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.tssrc/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.tssrc/main/runtime/orca-runtime-close-mobile-session-tab.tssrc/main/runtime/orca-runtime-terminal-close-no-widening.test.tssrc/main/runtime/orca-runtime-terminal-surface-close.test.tssrc/main/runtime/terminal-surface-close.tssrc/preload/api/workspace-session-api.tssrc/renderer/src/store/terminals/terminal-surface-close-intent.tssrc/renderer/src/store/terminals/terminal-tab-close-intent.test.tssrc/renderer/src/store/terminals/terminal-tab-close.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| // Why a tab this session never listed is still recorded: its spawn may commit later and graft it. | ||
| if (result.pinned) { | ||
| return { ...result, resolution: 'tab' } | ||
| } | ||
| const recorded: WorkspaceSessionState = { | ||
| ...result.session, | ||
| closedTerminalTabTombstonesByTabId: recordClosedTerminalTabTombstone( | ||
| result.session.closedTerminalTabTombstonesByTabId, | ||
| target.tabId, | ||
| { worktreeId, reason: options.reason }, | ||
| options.now ?? Date.now() | ||
| ) | ||
| } | ||
| return { | ||
| ...result, | ||
| ...(result.closed | ||
| ? { session: advanceTerminalTopologyRevision(result.session, worktreeId) } | ||
| : {}), | ||
| session: result.closed ? advanceTerminalTopologyRevision(recorded, worktreeId) : recorded, | ||
| resolution: 'tab' | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '75,235p' src/main/runtime/terminal-surface-close.ts
rg -n 'allowMissing|closeTerminalSurfaceInWorkspaceSession' src/main/runtimeRepository: stablyai/orca
Length of output: 8247
🏁 Script executed:
set -e
printf '%s\n' '--- terminal-surface-close.ts ---'
sed -n '1,280p' src/main/runtime/terminal-surface-close.ts
printf '%s\n' '--- close tab and tombstone definitions/usages ---'
rg -n -C 4 'function closeTerminalTabInWorkspaceSession|closeTerminalTabInWorkspaceSession|recordClosedTerminalTabTombstone|closedTerminalTabTombstonesByTabId|RuntimeSessionTabCloseReason' src
printf '%s\n' '--- allowMissing callers ---'
sed -n '130,270p' src/main/runtime/orca-runtime-close-mobile-session-tab.ts
sed -n '1,230p' src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts
sed -n '1,100p' src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.tsRepository: stablyai/orca
Length of output: 42919
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/architecture /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 47890
🏁 Script executed:
set -e
printf '%s\n' '--- workspace-session-terminal-tab-close.ts ---'
sed -n '1,250p' src/shared/workspace-session-terminal-tab-close.ts
printf '%s\n' '--- closed-terminal-tab-tombstones.ts ---'
sed -n '1,260p' src/shared/closed-terminal-tab-tombstones.ts
printf '%s\n' '--- exact tombstone consumers ---'
rg -l 'closedTerminalTabTombstonesByTabId|isClosedTerminalTab|closedTerminalTabTombstone' src --glob '!**/*.test.ts' | sort
rg -n -C 6 'closedTerminalTabTombstonesByTabId|isClosedTerminalTab|closedTerminalTabTombstone' src --glob '!**/*.test.ts'
printf '%s\n' '--- close entrypoint declarations and calls ---'
rg -n -C 5 'closeTerminalSurfaceFromRenderer|closeHeadlessMobileTerminalTab|closeTerminalSurface\(' src/main src/shared --glob '!**/*.test.ts'Repository: stablyai/orca
Length of output: 41805
🏁 Script executed:
set -e
printf '%s\n' '--- target type/parser and IPC ---'
cat -n src/shared/terminal-surface-close-target.ts
sed -n '1,90p' src/main/ipc/session.ts
rg -n -C 6 'closeTerminalSurfaceFromRenderer|terminalSurfaceClose|kind: .tab.|tabId:' src/renderer src/main --glob '!**/*.test.ts' | head -n 260
printf '%s\n' '--- orphan adoption ---'
sed -n '130,225p' src/main/runtime/runtime-terminal-orphan-adoption.ts
printf '%s\n' '--- PTY binding refusals ---'
sed -n '1,180p' src/main/persistence/loading-store/pty-binding-refusals.ts
printf '%s\n' '--- SSH lease tombstone matching ---'
sed -n '2690,2790p' src/main/ssh/ssh-relay-session.ts
printf '%s\n' '--- seeding/default terminal consumers ---'
rg -n -C 8 'hasClosedTerminalTabRecord|isTerminalWorkspaceEmptiedOnPurpose|closedTerminalTabTombstonesByTabId' src/main src/shared --glob '!**/*.test.ts'Repository: stablyai/orca
Length of output: 42832
🏁 Script executed:
set -e
printf '%s\n' '--- renderer close API and producers ---'
rg -n -C 8 'session:close-terminal-surface|closeTerminalSurfaceFromRenderer|closeTerminalSurface|terminal-surface-close' src/preload src/renderer src/main --glob '!**/*.test.ts' --glob '!src/main/runtime/terminal-surface-close.ts'
printf '%s\n' '--- purposeful-empty seeding consumers ---'
rg -n -C 12 'isTerminalWorkspaceEmptiedOnPurpose' src --glob '!**/*.test.ts'
printf '%s\n' '--- orphan adoption claim flow ---'
sed -n '1,235p' src/main/runtime/runtime-terminal-orphan-adoption.ts
printf '%s\n' '--- PTY binding refusal flow ---'
sed -n '1,125p' src/main/persistence/loading-store/pty-binding-refusals.tsRepository: stablyai/orca
Length of output: 42371
Reject a tab ID owned by another worktree before recording the tombstone.
The renderer close route accepts a worktree ID and tab ID without checking ownership. If the tab exists only in another worktree, the allowMissing close persists a tombstone for the wrong worktree. That record can reject orphan recovery for the real tab and can suppress terminal seeding when the requested worktree is empty.
Suggested fix
const result = closeTerminalTabInWorkspaceSession(session, worktreeId, target.tabId, {
force: options.force
})
// Why a tab this session never listed is still recorded: its spawn may commit later and graft it.
if (result.pinned) {
return { ...result, resolution: 'tab' }
}
+ const ownedByAnotherWorktree =
+ Object.entries(session.tabsByWorktree).some(
+ ([candidateWorktreeId, tabs]) =>
+ candidateWorktreeId !== worktreeId && tabs.some((tab) => tab.id === target.tabId)
+ ) ||
+ Object.entries(session.unifiedTabs ?? {}).some(
+ ([candidateWorktreeId, tabs]) =>
+ candidateWorktreeId !== worktreeId &&
+ tabs.some(
+ (tab) =>
+ tab.contentType === 'terminal' &&
+ (tab.entityId === target.tabId || tab.id === target.tabId)
+ )
+ )
+ if (!result.closed && ownedByAnotherWorktree) {
+ return { ...result, resolution: 'tab' }
+ }
const recorded: WorkspaceSessionState = {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Why a tab this session never listed is still recorded: its spawn may commit later and graft it. | |
| if (result.pinned) { | |
| return { ...result, resolution: 'tab' } | |
| } | |
| const recorded: WorkspaceSessionState = { | |
| ...result.session, | |
| closedTerminalTabTombstonesByTabId: recordClosedTerminalTabTombstone( | |
| result.session.closedTerminalTabTombstonesByTabId, | |
| target.tabId, | |
| { worktreeId, reason: options.reason }, | |
| options.now ?? Date.now() | |
| ) | |
| } | |
| return { | |
| ...result, | |
| ...(result.closed | |
| ? { session: advanceTerminalTopologyRevision(result.session, worktreeId) } | |
| : {}), | |
| session: result.closed ? advanceTerminalTopologyRevision(recorded, worktreeId) : recorded, | |
| resolution: 'tab' | |
| } | |
| } | |
| // Why a tab this session never listed is still recorded: its spawn may commit later and graft it. | |
| if (result.pinned) { | |
| return { ...result, resolution: 'tab' } | |
| } | |
| const ownedByAnotherWorktree = | |
| Object.entries(session.tabsByWorktree).some( | |
| ([candidateWorktreeId, tabs]) => | |
| candidateWorktreeId !== worktreeId && tabs.some((tab) => tab.id === target.tabId) | |
| ) || | |
| Object.entries(session.unifiedTabs ?? {}).some( | |
| ([candidateWorktreeId, tabs]) => | |
| candidateWorktreeId !== worktreeId && | |
| tabs.some( | |
| (tab) => | |
| tab.contentType === 'terminal' && | |
| (tab.entityId === target.tabId || tab.id === target.tabId) | |
| ) | |
| ) | |
| if (!result.closed && ownedByAnotherWorktree) { | |
| return { ...result, resolution: 'tab' } | |
| } | |
| const recorded: WorkspaceSessionState = { | |
| ...result.session, | |
| closedTerminalTabTombstonesByTabId: recordClosedTerminalTabTombstone( | |
| result.session.closedTerminalTabTombstonesByTabId, | |
| target.tabId, | |
| { worktreeId, reason: options.reason }, | |
| options.now ?? Date.now() | |
| ) | |
| } | |
| return { | |
| ...result, | |
| session: result.closed ? advanceTerminalTopologyRevision(recorded, worktreeId) : recorded, | |
| resolution: 'tab' | |
| } | |
| } |
There was a problem hiding this comment.
ℹ️ No new issues in this delta — no inline suggestions. The single new commit is a clean merge of
origin/mainthat touches none of the PR's own files; the previously-flaggedpty-exitdivergence is unchanged and its thread remains open.
Reviewed changes
- Merged
origin/main—551c34e1b8absorbs 150 files of unrelated main work (terminal subscription admission, agent-launch prestart failures, browser-tab creation placement, native-chat outbox, markdown-document search, i18n, e2e). None of the PR's 59 changed files is in the merge, so no close-record code was reconciled, reverted, or duplicated. - Integration verified —
pnpm tc:node && pnpm tc:webare clean, and theorca-runtime-terminal-close-recordsandworktree-initial-terminal-close-recordssuites pass (13 tests) against the merged tree.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…ookup honours the TTL
… an echo is skipped The echo of a close main already made never finds the tab listed, and the close transaction already skips it when a live record exists. The record helper kept the first record as well, which only ever applied to a close that did remove a listed tab, and there it kept a stale reason and TTL.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — no inline suggestions. The two new commits tighten the close-record lookups (TTL-aware reads, first-writer-wins writes); the previously-flagged
pty-exitplatform divergence is unchanged and its thread remains open.
Reviewed changes
- Every record lookup now honours the TTL —
hasClosedTerminalTabRecordreturnsfalsefor a record older thanCLOSED_TERMINAL_TAB_TOMBSTONE_TTL_MS, so the binding fence admits a late spawn for an expired record instead of refusing it forever. The relay-reattach test fixture moved fromclosedAt: 1toDate.now()to match. - The first close of a tab wins —
recordClosedTerminalTabTombstonenow keeps an existing live record (pruned) instead of overwriting its reason and time, so an echo of the same close cannot flipcleanupback touseror restart the TTL. - The allow-missing write is skipped when a record already exists —
terminalSurfaceCloseMutationreplacesresult.session !== sessionwith an explicittarget.kind === 'tab' && !hasClosedTerminalTabRecord(…)check. This is a strict subset of the old condition (a tab close always allocates a new session, and the pane path never changed the session), so it only drops redundant record writes.
Swept every hasClosedTerminalTabRecord caller — pty-binding-refusals, the relay reattach suppression, orphan adoption, and the direct-SSH renderer merge all now honour the TTL. The remaining raw-map readers (worktree-identity migration/rename, runtime-authored field preservation, boot hydration) are not suppression lookups, so the TTL does not apply to them.
Verified: src/shared/closed-terminal-tab-tombstones.test.ts and src/main/runtime/orca-runtime-terminal-close-records.test.ts pass (18 tests); oxlint clean on the changed files.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta — no inline suggestions. The new commit rolls back the over-broad first-writer-wins from its predecessor; the previously-flagged
pty-exitdivergence is unchanged and its thread remains open.
Reviewed changes
- A close that removes a listed tab records itself again —
recordClosedTerminalTabTombstonegoes back to a plain overwrite, so auserclose of a listed tab that already carried a stalecleanuprecord advances both the reason and the time instead of being pinned to the old record. - The echo skip now lives solely in the mutation guard — with the writer always overwriting,
terminalSurfaceCloseMutation'sallowMissing && target.kind === 'tab' && !hasClosedTerminalTabRecord(…)is the only place an existing record suppresses a second write. This separation is sound becausecloseTerminalSurfaceInWorkspaceSessionhas exactly one caller (that mutation): a close that actually removes a listed tab takes theresult.closed === truebranch and always persists its own record, while only a non-removing close with a live record is skipped. - Tests follow the behavior — the shared "keeps the first close" test is dropped (its premise no longer holds at the writer) and a new runtime test pins that a listed-tab close replaces the record; the existing echo test still holds through the guard, not the writer.
Verified: src/shared/closed-terminal-tab-tombstones.test.ts (7 tests) and src/main/runtime/orca-runtime-terminal-close-records.test.ts (11 tests) pass; oxlint clean on the changed files.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
SSH lane (post-merge note): only partly run before this merged. A live SSH run from a laptop against a throwaway Linux container at
|

Stacked on #22929.
ELI5
When you close a terminal tab, Orca now writes down "this tab was closed" in the main process, for every kind of workspace. Three things read that note: the check that decides whether an empty workspace gets a fresh terminal, the paths that could otherwise bring a closed tab back, and the order that stops a remote shell later if the kill could not reach the host.
What Changed
Before
After
user,cleanup, orpty-exit, which is reserved for main). Each host partition is pruned on its own at write time (30 days, 500 records), so churn on one host cannot evict another host's records. A pane close never writes a record. Only a close that main resolves to the whole tab does, through fix(terminal): every explicit terminal close commits through one main transaction #22929's single pane-to-tab resolver, so this PR has no rule of its own for "last pane".terminal_orphan_surface_retirederror.pty2:id. Those ids carry a per-start mint epoch, so the id alone names one process. On reconnect the order replays when the host lists the id, and retires when it does not. Legacypty-Norders without an incarnation are still dropped. The same recorder backs the close receipt's retry promise (pendingKillRecorded), so that promise holds for these ids too, and a stop recorded twice lands as one order.Why
Differences from the common pattern
pty2:ids. Legacy ids keep the incarnation requirement.Known weakness. "Empty plus any close record in the last 30 days" does not prove that the last removal was a close. Until every membership shrink goes through a close, something that is not a close can empty a workspace that also had a real close recently. Examples are a downgrade round trip, or the renderer's orphan sweep. That workspace then skips the startup seed, and an explicit activation still reseeds it. A test pins this. Also, until exit closes are recorded (a later change), typing
exitin the last shell leaves an empty row with no record, so the next launch gives that workspace one terminal. Before this PR it stayed empty.Linked Issue
No public issue. This is the close-record slice of the terminal tab membership work, stacked on #22929.
Visual Proof
Live Electron QA ran on a separate Mac against this branch (dev builds, isolated profiles), with the SSH checks against a throwaway Linux container.
A closed tab stays closed across a restart (git worktree; a folder workspace behaved the same):
Closing the last terminal, then restarting: the workspace stays empty at startup (selecting it in the sidebar still opens a terminal, as on main):
A legacy empty row with no record now seeds one terminal at startup. Dev builds need #22919 to show this, because React StrictMode double-runs the startup effect and, without #22919, the effect marks the workspace handled before its check returns. With #22919 merged locally into both builds, the base stayed blank at 40 s, and this PR created exactly one terminal with no click. After a user close on this PR, the same workspace stayed blank past 35 s.
SSH: a closed tab stays closed across a restart, and a kill that could not reach the host is replayed after it comes back. With the host paused, the close took effect at once and saved an owed kill on the lease. A restart while still paused kept the tab closed. After the host resumed, the owed kill replayed ("stop confirmed"), the remote
sleep 900was gone, and the tab stayed closed across reconnect, a reload and another restart.A split-pane close removes only that pane and writes no close record. Closing the last pane closes the tab and writes one. Re-checked after the typed close-target merge. Split with
echo LEFT/echo RIGHT, then the right pane closed; after a restart the tab still holds only the left pane:Also checked live: a close in the same tick as the tab's creation (spawn still in flight) never comes back and leaves no shell running; new tabs,
echo, restart restore, reattach andexitbehave as before. The owed-kill replay above had an incarnation, because the process was live before the pause. The branch for apty2:id with no incarnation is covered by the unit tests only.Testing
Each new test was checked against a copy with the core lines deleted, and each one failed for the expected reason:
orca-runtime-terminal-close-records.test.ts: a user or cleanup close is recorded and survives a renderer save plus a reload. A close whose spawn commits after a crash and reload is refused. A record in the SSH partition refuses a graft intolocal. Local churn past the cap leaves the SSH record in place.worktree-initial-terminal-close-records.test.ts: an empty row with a record does not seed. A legacy empty row seeds. A record past its TTL seeds. A record evicted by the cap seeds. The stale-record weakness suppresses the startup seed, and an explicit activation still reseeds.terminal-tab-close-tombstone.test.ts: the renderer's copy matches what main is told to write, and is not written for exit closes or closes a paired host owns.terminal-tab-close-tombstone.test.tsalso pins the reason the renderer keeps that copy: a direct-SSH pull that lands after the close and before main answers keeps the tab closed. Deleting the renderer's copy brings the tab back.orca-runtime-terminal-close-records.test.tsalso pins that main's own record writes survive later store writes. Letting the stored value always win loses a record.orca-runtime-terminal-close-records.test.tsalso pins that a pane close aimed at a tab's only pane records nothing and leaves the tab. Only a close that resolves to the whole tab writes a record. Widening a pane target to a tab close turns it red.pty-ssh-undelivered-kill.test.tsalso pins that an explicit close's unconfirmed stop on apty2:id with no incarnation records exactly one order and reports it. Restoring the incarnation requirement turns it red.remote-workspace-session-merge-closed-terminal-tombstone.test.ts: the record survives a direct-SSH re-hydration, so the workspace stays empty.ssh-pending-pty-kill.test.ts,persistence-ssh-pending-pty-kill.test.ts: apty2:order without an incarnation is kept across a restart, and a legacy one is dropped.ssh-pending-pty-kill-replay.test.ts: the order replays and then retires.pty-ssh-undelivered-kill.test.ts: an offline close records the order.ssh-relay-session-reconnect-incarnation.test.ts: a reattach into a closed tab is suppressed from either partition through the existing suppress path.terminal-output-and-worker-recovery-part-07.spec.ts: orphan adoption refuses a closed tab.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
local. Losing contact is never treated as death: a kill with no incarnation replays only when the host lists the id, and retires only on the host's own absence report.main). Resolved in this branch. The startup seed keeps fix(terminal): retry first-terminal seeding until a decision applies #22919's check-then-mark structure and readsisTerminalWorkspaceEmptiedOnPurpose(useAppStore.getState(), activeWorktreeId)at decision time. One of fix(terminal): retry first-terminal seeding until a decision applies #22919's tests now records the close the waycloseTabdoes, and a new test pins that a legacy empty row seeds.closeTerminalSurfaceto clear exit records. It is a textual conflict only.Author X handle: @BrennanKB5
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)