Skip to content

fix(terminal): main records every tab close, and seeding reads the records - #22955

Merged
brennanb2025 merged 37 commits into
mainfrom
brennanb2025/terminal-close-records
Sep 28, 2026
Merged

brennanb2025 merged 37 commits into
mainfrom
brennanb2025/terminal-close-records

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​800 $\color{#cf222e}{\Huge{\mathbf{−}}}$​218 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​582
Prod 29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​284 $\color{#cf222e}{\Huge{\mathbf{−}}}$​215 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​69

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

  • Only the renderer wrote a "closed tab" note, only for user closes, and only for SSH workspaces. The note was deleted as soon as the SSH host stopped listing the tab.
  • An empty workspace counted as "the user closed the last terminal" just because its row was present and empty. That row is also left behind by old builds and by closes that were only a process exiting, so those workspaces could stay empty forever. The watcher and the startup seed never gave them a terminal back.
  • A closed tab could come back in three ways: a spawn that committed after the close (even after a crash and relaunch), a relay reattach, or a paired-web client adopting an orphaned process after a host restart.
  • If an SSH close could not reach the host and the app never learned the process incarnation, no kill order was saved. The remote shell could run forever.

After

  • Main writes the record. Its close transaction (from fix(terminal): every explicit terminal close commits through one main transaction #22929) writes a close record for every tab close into the partition of the host that owns the worktree. The record holds the worktree, the time and the reason (user, cleanup, or pty-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".
    • A close for a tab main has never listed is recorded too, because that tab's spawn may still commit.
  • The renderer no longer persists records. The field is gone from the renderer's save payload and its patch. The store keeps main's value whenever a save leaves the field out, which is the existing rule for other fields main owns. The acknowledgement that used to delete records is gone. Records die only by TTL and the cap.
  • Seeding. An empty workspace stays empty only when it also has a close record from the last 30 days. An empty row with no record is unknown, so it seeds. That heals legacy data automatically. An explicit activation still reseeds as before.
  • Refusals.
    • A spawn commit may not create a tab that has a close record in any host partition.
    • The relay reattach backstop treats a recorded close like a retired surface when the pane is in no tab, and reuses the existing suppress path.
    • Paired-web orphan adoption refuses a closed tab id with the existing terminal_orphan_surface_retired error.
  • Owed SSH kill. A pending kill may now omit the incarnation when the relay id is a 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. Legacy pty-N orders 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

  • Why record every close in main. The record is a durable fact, so it needs one writer. Main already commits every close through one transaction, so writing the record there covers the CLI, mobile, the desktop renderer and cleanup closes without a helper at each caller.
  • What it stores. It stores a worktree, a time and a reason rather than a bare flag, because the reason is what a later change (main deciding what happens when a process exits) needs to tell an exit-close from a user close. The field is persisted, so its shape is chosen once. An older build strips the reason and reads the record as a user close, which is what the record meant there.
  • Why no acknowledgement. Deleting a record once the host stops listing the tab is exactly when a workspace the user emptied would start to read as never initialized and grow a new terminal.
  • Why the owed kill lives on the lease. The existing pending-kill record on the SSH lease already survives restarts and has its own TTL, cap and replay. A second copy on the close record would be a second journal, and the close record's own lifetime would silently drop the kill.
  • Alternatives rejected.
    • Keeping "empty row means closed": that cannot tell a close from legacy or exit-produced data.
    • Main always taking its prior value on every renderer save: the store applies the same rule to main's own writes, so main's new record would be thrown away. Instead the renderer does not send the field, and a save that leaves it out keeps main's.

Differences from the common pattern

  • The close fact. The common pattern stores a close reason on each terminal's row and keeps the row forever. This PR stores the same fact but gives it a bounded lifetime: the tab row is removed and a record with a 30-day, 500-per-host bound is kept.
  • The renderer's copy of the records. It is in memory and is updated from the close the renderer itself applies, not pushed from main. The direct-SSH pull merge still runs in the renderer and reads that copy synchronously. A push would leave a window in which a pull lands before main answers and brings the closed tab back for good. The copy is never persisted, and it lives no longer than the window that wrote it: a reload or a relaunch replaces it with main's records during boot hydration. It is not pruned, because it merges every host's records and one shared cap would drop SSH records the pull merge still reads. Moving the merge into main later removes this copy.
  • A kill with no incarnation. The owed kill uses the relay id as its fence only for epoch-scoped pty2: ids. Legacy ids keep the incarnation requirement.
  • Worktree removal does not prune records. Records die by TTL and the per-host cap only. A deleted worktree's records sit harmlessly until they expire.

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 exit in 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):

desktop-after-s1-after-close.jpg
desktop-after-s1-after-restart.jpg

Closing the last terminal, then restarting: the workspace stays empty at startup (selecting it in the sidebar still opens a terminal, as on main):

desktop-after-s2-after-restart.jpg

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.

desktop-s3b-before-late-40s.jpg
desktop-s3b-after-seeded-startup.jpg
desktop-s3b-after-control-35s.jpg

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 900 was gone, and the tab stayed closed across reconnect, a reload and another restart.

ssh-s1-after-restart.jpg
ssh-s2-restart-while-paused.jpg
ssh-s2-after-unpause.jpg

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:

recheck-s2-split-echo.jpg
recheck-s2-after-restart.jpg

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 and exit behave as before. The owed-kill replay above had an incarnation, because the process was live before the pause. The branch for a pty2: id with no incarnation is covered by the unit tests only.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

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 into local. 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.ts also 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.ts also 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.ts also 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.ts also pins that an explicit close's unconfirmed stop on a pty2: 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 owed kill:
    • ssh-pending-pty-kill.test.ts, persistence-ssh-pending-pty-kill.test.ts: a pty2: 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.
  • The cross-version wire suites passed (terminal wire, session-tabs retirement proof, worktree identity downgrade), as did the full runtime suite and the related renderer and persistence suites.
  • Typecheck (node and web), oxlint on the changed files, the changed-code quality gate and React Doctor are all clean.

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.
    • Records never cross the paired wire.
    • Older builds reading new data strip the reason and treat every record as a user close. Their direct-SSH merge then suppresses exactly as before.
    • A downgrade that leaves an exit-produced empty row with no record reads as unknown on upgrade, and seeds.
    • An older build's strict lease loader drops a pending kill without an incarnation, which is the same outcome as today.
    • Orphan adoption answers with an error code that paired clients already handle.
  • SSH. Records are written into the partition of the host that owns the worktree, and every refusal checks every partition, because a relay reattach binds into 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.
  • Folder workspaces use the same path as git worktrees.
  • fix(terminal): retry first-terminal seeding until a decision applies #22919 (now on 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 reads isTerminalWorkspaceEmptiedOnPurpose(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 way closeTab does, and a new test pins that a legacy empty row seeds.
  • Conflict with feat(terminal): main's exit record for a kept pane, its capability-gated publication and one restart #22953. That PR adds one call in closeTerminalSurface to clear exit records. It is a textual conflict only.
  • Performance. One small record per closed tab. Pruning runs only in the transaction that writes, and only over that host's map.

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)

… 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

@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 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 — closeTerminalSurfaceInWorkspaceSession now records every tab close with a reason into the owning host's partition; the renderer drops the field from its save payload (and SESSION_RELEVANT_FIELDS), mirrors it in memory only, and no longer acknowledges records away.
  • Seeding reads records — isTerminalWorkspaceEmptiedOnPurpose replaces 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, relay isRetiredReattachedPtySurface, 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/decideSshPendingPtyKill replay those, and prior && prior.incarnationId === … fixes a latent prior-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.

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

return (
Object.hasOwn(state.tabsByWorktree, worktreeId) &&
(state.tabsByWorktree[worktreeId]?.length ?? 0) === 0 &&
Object.values(state.closedTerminalTabTombstonesByTabId ?? {}).some(

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

brennanb2025 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status at 551c34e1b8: ready to merge. CI fully green. #22929 is on main (squash 993183afd7), and this PR now targets main.

This head merges current main. The diff GitHub shows is only this PR's own changes (59 files, +995/−431). Each file's changed lines were checked to match this PR's diff against #22929's final head, so nothing was dropped or reverted by the merge. The lockfile equals main's.

  • Close records on main's async durable store:
    • A close record is written inside the same durable write as the close.
    • A close for a tab main never listed still saves its record, so a late spawn is still refused.
    • The desktop renderer's own tab close skips the owner check, and it still records. A test pins this.
  • Typed close target: a record is written only when main resolves a close to the whole tab. A pane close never writes one, and this PR has no "last pane" rule of its own.
  • Startup seed with fix(terminal): retry first-terminal seeding until a decision applies #22919:
  • Owed SSH kill: one recorder backs both the offline-close order and the close receipt's retry promise, including relay ids with no known incarnation.
  • Review: three independent loops, plus a readiness checklist at the start and at the end.
  • Tests: each test added during review was checked by deleting the code it protects and watching it fail. That includes, on the SQLite store, the closed-tab binding refusal and the saved record for an unlisted tab.
  • Checks:
  • Live QA: run on a separate Mac after the merge, reading close records from the SQLite store. All passed:
    • tab close;
    • split-pane close (the sibling survives, no record);
    • last-pane close;
    • the startup seed: a legacy empty row seeds once with no click, and a user-closed workspace stays empty;
    • new terminals.
      The earlier SSH run covered a kill that couldn't reach a paused host being replayed after reconnect.
  • Not caused by this PR: after a full restart that starts a fresh shell, the pane doesn't replay its saved scrollback. That happens on main before and after the SQLite change and on fix(terminal): every explicit terminal close commits through one main transaction #22929 alike. The output is saved on disk (terminal-history/<pty>/checkpoint.json) but isn't replayed. It's tracked as its own follow-up.
  • Expected, not regressions:
    • Selecting an emptied workspace in the sidebar opens a terminal, as on main.
    • Until exit closes are recorded, exit in the last shell writes no record.

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

@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 — 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-exit platform divergence is unchanged and its thread remains open.

Reviewed changes

  • Base branch absorbed — 0e97e856 merges brennanb2025/terminal-close-intents. Intersecting the PR's 59-file diff with the merge's changes leaves three seeding files, base content in ssh-relay-session.ts (the PR-own closedByRecord lines are untouched), and two runtime tests switched to createSqliteTestStore/closeTestStores.
  • Close records read at decision time — use-terminal-watcher-effects.ts now derives the seeding verdict from isTerminalWorkspaceEmptiedOnPurpose(useAppStore.getState(), activeWorktreeId) inside the activation-gate callback, replacing the base branch's Object.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.

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

@brennanb2025
brennanb2025 changed the base branch from brennanb2025/terminal-close-intents to main September 27, 2026 22:30
…-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
@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.

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

Run ID: b0bb2f46-96f8-46b3-98d5-80841af2d43c

📥 Commits

Reviewing files that changed from the base of the PR and between 9b5a2f5 and 2693cf1.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-terminal-close-records.test.ts
  • src/main/runtime/terminal-surface-close.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/shared/closed-terminal-tab-tombstones.test.ts
  • src/shared/closed-terminal-tab-tombstones.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.


📝 Walkthrough

Walkthrough

The 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 2693c

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 Review

Security architecture risk: 🔵 Low · up to 2693c

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

  • Low · reliability · inferred: The renderer’s immediate close-record mirror no longer applies the TTL and 500-record cap used by the durable writer. Repeated closes of distinct tabs can make each subsequent map copy larger and increase renderer memory use; hydration does not consistently clear a map when the incoming session omits it.
Security review details

Security Blast Radius

  • inferred — The reviewed effects concern terminal state in the local app and PTYs on a selected SSH host. The reviewed paths do not establish a cross-tenant or broader service exposure.

Trust Boundaries and Controls

  • observed — Main preserves its close records when renderer saves omit them. Missing-incarnation stop recording requires an epoch-scoped relay ID; legacy IDs without that fence are rejected.

Resilience and Maintainability Implications

  • inferred — The unbounded renderer mirror increases local resource use as distinct tabs are closed; its immediate-merge role makes renderer responsiveness relevant to timely closed-tab suppression, although no resulting resurrection or exploitable denial of service was established.

Hardening Proposals

  • proposed — Apply the shared TTL and entry cap to the renderer’s immediate mirror while preserving its synchronous close-before-merge protection.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.12% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 34 functions across 56 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: main records terminal-tab closes, and startup seeding uses those records.
Description check ✅ Passed The description is comprehensive and follows the template. It explains the change, rationale, linked work, visual proof, testing, AI disclosure, and compatibility considerations. The Review section is…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • 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: a9918b2d-5782-4e5b-86b7-fba186cd27ce

📥 Commits

Reviewing files that changed from the base of the PR and between 993183a and 0e97e85.

📒 Files selected for processing (95)
  • src/cli/handlers/terminal-close.ts
  • src/cli/handlers/terminal.test.ts
  • src/cli/terminal-format.test.ts
  • src/cli/terminal-format.ts
  • src/main/ipc/pty-ssh-undelivered-kill.test.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/runtime/undelivered-ssh-kill.ts
  • src/main/ipc/register-core-handlers/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers/register-core-handlers.ts
  • src/main/ipc/session.ts
  • src/main/persistence-ssh-pending-pty-kill.test.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-normalization.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-kill-intent-operations.ts
  • src/main/persistence/loading-store/pty-binding-persistence.ts
  • src/main/persistence/loading-store/pty-binding-refusals.ts
  • src/main/persistence/loading-store/terminal-close-async-durability.test.ts
  • src/main/persistence/runtime-authored-workspace-session-fields.ts
  • src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-fixtures.ts
  • src/main/runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture.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-close-mobile-session-tab.ts
  • src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime-terminal-close-no-widening.test.ts
  • src/main/runtime/orca-runtime-terminal-close-records.test.ts
  • src/main/runtime/orca-runtime-terminal-surface-close.test.ts
  • src/main/runtime/orca-runtime-test-scenario-builders.spec.ts
  • src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts
  • src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts
  • src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts
  • src/main/runtime/orca-runtime-wait-for-leaf-pty-id.ts
  • src/main/runtime/runtime-notifier-contract.ts
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/runtime/runtime-terminal-orphan-adoption.ts
  • src/main/runtime/terminal-close-observed-exit-test-fixture.ts
  • src/main/runtime/terminal-surface-close.test.ts
  • src/main/runtime/terminal-surface-close.ts
  • src/main/ssh/ssh-pending-pty-kill-replay.test.ts
  • src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/window/runtime-window-lifecycle.ts
  • src/preload/api/session-bridge.ts
  • src/preload/api/ui-bridge-clipboard-and-window-controls.ts
  • src/preload/api/ui-command-event-api.ts
  • src/preload/api/workspace-session-api.ts
  • src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.test.ts
  • src/renderer/src/components/terminal-pane/closed-terminal-leaf-notice.ts
  • src/renderer/src/components/terminal-pane/pending-split-close.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-pty-watcher.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts
  • src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx
  • src/renderer/src/components/terminal/initial-terminal-wiring.test.ts
  • src/renderer/src/components/terminal/initial-terminal.ts
  • src/renderer/src/components/use-terminal-watcher-effects.ts
  • src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts
  • src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.ts
  • src/renderer/src/hooks/remote-workspace-session-merge-close-tombstones.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge-closed-terminal-tombstone.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply-deferred-session-write.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts
  • src/renderer/src/lib/session-write-subscriber-deferred-persist.test.ts
  • src/renderer/src/lib/workspace-session-browser-history.test.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/renderer/src/lib/workspace-session-patch.ts
  • src/renderer/src/lib/workspace-session-relevant-fields.test.ts
  • src/renderer/src/lib/workspace-session-ssh-partition-round-trip.test.ts
  • src/renderer/src/lib/workspace-session.ts
  • src/renderer/src/lib/worktree-activation-default-tabs.test.ts
  • src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts
  • src/renderer/src/lib/worktree-activation-store-contract.ts
  • src/renderer/src/lib/worktree-initial-terminal-close-records.test.ts
  • src/renderer/src/lib/worktree-initial-terminal-seeding.ts
  • src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-row-worktree-ids.test.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-tombstone.test.ts
  • src/renderer/src/store/terminals/terminal-tab-close.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts
  • src/renderer/src/store/terminals/workspace-terminal-hydration.ts
  • src/renderer/src/web/preload-api/web-workspace-session-api.ts
  • src/shared/closed-terminal-tab-tombstones.test.ts
  • src/shared/closed-terminal-tab-tombstones.ts
  • src/shared/pty-liveness-verdict.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/shared/ssh-pending-pty-kill.test.ts
  • src/shared/ssh-pending-pty-kill.ts
  • src/shared/terminal-surface-close-target.test.ts
  • src/shared/terminal-surface-close-target.ts
  • src/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.

Comment on lines 75 to 85
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

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.

🚀 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.closedTerminalTabTombstonesByTabId
import { recordClosedTerminalTabTombstone } from '../../../../shared/closed-terminal-tab-tombstones'

@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 — no inline suggestions. The two new commits are merges of origin/main whose conflict resolutions were audited and preserve the PR's semantics; the previously-flagged pty-exit divergence is unchanged and its thread remains open.

Reviewed changes

  • Merged origin/main twice — f67ace981f and dbaacdc908 absorb 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-arg closeTerminalSurfaceFromRenderer(worktreeId, target) was re-expanded to the PR's object form carrying reason; the tombstone write, the intentReason narrowing, 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.ts keeps the epoch-scoped-id coverage. Mechanical, no assertion weakened.

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

@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: ad96c400-7fb5-4eea-a8ae-eb291700cd8c

📥 Commits

Reviewing files that changed from the base of the PR and between 0e97e85 and dbaacdc.

📒 Files selected for processing (14)
  • 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-close-mobile-session-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

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

Comment on lines 139 to 157
// 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'
}
}

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.

🗄️ 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/runtime

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

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

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

Suggested change
// 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'
}
}

