Skip to content

fix(terminal): reset stale mouse tracking on cold restore (#12101); stop OSC color-reply echo leak in POSIX agent panes (#12112) - #12202

Merged
nwparker merged 6 commits into
mainfrom
nwparker/fix-terminal-mouse-mode-and-osc-leak
Aug 4, 2026
Merged

nwparker merged 6 commits into
mainfrom
nwparker/fix-terminal-mouse-mode-and-osc-leak

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #12101. Fixes #12112.

Two P0 terminal bugs. Unrelated in mechanism, but both are "a control sequence ends up in the wrong place," so they ship together.

ELI5

#12101 — the mouse-mode ghost.
Programs like Claude Code turn on "tell me when the mouse moves" by sending the terminal a secret code, and politely turn it off when they quit. If Orca force-kills one (workspace Sleep, for instance), it never gets to say the goodbye code. Orca had already written down "mouse reporting: ON" in its notes, and those notes get restored later. So the next time you open that pane you get a plain shell that still has mouse reporting armed — and every time you move the mouse over it, gibberish like ^[[<35;40;12M types itself at your prompt.

The fix has two halves, because the stale note is read by two different readers:

  • The daemon appends the "mouse off" code to the recovered history it seeds a revived session with, so the daemon's own emulator — which mobile and every other consumer re-serialize from — starts disarmed.
  • The desktop renderer stops trusting the pane's "this is a live agent" signal when the session was cold-restored. That signal is read from the pane's status and title, and both are persisted — so after a cold restore they describe the process that died. Preserving "its" modes armed them against the fresh shell that replaced it.

Live programs keep their mouse mode, so real TUI scroll gestures still work.

#12112 — the terminal talking to itself.
When opencode starts, it asks the terminal "what colour is your text? what colour is your background?" and waits for an answer. Orca answers on the agent's behalf. But it answered too fast, and the answer got echoed back onto the screen as visible junk (10;rgb:ffff/ffff/ffff11;rgb:2828/2c2c/3434).

There turn out to be two different things that can echo it, and they need different treatment:

  • The kernel echoes it when the terminal is in "show the user what they type" mode — the mode a shell is in before a full-screen program takes over. Whether the kernel is in that mode is something Orca can simply look up, so it now does, and holds the answer until the mode is off. That removes this echo outright rather than cleaning up after it.
  • The shell's line editor echoes it in software — bash's readline reacts to the answer as if you had typed it, even with the kernel's echo already off. Nothing Orca can look up covers this one, so the answer is still written with a small "if this exact shape comes back, it's my own echo" filter armed.

Windows already had a guard for the second kind; Linux and macOS had neither. A plain terminal tab never had the bug because its answer naturally comes a beat later — this gives agent panes that same timing, for a reason rather than by luck.

Proof of fix

#12112 — real node-pty, real bash -i, real agent, in the actual topology Orca uses (agent launched by writing a command into an interactive shell). Same harness, only the ingress swapped between HEAD and this branch. This is the pane text a user would see:

HEAD   leak=true   "$ node agent.js\r\n^[]10;rgb:ffff/ffff/ffff^[\^[]11;rgb:2828/2c2c/3434^[\\r\nAGENT_DONE"
FIXED  leak=false  "$ node agent.js\r\n\r\nAGENT_DONE"

3/3 runs each. HEAD reproduces the reported string verbatim; this branch is clean.

Critically, the agent still receives both replies in both arms — the deferral does not break delivery, which was the main regression risk:

delivered = "\x1b]10;rgb:ffff/ffff/ffff\x1b\\\x1b]11;rgb:2828/2c2c/3434\x1b\\"

The two-echo-source split is proven separately, because getting it wrong is what an adversarial round caught mid-PR (see below). Production PtyStartupIngress, real slave-device probe, real bash -i, with the foreground program issuing the query itself so the reply lands while readline owns the tty:

this branch   probe said 'quiet'   pane = "printf '\033]10;?\a'\r\nbash-3.2$ "
mutated       probe said 'quiet'   pane = "printf '\033]10;?\a'\r\nbash-3.2$ \x0710;rgb:2e2e/3434/3434"

The mutation is one line — treating the probe's quiet as proof that no echo can happen. The probe is telling the truth in both arms: the kernel really is quiet. Readline echoes it anyway.

#12101 — mutation-verified, both halves independently. Reverting terminal-history-seed-segments.ts and re-running:

Tests  5 failed | 4 passed (9)
x re-arms mouse reporting in the fresh shell that replaces a force-killed agent
x leaves the reattached renderer xterm armed against a dead agent (SGR reports into the prompt)
v control: a TUI that DID emit DECRST before exiting restores a clean shell   <- passes both ways

The second failure is the user-visible symptom read off a real @xterm/headless terminal: expected 'any' to be 'none' on term.modes.mouseTrackingMode. The third test is a control — a TUI that did say goodbye properly — so an over-broad reset would fail it.

The renderer half is pinned separately: reverting the cold-restore branch in pty-connection.ts fails ignores the stale agent signal on a cold restore and applies the fresh-shell reset.

The echo gate is mutation-verified seven ways. Each mutation applied alone, suite re-run:

Mutation Tests failed
Drop every projection once the probe says quiet (the pre-fix design) 1 — still suppresses the readline echo on a slave the probe called quiet
Ignore the probe's proof and always arm the kernel caret projection 1 — retires only the kernel caret projection once the probe proves ECHO is clear
Remove the poll budget 2 — stops polling a tty that never leaves cooked mode and answers it anyway, gives a later query its own probe budget
Read unknown as proof the kernel is quiet 1 — falls back to recognizing echo shapes when the probe cannot answer
Remove the withholding (answer inside the query's own turn) 7 — every timing-dependent gate test
Budget the pty once instead of once per query 1 — gives a later query its own probe budget, not the first query remainder
Latch the probe off on a transient failure too 1 — keeps probing after a transient failure and only latches a permanent one

50/50 green with the files restored. Every regression test in this PR was mutation-verified — restoring the old behavior makes exactly the intended test fail, and no other.

Root causes (both differ from the issue reports)

#12101. The report proposed resetting in handleSubprocessExit. That cannot work — onSessionExit → reapSession disposes the emulator in the same synchronous turn, so a reset written there reaches no snapshot and no file. TerminalModes is recreated per process, so the "stale object survives respawn" model is also wrong. The real chain: the armed mode is latched into the on-disk checkpoint while the TUI is alive, then faithfully re-derived from the dead process's own persisted bytes into each replacement emulator — via two channels, rehydrateSequences and SerializeAddon's mode trailer inside snapshotAnsi. A fix touching only buildRehydrateSequences would have gone green while leaving the bug live. (terminal-private-mode-tracker.ts, cited in the report, does not exist.)

#12112. The leading hypotheses were all wrong and were checked off one by one: the isReplaying() gate, the handler-install race, unresolved-owner-pty-transport, and OSC 4 parser corruption (tested against real xterm — swallowed, but harmless). The actual cause is that agent panes are the only pane class that arms a main-side PtyStartupIngress, and it answered synchronously inside onData while the tty was still cooked. Suppression existed but was gated on ownerBackend === 'windows-conpty' from the #9432 fix.

Why the diff is this size

27 files, but the shape is lopsided on purpose:

files lines changed
Tests & fixtures 14 1702
Production 13 811

67% of the diff is tests. Of the 811 production lines, 492 are three new files — pty-startup-reply-delivery.ts (349), pty-slave-line-discipline-echo.ts (102) and terminal-mode-reset-profiles.ts (41). The first two are reply-write timing and line-discipline state lifted out of pty-startup-ingress.ts so that policy has one owner instead of being interleaved with the span classifier; the third replaces three hand-maintained copies of the same escape literals, which is why the file count is high — deleting a duplicated constant touches every file that held one (layout-serialization.ts is net -33).

Across the nine remaining production files the total is 125 lines, and the largest single behavior change is 28 lines in pty-connection.ts.

Design: ask the tty what you can ask it, guess only at the rest

The first cut of #12112 tried to recognize the echo: for each written reply it registered predicted echo shapes ("projections") and deleted matching spans out of the output stream. That is a guess, and review kept finding defects in the same place — the guess has to be held across reads, which needs a hold timer, a byte budget, an ordering rule against pending queries, and a barrier-invalidation rule for each of deadline / snapshot / query-handoff / teardown. Nine of the P1s below are that one design decision failing in nine different ways.

The redesign starts from a distinction the first cut never drew: there are two independent echo sources, and only one of them is guesswork.

1. The kernel line discipline, when ECHO is set. This is readable state on the slave, not something that has to be inferred from returning bytes. src/shared/pty-slave-line-discipline-echo.ts reads the flag off the slave device and answers echoing / quiet / unknown. On POSIX the reply is withheld until the answer is quiet, polled at 20 ms. Waiting costs the querying program nothing it is not already spending — it is blocked on this reply either way — and the leak happens precisely because Orca answered before the program armed raw mode, so the program does get there. A quiet verdict is proof, and it retires the kernel's projection (the ECHOCTL caret form) outright.

2. The foreground line editor, in software. readline reacts to a master write as if it had been typed — while the tty is already raw with ECHO off. The probe's verdict says nothing about this one, so its projection stays armed on every path, quiet included. This is not theoretical: it is the second proof block above, on a live pty, at an ordinary bash prompt — which is the foreground for most of an agent pane's startup window.

So quiet gates the withholding and retires exactly one projection. It is never read as "no suppression needed."

  • unknown is never read as quiet either — it retires nothing and falls back to shape recognition, as does a tty still cooked when the poll budget expires. A tty that has not left cooked mode by then is one that never will, and waiting only delays a reply that will echo whenever it is sent.

  • The poll budget is wall-clock (200 ms), not a probe count. Each probe is a subprocess, so a multi-pane restore serializes them on fork; a count-based cap measured ~26 ms per probe across 30 panes, which turns a nominal 200 ms into ~8 s of withholding and blows past every query timeout at once. A deadline spends fewer probes under load instead of taking longer, which is the direction that fails safe. Measured on real ptys with real stty, against slaves that never leave cooked mode (so the loop always runs to its bound):

    panes    1    4   10   30   60  100
    spawns   8   32   75   92  120  113
    withhold 206  220  215  202  216  203   (ms, mean)
    

    Flat from 1 to 100 panes, with spawns plateauing rather than scaling. The count-based cap it replaced was 300 spawns / 7955 ms at 30 panes.

  • A probe failure that is contention (EAGAIN, EMFILE, ENFILE, timeout kill) is never latched — that is exactly what a multi-pane restore produces. Only a clean non-zero exit or a missing stty latches the probe off for the pty's life.

Verified against a real node-pty, both line-discipline states:

cooked tty (cat)      probe -> echoing   ldisc sent back "^[]11;rgb:ffff/ffff/ffff^[\"
raw tty (stty -echo)  probe -> quiet     ldisc sent back ""

That is the reported symptom on the left and silence on the right, with the probe agreeing with reality in both.

What this buys: on the primary path the kernel echo is eliminated rather than cleaned up after, and the hold timer / byte budget / ordering rules only ever run against a single well-understood software shape or in degraded mode. It shrinks the defect class rather than eliminating it, which is a weaker claim than the previous revision of this PR made, and the mutation table above is the evidence for the narrower claim.

Design: one reset-profile family, one owner per layer

The mode-reset literals had drifted into three hand-maintained copies (renderer, daemon test, parity fixture), which is what let the daemon and renderer disagree about a cold-restored pane in the first place. They now live in one shared module, src/shared/terminal-mode-reset-profiles.ts, composed from named primitives (RESET_MOUSE_REPORTING, RESET_KITTY_KEYBOARD_PROTOCOL, RESET_TERMINAL_CURSOR_STYLE) rather than repeated escape strings. Each profile carries the one thing that is not derivable from its bytes — why it omits what it omits. The renderer's re-export barrel in layout-serialization.ts is gone; every consumer imports from the shared module directly.

This also removed the reason the fix looked like two unrelated patches: the daemon seed and the renderer post-replay write are two readers of the same contract, and they now name it the same way.

Review found real defects — what changed as a result

A two-panel review over the /prod-release-scan seat set (01–08), plus successive adversarial rounds, found the first cut of the #12112 fix was largely a no-op on the platform it was written for:

  • P1 — echo matcher was anchored at offset 0 and one-shot. In the real topology the echo always arrives coalesced with other output (bash's echo of the command line, the agent's first frame), never at offset 0 — so it matched nothing, and a miss destroyed the expectation permanently. Proven on a real PTY: 8/8 leaks with the "fix" in place. Now searches the whole span and keeps all queued expectations.
  • P1 — out-of-order release. echoPending (later bytes) was flushed before queryPending (earlier bytes), which can park xterm inside an unterminated OSC that silently swallows everything after it — a permanently blank pane. Fixed; see honesty note 4.
  • P1 — a split echo leaked at any non-zero offset. The partial-echo hold only engaged when the candidate started at offset 0, but a tty coalesces its echo behind whatever the shell printed, so a split echo almost always arrives mid-span. The prefix is now emitted and only the candidate tail is held, so recognition survives a split at any byte boundary without stalling real output.
  • P1 — the search budget could never expire. The budget was charged only on the fall-through path, so a stream whose reads all end mid-candidate kept an unmatched projection alive for the rest of the session, silently deleting any output that later matched it. This was strictly worse than HEAD. The charge is now taken once per PTY read at the single entry point, in a finally, where no return path can skip it.
  • P1 — the budget's unit then broke suppression on slow links. Fixing the above by counting reads (8) meant any tty that chunked finer than ~4 bytes spent the whole budget inside the echo itself: 3-byte chunks took 9 reads and leaked ^[]10;rgb:...^[\\ to the pane, 1-byte chunks took 27. Exactly the SSH-relay and slow-drain case. Reconciled: the unit is bytes again, the real bound on a live projection is the startup deadline, and the byte count is only a backstop against a pathological pre-deadline stream. Pinned by a test that runs the same echo at chunk sizes 1, 2, 3, 5 and 13.
  • P1 — the echo leaked whenever a query was torn on an earlier read. The partial-echo hold was gated on !queryPending, and it bailed before emitting the prefix — so a query the tty had torn on a previous read never got the chance to be completed by this read's prefix, and the whole echo went out raw. Reproduced as the verbatim reported symptom: ^[]10;rgb:2e2e/3434/3434^[\\. The gate now runs after the prefix is emitted, which is the only point where "is a query still torn?" is actually answerable.
  • P1 — preferring a torn query over the echo behind it, even once the echo disproved it. The check above still deferred to any pending query candidate, which is right only while that candidate can still become a query — the held tail may legitimately open with the BEL that terminates one, since the readline projection starts with a BEL. But when the echo begins at offset 0 there is no prefix to complete the candidate, so a candidate like ESC ] 1 1 ; that the echo's very next byte disproves still won, and the live echo was handed to the raw path: ESC]11;^[]10;rgb:2e2e/3434/3434^[\ on the pane, with slot 11 never answered either. The candidate is now re-parsed against the arriving tail and released as ordinary output when the tail disproves it, so only the program's own five bytes survive and the echo is suppressed. Terminators that genuinely complete a torn query are unaffected and still answered.
  • P1 — the fix regressed itself over SSH-sized jitter. A partial echo is held for a moment so its other half can arrive; when the hold expires the bytes are released raw. That window was 50 ms, so any relay that stalled 50 ms mid-echo put the junk straight back on screen — measured gap=49ms -> "" vs gap=50ms -> "^[]10;rgb:2e2e/3434/3434^[\\". The window is now 500 ms. This costs nothing measurable: the timer is almost never what ends a hold (the next read is, at +0 ms), and the startup deadline and snapshot barrier already cap the wait independently. Pinned at 50/200/400 ms.
  • P1 — a failed write could duplicate a reply. Rolling back the "answered" bookkeeping cleared every slot, so a query that landed slot 10 and then threw on slot 11 un-claimed both, and a repeat query wrote reply 10 a second time — the exact corruption the deferral exists to avoid. Rollback is now scoped to the reply that actually failed.
  • P2 ×4 — the startup deadline wiping expectations for already-written replies; a partial-echo hold with no timer of its own (up to a 5 s stall); an unbounded suppression window past the startup deadline (now clamped to 512 bytes); the repro test modelling an echo that could only ever land at offset 0.

The redesign itself was then reviewed adversarially, and the first version of it was wrong. Worth stating plainly, because the previous revision of this PR description asserted the broken claim:

  • P0 — the redesign's premise was too strong. It read a quiet verdict as proof that no echo could occur and registered no projection at all. But quiet is proof only about the kernel; readline echoes a master write in software with the tty already raw and ECHO off. So the "elegant" version reintroduced [Bug]: Raw OSC 10/11 color-query replies leak as text in Linux agent pane (opencode) #12112 at a plain shell prompt — the foreground for most of an agent pane's startup window, and a strictly worse outcome than the design it replaced. Fixed by scoping quiet to retire exactly the kernel's own projection. Both directions are in the second proof block above; the earlier verification missed it because its test programs (cat, sleep) never put a line editor between the write and the output.
  • P1 — the poll was a subprocess storm. Measured: 1 pane → 10 spawns → 222 ms; 4 panes → 856 ms; 10 → 2155 ms; 30 panes → 300 spawns → 7955 ms. A 30-pane restore withheld every reply well past every query timeout at once. The attempt-count cap became a wall-clock budget, which under contention spends fewer probes instead of taking longer.
  • P2 — the poll budget never reset, so a second OSC query arriving more than the budget after the first (routine over SSH) got zero probes and went straight to guessing. Re-armed per query batch.
  • P2 — a transient probe failure latched the probe off permanently. EAGAIN/EMFILE and timeout kills are exactly what the burst in the P1 above produces, so the pty most in need of the probe was the one that lost it. Only genuinely permanent failures latch now.

Earlier rounds also caught a retry-on-echo in the first draft, premised on a false assumption (POSIX ECHO copies bytes to the master but does not consume them from the slave input queue; the common Go and Rust TUI runtimes use TCSANOW, not TCSAFLUSH). It would have injected duplicate replies into opencode's raw-mode stdin — recreating the symptom. Removed entirely. Another caught the #12101 fix destroying the length === 0 "nothing to recover" sentinel, which would have force-killed and respawned a just-created session.

A dedicated claims audit also rewrote several comments that asserted things that were not true — including one that said node-pty exposes neither the master fd nor the slave path. It exposes both (fd, ptsName). Following that thread is what produced the redesign: the audit's replacement text claimed the ECHO bit could not be read without a native tcgetattr, that claim was checked, and it was also false.

Testing

All of the below ran on the merged tree (main merged in at a4944f5343; one import-order conflict in local-pty-provider.ts, both sides kept):

  • pnpm lint — exit 0
  • pnpm typecheck — exit 0 (all 3 tsconfig projects)
  • Affected sweep (src/shared, src/main/daemon, src/main/providers, src/relay) — 6780 passed | 20 skipped | 2 failed, both pre-existing
  • Full sweep (whole src/) — 43701 passed | 76 skipped | 3 failed, all 3 accounted for below
  • CI on the merge commit — 44 pass, 5 skipped, 0 failures (all 16 test shards, package (windows), native-smoke (ubuntu-22.04), Git compatibility, static analysis)
  • Probe verified against a live node-pty in both line-discipline states, and end-to-end through the production ingress at a real bash -i prompt — re-executed on the merged tree, 4 runs per arm, byte-identical every run: fixed arm ends \r\nbash-3.2$ , the arm with the suppression reverted ends bash-3.2$ \x0710;rgb:2e2e/3434/3434. An out-of-band read of the same slave device reported -echo while bash sat at the prompt, so the kernel provably did not produce those bytes and the leak is the software-echo path the design targets. The harness is deliberately not committed: a real interactive shell plus multi-second waits is a CI flake source, and the regression is pinned deterministically by the unit tests instead
  • Platform matrix re-verified on the merged tree against real ptys: probe verdicts (echoing and quiet, each cross-checked against an out-of-band read of the same device) and end-to-end suppression under three independent stty implementations — the GNU userland and the two common multicall-binary variants — covering both the -f and -F argument arms. The false-quiet attack found nothing: unparseable output, empty output, echo-suffixed tokens with no bare echo, and -echo appearing inside an error string all land on unknown, never quiet. A localized host (LC_ALL=fr_FR.UTF-8) translates messages but not flag tokens, and its errors exit non-zero with empty stdout, so it also lands on unknown.
  • isPermanentSttyFailure latching confirmed behaviorally: a missing stty and a non-zero exit latch (measured 1 spawn across 3 polls — the process-per-poll guard), while a timeout-kill and a genuine EMFILE (fd table exhausted under a lowered nofile limit) do not — the same probe returns a real verdict once the pressure clears. That is the multi-pane-restore contention case reproduced for real.
  • pnpm build — not run
  • Every regression test mutation-verified to fail without its fix (7-way table above), plus the reattach reset test added for the spawn-adopted path

The three residual local failures, none from this PR — and all three pass or are absent in CI:

Residual coverage gaps, stated plainly: the platform matrix ran in containers — no real SSH host and no WSL — and BSD proper is unverified (macOS shares its -f arm). Windows needs none by construction: the probe is undefined there.

  • src/relay/agent-exec-handler.test.ts (2) — fails identically on a clean origin/main worktree; the assertions compare a spawned command's env against the developer's real environment variables. Pre-existing and environment-dependent.
  • src/main/updater.test.ts (1) — pre-existing on main and macOS-only. Both updater.ts and updater.test.ts are byte-identical to main's tip at this branch's HEAD; updater.ts:863 selects its error string on process.platform === 'darwin' and the test asserts the non-darwin string, so it passes on Linux CI and fails on any macOS dev machine. Untouched here.

Unrelated to this PR, pty-connection.test.ts crashes its vitest worker under --sequence.shuffle; that reproduces with this PR's test removed, so it is pre-existing order-coupling in a 541-test file, and CI runs the file sequentially (green).

An earlier sweep on this branch showed 12 additional failures in the installed-xterm IME tests; those were stale node_modules after main updated its xterm patch, and they pass after pnpm install (124/125). Earlier sweeps also showed ai-vault-session-worktree-map.test.tsx (a 194ms < 150ms wall-clock budget), transcript-watch-liveness.test.ts, remote-runtime-shared-control-connection.test.ts and pty-connection.test.ts flaking under parallel load; all pass in isolation and none recurred in the final sweep.

Screenshots

No visual change. The observable behavior is terminal byte streams; the before/after pane text is under Proof of fix.

AI Review Report

Two independent review panels ran the full /prod-release-scan seat set (01 SSH/remote/network, 02 crash/cast/retry/unbounded growth, 03 security/supply chain, 04 perf, 05 functional, 06 backcompat/data-loss, 07 cross-platform, 08 packaging), followed by verified synthesis and remediation. Successive adversarial rounds then attacked each round's fixes — including the redesign, which is where the P0 above came from. The final round independently mutation-reverted all four redesign fixes (each caught by a specific test), measured the poll budget to 100 concurrent panes, and returned no reproducible defect; its two remaining findings are the pre-existing limitations in notes 7 and 8. A final pass over the merge itself found the reset guard untested on one reattach entry point that main had newly widened — a spawn answered with an adopted session — and that path now has its own test. A further round attacked that test specifically and returned clean: it is caught by a mutation that strips the cold-restore payload through that call site alone (1 failure out of 541 in the file — no other test notices), it was traced by instrumentation to that entry point and no other, its negative assertion was shown to be armed rather than trivially true, and its tick budget has 6× headroom over the measured floor with no wall-clock dependence.

Seat Panel A Panel B Verdict
01 ssh/remote/network PASS P1 P1 confirmed → fixed
02 crash/retry/growth P2 P1 P1 confirmed → fixed
03 security/supply chain PASS — PASS
04 perf/resources P2 — P2 confirmed → fixed
05 functional P2 P1 P1 confirmed → fixed
06 backcompat/data-loss PASS PASS PASS (216-case differential: 0 emptiness, 0 content mismatches)
07 cross-platform P2 P2 P2 confirmed → fixed
08 release/packaging PASS — PASS (no packaging surface touched)

Cross-platform was explicitly checked. #12112 branches on PtyOwnerBackend: posix-pty (Linux/macOS) defers + suppresses; windows-conpty keeps its synchronous write because it must beat conhost's own responder; windows-wsl is byte-identical to HEAD, verified against git show HEAD:src/shared/pty-startup-ingress.ts. The probe is not even constructed off POSIX — no slave path, no stty. #12101's path is shared by POSIX SIGKILL and Windows taskkill /T /F — both land in the same "checkpoint on disk, endedAt null, fresh spawn seeded from disk" flow. Seat 06 traced the versioned daemon↔app boundary (measureTerminalHistorySeed, result.historySeeded on old daemons, canReanchorHistory at daemon-pty-adapter.ts:708) for scrollback-loss risk under new-app/old-daemon and rollback — clean. No metaKey, path-separator, or line-ending assumptions introduced. No UI surface, so no shortcut labels affected.

Security Audit

Seat 03 ran as a dedicated pass. No dependency, lockfile, package.json script, workflow, install-hook, or binary changes in this PR — verified, not assumed. Specific risks reviewed:

  • Reply content injection — reply bytes derive solely from Orca's own theme colors via terminalOscColorQueryReplies and are validated upstream; no untrusted process output is reflected back into the PTY write.
  • Output-hiding primitive — echo suppression can swallow pane output, so a hostile process shaping output to match a projection could hide it. Bounded on three axes: armed only inside the 5 s startup window, only around an actually-written reply, and — once that window closes — for at most 512 more bytes. A byte backstop retires a projection that never lands even before the deadline.
  • Subprocess execution — the probe runs stty, resolved via PATH, with a fixed argument vector (execFile, no shell) whose only variable is a device path read from node-pty, never from user or process input. 2 s timeout, windowsHide, output parsed by a single anchored regex. A hostile PATH is already game over for a terminal app that spawns the user's shell, so this adds no new trust.
  • Escape injection via checkpoint — [Bug]: Daemon never resets DECSET mouse tracking mode when a session's process dies, so it can survive into a later restore #12101 writes control bytes into a revived session's stream sourced from checkpoint.json. The injected constant is a fixed literal, not checkpoint-derived; checkpoint trust is unchanged by this PR.
  • No secrets, eval, shell execution, or new network sinks. No IPC payload shape changed.

Notes

Honest limitations — please read before merging:

  1. Verified on macOS and Linux; not on a real SSH host, WSL, or BSD proper. Both probe argument arms (stty -a -f <dev> on macOS/BSD, -F on the GNU userland) have now been executed against live ptys on the merged tree, under three independent stty implementations, with both echoing and quiet verdicts cross-checked out-of-band. What remains unexecuted is the host matrix rather than the platform arm: containers stood in for SSH and WSL hosts, and BSD proper is covered only inasmuch as macOS shares its flag spelling. Windows needs no coverage — the probe is undefined there by construction. If an invocation is ever wrong the probe answers unknown, which degrades to shape recognition rather than to a leak.
  2. [Bug]: Raw OSC 10/11 color-query replies leak as text in Linux agent pane (opencode) #12112 is not fixed on windows-wsl. That path is deliberately byte-identical to HEAD (WSL is ConPTY-hosted and its echo shape is unverified, so guessing risked a regression). Do not consider [Bug]: Raw OSC 10/11 color-query replies leak as text in Linux agent pane (opencode) #12112 closed for WSL.
  3. The two review panels shared a model. The scan's default layout uses different models per panel precisely so blind spots are uncorrelated. Panel B was diverged by method instead (work backward from failure; prefer executed proof over read-the-code proof) — a real mitigation, not a substitute. Correlated blind spots remain the main residual risk in this review, and the P0 above is a concrete instance of one that survived several rounds.
  4. P1-2's literal reorder is not independently pinnable. Once the narrow hold rule landed, echoPending and queryPending can no longer both be non-null, so the inversion is unreachable by construction and mutating the reorder alone passes. Kept as defense-in-depth. What is pinned is the user-visible defect it caused, via a companion mutation.
  5. The software-echo path keeps the limitations the projection design had. The readline projection is armed on every path, so its caveats are not confined to degraded mode: a split echo whose halves straddle the 500 ms hold is released raw and the matcher cannot resume mid-projection. Making the matcher resumable was considered and rejected — it only shrinks the leak (the released half is already on screen) while adding match-progress state that every barrier (deadline, snapshot, query handoff, teardown) would have to invalidate correctly, which is exactly the shape of the ordering bugs this review kept finding. When the probe answers unknown the kernel's caret projection comes back too, with the same caveats.
  6. A withheld reply is a latency the querying program pays. Up to ~200 ms on a tty that never goes raw, and up to the startup deadline only if the tty stays cooked and the budget has not expired, after which reset() flushes it. I have not measured any real agent CLI's color-query timeout against that bound, so a program with a very short timeout would see a missing reply where it previously saw a corrupted screen. Both are wrong; I believe the second is worse, but that judgement is not measured.
  7. Echo suppression is cosmetic, not semantic — and this is the sharpest edge in the PR. The readline projection keeps the echo off the screen, but the bytes are still in readline's edit buffer. Executed: after a suppressed echo, pressing Enter at an untouched prompt runs them — bash: 10: command not found / bash: rgb:2e2e/3434/3434: No such file or directory, with nothing on screen to explain where that came from. This is unchanged from HEAD (which suppressed nothing on POSIX, so the user at least saw the junk first) and is not fixable by suppressing harder — undoing it means writing a kill-line into someone's prompt. The withholding is what actually prevents this in the common case; the projection is the fallback, and the fallback is cosmetic. Recorded in a comment next to the projection so nobody later reads it as "handled".
  8. A quiet verdict ages before it is used. Measured ~2.5–6.5 ms between the probe returning and the write landing. If ECHO flips back on inside that window the caret echo leaks unsuppressed, because quiet retired that projection — reproduced by forcing the flip, producing [Bug]: Raw OSC 10/11 color-query replies leak as text in Linux agent pane (opencode) #12112 verbatim. No natural trigger was found; the plausible one is the querying program dying as Orca answers, leaving the shell to restore cooked mode. Accepted rather than armed against: keeping the caret projection always-armed puts every read ending in ^ back under a 500 ms partial hold, which is the machinery this redesign exists to stop depending on.
  9. The poll budget bounds when a probe starts, not one in flight. So the hard bound on withholding is 200 ms + STTY_TIMEOUT_MS (2 s) = 2.2 s, not 200 ms — still inside the startup deadline. Not reachable at 100 real panes (probes stayed ~2.5 ms); it needs an stty that hangs.
  10. One asymmetry left as-is: the fourth reattachReplayResetSequence call site (drainReplayDataQueue) takes no cold-restore flag. It is fed only by live-session replay events from the transport, which never carry a cold restore — traced end to end, and the daemon-side seed reset covers those bytes regardless. Left unflagged deliberately rather than defensively.

Deliberately out of scope (would widen the blast radius):

  • Passing excludeModes: true to SerializeAddon in headless-emulator.ts and widening TerminalModes, so buildRehydrateSequences becomes the single emitter of mode bits instead of one of two. This is the structurally correct end state and would delete the reason a reset is needed in the seed at all — but it changes every snapshot Orca takes, not just cold-restored ones.
  • Routing all three OSC color responders (main ingress, renderer terminal-capability-replies.ts, headless terminal-view-attribute-responder.ts) through one per-pty reply chokepoint. Today they are independent, which is why only one of them learned to defer.

Known-uncovered, adjacent (not regressions): the same cold-restore seed re-arms bracketedPaste (?2004h) and applicationCursor (?1h) from dead processes — same class, different symptom, not pinned by either issue. App-SSH relay panes have no emulator or mode mirror at all. Mobile cold-restore has no post-replay reset. The two POSIX projections cover the ECHOCTL caret form and the bash/readline form; stty -echoctl and zsh/ZLE are unmodeled third shapes and leak — unchanged from HEAD, which suppressed nothing at all on POSIX, so not a regression. (A verbatim projection was tried and rejected: it is byte-identical to the reply, so a bare trailing ESC would make every torn read an echo candidate and strand real queries.) Neither repro test is registered in config/reliability-gates.jsonc. On windows-conpty only, a stray ESC landing immediately before the echo can still absorb its first few bytes: that projection is ESC-stripped, so ESC + the echo's head parses as a partial OSC and the candidate consumes it before being disproven. Byte-identical to HEAD — the two POSIX projections cannot be extended out of a bare ESC this way, so POSIX is clean at every split.

Made with Orca 🐋

…top OSC color-reply echo leak in POSIX agent panes (#12112)

#12101: a force-killed TUI never emits its DECRST reset, so its armed mouse
mode is latched into the on-disk checkpoint and re-derived into the
replacement process's emulator via the cold-restore history seed -- through
both rehydrateSequences and SerializeAddon's own mode trailer. The revived
bare shell then echoed SGR motion reports at the prompt. Seed a
RESET_MOUSE_REPORTING segment after the snapshot (before the torn escape
tail), only when there is real recovered content so the empty-array
"nothing to recover" sentinel survives.

#12112: agent panes arm a main-side PtyStartupIngress that answered opencode's
startup OSC 10/11 queries synchronously inside node-pty's onData, while the
POSIX tty still had ECHO on. The line discipline echoed Orca's own reply back
out as visible text. Echo suppression existed but was gated on windows-conpty.
Add PtyStartupReplyDelivery: POSIX defers the write off the query's turn and
recognizes its own echo anywhere in a span (bounded, non-destructive); ConPTY
keeps its synchronous write; windows-wsl is byte-identical to before.

Fixes #12101

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

coderabbitai Bot commented Aug 3, 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 changes add shared terminal reset profiles and apply the cold-restore profile to recovered history and renderer reattachment. They add regression tests for stale mouse tracking after agent termination. They add PTY slave echo probing and integrate it with PtyStartupIngress. PtyStartupReplyDelivery now handles reply writes, echo matching, deferred POSIX delivery, timers, teardown, and rollback. Tests cover backend timing, cooked-echo suppression, split reads, deadlines, failures, and rendered output.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% 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
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.
Title check ✅ Passed The title clearly identifies both primary terminal fixes and is specific to the changeset.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes, and documents the skipped build.
✨ Finishing Touches 💡 1
📝 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: 3

🧹 Nitpick comments (4)
src/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts (1)

151-155: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

settle waits on wall-clock time.

settle awaits 12 real 1 ms timeouts. The two tests at Lines 162 and 184 use real timers, so they depend on the modeled work finishing inside roughly 12 ms. On a loaded CI machine the PTY deferred write and the xterm parse can take longer, which makes these tests flaky.

Consider polling for the expected condition with a deadline instead of a fixed tick count.

♻️ Proposed refactor
-async function settle(): Promise<void> {
-  for (let tick = 0; tick < 12; tick += 1) {
-    await new Promise((resolve) => setTimeout(resolve, 1))
-  }
-}
+async function settleUntil(condition: () => boolean, timeoutMs = 500): Promise<void> {
+  const deadline = Date.now() + timeoutMs
+  while (!condition() && Date.now() < deadline) {
+    await new Promise((resolve) => setTimeout(resolve, 1))
+  }
+}
src/main/daemon/terminal-history-seed-segments.ts (1)

3-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider centralizing RESET_MOUSE_REPORTING to avoid manual sync drift.

This constant is duplicated in the renderer's layout-serialization.ts, and the comment explicitly states it must be kept in sync manually. If the two definitions ever diverge, the divergence silently reintroduces the exact SGR-leak symptom this PR fixes. Since src/shared/ already hosts logic shared between main and renderer for the PTY-startup-reply layer, move RESET_MOUSE_REPORTING there and import it from both sides instead of maintaining two hand-synced copies.

src/main/daemon/terminal-history-seed-segments.test.ts (1)

65-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the "escape tail only" branch.

The sentinel test here covers recovered.length === 0 && !escapeTail. The sibling condition, recovered.length === 0 with pendingEscapeTailAnsi truthy, is not covered by any test. In that case, getRecoveredHistorySeedSegments returns [RESET_MOUSE_REPORTING, escapeTail] per Lines 22-27 of the source. Add a test case with empty rehydrateSequences/snapshotAnsi and a non-empty pendingEscapeTailAnsi to lock in this behavior.

src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts (1)

154-156: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This assertion cannot fail regardless of the fix.

historySeedChunks are written to this.emulator via writeSync, not to this.subprocess, per Session's constructor. At this point in the test, no code path pushes onto shellPty.written, so this array is empty whether or not the seed correctly disarms mouse reporting. The assertion passes vacuously and does not verify "the bare shell never arms mouse reporting." The meaningful checks already exist at Lines 162-168, which inspect shell.getSnapshot() directly. Remove this assertion or replace it with something that inspects data actually written to the subprocess (e.g., after a shell.write() round-trip), so the comment's claim is backed by a real check.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f9f2b4c2-f37d-4bd0-a765-c006d7f05a25

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and d97248f.

📒 Files selected for processing (9)
  • src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts
  • src/main/daemon/terminal-history-seed-segments.test.ts
  • src/main/daemon/terminal-history-seed-segments.ts
  • src/main/ipc/pty.test.ts
  • src/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts
  • src/shared/pty-startup-ingress-contract.ts
  • src/shared/pty-startup-ingress.test.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/pty-startup-reply-delivery.ts

@greptile-apps

greptile-apps Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Greptile Summary

Two orthogonal terminal bugs are fixed together: #12101 resets stale DECSET mouse-tracking state when cold-restoring a session after a force-killed TUI, and #12112 defers OSC color-query replies for POSIX agent panes by one event-loop turn so the cooked tty can enter raw mode before the reply is written, with a secondary echo-suppression layer.

Confidence Score: 4/5

Both fixes are targeted and well-scoped; the cold-restore mouse reset is idempotent and the deferred-write path leaves ConPTY and WSL byte-identical to HEAD.

The implementation is carefully designed and extensively tested with mutation-verified regressions. The two findings are non-blocking: a test hygiene gap and a budget-charging policy unlikely to matter given the 8 KB budget.

Files Needing Attention: src/shared/pty-startup-reply-delivery.ts and src/shared/pty-startup-ingress.ts carry the most complexity; src/shared/pty-startup-ingress.test.ts is missing afterEach timer cleanup.

Important Files Changed

Filename Overview
src/main/daemon/terminal-history-seed-segments.ts Appends RESET_MOUSE_REPORTING after every non-empty recovered seed to neutralize stale DECSET mouse-tracking state; respects the empty-list sentinel.
src/shared/pty-startup-reply-delivery.ts New class owning write timing and echo suppression; defers writes one turn on posix-pty, tracks ECHOCTL and readline projections with 8 KB budget.
src/shared/pty-startup-ingress.ts Replaces inline echo-expectation list with PtyStartupReplyDelivery; adds 50 ms echoHoldTimer for offset-0 partial spans with no torn query outstanding.
src/shared/pty-startup-ingress-contract.ts Adds release-echo to PtyStartupIngressOperation union for the echo-hold timer expiry path.
src/main/ipc/pty.test.ts IPC tests updated to assert write is not called before advanceTimersByTime(2), reflecting posix-pty deferred-write behavior.
src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts End-to-end regression for #12101; mutation-verified against both re-arming channels.
src/main/daemon/terminal-history-seed-segments.test.ts Unit tests covering alt-screen branch, empty sentinel, escape-tail placement, and emulator-level smoke test.
src/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts Renderer-level regression for #12112 with real xterm, IPC transport, and cooked-mode TTY model.
src/shared/pty-startup-ingress.test.ts Extensive new tests for deferred writes and echo suppression, but missing afterEach timer cleanup for tests using vi.useFakeTimers().

Comments Outside Diff (2)

  1. src/shared/pty-startup-ingress.test.ts, line 787-800 (link)

    P2 Fake timer state can leak across tests on assertion failure

    vi.useFakeTimers() is called at the top of this test (and several others in the file) but vi.useRealTimers() is only restored inside the test body of some cases and never in an afterEach. If any assertion inside a test that called vi.useFakeTimers() throws before reaching the cleanup, vitest enters the next test while fake timers are still active. Adding afterEach(() => vi.useRealTimers()) to the top-level describe block would make cleanup unconditional and idempotent.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

  2. src/shared/pty-startup-reply-delivery.ts, line 352-370 (link)

    P2 Echo budget charged against all entries even on a partial match

    When matchEcho finds no complete match, chargeEchoSearch(data.length) charges the full span length against every entry's remainingChars budget, including entries whose projection was matched partially. A partial hit is positive signal that the echo may still arrive yet it drains the budget at the same rate as a full miss. With ECHO_SEARCH_BUDGET_CHARS = 8192 this is unlikely to matter in practice, but a program that emits ~8 KB before its echo arrives could see the projection evicted just before the match lands.

Reviews (1): Last reviewed commit: "fix(terminal): reset stale mouse trackin..." | Re-trigger Greptile

nwparker and others added 2 commits August 3, 2026 14:17
The startup color reply was written into a PTY still in cooked mode, so the
line discipline echoed it back as visible junk (#12112). Whether that will
happen is readable state on the slave rather than something to infer from
returning bytes, so the reply now waits until the ECHO bit is observably
clear instead of guessing at echo shapes.

Two echo sources exist and only one is readable. A `quiet` verdict proves
the kernel will not echo, so it retires the caret projection; readline
echoes a master write in software with the tty already raw, so that
projection stays armed on every path. Scoping `quiet` narrowly is the whole
correctness argument here: reading it as "no suppression needed"
reintroduces the bug at a plain shell prompt.

Polling is bounded by a wall-clock budget rather than an attempt count,
because each probe is a subprocess and a multi-pane restore serializes them
on fork. Withholding measures flat at ~210ms from 1 to 100 panes.

Also resets a cold-restored pane's mouse reporting (#12101). The armed mode
is re-derived from the dead process's own persisted bytes through two
channels, so the daemon seeds a reset into recovered history and the
renderer stops trusting a persisted "live agent" signal after a cold
restore. The reset literals move to one shared profile module.

Fixes #12101
Fixes #12112

Co-authored-by: Orca <[email protected]>
# Conflicts:
#	src/main/providers/local-pty-provider.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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4a34d1e3-daeb-4b93-9143-531d684601a8

📥 Commits

Reviewing files that changed from the base of the PR and between d97248f and e9c02dc.

📒 Files selected for processing (25)
  • src/main/daemon/hibernation-cold-restore-repro.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts
  • src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-history-seed-segments.test.ts
  • src/main/daemon/terminal-history-seed-segments.ts
  • src/main/providers/local-pty-provider.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/layout-serialization.test.ts
  • src/renderer/src/components/terminal-pane/layout-serialization.ts
  • 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-replay-cursor-state.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/shared/pty-slave-line-discipline-echo.test.ts
  • src/shared/pty-slave-line-discipline-echo.ts
  • src/shared/pty-startup-ingress-contract.ts
  • src/shared/pty-startup-ingress.test.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/pty-startup-reply-delivery.ts
  • src/shared/terminal-mode-reset-profiles.test.ts
  • src/shared/terminal-mode-reset-profiles.ts
  • src/shared/terminal-restore-parity-fixture.ts
  • tests/e2e/terminal-attention.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/daemon/terminal-history-seed-segments.ts
  • src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts
  • src/shared/pty-startup-ingress.ts

…ach path

A spawn can be answered with an adopted session, which reaches the reattach
handler by a door that skips the restored-session path. Pin that the cold-restore
signal survives it, so #12101's junk cannot come back through it.

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.

🧹 Nitpick comments (2)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (2)

9048-9048: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the restore and spawn calls.

The mock accepts every request without a truthy sessionId. The test only checks the call count. Two spawn calls could therefore pass without exercising the restored-session fallback. Assert that the first call uses sessionId: 'tab-pty' and the second call has no sessionId.

Suggested assertions
     expect(transport.connect).toHaveBeenCalledTimes(2)
+    expect(transport.connect.mock.calls[0]?.[0]?.sessionId).toBe('tab-pty')
+    expect(transport.connect.mock.calls[1]?.[0]?.sessionId).toBeUndefined()

9049-9053: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Verify that the reset follows the replay snapshot.

The test checks only that POST_REPLAY_MODE_RESET appears in a write. It does not verify that the reset occurs after the snapshot enables mouse reporting. If the reset is sent first, the test passes but the stale mode remains enabled. Compare the ordered output and require the reset index to be greater than the snapshot index.

Suggested ordering assertion
     const writes = (pane.terminal.write as ReturnType<typeof vi.fn>).mock.calls.map(
       ([data]) => data as string
     )
+    const output = writes.join('')
+    const snapshotIndex = output.indexOf(
+      '\x1b[?1003h\x1b[?1006h\x1b[?2004huser@host ~ $ '
+    )
+    const resetIndex = output.indexOf(POST_REPLAY_MODE_RESET)
+    expect(snapshotIndex).toBeGreaterThanOrEqual(0)
+    expect(resetIndex).toBeGreaterThan(snapshotIndex)
     expect(writes).toContain(POST_REPLAY_MODE_RESET)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d041c08e-a2a1-4cd1-97da-e21ec52cea5c

📥 Commits

Reviewing files that changed from the base of the PR and between a982e6b and bffd8d1.

📒 Files selected for processing (1)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts

@nwparker
nwparker merged commit a6b14eb into main Aug 4, 2026
51 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…2101); stop OSC color-reply echo leak in POSIX agent panes (stablyai#12112) (stablyai#12202)

* fix(terminal): reset stale mouse tracking on cold restore (stablyai#12101); stop OSC color-reply echo leak in POSIX agent panes (stablyai#12112)

stablyai#12101: a force-killed TUI never emits its DECRST reset, so its armed mouse
mode is latched into the on-disk checkpoint and re-derived into the
replacement process's emulator via the cold-restore history seed -- through
both rehydrateSequences and SerializeAddon's own mode trailer. The revived
bare shell then echoed SGR motion reports at the prompt. Seed a
RESET_MOUSE_REPORTING segment after the snapshot (before the torn escape
tail), only when there is real recovered content so the empty-array
"nothing to recover" sentinel survives.

stablyai#12112: agent panes arm a main-side PtyStartupIngress that answered opencode's
startup OSC 10/11 queries synchronously inside node-pty's onData, while the
POSIX tty still had ECHO on. The line discipline echoed Orca's own reply back
out as visible text. Echo suppression existed but was gated on windows-conpty.
Add PtyStartupReplyDelivery: POSIX defers the write off the query's turn and
recognizes its own echo anywhere in a span (bounded, non-destructive); ConPTY
keeps its synchronous write; windows-wsl is byte-identical to before.

Fixes stablyai#12101

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

* fix(terminal): read the slave's ECHO bit before answering a color query

The startup color reply was written into a PTY still in cooked mode, so the
line discipline echoed it back as visible junk (stablyai#12112). Whether that will
happen is readable state on the slave rather than something to infer from
returning bytes, so the reply now waits until the ECHO bit is observably
clear instead of guessing at echo shapes.

Two echo sources exist and only one is readable. A `quiet` verdict proves
the kernel will not echo, so it retires the caret projection; readline
echoes a master write in software with the tty already raw, so that
projection stays armed on every path. Scoping `quiet` narrowly is the whole
correctness argument here: reading it as "no suppression needed"
reintroduces the bug at a plain shell prompt.

Polling is bounded by a wall-clock budget rather than an attempt count,
because each probe is a subprocess and a multi-pane restore serializes them
on fork. Withholding measures flat at ~210ms from 1 to 100 panes.

Also resets a cold-restored pane's mouse reporting (stablyai#12101). The armed mode
is re-derived from the dead process's own persisted bytes through two
channels, so the daemon seeds a reset into recovered history and the
renderer stops trusting a persisted "live agent" signal after a cold
restore. The reset literals move to one shared profile module.

Fixes stablyai#12101
Fixes stablyai#12112

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

* test(terminal): pin the cold-restore reset on the spawn-adopted reattach path

A spawn can be answered with an adopted session, which reaches the reattach
handler by a door that skips the restored-session path. Pin that the cold-restore
signal survives it, so stablyai#12101's junk cannot come back through it.

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

* test(terminal): note why the adopted-reattach snapshot leaves the cursor visible

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

* fix(terminal): harden startup reply delivery

---------

Co-authored-by: Orca <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant