Skip to content

Stop new terminal tabs from closing right after they open - #6801

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-tab-autoclose
Jun 30, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-tab-autoclose

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

New terminal tabs sometimes "pop in for a split second, then close" — and once it starts, it keeps happening until Orca is quit and relaunched.

Root cause is a TOCTOU race in the renderer's dead-session reconcile. reconcileDeadSessions / recheckLivenessAfterInput call window.api.pty.listSessions() (a renderer→main→daemon round-trip) and then ask, for each pane, whether its live PTY id is in the returned set (shouldReconcileDeadSession). If a freshly-created tab's PTY binds after that snapshot was requested but before it resolves, the new live id is absent from the stale snapshot — so a perfectly healthy newborn pane is judged dead and torn down. For a single-pane tab that teardown closes the whole tab (onExit → onPtyExitRef → closeTab).

Why it worsens over a session and clears on relaunch: the race window is how long listSessions() takes relative to a fresh bind. As a session accumulates terminals, the daemon enumerates more sessions and more resume/keystroke reconcile passes fire, widening exposure; relaunch resets to ~0 sessions and the window collapses.

Approach

Make the reconcile decision freshness-aware: a snapshot requested before a binding existed cannot prove that binding dead.

  • Stamp activePanePtyBindingBoundAt = performance.now() at the bind chokepoint (bindActivePanePty), reset in clearPanePtyFitBinding.
  • Capture requestedAt = performance.now() immediately before each listSessions() call (reconcileDeadSessions and recheckLivenessAfterInput) and thread it through to the decision.
  • shouldReconcileDeadSession now skips reconcile when ptyBoundAt >= snapshotRequestedAt (inclusive). Both timestamps are renderer-local performance.now() — same monotonic clock, no cross-process comparison. When either is omitted, behavior is exactly as before (back-compat).

Genuinely dead sessions are unaffected: a session reaped while hidden was bound long before the resume's snapshot request, so ptyBoundAt < requestedAt and reconcile still fires; a skipped round is re-evaluated by the next resume/keystroke pass against a fresher snapshot. SSH (connectionId != null) and remote-runtime (remote:) panes short-circuit before the new guard, so those paths are byte-for-byte unchanged.

Design review

Ran auto-design-review-fix (Claude + Codex in parallel, 2 rounds) on a scratch design doc; converged clean. The review independently traced the timestamp ordering to the daemon and confirmed the renderer-local performance.now() comparison is provably correct (the renderer→daemon ordering only ever makes the guard more conservative). Substantive doc hardening: a full happens-before correctness proof, correcting a "single chokepoint" overstatement (reattach-completion binds via setPanePtyFitBinding, intentionally left with null boundAt → guard disabled → fail-safe), and fail-open test-coverage requirements.

Implementation & deviations

Implemented exactly as designed across 5 renderer files (terminal-dead-session-reconcile.ts, pty-connection.ts, + their tests, and a use-terminal-pane-lifecycle.test.ts assertion update). No deviations. Intentional non-change: reattach-completed panes keep boundAt === null (guard disabled, pure-membership fallback) — they reuse a pre-existing daemon session id so membership already protects them.

Completeness verification

A read-only verification pass confirmed every design requirement, edge case, and validation item is satisfied, with no scope creep and no max-lines disables.

Code-review loop

Two independent reviewers per round (code-review, high effort), run in parallel:

  • Round 1: no P0/P1/P2. Actionable: add a ptyBoundAt === snapshotRequestedAt boundary test (guards the inclusive >=), and trim two over-length "why" comments per AGENTS.md. Both applied.
  • Round 2: one P2 — an oxfmt printWidth=100 format failure on a reflowed test line. Fixed with oxfmt.
  • Round 3 (confirming): both reviewers returned CLEAN — no actionable findings.

brennan-test-changes (merge confidence): LAND

Validated in a fresh dev build launched from this worktree (identity verified before interacting); test target was a local non-orca repo, with the session already holding 16 tabs (the long-running condition).

  • Reproduced the bug's precondition for real: a freshly-bound PTY id was genuinely absent from a listSessions() snapshot captured before the tab was created.
  • After the fix: that newborn tab survived 3.5s+; 10 rapidly-created tabs all bound a PTY and all 10 survived (screenshot evidence captured). No console/dev-log errors.
  • Accepted gap: driving the production visibility/keystroke reconcile through CDP was impractical (the preload exposes listSessions as a frozen contextBridge fn, so it can't be wrapped from the renderer console) — binding-level proof is instead carried by the integration tests that drive the real reconcileIfSessionDead with explicit timestamps.
  • Scope boundary (justified): brennan-test-ssh not required — SSH/remote short-circuit before the guard, so they cannot be affected.

Checks run

  • tsgo web typecheck: clean (exit 0)
  • oxlint (touched files): clean
  • oxfmt --check (all 5 files): clean
  • npx vitest run terminal-dead-session-reconcile.test.ts use-terminal-pane-lifecycle.test.ts: 35/35 pass
  • pty-connection.test.ts -t "reconcileIfSessionDead": 12/12 pass (incl. two new binding-level integration tests that drive the real reconcile body and fail if the guard is removed — verified by temporary revert)
  • git diff --check: clean

Tests

  • Regression unit tests fail before the fix (verified by reverting the guard)
  • Boundary-equality (===) and back-compat (omitted-args) cases covered
  • Both listSessions call sites thread requestedAt
  • Live Electron survival of fresh + rapidly-created tabs
  • Production visibility/keystroke reconcile driven via CDP (not feasible from renderer console; covered by integration tests) — accepted gap

Risks / notes

  • One pre-existing, unrelated pty-connection.test.ts failure ("does NOT re-assert while a mobile-fit override parks the PTY at phone dims") fails identically on the clean pre-diff tree (confirmed via git stash) — a mobile-fit-overrides global-state leak, not touched here.
  • Pure renderer-side logic change: no IPC/schema/persistence/settings changes, no migration.

Made with Orca 🐋


Relationship to #6796 (just merged)

While this PR was in review, #6796 "Keep new terminal tabs open during startup" merged to main and targets the same area (fixes #6773). The two changes are complementary, at different layers — verified by rebasing onto main (which includes #6796) and confirming the regression test here still fails when this PR's guard is reverted:

  • Keep new terminal tabs open during startup #6796 gates when reconcile fires: the dead-session pass and first-input liveness probe now only run after a real hidden→visible resume; fresh mounts start disarmed. This removes the startup-time trigger.
  • This PR makes the decision itself freshness-aware (shouldReconcileDeadSession): even when a reconcile pass legitimately fires — e.g. a tab created while its worktree is hidden, then resumed, or whose first post-resume keystroke probes liveness — a listSessions() snapshot requested before the PTY bound can no longer prove that PTY dead.

So #6796 narrows the trigger; this PR closes the residual TOCTOU inside the trigger that still survives. Rebased cleanly on top of #6796; all focused tests, typecheck, lint, and format pass on the merged tree.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d87635d8-baa5-4ce9-9570-7be94e2e5afe

📥 Commits

Reviewing files that changed from the base of the PR and between 54f12ce6325283ba6bd20db6a432dfcd7b2c0d62 and c53872d.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.test.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.test.ts

📝 Walkthrough

Walkthrough

The dead-session reconciliation logic now uses timestamps to distinguish stale snapshots from newer PTY bindings. shouldReconcileDeadSession accepts optional ptyBoundAt and snapshotRequestedAt values and skips reconciliation when the bind time is at or after the snapshot request time. reconcileDeadSessions records requestedAt before listSessions() and forwards it to each binding. connectPanePty stores the active pane bind time and passes it into reconciliation. Related tests now assert the extra timestamp argument and the new timing cases.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.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 main user-facing fix: preventing new terminal tabs from closing immediately after opening.
Description check ✅ Passed The description is detailed and covers summary, approach, testing, risks, and review, though explicit Screenshots and Security Audit sections are missing.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.test.ts (1)

174-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make this test fail on an after-await timestamp capture.

The current before <= requestedAt <= after assertion still passes if requestedAt is captured after listSessions() resolves. Pin a deterministic clock across the callback so the test asserts the exact pre-listSessions value.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 990d5be1-d54e-4cda-b84a-5c96d3c0d710

📥 Commits

Reviewing files that changed from the base of the PR and between 7caa582 and 54f12ce6325283ba6bd20db6a432dfcd7b2c0d62.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.test.ts
  • src/renderer/src/components/terminal-pane/terminal-dead-session-reconcile.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts

The dead-session reconcile compared a pane's live PTY id against a
listSessions() snapshot without regard to when that snapshot was taken.
When the snapshot was requested before a freshly-created tab's PTY bound,
the new PTY was absent from it, so a healthy newborn pane was mistaken for
a reaped session and torn down — closing the tab ~1s after it opened. The
window widened as a session accumulated terminals (slower enumeration, more
reconcile passes), which is why it worsened over time and cleared on relaunch.

Make the reconcile freshness-aware: stamp each binding's bind time and the
snapshot's request time (both renderer performance.now()), and skip reconcile
when the binding is newer than the snapshot request — a snapshot taken before
a PTY existed cannot prove it dead. Genuinely dead sessions still reconcile on
the next resume/keystroke pass against a fresher snapshot. SSH and remote-runtime
panes are unaffected (they short-circuit before the new guard).

Co-authored-by: Orca <[email protected]>
@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-tab-autoclose branch from 54f12ce to c53872d Compare June 29, 2026 23:40
@brennanb2025
brennanb2025 merged commit f9701a7 into main Jun 30, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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