Skip to content

fix(terminal): make close and handles incarnation-stable (STA-4327) - #14590

Merged
Jinwoo-H merged 10 commits into
mainfrom
aug14-p0-sta4327-terminal-close
Aug 15, 2026
Merged

Jinwoo-H merged 10 commits into
mainfrom
aug14-p0-sta4327-terminal-close

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

A — close said “done,” then an empty shell appeared

Two independent gaps combined. Orca killed the shell but acknowledged before the tab removal was durably saved. After the tab was correctly removed, reload hydration erased the meaningful empty row, so the “new workspace” fallback created a brand-new shell with new IDs. The closed PTY did not come back; Orca mistakenly made a replacement default terminal.

B — handles rotated

A renderer refresh discarded the CLI handle before checking whether the provider still reported the same PTY incarnation. Orca now keeps the handle when PTY ID and incarnation are unchanged. A real replacement incarnation still makes the old handle deterministically stale; that safety fence is expected and preserved.

What changed

  • Await the renderer’s durability-acknowledged whole-tab retirement for final-pane terminal.close.
  • Preserve explicit empty terminal rows through hydration and suppress initial/default creation only for a workspace with persisted terminal state.
  • Retain renderer handles by provider-attested PTY incarnation across renderer reload/re-key.
  • Fence replacement incarnation, hard graph loss, ambiguity, pruning, and preallocated-handle supersession.
  • Rebind retained tui-idle waiters if the idle transition arrives during the reload gap.
  • Register deterministic runtime, renderer, git-worktree, folder-workspace, and restart coverage in terminal-session.explicit-close-retirement.

No RPC field, stream opcode, persisted schema, polling loop, retry loop, provider listing, subprocess, or new wire traffic was added.

Red / green / disabled proof

Runtime close + incarnation oracle

Byte-identical SHA-256: cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af

Revision Result Exact outcome
Reported v1.4.180 0b62333cf1 2/5 pass final close never called durable relay; same incarnation reminted; preallocated supersession failed
Latest main 9bb8836bb6 2/5 pass same three failures
Runtime candidate 3cf8a37447 5/5 pass all close/continuity/fencing checks green
Candidate with runtime fix disabled 2/5 pass same three failures returned

Final code candidate 121e112d77 passes the expanded 6/6 oracle, including a tui-idle transition during renderer reload.

Persisted-empty/default-terminal oracle

Byte-identical SHA-256: 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea

Revision Result Exact outcome
Reported v1.4.180 0b62333cf1 0/2 pass hydration erased the empty row; fallback synthesized a terminal
Latest main 9bb8836bb6 0/2 pass same two failures
Renderer candidate 121e112d77 2/2 pass empty row survives; fallback stays off
Candidate with renderer fix disabled 0/2 pass same two failures returned

All four disposable matrix worktrees used the same oracle bytes and were removed afterward.

Headed Electron / CDP proof

Isolated local macOS app and fixture repo; no user terminal was touched.

  • Close target: handle term_49a01c5f-1db1-4e3c-b115-922261f8e031, PTY suffix 31722a8e, incarnation 29055fb9-6319-44af-bb5c-c583b2ce3533, tab db94668f-16d8-46c2-aefb-dba4c5e52f6a.
  • Ownership was verified from runtime worktree identity and the shell process cwd before close.
  • terminal.close returned ok:true, ptyKilled:true; the exact shell process died.
  • Immediately after close and again after renderer reload: explicit empty row present, zero tabs, zero layouts, zero runtime/provider terminals, zero visible terminal sessions.
  • Separate reload proof kept handle/PTY/incarnation/tab/leaf unchanged while the same shell remained readable.
Before close Latest-main failure: fresh shell after reload Candidate: stays empty after reload
Before close Fresh default shell Candidate stays empty

Validation

  • pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1 — 1 passed; empty after full restart
  • focused runtime/renderer oracle — 55 passed
  • impacted hydration/folder-workspace group — 87 passed
  • orca-runtime.test.ts + web-runtime-session.test.ts + continuity — 1,122 passed, 1 unrelated skip
  • pnpm run typecheck — passed
  • pnpm run lint — passed, including native/type-aware audits, max-lines ratchet, reliability manifest, skill and localization verification
  • changed React audit, touched-file oxlint/oxfmt, and reliability manifest — passed

Performance review: one empty row per persisted known workspace; the React effect depends only on active-row presence. No timers, polling, provider fanout, subprocesses, process scans, retries, or hot-path network calls were added.

Risks and gaps

  • Live headed proof is macOS local. The reported physical Windows 11 / ConPTY journey was not available and remains an explicit validation gap.
  • Live paired headed/headless and live SSH/WSL journeys were not run. Deterministic runtime/daemon/SSH ownership coverage is green, and no remote wire shape changed.
  • Mixed-version compatibility is unchanged because this uses existing close acknowledgements and local provider-attested incarnation state.

Linked issue

Fixes #14524

Linear: https://linear.app/stably/issue/STA-4327/terminal-close-returns-oktrue-but-the-tab-respawns-as-an-empty-shell

Checklist

  • Before/after behavior evidence attached
  • Automated deterministic and restart coverage added
  • Correctness, adversarial, performance, cross-platform, SSH/remote, and mixed-version review completed
  • Full local lint/typecheck and relevant test suites passed
  • CI green

Do not merge; awaiting review and CI.

@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The runtime tracks terminal handles by PTY incarnation and leaf association. It reuses matching handles during renderer recovery and invalidates stale handles when PTY identity, ownership, or incarnation changes. Single-pane terminal closure can use closeTerminalTab with verified PTY teardown. Renderer hydration preserves explicit empty terminal entries, which prevents automatic terminal creation after closure. Tests and reliability metadata cover closure, continuity, hydration, and restart persistence.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. 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 primary fixes: durable terminal closure and PTY-incarnation-stable handles.
Description check ✅ Passed The description covers the main changes, rationale, linked issue, visual evidence, testing, risks, and checklist status.
Linked Issues check ✅ Passed The changes address both linked issue symptoms: terminal respawn after close and handle rotation for unchanged PTY incarnations.
Out of Scope Changes check ✅ Passed The changed runtime, renderer, persistence, relay, and test files support the linked terminal closure and handle continuity objectives.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch aug14-p0-sta4327-terminal-close

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: Pro Plus

Run ID: 24f3c415-258c-4e8b-8bc3-4d8146a1a0c5

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb8836 and 5e0bb4fb710e21e90f6a7105140cff093fb600b9.

📒 Files selected for processing (3)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime.ts

Comment thread config/reliability-gates.jsonc Resolved
@Jinwoo-H
Jinwoo-H force-pushed the aug14-p0-sta4327-terminal-close branch from 2be9aa5 to 3cf8a37 Compare August 14, 2026 20:54

@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: Pro Plus

Run ID: 7821e92e-2194-4c00-bce5-885692ab0238

📥 Commits

Reviewing files that changed from the base of the PR and between 5e0bb4fb710e21e90f6a7105140cff093fb600b9 and 3cf8a37.

📒 Files selected for processing (3)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime.ts

Comment thread src/main/runtime/orca-runtime.ts Resolved

@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: Pro Plus

Run ID: c23a3828-17a1-4643-8fcd-8b4249455506

📥 Commits

Reviewing files that changed from the base of the PR and between 3cf8a37 and 50d08ba.

📒 Files selected for processing (11)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal/initial-terminal.test.ts
  • src/renderer/src/components/terminal/initial-terminal.ts
  • src/renderer/src/lib/worktree-activation.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • tests/e2e/terminal-tab-close-restart-persistence.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime.ts

Comment thread config/reliability-gates.jsonc Resolved

@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: Pro Plus

Run ID: a11b0743-34c3-4541-829b-28e55a6515af

📥 Commits

Reviewing files that changed from the base of the PR and between 50d08ba and 2cb8ccd.

📒 Files selected for processing (1)
  • tests/e2e/completed-worker-retirement-resume.unit.test.ts

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)

27701-27746: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle workspace_session_unavailable in the surface-based fast path.

If closeMobileSessionTab() throws this error after closeTerminalTab() succeeds, call this.notifier?.closeTerminal(tabId) and continue PTY cleanup. Re-throw other errors.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6f5fcfdd-f8da-4961-9b95-3d467688bcaa

📥 Commits

Reviewing files that changed from the base of the PR and between 2cb8ccd and fa25800.

📒 Files selected for processing (13)
  • src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/window/attach-main-window-services.ts
  • src/main/window/terminal-tab-close-request-relay.test.ts
  • src/main/window/terminal-tab-close-request-relay.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/worktree-activation.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/terminal-tab-close.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/renderer/src/lib/worktree-activation.test.ts

@Jinwoo-H
Jinwoo-H merged commit 2eb3e11 into main Aug 15, 2026
47 checks passed
@Jinwoo-H
Jinwoo-H deleted the aug14-p0-sta4327-terminal-close branch August 15, 2026 08:25
Jinwoo-H added a commit that referenced this pull request Aug 19, 2026
…ays re-seeds

