Repository navigation
Conversation
📝 WalkthroughWalkthroughThe 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)
✅ 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: 5
🧹 Nitpick comments (10)
src/shared/terminal-sgr-load.ts (1)
28-53: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReset the leading wrapper only when the strip actually removed a sequence.
The function always prepends and appends
\x18\x1b[0m, even whendatacontains no SGR sequence andoutputstays 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:
protectDensePendingForInteractiveOutputclamps the delta withMath.max(0, ...), and both call sites gate onisDenseTerminalSgrfirst, 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
dataunchanged when no SGR sequence was found.src/shared/terminal-sgr-load.test.ts (2)
4-4: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove the stripping tests into their own
describe.The
describetitle states "dense terminal SGR classification", but lines 33–47 teststripTerminalSgr, 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 winAdd 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 thousand1;bytes, and assert both thatisDenseTerminalSgrreturnsfalseand thatstripTerminalSgrreturns 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 winDocument 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_CHARSandINTERACTIVE_DROP_RESTORE_QUIET_MSare 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 winThe non-dropped branch is unreachable from the only caller.
getDiscardedPendingQueryDatais called once, at Line 3117, and that call sits insideif (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_STATEand runs a freshextractDroppedPtyQueryBytesover 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 winDedupe the restore marker here as the sibling path does.
This function sends the
interactive-dropmarker unconditionally, then adds the PTY tointeractiveDenseRestoreMarkedPtys. 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.datano longer classifies as dense, and after a dense drop the pending is deleted, so a second call returnsfalseat 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 winRestructure 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
isDenseTerminalSgrscan last, so a cheap length or projection rejection avoids it.
6778-6782: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated input bookkeeping.
writePtyInputandwritePtyInputAcceptednow repeat the same three-step sequence:notePtyInput, the conditionalinteractiveDenseProtectionPtys.add, thenprioritizePendingPtyDataForInput. The order matters, becausenotePtyInputclears the dense sets when the input gap exceedsINTERACTIVE_DROP_RESTORE_QUIET_MSand 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 winAssert full byte equality for the preserved SSH output.
The test checks
delivered.length, the first 512 characters, the last 512 characters, and therawLengthsum. 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 therawLengthsum and thetransformedassertions, 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 winAdd coverage for a
foreground: falsedense-SGR write.All four new tests use
foreground: truewithlatencySensitive: false. None writes dense SGR data withforeground: false. That background path is wheredenseParseBlockedTerminalscan never release the block (see the linked critical finding inpane-terminal-output-scheduler.ts, Lines 969-980), because the pacer that releases the block is only created whenentry.highPriorityis 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.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-input-write-queue.test.tssrc/renderer/src/components/terminal-pane/pty-input-write-queue.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.tssrc/shared/pty-model-restore-marker.tssrc/shared/terminal-sgr-load.test.tssrc/shared/terminal-sgr-load.tstests/e2e/terminal-dense-sgr-echo-latency.spec.ts
bb14a20 to
dbdabe1
Compare
|
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. |
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. |
|
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. |
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:
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.
The final live Docker/OpenSSH Electron matrix also passed 4/4:
Reliability contract
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.tests/e2e/terminal-dense-sgr-echo-latency.spec.tsmeasures 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.terminal-performance.output-backpressure-budgetgate, plus the diagnostic Electron oracle and deterministic unit coverage in this PR.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:
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 typecheckpnpm run lintpnpm run check:code-quality:changed -- origin/main— 0 findingsWSL_SGR_OK 2.7msWINDOWS_SGR_OK 1.6msSecurity 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
undefinedor a boolean. PTY-scoped sets and restore timers clear on teardown, exit, renderer lifecycle reset, rebind, and dispose.