Skip to content

Fix delayed terminal color-scheme replies leaking into fish - #8206

Merged
nwparker merged 2 commits into
mainfrom
nwparker/bug-terminal-leaks-dsr-escape-sequence-responses
Jul 11, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/bug-terminal-leaks-dsr-escape-sequence-responses

Conversation

@nwparker

@nwparker nwparker commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #8128.

fish 4.7.1 subscribes to terminal color-scheme updates with CSI ?2031h and expects the terminal's CSI ?997;1n/;2n response while it still owns a short raw-input read window. The visible-pane responder used ordinary remote input batching, so an 8 ms-delayed response could arrive after fish ran CSI ?2031l and handed input to a foreground command. The escaped response then appeared as ^[[?997;1n.

This PR:

  • routes visible mode-2031 seed and theme-flip replies through sendInputImmediate, matching other latency-sensitive terminal-query responders;
  • rechecks the live mode-2031 subscription before every bounded pre-connect retry, so ?2031l cancels a stale seed;
  • extracts the timing policy into terminal-mode-2031-replies.ts with deterministic regression tests.

Evidence of fix

Before: reproduced

Reproduction and protocol analysis: #8128 (comment)

A real fish 4.7.1 + node-pty + Orca xterm.js harness ran sleep 0.15 immediately after fish subscribed:

8 ms ordinary-input delay: leak=true  matches=["sleep 0.15", "^[[?997;1n..."] rawEcho=true
0 ms immediate control:   leak=false matches=["sleep 0.15"]                 rawEcho=false

This was rerun after implementation with the same result, proving the timing oracle independently of mocks. No external downloads or untrusted artifacts were used.

After: fixed source path

pnpm exec vitest run --config config/vitest.config.ts \
  src/renderer/src/components/terminal-pane/terminal-mode-2031-replies.test.ts \
  src/renderer/src/components/terminal-pane/terminal-appearance.test.ts \
  src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts
Test Files  3 passed (3)
Tests       28 passed (28)

The regression oracle proves that the visible mode-2031 response calls sendInputImmediate with CSI ?997;1n, never calls ordinary sendInput, and sends nothing when a queued pre-connect attempt runs after unsubscribe. Existing remote-transport coverage also proves immediate replies flush earlier typed bytes in order before bypassing the 8 ms batch.

Additional checks:

  • pnpm typecheck:web — passed.
  • focused oxlint on all five changed files — passed.
  • pnpm check:max-lines-ratchet — passed; no new suppression.
  • pnpm check:reliability-gates — passed.
  • Pre-rebase full pnpm test — 26,490 passed, 33 skipped, one unrelated 100-tab wall-clock threshold failure (57.17 ms > 50 ms); the isolated test rerun passed (1/1, 51 ms total test duration).
  • Full pnpm lint reached an unrelated existing Japanese localization interpolation mismatch at components.native-chat.composer.uploadingAttachments; changed-file lint and all relevant gates passed.

ELI5

fish briefly asks Orca, “am I using dark or light colors?” Orca knew the answer, but remote terminals sometimes held that tiny answer for 8 ms to batch it with typing. By then fish had stopped listening, so the answer was treated like text typed into the next command and printed as random characters. Orca now sends this terminal-only answer immediately, and throws it away if fish has already said it no longer wants updates.

