Skip to content

fix(terminal): keep input responsive during dense SGR output - #12624

Draft
nwparker wants to merge 2 commits into
mainfrom
nwparker/fix-terminal-keep-keystroke-echo-responsive-unde
Draft

nwparker wants to merge 2 commits into
mainfrom
nwparker/fix-terminal-keep-keystroke-echo-responsive-unde

Conversation

@nwparker

@nwparker nwparker commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #12523.

Dense per-character SGR output parses about 50× slower than plain text in xterm. That lets renderer, parser, and main-delivery FIFO backlogs place seconds of work ahead of the real shell echo for a keystroke.

This change bounds that delay while keeping ordinary output behavior intact:

  • pace dense output from xterm's parse-completion callback in 4 KiB slices;
  • when real input meets a measured dense backlog, discard only stale queued dense chunks, settle their ACK credit, and retain ordinary output and terminal queries;
  • strip SGR styling in main only after measured saturation, preserving text, queries, raw sequence lengths, and source accounting;
  • exclude source-tracked SSH projection spans from transformation;
  • repaint from the exact authoritative terminal snapshot after 500 ms of typing quiet.

Unsaturated output remains byte-identical. The implementation does not add a priority delivery lane or a stateful SGR normalizer.

ELI5

Dense color output is like putting thousands of tiny decorated cards in front of every typed character. Orca now lets xterm process only a small stack at a time. When the user types, it removes only stale decoration-heavy cards still waiting in line, preserves normal output and terminal questions, shows the real shell echo promptly, then repaints from the authoritative terminal snapshot after typing pauses.

Measurement

The Electron diagnostic sends 26 real key events at a 250 ms cadence into the same PTY that emits the issue's per-character SGR shape. It measures keydown to the matching echo being parsed by xterm; a missing echo fails the run.

Workload Echoes p50 p95 max
Issue baseline, per-character SGR 26/26 ~0.3–3 s ~0.6–8 s ~2–10 s
Final plain control 26/26 11.6 ms 18.9 ms 19.0 ms
Final 8× dense-SGR overload 26/26 11.3 ms 47.8 ms 61.4 ms

The final live Docker/OpenSSH Electron matrix also passed 4/4:

Scenario Result
TUI stream 3.2 ms median, 110.8 ms worst
Background ACK-stalled SSH PTY 4.0 ms median, 6.6 ms worst
File streams plus Git churn 146.3 ms median, 164.2 ms worst
Disconnect/reconnect passed

Reliability contract

  • Invariant: terminal-performance.output-backpressure-budget — dense display styling cannot starve focused input; ordinary bytes and terminal queries survive saturation, ACK credit stays balanced, source-tracked SSH bytes remain exact, and simplified display state converges from the authoritative snapshot.
  • Failure source: [Bug]: Terminal input echo lags 1-3s while agent streams dense-SGR output #12523.
  • Oracle: tests/e2e/terminal-dense-sgr-echo-latency.spec.ts measures real keyboard-to-xterm parse latency and exact echo cardinality. Lower-layer tests prove query retention, incomplete-sequence fencing, source accounting, ACK cleanup, and restore timing.
  • Gate: existing experimental terminal-performance.output-backpressure-budget gate, plus the diagnostic Electron oracle and deterministic unit coverage in this PR.
  • Provider/platform coverage: macOS Electron measured directly; Docker/OpenSSH exercised Linux and live SSH; exact-source assertions ran in WSL2 Ubuntu and native Windows; Windows packaging CI passed. Local and daemon PTYs share the tested delivery pipeline. Mobile/relay wire contracts are unaffected.
  • Performance budget: plain and unsaturated output remain on existing paths; dense scans and queues are bounded, xterm admits one dense slice at a time, and no polling, subprocess fanout, or persistent wake loop was added.
  • Diagnostics: existing scheduler/main delivery snapshots expose queue, in-flight, and drop pressure. Bounded crash breadcrumbs record dropped character counts without terminal contents.
  • Residual gap: no live installed Windows/ConPTY Electron dense-latency run was available. Exact-source native Windows/WSL checks and Windows package CI passed; Linux/SSH has the stronger live Electron coverage.

Contributor PR comparison and credit

#12525 is the only other open PR found for #12523. It correctly identified xterm parsing as the bottleneck and the value of 4 KiB parse-clock slices; this implementation adopts that insight and credits its author in the commit trailer:

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