Review found the carve-out fires nondeterministically: the entry points disagree
about `executionHostId` for the *same* local workspace — the sidebar derives
`'local'` (use-worktree-card-activation-actions.ts:84 via getRepoExecutionHostId)
while the Cmd+J palette (WorktreeJumpPalette.tsx:2520, :2896), keyboard cycling,
and back/forward pass nothing — so `activeWorkspaceExecutionHostId === (opts
?.executionHostId ?? null)` flips on how you last opened the workspace.

Host-qualifying the comparison was the wrong repair. The carve-out guards a state
that closing a tab never produces: `leaveWorktreeIfEmpty` clears activeWorktreeId
when the last renderable tab closes (TerminalPaneOverlayLayer.tsx:65-74), so there
is no already-active emptied workspace to reselect. It only fires after hydration
restores an emptied workspace as active — where suppressing re-seeds the original
bug. Clicking the sidebar row of a blank workspace after a restart did nothing,
which is the exact report this branch set out to fix.

So the guard is removed rather than corrected: explicit activation always re-seeds,
startup hydration never does. That restores pre-#14590 behavior wholesale for
activation and makes the host asymmetry irrelevant to terminal creation. It also
removes the local/remote divergence, since the runtime path's
ensureWebRuntimeWorktreeTerminalAfterWake never had a reselect guard either.

Reverts the folder-workspace host qualification from 3113610 (the predicate it
fixed no longer exists) and keeps its coverage. Tests now pin: explicit activation,
the restored-active workspace, host-passed vs host-omitted equivalence, folder
same-host and cross-host, the hydration path staying empty, and a browser-only
workspace not gaining a terminal. Mutation-checked both ways — forcing the
tombstone off fails the hydration case, ignoring the flag fails six.
Jinwoo-H added a commit that referenced this pull request Aug 19, 2026
The previous commit fixed the two editor-opening callers but my sweep only
matched openFile/openDiff/setActiveTab, so it missed three call sites that
activate purely to route and then create a *browser* tab:

  - terminal-file-open-routing.ts openHtmlFileInBrowser -> createBrowserTab
  - workspace-port-actions.ts -> browser tab creation
  - FeatureWallBrowserAction.tsx -> openNewBrowserTabInActiveWorkspace

Same regression: following an HTML file link or a port into a workspace whose
last terminal was closed spawned a shell beside the browser tab, and on a remote
workspace that is a real SSH PTY. All three now pass providesInitialSurface.

Also pins the passive half's wiring. Terminal.tsx is the side of the contract that
must keep honouring the tombstone, and its only end-to-end cover is an e2e that
did not run on this PR. Mounting a 2892-line component is not worth it, but this
repo already asserts un-mountable wiring as source text (app-startup-routing.test.ts
and the startup ordering tests), so initial-terminal-wiring.test.ts asserts the
effect still derives the tombstone from the active row and passes that identifier —
not a literal — into shouldAutoCreateInitialTerminal. Dropping the argument, the
established way to re-introduce #14590's bug, now fails a test that runs.

Renames the cross-host folder test to say what it actually checks (the shared row
is re-seeded, not that the tab lands on the requested host) and records why: the
host-blind resolver makes that tab resolve local, which is pre-existing and out of
scope. Extends the close-path comment to include closeTabPreservingPty and to note
the runtime-owned exception holds only while that session is live.
Jinwoo-H added a commit that referenced this pull request Aug 19, 2026
…icitly activated

PR #14590 made an explicit empty tabsByWorktree row a durable closed-last-
terminal tombstone, but the same gate sat in the activation path, so waking
a sleeping/emptied workspace or clicking automations' Resume gave a blank
tab bar. Explicit activation now re-seeds by default; passive startup
hydration still honours the tombstone via Terminal.tsx.

Callers that activate only as a prelude to opening their own surface (an
editor file, browser tab, diff panel, or agent tab) pass
providesInitialSurface: true, which reproduces main's pre-#14590 behavior
at that call site. The full activation call-site census lives in
worktree-activation-surface-caller-wiring.test.ts, which fails if any
opt-out is dropped or a new one is added without classifying it there;
the census assertion is bound to an actual activateAndReveal* call with
comments stripped first, so commenting the flag out in place fails it.
The option is also plumbed through activateAndRevealWorkspace and
activateAndRevealFolderWorkspace so both workspace shapes share one
contract.
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.

terminal close returns ok:true but the tab respawns as an empty shell; handles rotate causing terminal_handle_stale

1 participant