User-facing trade-offs

  • Users should no longer see ^[[?997;1n/^[[?997;2n leak into fish prompts or foreground commands on delayed remote paths.
  • A rare mode-2031 subscribe/theme-change reply bypasses the normal 8 ms input batch. The immediate transport flushes pending user input first, preserving byte order, but may end one typing batch slightly early.
  • If a program unsubscribes while its PTY is still connecting, Orca intentionally drops the stale initial color reply. A later fresh subscribe still triggers a new reply.
  • No setting, UI, shell-specific filesystem assumption, or provider-specific protocol was added.

Terminal reliability proof

  • Reliability invariant: terminal-capability.query-reply-timeliness — a mode-2031 CSI 997 response must reach the subscribing program before its raw-read window closes, in byte order, and must never be sent for a subscription that has since been cleared. Motivated by [Bug]: Terminal leaks DSR escape sequence responses as garbled text (997;1n) with fish shell #8128.
  • Failure source: deterministic fish 4.7.1/node-pty/xterm reproduction of an 8 ms delayed remote-style reply escaping into the next input owner.
  • Material impact: makes delayed/stale color-scheme responses harder to reintroduce on visible panes; both immediate routing and unsubscribe-during-connect are pinned independently.
  • Product change type: mixed product runtime hardening and renderer contract coverage.
  • Manifest status: accepted gap. The adjacent experimental terminal-capability.startup-color-query gate is OSC 10/11-specific and remains unchanged. Intended future gate id is terminal-capability.mode-2031-reply-timeliness; this PR does not claim promotion from a mismatched gate.
  • Oracle: delayed real-fish reply renders ^[[?997;1n; immediate reply does not. Source-coupled tests require the immediate method and zero post-unsubscribe sends.
  • Performance risk inventory: touches rare mode-2031 subscribe/theme responses and the existing pane-connect retry only. It does not touch per-keystroke typing work, PTY output, rendering, focus, resize, startup awaits, provider listing, subprocesses, or retained buffers.
  • No-regression evidence: no new polling, timers, scans, provider calls, hidden-pane wakeups, or output buffering. The existing retry remains capped at eight total attempts/25 ms spacing; the stale-retry test proves unsubscribe stops rescheduling. Immediate remote input uses the existing ordered flush contract.
  • Diagnostics: the deterministic fish harness captures leak, matching rendered lines, and raw PTY echo; focused tests identify whether immediate routing or stale cancellation regressed. No raw-terminal telemetry/logging was added.
  • Provider/platform coverage: local PTY behavior covered by real fish on macOS and local immediate transport semantics; remote-runtime ordering covered by the existing immediate-reply transport test; daemon/local IPC uses the same immediate alias and is unaffected apart from routing; SSH uses the provider-neutral transport interface with no local filesystem/process assumption. Linux behavior is represented by fish protocol semantics but not live-tested in this run. WSL/Windows and mobile/relay are accepted live-test gaps; gate-managed hidden mode-2031 handling was already immediate and is unchanged; snapshot-skip, discarded-query salvage, and resubscribe-generation paths remain explicit follow-up gaps from the similar-class audit.
  • Residual gaps: no packaged Electron end-to-end run, live SSH host run, Linux host run, or Windows/WSL shell run. The real harness controls the response timing directly; the renderer contract test is the source-coupled after proof.
  • Promotion status: none — deterministic red/green coverage exists, but there is no registered manifest command or cross-platform stability history yet.
  • Rollback/demotion rule: revert or follow up if immediate mode replies reorder pending typed bytes, create duplicate theme responses, or a live provider shows a regression. Do not promote the future gate until remote/SSH and platform evidence is stable.

@nwparker
nwparker force-pushed the nwparker/bug-terminal-leaks-dsr-escape-sequence-responses branch from ebc2a68 to cc2ceec Compare July 11, 2026 03:44
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Mode 2031 seed and theme-flip replies are centralized in a new module using immediate transport sends. Seed replies retry while disconnected, revalidate pane subscription state, and record successful modes. Appearance handling imports the shared flip helper and no longer re-exports the sequence helper. Lifecycle seeding delegates pane state, transport, mode resolution, recording, and scheduling through injected callbacks. Tests cover immediate-send routing, retry cancellation, gating, failure handling, and per-pane isolation.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it doesn't follow the required template and lacks explicit Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Restructure the PR description to use the template headings and add concise content for screenshots, testing, AI review, security audit, and notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #8128 by sending mode-2031 replies immediately and canceling stale retries so leaked escape responses no longer reach visible output.
Out of Scope Changes check ✅ Passed The module split and tests are directly tied to the bug fix and no unrelated code changes are indicated.
Title check ✅ Passed The title clearly summarizes the main change: immediate routing of delayed terminal color-scheme replies leaking into fish.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/terminal-mode-2031-replies.test.ts (1)

67-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the retry-success path.

The suite covers the immediate-send routing and the unsubscribe cancellation, but doesn't verify that a scheduled retry actually delivers the reply when the transport connects while still subscribed. This is a core behavior of pushMode2031SeedReply and the harness already supports it.

♻️ Proposed test addition
   it('cancels a pre-connect retry after the program unsubscribes', () => {
     const harness = createHarness(false)

     harness.push()
     expect(harness.scheduled).toHaveLength(1)

     harness.subscribed.current = false
     harness.connected.current = true
     harness.scheduled.shift()?.()

     expect(harness.sendInputImmediate).not.toHaveBeenCalled()
     expect(harness.sendInput).not.toHaveBeenCalled()
     expect(harness.scheduled).toHaveLength(0)
   })
+
+  it('sends the reply when the transport connects during retry', () => {
+    const harness = createHarness(false)
+
+    harness.push()
+    expect(harness.scheduled).toHaveLength(1)
+
+    harness.connected.current = true
+    harness.scheduled.shift()?.()
+
+    expect(harness.sendInputImmediate).toHaveBeenCalledWith('\x1b[?997;1n')
+    expect(harness.sendInput).not.toHaveBeenCalled()
+    expect(harness.recordMode).toHaveBeenCalledWith(1, 'dark')
+  })
 })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d2fa06af-7e00-4eab-bb5b-51c7430668fb

📥 Commits

Reviewing files that changed from the base of the PR and between 5e10091 and 88397ef.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/terminal-appearance.test.ts
  • src/renderer/src/components/terminal-pane/terminal-appearance.ts
  • src/renderer/src/components/terminal-pane/terminal-mode-2031-replies.test.ts
  • src/renderer/src/components/terminal-pane/terminal-mode-2031-replies.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Terminal leaks DSR escape sequence responses as garbled text (997;1n) with fish shell

1 participant