The implementations make different reliability trade-offs:

  • fix(terminal): keep keystroke echo responsive under dense-SGR output floods #12525 always normalizes dense SGR and adds a dedicated interactive lane; this PR transforms styling only after measured saturation and keeps the existing delivery/accounting lane.
  • This PR retains non-SGR bytes and terminal queries instead of dropping mixed flood-plus-echo payloads.
  • This PR avoids cross-slice style state and repairs temporary display simplification from the authoritative snapshot.
  • Source-tracked SSH spans remain byte-exact.

Production-code diff: this PR is +500/-76; #12525 is +760/-32. That is 34.2% fewer added production lines. This PR's total diff is larger because it adds 902 lines of repro, latency, failure-path, SSH, ACK, and recovery tests.

Testing

  • pnpm run typecheck
  • pnpm run lint
    • reliability manifest: 66 gates
    • max-lines ratchet
    • localization and bundled-skill checks
  • pnpm run check:code-quality:changed -- origin/main — 0 findings
  • touched terminal matrix — 1,194 tests passed
  • final Electron latency diagnostic — plain and 8× dense-SGR workloads, 52/52 echoes
  • live Docker/OpenSSH Electron matrix — 4/4 passed, including disconnect/reconnect
  • WSL2 Ubuntu exact-source assertion — WSL_SGR_OK 2.7ms
  • native Windows exact-source assertion — WINDOWS_SGR_OK 1.6ms
  • GitHub CI — static analysis/typecheck; Node 24 and 26 across all 32 shards; changed E2E specs; Git compatibility; macOS and Windows packaging

Security and compatibility

No dependency, lockfile, binary, persistence, auth, route, command-execution, or new network changes. No mobile-facing RPC/protocol surface changed. The renderer backlog hint is additive and optional; older renderers omit it, and runtime validation accepts only undefined or a boolean. PTY-scoped sets and restore timers clear on teardown, exit, renderer lifecycle reset, rebind, and dispose.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PTY pipeline now classifies dense ANSI SGR output and limits its scheduling impact. Renderer input can prioritize queued input and report dropped backlog through the preload and IPC layers. The main process strips dense styling, preserves bounded query data and output metadata, and emits restore markers. The renderer delays interactive restoration, forwards backlog state through input queues, and cancels pending restoration during disposal. Tests cover scheduler behavior, PTY delivery, IPC validation, renderer recovery, and diagnostic latency measurements.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.53% 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 The implementation addresses issue #12523 by pacing dense SGR output, protecting input, preserving non-SGR data, and restoring terminal state.
Out of Scope Changes check ✅ Passed The code and tests remain focused on dense SGR terminal output, input latency, backlog handling, delivery accounting, and restoration.
Title check ✅ Passed The title clearly and concisely describes the main change: keeping terminal input responsive during dense SGR output.
Description check ✅ Passed The description thoroughly explains the change, testing, security, compatibility, risks, and residual gap, despite omitting some template headings.
✨ 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: 5

🧹 Nitpick comments (10)
src/shared/terminal-sgr-load.ts (1)

28-53: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reset the leading wrapper only when the strip actually removed a sequence.

