Repository navigation
Coalesce PTY input write bursts - #7205
Conversation
Co-authored-by: Orca <help@stably.ai>
8d3687c to
2c32370
Compare
📝 WalkthroughWalkthroughThis PR introduces a Sequence Diagram(s)sequenceDiagram
participant Renderer
participant IpcPtyTransport
participant InputWriteQueue
participant WindowApi
Renderer->>IpcPtyTransport: sendInput(data)
IpcPtyTransport->>InputWriteQueue: enqueue(ptyId, data)
InputWriteQueue->>InputWriteQueue: coalesce/chunk pending items
InputWriteQueue->>WindowApi: write(ptyId, data)
Renderer->>IpcPtyTransport: sendInputAccepted(data)
IpcPtyTransport->>InputWriteQueue: waitForDrain()
IpcPtyTransport->>IpcPtyTransport: writeAcceptedPtyInput()
Renderer->>IpcPtyTransport: disconnect() / detach()
IpcPtyTransport->>InputWriteQueue: clear()
Related PRs: No related PRs identified. Suggested labels: area:terminal, area:testing Suggested reviewers: No reviewer information available. 🐰 A poem for the burrow: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
⚔️ Resolve merge conflicts
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: 1
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/components/terminal-pane/pty-transport.ts (1)
844-849: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftSerialize acknowledged PTY writes with the queue.
sendInputAcceptedwaits for the current drain, but a concurrentsendInput()can enqueue after that await and beforewriteAcceptedPtyInput()runs, so queued writes and accepted writes can land out of order. Route both paths through the same serialization mechanism or hold an exclusive lock for the whole accepted write.
🧹 Nitpick comments (5)
src/renderer/src/components/terminal-pane/pty-input-write-queue.ts (3)
66-72: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the "why" comment to comply with guideline.
This is a valuable explanation, but it's 7 lines; the path guideline caps "why" comments at one or two lines capturing only the non-obvious reason.
As per path instructions,
**/*.{ts,tsx,js,jsx}: "Keep comments short — one or two lines, capturing only the non-obvious reason."Source: Path instructions
44-116: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value
pending.shift()is O(n) per dequeue.Each item removal shifts the whole array, so draining a queue of length n costs O(n²) in the worst case. For the documented burst sizes (hundreds of events) this is negligible, but a head-index cursor or a proper deque would be more robust if burst sizes grow.
31-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicate yield helper.
defaultYieldBetweenWriteshere is identical toyieldToInputWriteDraininpty-transport.ts(lines 535-537). Consider extracting a sharedyieldMacrotask()utility.src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts (1)
111-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMissing coverage for the async "resolves too large later" drop path.
This test only exercises the synchronous
text.length > maxBytesbranch ofisTerminalInputTooLargeWithDeferredMeasurement. The deferred/async branch (large text under the yield-measurement threshold, later resolvingtrue) isn't covered — this is also the path tied to the unhandled-rejection concern raised inpty-input-write-queue.ts. Consider adding a case with a mocked/stubbed deps or a text length crossing the yield threshold to assert the item is silently dropped without writing.src/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.ts (1)
87-99: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
canBurstBoostWheelEventandisTrackpadLikePixelWheelEventare exact negations — the guard at Line 151 is now dead code.
canBurstBoostWheelEvent(event)istrueiffdeltaMode !== PIXEL || hasDiscreteLegacyWheelDelta(event), which is precisely!isTrackpadLikePixelWheelEvent(event). SinceresolveTerminalTuiMouseWheelReportCountalready returns early viaresolveTrackpadPixelWheelReportCount(Lines 241-244) wheneverisTrackpadLikePixelWheelEventis true,resolveBurstWheelDistanceRowsis only ever invoked whencanBurstBoostWheelEventis alreadytrue— theif (!canBurstBoostWheelEvent(event))branch at Line 151 can never execute from this call site.This isn't a functional bug today, but the two predicates are maintained independently; if one is edited without the other, the intended equivalence silently breaks (either resurrecting genuinely dead logic with different semantics, or causing double-handling of what should be routed as trackpad-like). Consider deriving one from the other explicitly (e.g.
canBurstBoostWheelEvent = (event) => !isTrackpadLikePixelWheelEvent(event)) or removing the now-unreachable guard and documenting the invariant at the call site.♻️ Suggested consolidation
-function canBurstBoostWheelEvent(event: TerminalTuiWheelEventInput): boolean { - if ((event.deltaMode ?? DOM_DELTA_PIXEL) !== DOM_DELTA_PIXEL) { - return true - } - - return hasDiscreteLegacyWheelDelta(event) -} - function isTrackpadLikePixelWheelEvent(event: TerminalTuiWheelEventInput): boolean { return ( (event.deltaMode ?? DOM_DELTA_PIXEL) === DOM_DELTA_PIXEL && !hasDiscreteLegacyWheelDelta(event) ) } + +// canBurstBoostWheelEvent is intentionally the negation of isTrackpadLikePixelWheelEvent: +// only non-trackpad-like events reach resolveBurstWheelDistanceRows. +function canBurstBoostWheelEvent(event: TerminalTuiWheelEventInput): boolean { + return !isTrackpadLikePixelWheelEvent(event) +}Also applies to: 151-157
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 7462dd74-9600-4a74-8ba4-445f5c8a1e9b
📒 Files selected for processing (8)
src/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.tssrc/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.tssrc/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.tssrc/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.tstests/e2e/fixtures/visible-tui-scroll-fixture.cjstests/e2e/terminal-tui-wheel-drain.spec.ts
| test('aggressive alternating trackpad-like gesture does not replay after input ends', async ({ | ||
| orcaPage | ||
| }) => { | ||
| const logPath = path.join(os.tmpdir(), `tui-wheel-drain-alt-${Date.now()}.log`) | ||
| await startHeavyTuiFixture(orcaPage, logPath) | ||
|
|
||
| const target = await terminalWheelTarget(orcaPage) | ||
| const input = await dispatchTrackpadWheelStream(orcaPage, { | ||
| alternate: true, | ||
| events: WHEEL_EVENTS, | ||
| deltaY: Math.min(49, target.cellHeight) | ||
| }) | ||
| await orcaPage.waitForTimeout(8000) | ||
|
|
||
| const summary = summarizeArrivals(readReportArrivalLog(logPath), input) | ||
| fs.rmSync(logPath, { force: true }) | ||
| console.log(`[tui-wheel-drain] alternate: ${JSON.stringify(summary)}`) | ||
|
|
||
| expect(summary.arrivalLagMs, JSON.stringify(summary)).toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Second test can pass trivially if zero reports ever arrive.
Unlike the first test (Line 170), this test never asserts summary.totalReports. readReportArrivalLog returns [] when the log file doesn't exist (i.e., the fixture never matched an SGR report), which makes summarizeArrivals compute arrivalLagMs = 0 - input.inputEndWallClockMs — a large negative number that trivially satisfies toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS). A regression that drops the alternating gesture entirely (e.g. reports getting eaten instead of delayed) would pass this test undetected, defeating the purpose of this harness for the buffered-playback failure mode it's meant to guard.
🐛 Suggested fix
const summary = summarizeArrivals(readReportArrivalLog(logPath), input)
fs.rmSync(logPath, { force: true })
console.log(`[tui-wheel-drain] alternate: ${JSON.stringify(summary)}`)
+ expect(summary.totalReports, JSON.stringify(summary)).toBeGreaterThan(0)
expect(summary.arrivalLagMs, JSON.stringify(summary)).toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS)📝 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.
| test('aggressive alternating trackpad-like gesture does not replay after input ends', async ({ | |
| orcaPage | |
| }) => { | |
| const logPath = path.join(os.tmpdir(), `tui-wheel-drain-alt-${Date.now()}.log`) | |
| await startHeavyTuiFixture(orcaPage, logPath) | |
| const target = await terminalWheelTarget(orcaPage) | |
| const input = await dispatchTrackpadWheelStream(orcaPage, { | |
| alternate: true, | |
| events: WHEEL_EVENTS, | |
| deltaY: Math.min(49, target.cellHeight) | |
| }) | |
| await orcaPage.waitForTimeout(8000) | |
| const summary = summarizeArrivals(readReportArrivalLog(logPath), input) | |
| fs.rmSync(logPath, { force: true }) | |
| console.log(`[tui-wheel-drain] alternate: ${JSON.stringify(summary)}`) | |
| expect(summary.arrivalLagMs, JSON.stringify(summary)).toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS) | |
| }) | |
| test('aggressive alternating trackpad-like gesture does not replay after input ends', async ({ | |
| orcaPage | |
| }) => { | |
| const logPath = path.join(os.tmpdir(), `tui-wheel-drain-alt-${Date.now()}.log`) | |
| await startHeavyTuiFixture(orcaPage, logPath) | |
| const target = await terminalWheelTarget(orcaPage) | |
| const input = await dispatchTrackpadWheelStream(orcaPage, { | |
| alternate: true, | |
| events: WHEEL_EVENTS, | |
| deltaY: Math.min(49, target.cellHeight) | |
| }) | |
| await orcaPage.waitForTimeout(8000) | |
| const summary = summarizeArrivals(readReportArrivalLog(logPath), input) | |
| fs.rmSync(logPath, { force: true }) | |
| console.log(`[tui-wheel-drain] alternate: ${JSON.stringify(summary)}`) | |
| expect(summary.totalReports, JSON.stringify(summary)).toBeGreaterThan(0) | |
| expect(summary.arrivalLagMs, JSON.stringify(summary)).toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS) | |
| }) |
Conflict resolutions: - terminal-stream-protocol: Metadata keeps opcode 12 (shipped to mobile in v1.4.120); branch-only Ack renumbers to 13. - scheduler: keep HIGH_PRIORITY_MAX_WRITES_PER_DRAIN=8 (perf fix) over main's 2 (#7139 landed there with the old constant). - headless-emulator: keep chain structure (scanner classes, query-reply forwarding); graft main's pathFlavor/remotePosixFileUriAuthority OSC7 options through TerminalOscCwdTitleScanner. Main's TerminalPrivateModeTracker is logic-identical to the chain's TerminalMouseModeMirror (kept, with pre-filter). - orca-runtime: keep chain factory; graft main's pathFlavor wiring and snapshot cwd fallback; keep both teardown lines. - pty-connection: keep both chain reconcile and main's ordered-seq tracking; clear the chain's restored-snapshot baseline on pty exit (same seq-domain boundary main's reset enforces) — fixes revive with restarted seq counter dropping chunks as duplicates. - subscribe-buffer tests: updated to merged semantics — main's inline overflow recovery ships current data as the FIRST snapshot; the chain's resized/pending-output-overflow follow-up remains as backstop. Validation: typecheck clean; 7,548 tests green across daemon/ipc/ runtime/pane-manager/terminal-pane/shared/mobile-transport (1 documented pre-existing WSL failure). Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Orca <help@stably.ai>
Summary
Verification
Notes