Repository navigation
Conversation
…floods Typing into a pane whose agent streams character-level SGR styling (syntax- highlighted output parses ~50x slower than plain text in xterm) parks the keystroke echo behind the parse backlog in every FIFO layer, so keystrokes lag while the agent prints. Fix on three layers: - main (pty.ts): inside the 500ms input window, drop flood-size chunks before they queue and route echo-sized chunks onto a dedicated interactive lane that bypasses the flood-saturated in-flight window. Byte order is preserved because xterm's FIFO still parses the echo after already- delivered flood bytes. - renderer scheduler: freeze dense-SGR backlog delivery while the user types, pace dense-SGR batches on xterm's parse clock (at most one batch in flight per terminal), and drop the backlog once it exceeds 16KB inside the input window so echo latency stays bounded instead of growing with the flood. Plain-text output is unaffected. - renderer: normalize redundant SGR bytes (identical adjacent sequences, reset-then-covering-SGR) before the write via a strict, semantics- preserving state machine, cutting parse load without changing the rendered result. Add input-protection and interactive-lane counters to the delivery debug snapshot, unit tests for the SGR normalizer, and a diagnostic e2e repro that measures echo latency under dense-SGR output.
7a9f8cd to
c552766
Compare
📝 WalkthroughWalkthroughThe terminal output path now detects and normalizes dense SGR sequences. The scheduler tracks parse completion and recent user input, limits dense-SGR drains, and replaces eligible backlogs with warnings. PTY delivery adds post-input flood protection, a dedicated interactive lane, pending-tail classification, and delivery diagnostics. Terminal input paths mark recent user activity. A diagnostic Playwright test measures input and rendering latency under dense-SGR, plain-text, and disabled-output modes. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 12
🧹 Nitpick comments (7)
src/relay/git-handler-commit-diff-ops.ts (1)
104-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winType the merge dedup entries instead of casting each field.
Every field access casts from
unknown. That hides shape drift inparseBranchDiff. Declare a local entry type and cast once at the boundary.Note: the per-parent stats aggregation concern raised on
src/main/git/status.tslines 1687-1718 applies here as well, becauseparseNumstatalso receives the whole-mnumstat output.♻️ Proposed typed dedup
- const seenByPath = new Map<string, Record<string, unknown>>() - for (const entry of parsedEntries) { - const path = entry.path as string - const existing = seenByPath.get(path) - if (!existing) { - seenByPath.set(path, { ...entry }) - } else { - existing.added = Math.max((existing.added as number) ?? 0, (entry.added as number) ?? 0) - existing.removed = Math.max( - (existing.removed as number) ?? 0, - (entry.removed as number) ?? 0 - ) - if ((existing.status as string) === 'deleted' && (entry.status as string) !== 'deleted') { - existing.status = entry.status - existing.oldPath = entry.oldPath - } - } - } + type MergeDiffEntry = { + path: string + status: string + oldPath?: string + added?: number + removed?: number + } + const seenByPath = new Map<string, MergeDiffEntry>() + for (const raw of parsedEntries) { + const entry = raw as unknown as MergeDiffEntry + const existing = seenByPath.get(entry.path) + if (!existing) { + seenByPath.set(entry.path, { ...entry }) + continue + } + existing.added = Math.max(existing.added ?? 0, entry.added ?? 0) + existing.removed = Math.max(existing.removed ?? 0, entry.removed ?? 0) + if (existing.status === 'deleted' && entry.status !== 'deleted') { + existing.status = entry.status + existing.oldPath = entry.oldPath + } + }src/main/git/status.test.ts (1)
2485-2485: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd merge-commit coverage for
getCommitCompare.The existing cases cover the single-parent commit form only. The new merge branch in
loadCommitChangesis untested. Add a case whererev-list --parentsreturns two parents, then assert thediff-tree -margument arrays and the deduplicated entries, including thedeletedstatus replacement and the added/removed maxima. Add a root-commit case for the--rootform as well.I can generate these tests if you want.
src/renderer/src/lib/pane-manager/terminal-sgr-normalizer.test.ts (2)
9-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename this test;
normalizeSgrDensityapplies no density threshold.The density threshold lives in
isDenseSgr, which this test does not call. The input stays unchanged because each reset is followed by text, soflushPendingSgremits it. The current name suggests a gate that does not exist innormalizeSgrDensity.♻️ Proposed rename
- it('leaves sparse SGR output untouched (under density threshold)', () => { + it('keeps a reset that is followed by text', () => {
83-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove these three tests inside the
describeblock and add regression cases for state tracking.The
describe('normalizeSgrDensity')block closes at line 81, so the last three tests report at the file root. Also, the suite does not cover the two state-tracking paths where a reset can be dropped incorrectly:
- a combined reset such as
\x1b[0;1mfollowed later by\x1b[0m\x1b[32m- an OSC string between an active color and a later
\x1b[0m\x1b[1mBoth cases are described in my comments on
terminal-sgr-normalizer.ts.💚 Proposed regression tests
+ it('keeps the reset when a combined reset set attributes', () => { + expect(normalizeSgrDensity('\x1b[0;1mX\x1b[0m\x1b[32mY')).toBe( + '\x1b[0;1mX\x1b[0m\x1b[32mY' + ) + }) + + it('keeps SGR state across an OSC string', () => { + expect(normalizeSgrDensity('\x1b[31mX\x1b]0;title\x07\x1b[0m\x1b[1mY')).toBe( + '\x1b[31mX\x1b]0;title\x07\x1b[0m\x1b[1mY' + ) + })src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts (2)
1038-1046: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winNormalization is applied on the drain path only.
normalizeSgrDensityruns here, but the two other write paths keep the raw data:
flushTerminalOutputat lines 1443-1447 and 1461-1466, which already usesDENSE_SGR_CHUNK_CHARS.- The direct latency-sensitive foreground write at lines 1352-1363.
The echo write is small, so skipping it there is reasonable. The flush path can carry the full dense-SGR backlog, so it pays the full parse cost that this PR is trying to reduce. Consider normalizing there as well.
1220-1228: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the input-protection predicate; it now exists in three places.
The same three-part condition appears at lines 1220-1224, lines 1324-1328, and in the debug snapshot at lines 343-347. The debug snapshot omits the
denseSgrterm, so the reportedinputProtectionDropPendingvalue does not match the condition that actually drops the backlog. That divergence is exactly what a shared helper prevents.♻️ Proposed helper
+function shouldDropInputProtectedBacklog(entry: QueueEntry): boolean { + return ( + entry.denseSgr && + hasRecentTerminalInput(entry.terminal) && + entry.queuedChars > FOREGROUND_INPUT_SENSITIVE_BACKLOG_CHARS + ) +}Then use it at both write sites and in
exposeDebugApi.tests/e2e/diag-output-input-latency.spec.ts (1)
121-121: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe
nodecommand quoting is not Windows-safe.
JSON.stringify(scriptPath)escapes Windows separators, so a path such asC:\repo\.diag-sgr-x.mjsbecomes"C:\\repo\\.diag-sgr-x.mjs".cmd.exeand PowerShell do not unescape the doubled backslashes the way a JSON parser does, so the command fails on a Windows host.The test is diagnostic-only and gated by
ORCA_DIAG=1, but the repository requires commands to work on macOS, Linux, and Windows. Convert the path to forward slashes for the shell, or quote it without JSON escaping.Based on coding guidelines: "code, commands, and scripts must work on macOS, Linux, and Windows".
♻️ Proposed fix
- await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) + // Why forward slashes: Node accepts them on Windows, and cmd/PowerShell + // do not unescape JSON-doubled backslashes. + await sendToTerminal(orcaPage, ptyId, `node "${scriptPath.replace(/\\/g, '/')}"\r`)Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3b10b460-f79f-4bec-b62f-2474c1aafb2c
📥 Commits
Reviewing files that changed from the base of the PR and between 4734428 and 7a9f8cdf773216111a4b27d74b64fd9c3f084c62.
📒 Files selected for processing (12)
src/main/git/status.test.tssrc/main/git/status.tssrc/main/ipc/pty.tssrc/relay/git-handler-commit-diff-ops.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/i18n/locales/zh.jsonsrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.tssrc/renderer/src/lib/pane-manager/terminal-sgr-normalizer.test.tssrc/renderer/src/lib/pane-manager/terminal-sgr-normalizer.tssrc/shared/git-rev-list-output.test.tssrc/shared/git-rev-list-output.tstests/e2e/diag-output-input-latency.spec.ts
| "6f90ebe3fd": "在归档或删除工作树之前运行。", | ||
| "a3fc966677": "# e.g. pnpm install cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"", | ||
| "a3fc966677": "# 例如 pnpm install cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add a command separator to the hook example.
pnpm install cp ... is parsed as one pnpm install command. It does not run cp, so the example does not copy the environment file as described.
Proposed fix
- "a3fc966677": "# 例如 pnpm install cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"",
+ "a3fc966677": "# 例如 pnpm install; cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "a3fc966677": "# 例如 pnpm install cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"", | |
| "a3fc966677": "# 例如 pnpm install; cp \"$ORCA_ROOT_PATH/.env\" \"$ORCA_WORKTREE_PATH/.env\"", |
| "connecting": "连接中…", | ||
| "certificateChallengeExpired": "此证书批准已过期。重新加载页面以请求新批准。", | ||
| "certificateChallengeChanged": "证书请求已更改。重新加载页面并查看新警告。", | ||
| "certificateChallengeUnavailable": "此证书请求不再可用。重新加载页面以请求新的证书请求。", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use clear certificate-challenge wording.
The text repeats 证书请求 and can be read as a certificate-signing request. Use wording that identifies a browser certificate validation request.
Proposed fix
- "certificateChallengeUnavailable": "此证书请求不再可用。重新加载页面以请求新的证书请求。",
+ "certificateChallengeUnavailable": "此证书验证请求不再可用。重新加载页面以发起新的证书验证请求。",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "certificateChallengeUnavailable": "此证书请求不再可用。重新加载页面以请求新的证书请求。", | |
| "certificateChallengeUnavailable": "此证书验证请求不再可用。重新加载页面以发起新的证书验证请求。", |
… recovery Follow-up to the echo-latency fix, addressing review findings. - main: the input-protection drop now requires isDenseSgr (shared with the renderer scheduler), so typing never truncates plain-text floods or TUI repaints that parse fast — previously ANY >16KB chunk inside the input window was dropped (e.g. `npm run build` output right after Enter, vim full-screen repaints). - main: the interactive lane reuses the interactive in-flight gate instead of a 64KB lane-only budget, so a flood-saturated window (exactly when the echo needs the lane) no longer strands keystroke echo on the batch path. - main: fix lane projection bookkeeping (compactPendingProjectionState for the merged tail) and skip dropped pendings; fix the invalid `desktopSpan !== true` comparisons (TS2367). - renderer: drain once the input window expires so a dense-SGR backlog frozen while typing resumes even when the flood stops inside the window (previously it stranded until the next output chunk). - tests: density probe unit tests, scheduler freeze/recovery/plain-text regressions.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/shared/terminal-sgr-density.ts (1)
1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the explanatory comments.
Keep one short comment that states the shared density contract. Remove benchmark details and implementation walkthroughs from this module.
Proposed simplification
-/** - * Dense-SGR density probe shared by the main delivery gate (input-protection - * drop) and the renderer output scheduler (freeze/drop/parse-clock pacing). - * - * Why: character-level SGR styling parses ~50x slower than plain text in - * xterm. The main gate must use the SAME threshold as the renderer scheduler, - * or it would drop ordinary plain-text floods and TUI repaints (which parse - * fine) while the user types. - */ +/** Classify dense SGR chunks for shared output handling. */ @@ - // Character-level highlighting emits ~1 SGR per character; the parse-starved - // threshold is one SGR per ~2 characters. Non-SGR CSI (cursor moves, DEC - // modes) does not count. Token/word-level styling (~1 per 10+ chars) parses - // fine and must NOT trip the input-protection freeze. + // Use one SGR per two non-CSI characters as the dense-output threshold.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Also applies to: 32-35
Source: Coding guidelines
src/shared/terminal-sgr-density.test.ts (1)
13-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTest the density threshold boundary.
The current cases only test ratios far above and below the boundary. Add one case for
\x1b[31mXYreturningtrue, and one for\x1b[31mXYZreturningfalse. This protects the shared scheduler and PTY-delivery decision boundary.Proposed test
+ it('uses one SGR per two characters as the inclusive threshold', () => { + expect(isDenseSgr('\x1b[31mXY')).toBe(true) + expect(isDenseSgr('\x1b[31mXYZ')).toBe(false) + }) +
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 565f465a-e1f9-4f03-ade3-38342bc25010
📒 Files selected for processing (6)
src/main/ipc/pty.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.tssrc/renderer/src/lib/pane-manager/terminal-sgr-normalizer.tssrc/shared/terminal-sgr-density.test.tssrc/shared/terminal-sgr-density.ts
💤 Files with no reviewable changes (1)
- src/renderer/src/lib/pane-manager/terminal-sgr-normalizer.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/ipc/pty.ts
- src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts
- emit droppedOutput sentinel with salvaged query bytes on input-protection drop - keep lastEmittedState accurate across combined resets and string sequences - mark terminal input only after onData guards (replay/lock/stale/query-reply) - clear in-flight batches on discardTerminalOutput; share input-protection predicate - normalize dense-SGR on the flush path; add regression and boundary tests Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts (1)
1079-1096: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftPreserve SGR state across queue slices.
takeQueuedChunk()can split one terminal stream, butnormalizeSgrDensity()initializes style state for each slice. xterm preserves SGR state acrossterminal.write()calls. If one slice emits\x1b[1mand the next starts with\x1b[0m\x1b[31m, normalization treats the prior state as empty and can remove the reset. Subsequent text remains bold.Keep normalizer state on the queued terminal stream, or normalize before splitting. Apply the same stateful handling to the flush path. Add a regression test that crosses
DENSE_SGR_CHUNK_CHARS.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6cc9748c-f989-470d-8725-98e69f3116cd
📒 Files selected for processing (8)
src/main/ipc/pty.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.tssrc/renderer/src/lib/pane-manager/terminal-sgr-normalizer.test.tssrc/renderer/src/lib/pane-manager/terminal-sgr-normalizer.tssrc/shared/terminal-sgr-density.test.tssrc/shared/terminal-sgr-density.tstests/e2e/diag-output-input-latency.spec.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- src/shared/terminal-sgr-density.test.ts
- src/renderer/src/lib/pane-manager/terminal-sgr-normalizer.ts
- src/main/ipc/pty.ts
- tests/e2e/diag-output-input-latency.spec.ts
- src/renderer/src/components/terminal-pane/pty-connection.ts
- src/shared/terminal-sgr-density.ts
- src/renderer/src/lib/pane-manager/terminal-sgr-normalizer.test.ts
Summary
Fixes #12523: typing into a terminal while an agent streams dense-SGR output (per-character color styling — highlighted code, colored diff/log streams) made the keystroke echo appear 1-3 s late. Input was never lost, it just queued behind the flood in every FIFO layer.
Root cause: per-character SGR parses ~50x slower than plain text in xterm (~1-2 MB/s vs ~100 MB/s), the synchronous parse runs on the renderer main thread, and the flood piles up in front of the echo at every layer (renderer scheduler backlog, xterm's internal FIFO, main-process delivery window).
The fix (user-visible result: echo latency bounded instead of growing with flood depth):
With these, the same repro measures ~10x improvement in echo latency (issue's measured p50 ~300 ms from ~300-3000 ms) with no plain-text regression. Diagnostics: input-protection and interactive-lane counters added to the delivery debug snapshot, plus the deterministic e2e repro from the issue (
tests/e2e/diag-output-input-latency.spec.ts, gated behindORCA_DIAG=1).Screenshots
No visual change.
Testing
pnpm vitest runfor the touched areas:terminal-sgr-normalizer.test.ts(17 tests),pane-terminal-output-scheduler.test.ts+pty.test.ts(499 tests), pty pending-data/projection/flow-control suites (36 tests) — all pass.pnpm lint— not run yetpnpm typecheck— passes (3 errors found in review were fixed in the follow-up commit: invaliddesktopSpan !== truecomparisons, lane projection bookkeeping)pnpm build— not run yetORCA_DIAG=1.AI Review Report
AI review covered:
!projection?.desktopSpan) so projection accounting stays intact; the interactive lane preserves projection admission bookkeeping viacompactPendingProjectionState.Security Audit
No new input handling, command execution, path handling, auth, secrets, or IPC surface. The change is internal to the PTY renderer-delivery pipeline: it drops/delays/rewrites rendered output bytes only (never input), and the SGR normalizer is a strict state machine that passes through any sequence it cannot prove safe to drop byte-identical. IPC payloads are unchanged in shape. No secrets or credentials pass through the normalized path.
Notes
ORCA_DIAG=1), not part of CI, because Playwright timing assertions are flaky.