Repository navigation
fix(terminal): keep a live TUI's mouse modes across daemon reattach - #12461
Conversation
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]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughPTY 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)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)
9234-9270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider adding a cold-restore case that asserts no re-arm.
This test locks the non-agent reattach path. The sibling branch in
reattachReplayResetSequencereturnsPOST_REPLAY_MODE_RESETwhenownerProcessEndedis true, which deliberately skips the mouse-mode re-arm for#12101. A snapshot carrying\x1b[?1002hpluscoldRestorewould 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
📒 Files selected for processing (7)
src/main/daemon/terminal-mode-rehydrate-sequences.tssrc/main/daemon/terminal-mouse-mode-mirror.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/shared/terminal-mode-reset-profiles.tssrc/shared/terminal-mouse-mode-sequences.test.tssrc/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]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts (1)
1-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten 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
📒 Files selected for processing (1)
tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts
| const repoPath = createIsolatedProofRepo() | ||
| const session = createRestartSession(testInfo) | ||
| let firstApp: ElectronApplication | null = null | ||
| let secondApp: ElectronApplication | null = null | ||
|
|
||
| try { |
There was a problem hiding this comment.
🩺 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
Visual proofScreenshot, 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. What you are looking atEverything happens inside the terminal pane of a real Orca window, twice launched against the same profile. Timeline a reviewer sees:
It actually captures the bugSame spec on Test: Caveats and setup notes from building this proof
|
…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]>
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/shared/terminal-mode-reset-profiles.tssrc/shared/terminal-mouse-mode-sequences.test.tssrc/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
| it('treats RIS as clearing every mouse mode', () => { | ||
| expect(scanReplayedMouseModeRearm('\x1b[?1003h\x1b[?1016h\x1bcfresh')).toBe('') | ||
| }) |
There was a problem hiding this comment.
🎯 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]>
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/shared/terminal-mode-reset-profiles.tstests/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
| * 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. |
There was a problem hiding this comment.
📐 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.
| * 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. |
| // 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> { |
There was a problem hiding this comment.
🩺 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' || trueRepository: 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:
- 1: http://xtermjs.org/docs/api/terminal/classes/terminal/
- 2: https://github.com/xtermjs/xterm.js/blob/2fdb46919ce7a329afe65fe69bcf948d310a2b8a/typings/xterm.d.ts
- 3: https://github.com/xtermjs/xterm.js/blob/a73fe62b7aedcd331e01130b92d7e753bb5be55b/typings/xterm.d.ts
- 4: registerMarker/registerDecoration in overviewRuler does not work if invoked immediately xtermjs/xterm.js#5214
- 5: http://xtermjs.org/docs/guides/flowcontrol/
- 6: http://xtermjs.org/docs/guides/hooks/
- 7: https://github.com/xtermjs/xterm.js/blob/master/src/common/CoreTerminal.ts
🏁 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' || trueRepository: 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.

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
rehydrateSequencesre-arm the session's mouse protocol and encoding — and then immediately writesPOST_REPLAY_REATTACH_RESET, whoseRESET_MOUSE_REPORTINGwipes 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.tsdrives the whole thing through the rendered surface: a real alt-screen TUI in a daemon-backed pane, a genuine app quit/relaunch against the sameuserDataDir(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:
offset=row advances from the wheelRESET_MOUSE_REPORTINGrestoreddragging over a live mouse-tracking TUI must not paint xterm row selectionNo mocks and no direct mode assertions — it fails on the user-visible symptom.
Fix
POST_REPLAY_REATTACH_RESET_KEEP_MOUSE: the same reattach reset minusRESET_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:
ownerProcessEnded) still takes the fullPOST_REPLAY_MODE_RESET— a dead owner's modes must not reach the fresh shell ([Bug]: Daemon never resets DECSET mouse tracking mode when a session's process dies, so it can survive into a later restore #12101)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 typecheckcleanpty-connection.test.ts: 544 pass, including a positive case (alt-screen keeps mouse) and a negative control (normal buffer still disarms)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 🐋