@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 — no inline suggestions. The single new commit is a clean merge of origin/main that touches none of the PR's own files; the previously-flagged pty-exit divergence is unchanged and its thread remains open.

Reviewed changes

  • Merged origin/main — 551c34e1b8 absorbs 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:web are clean, and the orca-runtime-terminal-close-records and worktree-initial-terminal-close-records suites pass (13 tests) against the merged tree.

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

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

@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 — no inline suggestions. The two new commits tighten the close-record lookups (TTL-aware reads, first-writer-wins writes); the previously-flagged pty-exit platform divergence is unchanged and its thread remains open.

Reviewed changes

  • Every record lookup now honours the TTL — hasClosedTerminalTabRecord returns false for a record older than CLOSED_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 from closedAt: 1 to Date.now() to match.
  • The first close of a tab wins — recordClosedTerminalTabTombstone now keeps an existing live record (pruned) instead of overwriting its reason and time, so an echo of the same close cannot flip cleanup back to user or restart the TTL.
  • The allow-missing write is skipped when a record already exists — terminalSurfaceCloseMutation replaces result.session !== session with an explicit target.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.

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

ℹ️ 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-exit divergence is unchanged and its thread remains open.

Reviewed changes

  • A close that removes a listed tab records itself again — recordClosedTerminalTabTombstone goes back to a plain overwrite, so a user close of a listed tab that already carried a stale cleanup record 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's allowMissing && target.kind === 'tab' && !hasClosedTerminalTabRecord(…) is the only place an existing record suppresses a second write. This separation is sound because closeTerminalSurfaceInWorkspaceSession has exactly one caller (that mutation): a close that actually removes a listed tab takes the result.closed === true branch 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.

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

@brennanb2025
brennanb2025 merged commit 6c4625d into main Sep 28, 2026
47 of 50 checks passed
@brennanb2025

Copy link
Copy Markdown
Contributor Author

SSH lane (post-merge note): only partly run before this merged.

A live SSH run from a laptop against a throwaway Linux container at 2693cf1d14 completed only its first scenario before the PR merged:

  • Tab close plus restart over SSH: PASS. The closed tab disappeared, and a reason: "user" close record landed in the SSH host's partition of the SQLite profile store; the local partition got none. The remote sleep 600 was killed, and the other tab survived.
  • Not run on this head: split-pane close, the undeliverable kill across a paused host, closing the last tab then restarting, and the negative control. The undeliverable-kill replay and the pane and last-pane closes did pass live earlier, on the pre-async head and on a separate Mac respectively (see Visual Proof).
  • Observation, not confirmed as a regression: the run's profile had inherited a host session file from an earlier, aborted run with a different SSH target id. After the close, that leftover tab joined the tab group as a second "Terminal 1". No main arm was run, so it isn't established whether this PR is involved. It looks like tab-group reconciliation adopting a leftover listed tab, not the close record.

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