Skip to content

fix(terminal): guard PTY handler unregistration against detach/attach remount races (frozen pane) - #7894

Merged
AmethystLiang merged 1 commit into
mainfrom
fix-pty-handler-loss-pane-detach
Jul 9, 2026
Merged

AmethystLiang merged 1 commit into
mainfrom
fix-pty-handler-loss-pane-detach

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Symptom

A terminal pane permanently stops updating while its PTY/process stays alive (the "frozen pane" bug). The pane still repaints on theme changes (rendering is healthy) but never receives another byte; the main process side (agent status, PTY drain, ACKs) stays fully live. Live-debugged in production 1.4.129-rc.2 on 2026-07-08.

Root cause

Renderer PTY data delivery routes through a module-global ptyDataHandlers map keyed by ptyId. Pane→tab detach and split-group moves rehome the React subtree: the old TerminalPane unmounts (→ transport.detach()) while a new TerminalPane attaches to the same ptyId, and ordering across the two React trees is not guaranteed. detach() called unregisterPtyDataAndStatusHandlers(ptyId), which deleted the ptyDataHandlers/ptyReplayHandlers entries unconditionally — no check that the registered handler belonged to that transport instance. When the new pane's attach() registered its handler before the old pane's detach() ran, the delete destroyed the live handler. From then on the dispatcher found no handler and diverted all data into the pre-handler buffer (512 KB tail cap) forever — nothing drains it because draining only happens at handler registration, which the live pane had already done.

This flow was armed by #7215 (isDetachedToTab → transport.detach() in the common pane→tab path); user freeze reports started right after it shipped in v1.4.122.

Fix

  • pty-transport.ts: each transport instance now tracks the data/replay/exit handlers it registered (per ptyId). unregisterPtyHandlers / unregisterPtyDataAndStatusHandlers delete a map entry only if it still points to a handler this instance owns — the same identity-guard pattern already used by registerTerminalBacklogRecovery and the eager-buffer dispose(). The teardown-handler delete is identity-guarded the same way. The exit handler's existing ptyId !== id stale-path now also cleans up only owned entries.
  • pty-dispatcher.ts: the eager-buffer exit handler's cleanup gets the same identity guard (it previously deleted ptyDataHandlers/ptyReplayHandlers unconditionally).
  • pty-pre-handler-buffer.ts: one-shot console.warn breadcrumb when >64 KB accumulates for a ptyId with no registered handler — sustained accumulation is exactly this bug class and legit pre-attach windows drain within milliseconds.
  • remote-runtime-pty-transport.ts (SSH/remote runtime) was audited and is not affected: its detach() closes only its own instance-held multiplexed stream, and the multiplexer keys subscriptions by a per-subscription stream id, so a stale detach cannot destroy a newer pane's subscription. No change needed there; SSH paths are untouched by this diff.

Regression tests

  • Failure ordering (fails without the fix): transport A connected to ptyId X; transport B attaches to X; A's detach() runs afterward → data, replay, and exit for X still reach B, and A's callbacks stay silent.
  • Normal ordering: A detaches, data arrives in the gap (buffered), B attaches → buffered data drains to B and live data flows.

Verification

  • pty-transport.test.ts: 60/60 pass (new race test fails on unfixed code, verified by stash-run).
  • Full terminal-pane suite: 1687 pass. pane-manager suite: 391 pass.
  • typecheck:web and oxlint clean.

Fixes the frozen-pane regression introduced alongside #7215.

Made with Orca 🐋

… remount races

Pane->tab detach and split-group moves rehome the React subtree, so a new
TerminalPane can attach to the same ptyId before the old instance's
detach() runs. detach()/disconnect()/exit paths deleted the shared
ptyDataHandlers/ptyReplayHandlers entries unconditionally, destroying the
NEW pane's live handler; all subsequent PTY data diverted into the
pre-handler buffer forever and the pane froze while its process stayed
alive.

