Skip to content

Coalesce PTY input write bursts - #7205

Merged
Jinwoo-H merged 1 commit into
mainfrom
Jinwoo-H/tui-wheel-pty-drain
Jul 3, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
Jinwoo-H/tui-wheel-pty-drain

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • extract PTY input draining into a dedicated write queue
  • coalesce dense bursts of small PTY input writes, especially SGR wheel reports, so they do not drain one timer turn at a time after the gesture ends
  • keep oversized input chunking and disconnected-PTY dropping behavior intact
  • add a drain/backlog regression harness using the visible mouse-reporting TUI fixture

Verification

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
  • pnpm exec oxlint src/renderer/src/components/terminal-pane/pty-transport.ts src/renderer/src/components/terminal-pane/pty-input-write-queue.ts src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts src/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.ts tests/e2e/fixtures/visible-tui-scroll-fixture.cjs tests/e2e/terminal-tui-wheel-drain.spec.ts

Notes

  • Refine TUI wheel scroll feel #7179 has merged, so this PR now targets main directly while staying a separate follow-up PR.
  • The e2e spec is a regression guard for dense report draining; I did not run Electron e2e locally in this pass.

Co-authored-by: Orca <help@stably.ai>
@Jinwoo-H
Jinwoo-H force-pushed the Jinwoo-H/tui-wheel-pty-drain branch from 8d3687c to 2c32370 Compare July 3, 2026 06:34
@Jinwoo-H
Jinwoo-H changed the base branch from Jinwoo-H/tui-scroll-feel to main July 3, 2026 06:34
@Jinwoo-H
Jinwoo-H merged commit 10e8f86 into main Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a PtyInputWriteQueue that coalesces and chunks PTY input writes, replacing the previous pending-write buffering in pty-transport.ts, with sendInput, sendInputAccepted, disconnect, and detach updated accordingly and new unit tests added. Separately, terminal TUI mouse wheel handling is extended with trackpad-like pixel scrolling support: a new report-count resolver for trackpad pixel deltas, refactored discrete-wheel-delta detection, removal of a discrete-event gating check in the multiplier decision, updated/new unit tests, an enhanced e2e fixture with logging and heavy-render flags, and a new e2e spec validating wheel input drain timing.

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()
Loading

Related PRs: No related PRs identified.

Suggested labels: area:terminal, area:testing

Suggested reviewers: No reviewer information available.

🐰 A poem for the burrow:
Wheels of a trackpad, whisper-light,
Rows now trickle, smooth and right,
PTY writes queue up in line,
Coalesced, chunked, drained on time,
Tests confirm each hop's delight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning Summary and verification are present, but the required Screenshots, AI Review Report, and Security Audit sections are missing. Add the missing template sections (Screenshots, AI Review Report, Security Audit) and include the testing checklist or note no visual change.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly captures the main change: coalescing PTY input write bursts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch Jinwoo-H/tui-wheel-pty-drain

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: 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 lift

Serialize acknowledged PTY writes with the queue. sendInputAccepted waits for the current drain, but a concurrent sendInput() can enqueue after that await and before writeAcceptedPtyInput() 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 value

Shorten 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 value

Duplicate yield helper.

defaultYieldBetweenWrites here is identical to yieldToInputWriteDrain in pty-transport.ts (lines 535-537). Consider extracting a shared yieldMacrotask() utility.

src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts (1)

111-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing coverage for the async "resolves too large later" drop path.

This test only exercises the synchronous text.length > maxBytes branch of isTerminalInputTooLargeWithDeferredMeasurement. The deferred/async branch (large text under the yield-measurement threshold, later resolving true) isn't covered — this is also the path tied to the unhandled-rejection concern raised in pty-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

canBurstBoostWheelEvent and isTrackpadLikePixelWheelEvent are exact negations — the guard at Line 151 is now dead code.

canBurstBoostWheelEvent(event) is true iff deltaMode !== PIXEL || hasDiscreteLegacyWheelDelta(event), which is precisely !isTrackpadLikePixelWheelEvent(event). Since resolveTerminalTuiMouseWheelReportCount already returns early via resolveTrackpadPixelWheelReportCount (Lines 241-244) whenever isTrackpadLikePixelWheelEvent is true, resolveBurstWheelDistanceRows is only ever invoked when canBurstBoostWheelEvent is already true — the if (!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

📥 Commits

Reviewing files that changed from the base of the PR and between 09fc57e and 2c32370.

📒 Files selected for processing (8)
  • 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.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-tui-wheel-reports.ts
  • tests/e2e/fixtures/visible-tui-scroll-fixture.cjs
  • tests/e2e/terminal-tui-wheel-drain.spec.ts

Comment on lines +175 to +194
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)
})

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.

🎯 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.

Suggested change
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)
})

Jinwoo-H added a commit that referenced this pull request Jul 3, 2026
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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Co-authored-by: Orca <help@stably.ai>
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.

1 participant