The function always prepends and appends \x18\x1b[0m, even when data contains no SGR sequence and output stays empty. In that case the return value is 8 characters longer than the input and injects a CAN plus a style reset that the source never emitted.

The current callers protect themselves: protectDensePendingForInteractiveOutput clamps the delta with Math.max(0, ...), and both call sites gate on isDenseTerminalSgr first, so a no-SGR input does not reach here today. The unconditional wrapper is still a trap for a future caller that strips unconditionally and then compares lengths or relies on byte-identity.

Consider returning data unchanged when no SGR sequence was found.

src/shared/terminal-sgr-load.test.ts (2)

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

Move the stripping tests into their own describe.

The describe title states "dense terminal SGR classification", but lines 33–47 test stripTerminalSgr, not classification. Split the block so a failure name identifies which helper broke.

Also applies to: 33-47


43-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for a long unterminated CSI.

The suite covers a short incomplete CSI tail (\x1b[38;5). It does not cover a long unterminated parameter run, which is the input that makes both scanners rescan the same tail once per character. Add a case such as \x1b[ followed by a few thousand 1; bytes, and assert both that isDenseTerminalSgr returns false and that stripTerminalSgr returns the tail unchanged inside the wrapper. That case also pins the behavior if the loop is changed to stop at an unterminated sequence.

src/main/ipc/pty.ts (5)

2444-2445: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the rationale for the two new thresholds.

Every neighboring constant in this block carries a "Why" comment that states the tuning reason (see PTY_BATCH_INTERVAL_MS, PTY_RENDERER_INTERACTIVE_RESERVE_CHARS, INTERACTIVE_OUTPUT_WINDOW_MS). INTERACTIVE_DENSE_BACKLOG_DROP_CHARS and INTERACTIVE_DROP_RESTORE_QUIET_MS are both tuned magic numbers that gate user-visible behavior: the first decides when a backlog is large enough to strip, and the second decides how long typing must stop before dense protection is released. State why 32 KiB and 500 ms were chosen so a later tuning pass has the constraint.


3086-3098: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The non-dropped branch is unreachable from the only caller.

getDiscardedPendingQueryData is called once, at Line 3117, and that call sits inside if (pending.droppedOutput === true). The function then re-tests the same condition, so lines 3093–3097 never execute.

Remove the dead branch and the redundant condition, or keep the branch and drop the caller's guard so one place owns the decision. As written the second path also implies a state the caller never produces: it reseeds the mode-2031 scan from INITIAL_MODE_2031_REPLY_SCAN_STATE and runs a fresh extractDroppedPtyQueryBytes over the full buffer, which would be a full rescan of an arbitrarily large pending buffer if it were ever reached.

♻️ Proposed simplification
-  function getDiscardedPendingQueryData(pending: PendingPtyData): string {
-    if (pending.droppedOutput === true) {
-      return (pending.data + getDroppedMode2031RendererData(pending)).slice(
-        0,
-        DROPPED_QUERY_SALVAGE_MAX_CHARS
-      )
-    }
-    const mode2031 = scanDroppedMode2031Data(pending.data, INITIAL_MODE_2031_REPLY_SCAN_STATE)
-    return (extractDroppedPtyQueryBytes(pending.data) + mode2031.data).slice(
-      0,
-      DROPPED_QUERY_SALVAGE_MAX_CHARS
-    )
-  }
+  // Only called for a droppedOutput sentinel, whose data already holds just salvaged query bytes.
+  function getDiscardedPendingQueryData(pending: PendingPtyData): string {
+    return (pending.data + getDroppedMode2031RendererData(pending)).slice(
+      0,
+      DROPPED_QUERY_SALVAGE_MAX_CHARS
+    )
+  }

3132-3134: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Dedupe the restore marker here as the sibling path does.

This function sends the interactive-drop marker unconditionally, then adds the PTY to interactiveDenseRestoreMarkedPtys. The other emitter of the same reason, at Line 3740, checks the set first:

if (collapseDenseStyling && !interactiveDenseRestoreMarkedPtys.has(payload.id)) {

Both paths write the same set, so the set expresses a "one marker per protection episode" rule that only one path enforces. Today the guards make a duplicate unreachable: after a strip, pending.data no longer classifies as dense, and after a dense drop the pending is deleted, so a second call returns false at the entry guard. The invariant therefore rests on the classifier's behavior rather than on the flag that exists to record it.

Check the set here too. A duplicate marker costs the user a second full pane repaint.

♻️ Proposed consistency fix
     updateProducerFlowControl(id)
-    sendModelRestoreNeededMarker(id, 'interactive-drop', markerSeq, discardedQueryData)
+    if (!interactiveDenseRestoreMarkedPtys.has(id)) {
+      sendModelRestoreNeededMarker(id, 'interactive-drop', markerSeq, discardedQueryData)
+    }
     interactiveDenseProtectionPtys.add(id)
     interactiveDenseRestoreMarkedPtys.add(id)
     return true

3105-3114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Restructure the guard as positive early returns.

The predicate negates a compound expression that contains a nested ternary across two different pending shapes. A reader must invert three OR-ed clauses to learn when the function proceeds. This predicate decides whether buffered terminal output is discarded or rewritten, so it should be readable without inversion.

♻️ Proposed restructure
-    if (
-      !pending ||
-      (pending.droppedOutput === true
-        ? pending.denseSgrDrop !== true
-        : pending.data.length <= INTERACTIVE_DENSE_BACKLOG_DROP_CHARS ||
-          !isDenseTerminalSgr(pending.data) ||
-          pending.projectionAdmissionIds !== undefined)
-    ) {
-      return false
-    }
+    if (!pending) {
+      return false
+    }
+    if (pending.droppedOutput === true) {
+      // A cap drop is protectable only when it was classified as a dense SGR drop.
+      if (pending.denseSgrDrop !== true) {
+        return false
+      }
+    } else if (
+      pending.data.length <= INTERACTIVE_DENSE_BACKLOG_DROP_CHARS ||
+      // Source-tracked SSH spans keep their reserved display/accounting mapping.
+      pending.projectionAdmissionIds !== undefined ||
+      !isDenseTerminalSgr(pending.data)
+    ) {
+      return false
+    }

The reorder also moves the isDenseTerminalSgr scan last, so a cheap length or projection rejection avoids it.


6778-6782: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated input bookkeeping.

writePtyInput and writePtyInputAccepted now repeat the same three-step sequence: notePtyInput, the conditional interactiveDenseProtectionPtys.add, then prioritizePendingPtyDataForInput. The order matters, because notePtyInput clears the dense sets when the input gap exceeds INTERACTIVE_DROP_RESTORE_QUIET_MS and must therefore run before the add. Two copies let that ordering drift.

Extract a single helper so one place owns the sequence.

♻️ Proposed extraction
+  const notePtyInputForWrite = (args: PtyWritePayload, now: number): void => {
+    // Order matters: notePtyInput may clear dense protection after a quiet gap.
+    notePtyInput(args.id, now)
+    if (args.rendererBacklogDropped) {
+      interactiveDenseProtectionPtys.add(args.id)
+    }
+    prioritizePendingPtyDataForInput(args.id)
+  }

Then both handlers call notePtyInputForWrite(args, now) in place of the three lines.

Also applies to: 6806-6810

src/main/ipc/pty.test.ts (1)

16428-16435: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert full byte equality for the preserved SSH output.

The test checks delivered.length, the first 512 characters, the last 512 characters, and the rawLength sum. Together those make a corruption in the middle unlikely, but they do not exclude it: a transformation that removed one sequence and inserted another of equal length inside the body would pass.

The stated property is that source-tracked projection bytes are preserved exactly. Assert that directly with expect(delivered).toBe(dense). The check is cheaper to read and it cannot miss an interior change. Keep the rawLength sum and the transformed assertions, which cover the accounting metadata rather than the bytes.

💚 Proposed assertion
       const delivered = payloads.map(({ data }) => data).join('')
-      expect(delivered.length).toBe(dense.length)
-      expect(delivered.slice(0, 512)).toBe(dense.slice(0, 512))
-      expect(delivered.slice(-512)).toBe(dense.slice(-512))
+      expect(delivered).toBe(dense)
       expect(payloads.reduce((sum, payload) => sum + (payload.rawLength ?? 0), 0)).toBe(
         dense.length
       )
       expect(payloads.every((payload) => payload.transformed !== true)).toBe(true)
src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts (1)

1484-1507: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for a foreground: false dense-SGR write.

All four new tests use foreground: true with latencySensitive: false. None writes dense SGR data with foreground: false. That background path is where denseParseBlockedTerminals can never release the block (see the linked critical finding in pane-terminal-output-scheduler.ts, Lines 969-980), because the pacer that releases the block is only created when entry.highPriority is true.

Add a test that writes a dense chunk with foreground: false, advances timers, and asserts the terminal keeps draining subsequent background chunks instead of stalling.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1c969556-8156-42b7-bac7-9a88db87b2e8

📥 Commits

Reviewing files that changed from the base of the PR and between c511e51 and bb14a20bf8cc04bddceab80f93c93ecc303390c6.

📒 Files selected for processing (18)
  • src/main/ipc/pty-pending-data-drain-contract.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.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/pty-input-write-queue.test.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts
  • src/shared/pty-model-restore-marker.ts
  • src/shared/terminal-sgr-load.test.ts
  • src/shared/terminal-sgr-load.ts
  • tests/e2e/terminal-dense-sgr-echo-latency.spec.ts

Comment thread src/main/ipc/pty.ts Resolved
Comment thread src/main/ipc/pty.ts Resolved
Comment thread src/shared/terminal-sgr-load.ts Resolved
@nwparker
nwparker force-pushed the nwparker/fix-terminal-keep-keystroke-echo-responsive-unde branch from bb14a20 to dbdabe1 Compare August 5, 2026 04:17
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@AmethystLiang

Copy link
Copy Markdown
Contributor

Related PR (not auto-closed as duplicate)

#12525 (by issue author @fsdwen) also targets #12523 with a dense-SGR / keystroke-echo approach (SGR density normalizer + output scheduler + e2e). Both PRs are substantial with different surfaces — leaving both open for maintainer pick. Coordinate so only one lands, or cherry-pick complementary pieces.

@OrcaWin

OrcaWin commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-08-05T19:43:59Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

This branch has not been deployed

No deployments
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 input echo lags 1-3s while agent streams dense-SGR output

3 participants