Track the handlers each transport instance registered and only delete map
entries the instance still owns (same identity-guard pattern as
registerTerminalBacklogRecovery). Apply the same guard to the eager-buffer
exit handler, and leave a one-shot console.warn breadcrumb when the
pre-handler buffer accumulates with no registered handler.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR addresses a race condition where PTY handler cleanup from an older terminal-pane instance could remove live handlers registered by a newer instance attached to the same PTY id during pane rehome. Ownership tracking maps were added so teardown only deletes handlers the current instance actually registered, applied to both pty-transport.ts and pty-dispatcher.ts. Additionally, pty-pre-handler-buffer.ts now warns once per ptyId when data buffers exceed a threshold without a registered handler, clearing that warning state on drain or clear. New tests cover detach/attach race scenarios and buffered data delivery on reattachment.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the bug, root cause, fix, tests, and verification, but it omits required template sections like Summary, Screenshots, Testing, Security Audit, and Notes. Add the missing template sections: Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes, or clearly mark them as not applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: guarding PTY handler unregistration during detach/attach remount races.
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.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-dispatcher.ts (1)

249-254: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider identity-guarding ptyExitHandlers.delete(ptyId) for consistency with dispose().

The exitHandler identity-guards ptyDataHandlers/ptyReplayHandlers deletion but unconditionally deletes ptyExitHandlers. This is currently safe — the handler can only fire while it's still the registered entry — but dispose() already guards the same deletion with if (ptyExitHandlers.get(ptyId) === exitHandler). Applying the same guard here would make the pattern consistent and protect against future code paths that might invoke the handler after a transport has replaced it.

♻️ Suggested consistency fix
     if (ptyDataHandlers.get(ptyId) === dataHandler) {
       ptyDataHandlers.delete(ptyId)
       ptyReplayHandlers.delete(ptyId)
     }
-    ptyExitHandlers.delete(ptyId)
+    if (ptyExitHandlers.get(ptyId) === exitHandler) {
+      ptyExitHandlers.delete(ptyId)
+    }
     eagerPtyHandles.delete(ptyId)
     onExit(ptyId, code)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f03c0b03-744c-4a3f-b4ee-876f12fed669

📥 Commits

Reviewing files that changed from the base of the PR and between 4048047 and 28c0a1a.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts

@AmethystLiang
AmethystLiang merged commit 52c7de1 into main Jul 9, 2026
2 checks passed
@AmethystLiang
AmethystLiang deleted the fix-pty-handler-loss-pane-detach branch July 9, 2026 10:11
Jinwoo-H added a commit that referenced this pull request Jul 9, 2026
36 commits from main incl. the v1.4.130 release. Two conflicts, both the
branch-guide pattern (our restructured shape wins; main's new semantics graft in):

- pty-dispatcher.ts (eager-buffer exitHandler): kept our releaseDeliveryInterest()
  (hidden-delivery-gate ref-count invariant) AND grafted main's identity guard
  (#7894 detach/attach remount race) around the handler deletions.
- orca-runtime.ts: (1) kept our isCursorNativeAgentTitle import; (2) OSC-title
  path — kept our 4-arg trackHeadlessTerminalData(...forwardQueryReplies) and the
  shared per-PTY title tracker, dropped main's superseded inline OSC extraction.

Grafting main's #7863 Grok/#7880 Pi title-normalization required a real fix, not
just keeping our block: the runtime's normalizeTerminalTitle re-export chain
(agent-detection → agent-title-status.ts) lacked the Grok-collapse branch main
added to the sibling terminal-title-display.ts impl. Added isGrokRotatingWorkingTitle
collapsing to agent-title-status.ts and made applyTrackedPtyTitle store the
NORMALIZED title (matching main's inline block) — restores 4 Grok/Pi runtime tests.

Gates: typecheck 0 errors; lint 0 errors; terminal-pane+ipc/pty+daemon+pane-manager
4574 passed; runtime+renderer-runtime+shared 4063 passed / 0 failed.

Co-authored-by: Orca <[email protected]>
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