Skip to content

fix(terminal): keep a live TUI's mouse modes across daemon reattach - #12461

Merged
nwparker merged 5 commits into
mainfrom
fix/terminal-reattach-mouse-mode-rearm
Aug 5, 2026
Merged

nwparker merged 5 commits into
mainfrom
fix/terminal-reattach-mouse-mode-rearm

Conversation

@nwparker

@nwparker nwparker commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Quit Orca while a full-screen TUI is running, relaunch, and drag across the pane: instead of the TUI receiving the drag, xterm paints a row selection over it and the wheel stops scrolling it.

Cause: on reattach the renderer replays the daemon snapshot — whose rehydrateSequences re-arm the session's mouse protocol and encoding — and then immediately writes POST_REPLAY_REATTACH_RESET, whose RESET_MOUSE_REPORTING wipes what the replay just restored. xterm concludes the still-running TUI has no mouse tracking and takes the drag for itself.

Proof

tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts drives the whole thing through the rendered surface: a real alt-screen TUI in a daemon-backed pane, a genuine app quit/relaunch against the same userDataDir (the daemon and the TUI process survive, so the second launch warm-reattaches), then a CDP drag and wheel over the reattached pane.

Run against this branch's code, both locally:

Result
With the fix passes — no selection, TUI's offset= row advances from the wheel
With RESET_MOUSE_REPORTING restored fails at dragging over a live mouse-tracking TUI must not paint xterm row selection

No mocks and no direct mode assertions — it fails on the user-visible symptom.

Fix

POST_REPLAY_REATTACH_RESET_KEEP_MOUSE: the same reattach reset minus RESET_MOUSE_REPORTING, used when the pane is on the alternate screen. Nothing re-derives or re-emits the modes — the replayed payload already armed them, so the renderer just stops clobbering xterm's own parse.

Alt-screen comes from the daemon's authoritative isAlternateScreen, falling back to the kitty keyboard tracker, which has already scanned the identical payload at every one of these call sites. Zero added passes over the payload.

Composition with the existing resets is unchanged:

Known gap, unchanged in kind by this PR: an alt-screen TUI killed uncleanly leaves the daemon emulator on the alt buffer with modes armed, so a reattach preserves them. The confirmed-return-to-shell disarm (#9608) is the backstop.

Perf

The reattach replay path is synchronous renderer main-thread work with no yield, over a payload capped only by the 16MB daemon frame (5,000 serialized rows), and up to 50,000 rows on the park-reveal branch. It already runs a char-loop agent-signal scan, a kitty-tracker regex pass, and xterm's own parse. This change adds none — it is a constant lookup.

Verification

  • pnpm typecheck clean
  • pty-connection.test.ts: 544 pass, including a positive case (alt-screen keeps mouse) and a negative control (normal buffer still disarms)
  • e2e pass/fail pair above

On #8291

Refs #8291. That report is Windows-only, self-resolved, and labelled cannot_repro, and its literal symptom — selection bleeding into the side panel — is not something this branch reproduces. What it does establish is that the reporter's trigger (drag-select misbehaving right after an in-app update restart) corresponds to a real, independently reproducible regression on the reattach path. Treat the issue as the lead, the e2e as the evidence.

Made with Orca 🐋

On daemon reattach Orca replayed the snapshot and then immediately wrote a mode reset that wiped the mouse modes the snapshot had just rehydrated. xterm no longer knew the still-running TUI had mouse tracking on, so it fell back to row-wise selection over the TUI — the reporter saw drag selection appear after an in-app update restart.

Re-arm the modes the replayed payload actually left on, instead of resetting them. A TUI that died leaving modes armed is still cleaned up by the confirmed-shell-foreground reset, so this only preserves modes that were genuinely on. Composed with the newer cold-restore branch from #12101: when the owner process ended, the full reset still wins.

Fixes #8291

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

coderabbitai Bot commented Aug 4, 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

PTY reattach reset sequencing now receives alternate-screen metadata from snapshot, model, and relay replay paths. Alternate-screen non-agent reattachments use a reset profile that preserves mouse reporting, while normal-buffer reattachments keep the standard reset. Unit tests cover both snapshot cases. An end-to-end test verifies mouse drag and wheel behavior across Orca restart and daemon reattachment.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the bug, fix, risks, and verification, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and include the required cross-platform review, security audit, screenshots statement, and platform-specific notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses the reattach-related terminal drag failure by preserving live TUI mouse tracking while retaining cleanup for terminated or normal-buffer sessions [#8291].
Out of Scope Changes check ✅ Passed All production and test changes target terminal mouse-mode preservation during daemon reattach and its regression coverage; no unrelated code changes are evident.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The title clearly and concisely describes preserving a live TUI's mouse modes during daemon reattach.
✨ 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-connection.test.ts (1)

9234-9270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a cold-restore case that asserts no re-arm.

This test locks the non-agent reattach path. The sibling branch in reattachReplayResetSequence returns POST_REPLAY_MODE_RESET when ownerProcessEnded is true, which deliberately skips the mouse-mode re-arm for #12101. A snapshot carrying \x1b[?1002h plus coldRestore would pin that behavior, so a later change cannot re-arm modes against a fresh shell.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 13fc0e8d-2068-46dd-bbbb-8fa7e75a2dde

📥 Commits

Reviewing files that changed from the base of the PR and between c498d2d and 0f7aa33.

📒 Files selected for processing (7)
  • src/main/daemon/terminal-mode-rehydrate-sequences.ts
  • src/main/daemon/terminal-mouse-mode-mirror.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/shared/terminal-mode-reset-profiles.ts
  • src/shared/terminal-mouse-mode-sequences.test.ts
  • src/shared/terminal-mouse-mode-sequences.ts

Fails on origin/main, passes on this branch.

Test: live TUI keeps mouse tracking after an app restart reattach instead of falling back to drag selection

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

@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)
tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts (1)

1-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the file header comment.

This block documents defect history and test flow. Keep one sentence that states the regression and expected behavior.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: db3ce5ad-2acb-41ca-babe-bfcaa3129fee

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7aa33 and 2db88d4.

📒 Files selected for processing (1)
  • tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts

Comment on lines +179 to +184
const repoPath = createIsolatedProofRepo()
const session = createRestartSession(testInfo)
let firstApp: ElectronApplication | null = null
let secondApp: ElectronApplication | null = null

try {

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guarantee all teardown actions run.

If createRestartSession() fails, repoPath is outside the cleanup boundary. If session.close() or session.dispose() rejects, later cleanup statements do not run. Allocate resources inside the cleanup boundary and isolate each teardown action with nested try/finally blocks or a cleanup collector.

Also applies to: 265-273

@nwparker

nwparker commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Visual proof

Screenshot, not video — this spec quits and relaunches Orca to force a warm daemon reattach, so the recorder's WebM never flushes. The frame below is captured at the decisive moment (a drag across the live TUI) on both branches.

before/after

What you are looking at

Everything happens inside the terminal pane of a real Orca window, twice launched against the same profile.

Timeline a reviewer sees:

  1. Launch 1: a project is added, a terminal tab opens, and a real alt-screen TUI paints — top row TUI_SCROLL_READY offset=0 followed by ~70 rows of TUI_SCROLL_ROW_0000…. This TUI armed ?1003h + ?1006h.
  2. The window closes and a second Orca window launches. The same TUI screen is restored via daemon reattach and repaints as TUI_SCROLL_READY offset=1 (proof the live process is still attached, not a replayed corpse).
  3. A real mouse drag is dragged across TUI rows 2→5 in the pane.
    • On origin/main: a solid blue selection band paints across TUI_SCROLL_ROW_0002 through TUI_SCROLL_ROW_0005 — xterm's row-wise selection on top of a live TUI. I confirmed this on the failure screenshot (test-failed-2.png), which shows offset=1 at the top and the highlighted rows 0002–0005. The test then fails with those exact row labels as the selection text.
    • On the fix branch: the drag leaves the TUI untouched, nothing highlights.
  4. Five wheel ticks over the pane centre.
    • On the fix branch: the TUI's own header row visibly counts up past offset=1 and every row label re-renders (0002…, 0003…), because the wheel now reaches the TUI as SGR mouse reports.
      …

It actually captures the bug

Same spec on origin/main:

Run on detached origin/main (f6878d660f), rebuilt with `pnpm exec electron-vite build --mode e2e`, spec restored from /tmp:

[e2e] SKIP_BUILD set and out/main/index.js exists — skipping build
[e2e] SKIP_BUILD set and out/cli/index.js exists — skipping CLI build
[e2e] Secondary worktree created at /private/var/folders/td/0d_w3jrs3654mtmk1gd6kpq00000gn/T/orca-e2e-worktree-dab6314d-5d83-4a30-b2a2-34ffa604e4e8
[e2e] Test repo created at /private/var/folders/td/0d_w3jrs3654mtmk1gd6kpq00000gn/T/orca-e2e-repo-DsTrTs

Running 1 test using 1 worker

  ✘  1 [electron-headless] › tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts:177:7 › terminal reattach mouse mode › live TUI keeps mouse tracking after an app restart reattach instead of falling back to drag selection (9.2s)


…

Test: live TUI keeps mouse tracking after an app restart reattach instead of falling back to drag selection
Spec: tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts (committed to this branch)

Caveats and setup notes from building this proof
  • Spec: /tmp/proof-specs/terminal-reattach-tui-mouse-mode.spec.ts, also present (uncommitted, untracked) at /Users/nwparker/projects/orca/.claude/worktrees/wf_7377b4a2-62e-2/tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts on branch fix/terminal-reattach-mouse-mode-rearm. Nothing was committed.
  • Grep target for recording: --grep "live TUI keeps mouse tracking after an app restart reattach". Rebuild pnpm exec electron-vite build --mode e2e before recording; the worktree's out/ currently holds the fix-branch build.
  • Reuses the existing helpers: helpers/orca-restart.ts (createRestartSession + attachRepoAndOpenTerminal), helpers/terminal.ts, helpers/store.ts, and the existing tests/e2e/fixtures/visible-tui-scroll-fixture.cjs as the live third-party TUI (same fixture terminal-tui-wheel-drain.spec.ts uses).
    …

nwparker and others added 2 commits August 4, 2026 01:37
…CREENSHOT

The spec relaunches Orca, so the video fixture never flushes a WebM. Opt-in screenshot at the decisive frame instead.

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

@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: 5bdaa03f-347a-4677-891b-00ec1e1e6ac1

📥 Commits

Reviewing files that changed from the base of the PR and between aa9352c and 1d40496.

📒 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/shared/terminal-mode-reset-profiles.ts
  • src/shared/terminal-mouse-mode-sequences.test.ts
  • src/shared/terminal-mouse-mode-sequences.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/shared/terminal-mode-reset-profiles.ts

Comment on lines +22 to +24
it('treats RIS as clearing every mouse mode', () => {
expect(scanReplayedMouseModeRearm('\x1b[?1003h\x1b[?1016h\x1bcfresh')).toBe('')
})

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Test RIS reset state directly.

scanReplayedMouseModeRearm returns before it scans this payload because RIS leaves the replay outside the alternate screen. This assertion does not test TerminalMouseModeMirror reset handling. Scan a mouse-enabled payload with a mirror and assert that tracking and both encoding modes reset.

Proposed test
 describe('TerminalMouseModeMirror', () => {
+  it('clears mouse modes on RIS', () => {
+    const mirror = new TerminalMouseModeMirror()
+    mirror.scan('\x1b[?1003h\x1b[?1006h\x1b[?1016h\x1bc')
+    expect(mirror.mouseTrackingMode).toBe('none')
+    expect(mirror.sgrMouseMode).toBe(false)
+    expect(mirror.sgrMousePixelsMode).toBe(false)
+  })
+
   it('detects a DECSET split across two scan calls', () => {

Replaces the renderer-side replay rescan with a reset profile that omits
RESET_MOUSE_REPORTING on an alternate-screen reattach. The daemon's
rehydrateSequences already re-arm the live TUI's protocol and encoding inside
the replayed payload, so xterm's own parse is the authority — the renderer only
had to stop clobbering it. Alt-screen comes from the daemon's authoritative
flag, falling back to the kitty tracker that already scanned the same payload.

Drops the shared DECSET rescan module (196 lines) and its two full-payload
regex passes per reattach; the payload is uncapped up to the 16MB daemon frame
and this ran synchronously on the renderer main thread. The daemon mouse-mode
mirror stays in the daemon, where the only full emulator lives.

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

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bca62256-b4f8-4713-86be-4f208825b4cb

📥 Commits

Reviewing files that changed from the base of the PR and between 1d40496 and 39ea946.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/shared/terminal-mode-reset-profiles.ts
  • tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/terminal-pane/pty-connection.ts

Comment on lines +2 to +4
* Regression proof for #8291: a real alt-screen TUI survives an Orca quit/relaunch, and after the
* warm reattach a drag over it must still go to the TUI as mouse reports, not to xterm's row
* selection. Drives the rendered surface only — no mocks, no direct mode assertions.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Align the test description with the mode check.

The comment says there are “no direct mode assertions,” but readTerminalSurface reads pane.terminal.modes.mouseTrackingMode at Line 94. Update the comment to describe this check, or remove the mode read if the test must remain surface-only.

Based on the PR objectives, the wheel assertion also verifies that mouse tracking remains enabled.

Proposed comment update
- * selection. Drives the rendered surface only — no mocks, no direct mode assertions.
+ * selection. Drives the rendered surface and records xterm mouse mode — no mocks.
📝 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
* Regression proof for #8291: a real alt-screen TUI survives an Orca quit/relaunch, and after the
* warm reattach a drag over it must still go to the TUI as mouse reports, not to xterm's row
* selection. Drives the rendered surface only — no mocks, no direct mode assertions.
* Regression proof for `#8291`: a real alt-screen TUI survives an Orca quit/relaunch, and after the
* warm reattach a drag over it must still go to the TUI as mouse reports, not to xterm's row
* selection. Drives the rendered surface and records xterm mouse mode — no mocks.

Comment on lines +58 to +60
// Why one evaluate for everything: it flushes xterm's write queue first, so a caller can never
// sample mode/selection state mid-replay.
async function readTerminalSurface(page: Page): Promise<TerminalSurface | null> {

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
fd -a 'terminal-reattach-tui-mouse-mode.spec.ts' . || true

echo "== read relevant sections =="
file="$(fd 'terminal-reattach-tui-mouse-mode.spec.ts' . | head -n 1 || true)"
if [ -n "${file:-}" ]; then
  wc -l "$file"
  sed -n '1,140p' "$file" | cat -n
fi

echo "== search related helpers/usages =="
rg -n "readTerminalSurface|readTerminalSurface\(|`@xterm/xterm`|xterm|terminal\.write\(" -S . --glob '!node_modules' --glob '!dist' --glob '!build' || true

Repository: stablyai/orca

Length of output: 1915


🌐 Web query:

xtermjs Terminal write callback API documentation callback called after write completed

💡 Result:

In xterm.js, the terminal.write and terminal.writeln methods accept an optional callback function that is invoked once the provided data chunk has been fully processed by the terminal's parser [1][2][3]. API Signature The write method is defined as: write(data: string | Uint8Array, callback?: => void): void [1][2][3] Purpose and Behavior 1. Completion Notification: The callback signals that the parser has finished processing the specific chunk of data passed to that write call [4][5][6]. 2. Asynchronous Processing: Because data processing in xterm.js can be asynchronous, changes made by a write operation may not be immediately reflected in the terminal buffer [1]. Providing a callback allows you to execute code precisely after the data has been committed to the buffer [4]. 3. Flow Control: The callback is a primary mechanism for implementing flow control (backpressure). For example, if you are reading from a PTY, you can pause the stream when writing a large chunk and resume it only after the callback fires, ensuring the terminal is not overwhelmed [5]. Key Considerations - Execution: The callback is triggered synchronously immediately after the specific chunk is processed by the parser [4]. - Scope: The callback is associated with the completion of the specific chunk of data, not necessarily with individual lines or sequences unless you manually chunk your data accordingly [4]. - Deprecation of Sync Methods: Older synchronous write methods (such as writeSync) are considered unreliable due to their incompatibility with asynchronous parser handlers and are deprecated [7]. Example Usage terminal.write(data, => { // Executed after 'data' has been processed and committed to the buffer console.log('Write completed'); }); For further details on managing data streams and backpressure, see the official xterm.js flow control documentation [5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Try repository access =="
pwd
git ls-files | sed -n '1,80p' || true

file="$(git ls-files | grep 'terminal-reattach-tui-mouse-mode.spec.ts$' | head -n 1 || true)"
if [ -n "${file:-}" ]; then
  echo "== File found: $file =="
  wc -l "$file"
  sed -n '1,150p' "$file" | cat -n
fi

echo "== Search relevant helpers/usages =="
rg -n "readTerminalSurface|readTerminalSurface\(|pane\.terminal\.write|terminal\.write\(" -S . --glob '!node_modules' --glob '!dist' --glob '!build' || true

Repository: stablyai/orca

Length of output: 1915


Confirm pane.terminal.write('', ...) completion before reading the terminal surface.

The pane.terminal.write('', callback) barrier does not guarantee the parser has flushed changes when the 3s timer resolves. Reading the buffer, selection, and mouse mode after that path can sample the old state and make the regression test pass incorrectly. Only consume the surface after the write callback runs; return null or reject on timeout so the caller retries or fails.

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