Repository navigation
fix(terminal): reset stale mouse tracking on cold restore (#12101); stop OSC color-reply echo leak in POSIX agent panes (#12112) - #12202
Conversation
…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]>
|
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:
📝 WalkthroughWalkthroughThe 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 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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.
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
settlewaits on wall-clock time.
settleawaits 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 winConsider centralizing
RESET_MOUSE_REPORTINGto 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. Sincesrc/shared/already hosts logic shared between main and renderer for the PTY-startup-reply layer, moveRESET_MOUSE_REPORTINGthere 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 winAdd coverage for the "escape tail only" branch.
The sentinel test here covers
recovered.length === 0 && !escapeTail. The sibling condition,recovered.length === 0withpendingEscapeTailAnsitruthy, is not covered by any test. In that case,getRecoveredHistorySeedSegmentsreturns[RESET_MOUSE_REPORTING, escapeTail]per Lines 22-27 of the source. Add a test case with emptyrehydrateSequences/snapshotAnsiand a non-emptypendingEscapeTailAnsito lock in this behavior.src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts (1)
154-156: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis assertion cannot fail regardless of the fix.
historySeedChunksare written tothis.emulatorviawriteSync, not tothis.subprocess, per Session's constructor. At this point in the test, no code path pushes ontoshellPty.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 inspectshell.getSnapshot()directly. Remove this assertion or replace it with something that inspects data actually written to the subprocess (e.g., after ashell.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
📒 Files selected for processing (9)
src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.tssrc/main/daemon/terminal-history-seed-segments.test.tssrc/main/daemon/terminal-history-seed-segments.tssrc/main/ipc/pty.test.tssrc/renderer/src/components/terminal-pane/issue-12112-agent-pane-startup-color-reply-leak.repro.test.tssrc/shared/pty-startup-ingress-contract.tssrc/shared/pty-startup-ingress.test.tssrc/shared/pty-startup-ingress.tssrc/shared/pty-startup-reply-delivery.ts
Greptile SummaryTwo 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/5Both 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.
|
| 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)
-
src/shared/pty-startup-ingress.test.ts, line 787-800 (link)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) butvi.useRealTimers()is only restored inside the test body of some cases and never in anafterEach. If any assertion inside a test that calledvi.useFakeTimers()throws before reaching the cleanup, vitest enters the next test while fake timers are still active. AddingafterEach(() => vi.useRealTimers())to the top-leveldescribeblock 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!
-
src/shared/pty-startup-reply-delivery.ts, line 352-370 (link)Echo budget charged against all entries even on a partial match
When
matchEchofinds no complete match,chargeEchoSearch(data.length)charges the full span length against every entry'sremainingCharsbudget, 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. WithECHO_SEARCH_BUDGET_CHARS = 8192this 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
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
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: 4a34d1e3-daeb-4b93-9143-531d684601a8
📒 Files selected for processing (25)
src/main/daemon/hibernation-cold-restore-repro.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.tssrc/main/daemon/repro-7329-remote-snapshot-corruption.test.tssrc/main/daemon/session.tssrc/main/daemon/terminal-history-seed-segments.test.tssrc/main/daemon/terminal-history-seed-segments.tssrc/main/providers/local-pty-provider.tssrc/relay/pty-handler.tssrc/renderer/src/components/terminal-pane/layout-serialization.test.tssrc/renderer/src/components/terminal-pane/layout-serialization.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/terminal-replay-cursor-state.test.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/shared/pty-slave-line-discipline-echo.test.tssrc/shared/pty-slave-line-discipline-echo.tssrc/shared/pty-startup-ingress-contract.tssrc/shared/pty-startup-ingress.test.tssrc/shared/pty-startup-ingress.tssrc/shared/pty-startup-reply-delivery.tssrc/shared/terminal-mode-reset-profiles.test.tssrc/shared/terminal-mode-reset-profiles.tssrc/shared/terminal-restore-parity-fixture.tstests/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]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (2)
9048-9048: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert 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 usessessionId: 'tab-pty'and the second call has nosessionId.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 winVerify that the reset follows the replay snapshot.
The test checks only that
POST_REPLAY_MODE_RESETappears 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
📒 Files selected for processing (1)
src/renderer/src/components/terminal-pane/pty-connection.test.ts
…sor visible Co-authored-by: Orca <[email protected]>
…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]>
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;12Mtypes itself at your prompt.The fix has two halves, because the stale note is read by two different readers:
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:
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, realbash -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 betweenHEADand this branch. This is the pane text a user would see: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:
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, realbash -i, with the foreground program issuing the query itself so the reply lands while readline owns the tty:The mutation is one line — treating the probe's
quietas 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.tsand re-running:The second failure is the user-visible symptom read off a real
@xterm/headlessterminal:expected 'any' to be 'none'onterm.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.tsfailsignores 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:
quiet(the pre-fix design)still suppresses the readline echo on a slave the probe called quietretires only the kernel caret projection once the probe proves ECHO is clearstops polling a tty that never leaves cooked mode and answers it anyway,gives a later query its own probe budgetunknownas proof the kernel is quietfalls back to recognizing echo shapes when the probe cannot answergives a later query its own probe budget, not the first query remainderkeeps probing after a transient failure and only latches a permanent one50/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→reapSessiondisposes the emulator in the same synchronous turn, so a reset written there reaches no snapshot and no file.TerminalModesis 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,rehydrateSequencesand SerializeAddon's mode trailer insidesnapshotAnsi. A fix touching onlybuildRehydrateSequenceswould 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-sidePtyStartupIngress, and it answered synchronously insideonDatawhile the tty was still cooked. Suppression existed but was gated onownerBackend === 'windows-conpty'from the #9432 fix.Why the diff is this size
27 files, but the shape is lopsided on purpose:
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) andterminal-mode-reset-profiles.ts(41). The first two are reply-write timing and line-discipline state lifted out ofpty-startup-ingress.tsso 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.tsis 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
ECHOis 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.tsreads the flag off the slave device and answersechoing/quiet/unknown. On POSIX the reply is withheld until the answer isquiet, 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. Aquietverdict 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
ECHOoff. The probe's verdict says nothing about this one, so its projection stays armed on every path,quietincluded. 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
quietgates the withholding and retires exactly one projection. It is never read as "no suppression needed."unknownis never read asquieteither — 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):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 missingsttylatches the probe off for the pty's life.Verified against a real
node-pty, both line-discipline states: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 inlayout-serialization.tsis 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-scanseat 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:echoPending(later bytes) was flushed beforequeryPending(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.HEAD. The charge is now taken once per PTY read at the single entry point, in afinally, where no return path can skip it.^[]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.!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.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.gap=49ms -> ""vsgap=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.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:
quietverdict as proof that no echo could occur and registered no projection at all. Butquietis proof only about the kernel; readline echoes a master write in software with the tty already raw andECHOoff. 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 scopingquietto 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.EAGAIN/EMFILEand 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
ECHOcopies bytes to the master but does not consume them from the slave input queue; the common Go and Rust TUI runtimes useTCSANOW, notTCSAFLUSH). It would have injected duplicate replies into opencode's raw-mode stdin — recreating the symptom. Removed entirely. Another caught the #12101 fix destroying thelength === 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 theECHObit could not be read without a nativetcgetattr, that claim was checked, and it was also false.Testing
All of the below ran on the merged tree (
mainmerged in ata4944f5343; one import-order conflict inlocal-pty-provider.ts, both sides kept):pnpm lint— exit 0pnpm typecheck— exit 0 (all 3 tsconfig projects)src/shared,src/main/daemon,src/main/providers,src/relay) —6780 passed | 20 skipped | 2 failed, both pre-existingsrc/) —43701 passed | 76 skipped | 3 failed, all 3 accounted for belowpackage (windows),native-smoke (ubuntu-22.04), Git compatibility, static analysis)node-ptyin both line-discipline states, and end-to-end through the production ingress at a realbash -iprompt — 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 endsbash-3.2$ \x0710;rgb:2e2e/3434/3434. An out-of-band read of the same slave device reported-echowhile 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 insteadechoingandquiet, each cross-checked against an out-of-band read of the same device) and end-to-end suppression under three independentsttyimplementations — the GNU userland and the two common multicall-binary variants — covering both the-fand-Fargument arms. The false-quietattack found nothing: unparseable output, empty output, echo-suffixed tokens with no bareecho, and-echoappearing inside an error string all land onunknown, neverquiet. 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 onunknown.isPermanentSttyFailurelatching confirmed behaviorally: a missingsttyand a non-zero exit latch (measured 1 spawn across 3 polls — the process-per-poll guard), while a timeout-kill and a genuineEMFILE(fd table exhausted under a lowerednofilelimit) 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 runThe 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
-farm). Windows needs none by construction: the probe isundefinedthere.src/relay/agent-exec-handler.test.ts(2) — fails identically on a cleanorigin/mainworktree; 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 onmainand macOS-only. Bothupdater.tsandupdater.test.tsare byte-identical tomain's tip at this branch's HEAD;updater.ts:863selects its error string onprocess.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.tscrashes 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_modulesaftermainupdated its xterm patch, and they pass afterpnpm install(124/125). Earlier sweeps also showedai-vault-session-worktree-map.test.tsx(a194ms < 150mswall-clock budget),transcript-watch-liveness.test.ts,remote-runtime-shared-control-connection.test.tsandpty-connection.test.tsflaking 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-scanseat 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 thatmainhad 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.Cross-platform was explicitly checked. #12112 branches on
PtyOwnerBackend:posix-pty(Linux/macOS) defers + suppresses;windows-conptykeeps its synchronous write because it must beat conhost's own responder;windows-wslis byte-identical toHEAD, verified againstgit show HEAD:src/shared/pty-startup-ingress.ts. The probe is not even constructed off POSIX — no slave path, nostty. #12101's path is shared by POSIXSIGKILLand Windowstaskkill /T /F— both land in the same "checkpoint on disk,endedAtnull, fresh spawn seeded from disk" flow. Seat 06 traced the versioned daemon↔app boundary (measureTerminalHistorySeed,result.historySeededon old daemons,canReanchorHistoryatdaemon-pty-adapter.ts:708) for scrollback-loss risk under new-app/old-daemon and rollback — clean. NometaKey, 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.jsonscript, workflow, install-hook, or binary changes in this PR — verified, not assumed. Specific risks reviewed:terminalOscColorQueryRepliesand are validated upstream; no untrusted process output is reflected back into the PTY write.stty, resolved viaPATH, 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 hostilePATHis already game over for a terminal app that spawns the user's shell, so this adds no new trust.checkpoint.json. The injected constant is a fixed literal, not checkpoint-derived; checkpoint trust is unchanged by this PR.eval, shell execution, or new network sinks. No IPC payload shape changed.Notes
Honest limitations — please read before merging:
stty -a -f <dev>on macOS/BSD,-Fon the GNU userland) have now been executed against live ptys on the merged tree, under three independentsttyimplementations, with bothechoingandquietverdicts 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 isundefinedthere by construction. If an invocation is ever wrong the probe answersunknown, which degrades to shape recognition rather than to a leak.windows-wsl. That path is deliberately byte-identical toHEAD(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.echoPendingandqueryPendingcan 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.unknownthe kernel's caret projection comes back too, with the same caveats.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.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 fromHEAD(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".quietverdict ages before it is used. Measured ~2.5–6.5 ms between the probe returning and the write landing. IfECHOflips back on inside that window the caret echo leaks unsuppressed, becausequietretired 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.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 ansttythat hangs.reattachReplayResetSequencecall 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):
excludeModes: truetoSerializeAddoninheadless-emulator.tsand wideningTerminalModes, sobuildRehydrateSequencesbecomes 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.terminal-capability-replies.ts, headlessterminal-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) andapplicationCursor(?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 -echoctland zsh/ZLE are unmodeled third shapes and leak — unchanged fromHEAD, 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 trailingESCwould make every torn read an echo candidate and strand real queries.) Neither repro test is registered inconfig/reliability-gates.jsonc. Onwindows-conptyonly, a strayESClanding immediately before the echo can still absorb its first few bytes: that projection is ESC-stripped, soESC+ the echo's head parses as a partial OSC and the candidate consumes it before being disproven. Byte-identical toHEAD— the two POSIX projections cannot be extended out of a bareESCthis way, so POSIX is clean at every split.Made with Orca 🐋