Skip to content

perf(terminal): stop forcing a foreground repaint per output frame - #35251

Closed
ceolinrenato wants to merge 9 commits into
stablyai:mainfrom
ceolinrenato:fix/terminal-foreground-repaint-throttle
Closed

ceolinrenato wants to merge 9 commits into
stablyai:mainfrom
ceolinrenato:fix/terminal-foreground-repaint-throttle

Conversation

@ceolinrenato

@ceolinrenato ceolinrenato commented Oct 28, 2026 •

Copy link
Copy Markdown

ELI5

When an agent (OpenCode, Claude Code, Codex…) is busy, Orca's terminal pane asked xterm to repaint itself on every chunk of output. On Linux/Wayland — where Orca disables the WebGL terminal renderer and xterm falls back to its DOM renderer — that duplicated work saturates the renderer's main thread, so typing and scrolling in that pane (and the rest of the window) crawl. This change bounds the forced repaint to at most one per 100 ms; between repairs xterm's own dirty-row repaint still covers the output.

What Changed

Before: every foreground chunk classified as an erase/CR/risk rewrite forced a full-span xterm repaint on top of xterm's own dirty-row repaint, once per frame.

After: the bound lives in writeForegroundTerminalChunk — the single place a forced repaint happens — keyed per terminal and opted into by the three live writers (writer, pipeline, flusher), so the repair runs at most once per FORCED_REFRESH_MIN_MS (100 ms) however the output was queued or drained. A suppressed repair arms a trailing full-span repair, so a burst that ends mid-window still repaints every row it dirtied instead of leaving stale cells. Its parse-span window spans repairs rather than writes, so rows that a suppressed batch dirtied are absorbed by the next eligible repair instead of being dropped when the window reopens. A suppressed repair's followupViewportRefresh request is carried to the repair that lands — the next eligible one, or the trailing repair — so its next-frame repaint still happens, and the trailing repair waits for the suppressed parses to land rather than repainting mid-backlog. Replay and snapshot writers don't opt in, so their repairs stay unthrottled, and the inPlaceRewrite hint is still passed through for the Windows follow-up repaint. The throttled-repair state machine lives in terminal-forced-refresh-window.ts, keeping the settle module under the repo's max-lines budget.

Measured on Arch Linux / Wayland (xterm DOM renderer) with this shape applied, renderer CPU profile during a real OpenCode build (~20 s window), time under each path:

path unpatched this change
forced repaint (refreshRows <- TU) 1943 ms 904 ms
xterm's own dirty-row repaint (_innerRefresh) 720 ms 2046 ms

The forced path roughly halves and xterm's own dirty-row repaint takes over what is left, so total DOM work shifts rather than vanishing; the largest remaining renderer cost is the grid-drift probe, which is deliberately out of scope here. Typing and wheel-scrolling in the streaming pane go from unusable to responsive, and A/B-toggling only this policy against the same build reproduces and removes the stall.

Why

shouldForceForegroundRenderRefresh exists to repair stale cells after in-place rewrites, but it fired per frame. The DOM renderer already repaints its own dirty rows, so the repair was duplicating work on the shared renderer main thread — the same thread that dispatches keystrokes and wheel events. Rate-limiting keeps the repair and removes the duplication.

Out of scope (considered and deliberately dropped). The same profile showed Orca's per-write grid-drift probe (scheduleForegroundGridDriftCheck → fitAddon.proposeDimensions() → getPropertyValue, a forced style/layout read) growing once the forced repaints were removed (267 ms → 1424 ms), because the probe re-reads on every foreground output. I tried skipping it while output streams; pty-connection-visibility-resume-size.spec.ts correctly failed, because that repair is supposed to be triggered by foreground output (it catches drift no resize reported). That needs its own design (e.g. only suppressing re-reads when the probe last found no drift), so it is left as a follow-up rather than smuggled into this PR.

Scope note: this only changes behavior where xterm uses the DOM renderer (Linux/Wayland, or any pane whose WebGL attach failed) — on WebGL panes shouldRefreshForegroundSynchronously() is already false and the refresh is queued.

Why this is worst on OpenCode 2

Not a claim that other agents are immune — but OpenCode 2 (OC2) compounds three things, and two of them are OC2-only:

  1. Orca runs its plugin inside the OC2 TUI process. Both major versions install as opencode; the loader picks server() for v1 and setup() for v2 (src/main/opencode/status-plugin-module-source.ts:11). The OC2 service is registered with installsTuiPlugin: true and its TUI source opens ctx.data.listen(...) and runs setInterval(tick, TUI_TICK_MS) at 100 ms, alongside per-event translation and session-lineage reporting (src/main/opencode/hook-service.ts → openCode2HookService; src/main/opencode2/status-plugin-tui-source.ts; src/main/opencode2/status-plugin-setup-source.ts). It is gated on ORCA_PANE_KEY, which is why the same OpenCode 2 is fine in a plain terminal. A busy turn therefore feeds a 10 Hz tick and a stream of events inside the process that has to stay responsive — OpenCode 1's server() plugin is not on that path, and other agents are wired through hook files.
  2. The OC2 TUI repaints the whole screen, continuously. It is an alternate-screen, full-grid OpenTUI redraw at targetFps: 60, kept hot while an agent is busy (spinner plus live shimmers keep the render loop alive). In the committed capture (tests/e2e/fixtures/opencode-small-redraw-capture.json), 119 of 119 frames position-address rows with \x1b[<row>;<col>H across the full 40-row pane. Claude Code / Codex / Kiro are inline UIs — Orca's own benchmark generator describes the comparison fixture as "Inline Claude-shaped transcript plus DEC 2026 bottom-status redraw, not an alt-screen TUI" (tests/tools/benchmarks/terminal-pipeline-bench.mjs) — so they emit far fewer foreground chunks, and far fewer carrying the erase / rewrite / background-SGR signals this policy keys on.
  3. On Linux/Wayland the refresh is synchronous. Orca disables the WebGL renderer there, so the forced repaint lands on the DOM renderer's main thread; the same agent on macOS/Windows already gets a queued refresh.

(1) is a separate amplifier from this PR — it is the lead recorded on #22458 — and is not changed here. This PR removes the repaint duplication that (2) and (3) turn into a stall.

Linked Issue

Fixes #22458

Related: #12525 (echo latency under dense-SGR floods — different mechanism, same symptom family), #7905, #16137 (wheel scrolling in mouse-reporting TUIs), #11363.

Note on scope: #22458's recorded lead is Orca's OpenCode-2 status plugin stalling the TUI process; the maintainer asked for a profile of the TUI process. This PR addresses a separate, measured contributor on the renderer side (profile above). It does not touch the plugin path and I am not claiming it closes the plugin theory — only that it removes a real, reproducible renderer stall for the same user-visible symptom.

Visual Proof

N/A — no visual or interaction change is intended; this changes a repaint policy in the terminal hot path, so there is no before/after frame to show. Happy to attach the raw .cpuprofile and trace JSON on request.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Manual: reproduced with a real opencode build on Arch Linux / Wayland (20 s renderer profile, 0.1 % idle).

I am also running this as a local POC for longer, real use — a patched copy of the shipped 1.4.243 bundle (AppImage extracted, patched in the packed app.asar) with the equivalent of this change applied, A/B-toggled against the same unpatched build. So far the original symptom is gone: typing and wheel-scrolling in the pane that is actively streaming no longer stall, and the whole window stays responsive. I'll keep using it before moving this PR out of draft and will report back if anything regresses.

Automated: pane-terminal-foreground-render-settle.test.ts covers the policy — first repair allowed, suppression inside the window (keeping the inPlaceRewrite hint), one trailing repair however many batches were suppressed, replay staying unthrottled when the writer does not opt in, rows a suppressed batch dirtied being covered once the window reopens, and a suppressed batch's next-frame follow-up being honored by the repair that lands, and the trailing repair waiting for suppressed parses to land (the last three fail without their fix).

Checks run locally (Node 24.18.0, pinned via mise):

  • pnpm tc:web — pass (exit 0)
  • pnpm test src/renderer/src/lib/pane-manager src/renderer/src/components/terminal-pane --maxWorkers=2 — 666 files passed, 6827 tests passed, 2 skipped, 0 failed (279 s), including pty-connection-visibility-and-exit.test.ts (90 tests) which covers the grid-drift repair contract
  • pnpm lint --maxWorkers=2 — pass (36 lint steps, 111 s)
  • pnpm build — desktop/electron-vite (main, preload, renderer, web), native and verify-skills-cli-runtime all pass (out/ 230 MB, 15 402 modules); the trailing build-mobile-web-app-bundle step fails only because the separate mobile/ workspace dependencies are not installed in this checkout (mobile/ dependencies are not installed; run pnpm -C mobile install) — a checkout/environment issue, unrelated to this change and covered by CI.

Platform notes: the behavior change matters where xterm uses the DOM renderer (Linux/Wayland, or a pane whose WebGL attach failed). The Windows inPlaceRewrite follow-up path is untouched.

AI Disclosure

Implemented with assistance from OpenCode + DeepSeek V4.1 Flash (profiling, reproduction harness, patch authoring). The measurements and the A/B validation were run on real hardware.

Review

Agent code review summary

  • Cross-platform: policy is platform-agnostic and adds no platform branches; the inPlaceRewrite hint is forwarded unchanged, so the Windows ConPTY follow-up repaint is unaffected. On WebGL panes the refresh is already debounced, so this is a no-op there.
  • SSH/remote/local: runs renderer-side after delivery; unaffected by transport.
  • Agent/integration: agent-agnostic; no provider-specific code.
  • Performance risk: strictly less work in a hot path; worst case a repair is deferred by ≤100 ms, and xterm's own dirty-row repaint still runs in between.
  • UI quality: no intended visual change; the stale-cell repair still happens, at a bounded rate.
  • Security: no input, auth, credential, or filesystem surface touched.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance.

Author: (no X/Twitter handle)

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, and affected tests pass locally; pnpm build passes except the unrelated mobile/ bundle step (needs the separate mobile/ workspace install)

The DOM renderer's dirty-row repaint already covers continuous output, but
every foreground chunk that classified as an erase/rewrite forced another
full-span repaint on the renderer main thread. A renderer profile taken during
an OpenCode build on Wayland showed the forced path (refreshRows <- TU) costing
roughly 2.5x xterm's own _innerRefresh (DOM render cost 13.1% -> 7.4% once the
forced repaint was removed).

Rate-limit the forced repair to at most one per FOREGROUND_FORCED_REFRESH_MIN_MS
and skip the forced-layout grid-drift probe (proposeDimensions -> getPropertyValue)
while output is streaming, so a busy pane no longer starves typing and scrolling.
@ceolinrenato
ceolinrenato marked this pull request as ready for review October 28, 2026 18:51
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b88b43b1-aa12-48ed-b1ac-c3922b5f0dc2
Commits

Reviewing files that changed from the base of the PR and between bfa8832 and f8a4c44.

Files selected for processing: 3
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
  • src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts
Files skipped from review as they are similar to previous changes: 1
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

Foreground terminal writes can opt into per-terminal throttling of forced viewport refreshes. A refresh runs when at least 100 ms have elapsed since the previous refresh. Otherwise, the code schedules a trailing repair after suppressed parses complete. The output flusher, pipeline, and synchronous writer enable throttling. Tests cover throttled and unthrottled writes, trailing repairs, follow-up refreshes, pending parses, and dirty-row coverage.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Low · up to f8a4c

During a PTY change, an old callback can cause an extra repaint and briefly delay a new repair. The repair remains scheduled, so this is a bounded merge risk.

Pre-merge checks: Passed 5
Check name Status Explanation
Description check Passed The description is complete and relevant. It includes the required ELI5, change summary, rationale, linked issue, visual-proof explanation, testing results, AI disclosure, review notes, scope consider…
Title check Passed The title clearly and concisely describes the primary change: throttling forced foreground terminal repaints to improve performance.
Linked Issues check Passed Issue #22458 reports OpenCode TUI slowness but defines no coding acceptance criteria. The PR addresses the reported symptom with a renderer-side change: live foreground writers throttle forced repairs…
Out of Scope Changes check Passed The changes remain focused on the forced foreground terminal repaint policy for #22458. The state module, live-writer opt-in, settle-path integration, and regression tests support that policy. No unre…
Docstring Coverage Passed Docstring coverage is 80.95% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Full details: Description check

Explanation

The description is complete and relevant. It includes the required ELI5, change summary, rationale, linked issue, visual-proof explanation, testing results, AI disclosure, review notes, scope considerations, and checklist status. It also clearly documents the unrelated mobile build dependency failure.

Full details: Linked Issues check

Explanation

Issue #22458 reports OpenCode TUI slowness but defines no coding acceptance criteria. The PR addresses the reported symptom with a renderer-side change: live foreground writers throttle forced repairs to one per 100 ms, preserve suppressed row coverage and follow-up refreshes, and leave replay and snapshot writers unthrottled. Focused tests cover these behaviors. The OpenCode plugin path is not required by the issue text.

Full details: Out of Scope Changes check

Explanation

The changes remain focused on the forced foreground terminal repaint policy for #22458. The state module, live-writer opt-in, settle-path integration, and regression tests support that policy. No unrelated change is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 80.95% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 21 functions across 6 files.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving 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.

❤️ 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: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cf3eb6c6-1894-462f-a16f-16e732dbab68
Commits

Reviewing files that changed from the base of the PR and between 797e549 and 9bbd427.

Files selected for processing: 5
  • src/renderer/src/components/terminal-pane/pty-connection/foreground-forced-refresh.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/foreground-forced-refresh.ts
  • src/renderer/src/components/terminal-pane/pty-connection/foreground-output-budgets.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pane-host-capability-flags.ts
  • src/renderer/src/components/terminal-pane/pty-connection/write-pty-output-to-xterm.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Review feedback: the 100 ms gate ran at arrival, but a queued chunk keeps its
forceForegroundRefresh flag until a flush or drain writes it, so batches drained
back to back could each issue their own repaint and defeat the bound.

Move the bound to writeForegroundTerminalChunk, the single place a forced repaint
happens, opted into by the three live writers (writer, pipeline, flusher) so
replay and snapshot repairs stay unthrottled. A suppressed repair now arms a
trailing full-span repair, so a burst that ends mid-window still repaints every
row it dirtied rather than leaving stale cells.
@ceolinrenato

Copy link
Copy Markdown
Author

Both addressed in 59e8036.

  1. The window now runs where the repaint actually happens — writeForegroundTerminalChunk, keyed per terminal — and is opted into by the three live writers (writer, pipeline, flusher) instead of being applied at arrival, so batches drained back to back can no longer each issue their own repaint. Replay and snapshot writers don't opt in, so their repairs stay unthrottled.
  2. A suppressed repair now arms a trailing full-span repair, so a burst that ends mid-window still repaints every row it dirtied rather than leaving stale cells behind.

Covered in pane-terminal-foreground-render-settle.test.ts: first repair allowed, suppression inside the window (keeping inPlaceRewrite), one trailing repair however many batches were suppressed, and replay staying unthrottled. pane-manager + terminal-pane suites pass — 666 files / 6827 tests.

For what it's worth, a local hot-patched build with this shape halves the forced-repaint path (1943 ms → 904 ms in a 20 s renderer profile); the largest remaining renderer cost is the grid-drift probe, which is deliberately not part of this PR.

@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


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5bb16456-9d7a-438f-86e3-d633ed921e3d
Commits

Reviewing files that changed from the base of the PR and between 9bbd427 and 59e8036.

Files selected for processing: 5
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-flusher.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-pipeline.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-writer.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Review feedback: a throttled repair reset the parse-span window before its
write, so rows an earlier suppressed batch had already dirtied were cleared
before that repair read the span — and cancelling the trailing repair then left
them uncovered.

Start the window after the repair instead, so a throttled repair covers every
row dirtied since the previous one, and restart it in the trailing repair,
whose full-span repaint already owns those rows. Adds a regression test that
fails with the old ordering (span ends at 4 instead of covering row 22).
@ceolinrenato

Copy link
Copy Markdown
Author

Fixed in 54289b7. The parse-span window now spans repairs instead of writes: a throttled repair consumes every row dirtied since the previous one, so rows a suppressed batch dirtied are absorbed by the next eligible repair rather than cleared when the window reopens, and the trailing repair restarts the window after its full-span repaint. Added a regression test that fails without it (expected 4 to be greater than or equal to 22).

@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


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3a544a5f-8d86-49b7-b7c0-1577d099214d
Commits

Reviewing files that changed from the base of the PR and between 59e8036 and 54289b7.

Files selected for processing: 2
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
Files skipped from review as they are similar to previous changes: 1
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Review feedback: a suppressed throttled write skipped settleForegroundRender, so
it dropped its followupViewportRefresh request, and a later eligible write that
did not ask for one then cancelled the trailing repair — leaving nothing to
schedule the next-frame repaint.

Record the follow-up on suppression and honour it in the repair that lands, the
next eligible one or the trailing repair, clearing it on teardown. Adds a test
that fails with the old behaviour (2 refreshes instead of 3).
@ceolinrenato

Copy link
Copy Markdown
Author

Fixed in 64b25a5. A suppressed repair now records the next-frame follow-up it was asked for, and the repair that actually lands — the next eligible one, or the trailing repair — honors it after its repaint. Covered by a test that fails with the old behaviour (expected "vi.fn()" to be called 3 times, but got 2 times).

CodeRabbit's docstring gate flags functions this diff adds or changes that have a
branch. Adds one-line why-docstrings for the slot/window/trailing helpers, the
settle step and the write entry point. Comment-only change.
@ceolinrenato

Copy link
Copy Markdown
Author

Docstring gate: added one-line why-docstrings to the functions this diff adds or changes (7065348). Comment-only, so the previous commit's full suite result still applies.

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues remain.

Summary

This PR limits forced terminal repaints for live output while leaving replay repairs unthrottled.

  • Live terminal output gets fewer forced repaints during busy streams.

Reviews (5) · Last reviewed commit: "perf(terminal): throttle the repair wher..." · Reviewed by Greptile

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Repair suppressed writes that complete after… · pane-terminal-foreground-render-settle.ts:80-126

src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts:80-126
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Repair suppressed writes that complete after the trailing timer.

takeForcedRefreshSlot runs before terminal.write, so a suppressed write can arm the trailing timer before its parse callback runs. If the callback runs after the timer, the timer clears dirty-row tracking before the late parse dirties its rows. The suppressed write then has no foreground-settle path, and those rows can remain stale.

When a suppressed write completes, schedule another trailing repair if the previous timer already fired.

Suggested fix
   let forcedRefresh = options.forceViewportRefresh === true
   let followupViewportRefresh = options.followupViewportRefresh === true
+  let suppressedForcedRefresh = false
   if (forcedRefresh && throttled) {
     forcedRefresh = takeForcedRefreshSlot(terminal, options)
@@
     } else {
+      suppressedForcedRefresh = true
       noteSuppressedFollowupRefresh(terminal, options)
@@
     if (beforeWriteViewport) {
       runGuardedWriteCompletionStep('foreground-render-settle', () =>
@@
       )
     }
+    if (suppressedForcedRefresh) {
+      scheduleTrailingForcedRefresh(terminal, options)
+    }
     if (options.onParsed) {

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b5816114-7507-4512-b3fc-122767559390
Commits

Reviewing files that changed from the base of the PR and between 64b25a5 and 7065348.

Files selected for processing: 1
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
Files skipped from review as they are similar to previous changes: 1
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Review feedback (Greptile P1, CodeRabbit): the trailing timer was armed before
terminal.write, so a parse backlog longer than the window could be repainted
mid-parse. A repair taken there cannot cover the rows the rest of that parse
dirties, and it cleared the window those rows would have used.

Count suppressed writes whose parse is still in flight and arm the trailing
repair from the write callback once that count reaches zero, matching the eligible
path, which already repairs from its parse callback. A synchronous write failure
also ends the batch's parse, so its owed repair does not wait on a callback that
will never come.

Extracts the throttled-repair state machine into terminal-forced-refresh-window.ts
so the settle module stays under the max-lines budget. Adds a test that fails with
the old ordering (a mid-parse repair runs: 1 call where 0 is expected).
@ceolinrenato

Copy link
Copy Markdown
Author

Same root cause as Greptile's P1 above, and fixed in 0826576. The trailing timer is no longer armed at write time at all: a suppressed write records the parse it still owes, and the trailing repair is armed from that write's parse callback once no suppressed parse is still in flight — so no repair can run before the late parse dirties its rows, while the window still bounds the eligible repairs. Covered by a test that fails with the old ordering (expected "vi.fn()" to not be called at all, but actually been called 1 times).

@ceolinrenato

Copy link
Copy Markdown
Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed and review finished.

@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


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b2d6a2b3-7273-4e14-97e6-4089eab98740
Commits

Reviewing files that changed from the base of the PR and between 7065348 and 0826576.

Files selected for processing: 3
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
  • src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Review feedback (CodeRabbit): a suppressed write can land after a later write
claimed the slot, so its callback arms a trailing timer that the later repair
makes redundant — a full-span repaint for rows it already covers. Cancel that
timer when the covering repair completes, once no suppressed parse is still in
flight.

Also settles a suppressed write at most once (its parse ends by callback or by
the synchronous failure, not both), and narrows the window key to terminal
identity so it does not restate the settle module's target type. Documents the
remaining helpers to clear the docstring gate.

Adds a test that fails without the cancel (3 refreshes where 2 are expected).

@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 GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Tie suppressed-parse callbacks to their refresh… · pane-terminal-foreground-render-settle.ts:321

src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts:321
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Tie suppressed-parse callbacks to their refresh window.

discardTerminalOutput can run during a PTY change without certified-dead status. A subsequent live foreground write can reuse the same xterm while a callback from the discarded window is pending. If that old callback lands after the new write is suppressed, noteSuppressedParseLanded can reduce the new window's count to zero. The trailing repair can then consume the new write's suppressedFollowupRefresh flag before its parse completes. The new callback arms another full repair after the flag is cleared, so the requested next-frame repaint is lost.

Store a per-window token when suppressing a write and ignore callbacks whose token is no longer current.

Suggested fix
diff --git a/src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts b/src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts
@@
 type ForcedRefreshState = {
   lastRepairAt: number
   trailingTimer: ReturnType<typeof setTimeout> | null
   suppressedParsesInFlight: number
   suppressedFollowupRefresh: boolean
+  generation: symbol
 }
@@
       trailingTimer: null,
       suppressedParsesInFlight: 0,
-      suppressedFollowupRefresh: false
+      suppressedFollowupRefresh: false,
+      generation: Symbol()
@@
 export function noteSuppressedRepair(
   terminal: ForcedRefreshTarget,
   options: { followupViewportRefresh?: boolean }
-): void {
+): symbol {
   const state = stateFor(terminal)
   state.suppressedParsesInFlight += 1
   if (options.followupViewportRefresh) {
     state.suppressedFollowupRefresh = true
   }
+  return state.generation
 }
@@
-export function noteSuppressedParseLanded(terminal: ForcedRefreshTarget): boolean {
-  const state = stateFor(terminal)
+export function noteSuppressedParseLanded(
+  terminal: ForcedRefreshTarget,
+  generation: symbol
+): boolean {
+  const state = stateByTerminal.get(terminal)
+  if (!state || state.generation !== generation) {
+    return false
+  }
   state.suppressedParsesInFlight = Math.max(0, state.suppressedParsesInFlight - 1)
   return state.suppressedParsesInFlight === 0
 }
diff --git a/src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts b/src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
@@
   let forcedRefresh = options.forceViewportRefresh === true
   let followupViewportRefresh = options.followupViewportRefresh === true
   let suppressedForcedRefresh = false
+  let suppressedRepairGeneration: symbol | null = null
@@
     } else {
       suppressedForcedRefresh = true
-      noteSuppressedRepair(terminal, options)
+      suppressedRepairGeneration = noteSuppressedRepair(terminal, options)
@@
-    if (noteSuppressedParseLanded(terminal)) {
+    if (
+      suppressedRepairGeneration !== null &&
+      noteSuppressedParseLanded(terminal, suppressedRepairGeneration)
+    ) {
       armTrailingForcedRefresh(terminal, () => repairSuppressedForegroundRows(terminal, options))
     }

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0adbb8d6-d5c1-4d6f-9159-f9549a4186c7
Commits

Reviewing files that changed from the base of the PR and between 0826576 and d9b5b81.

Files selected for processing: 3
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
  • src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

…lled

Review feedback (CodeRabbit): the suppressed-repair obligation lived only in the
trailing timer. An eligible write cancelling that timer at slot-claim time left
no trace, so a following replay write reset the dirty-row tracker and dropped the
suppressed rows before any repair covered them.

Track the obligation in its own flag: set on suppression, cleared only by a
repair that has read the tracker and only when no suppressed parse is still in
flight, and used to hold off the pre-replay reset. Also stops the trailing timer
re-arming itself for another full window (a later suppressed parse's own callback
re-arms it), and keys the window by `WeakKey` like the dirty-row tracker.

Adds a test that fails without the flag (a replay repair drops the rows).

@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


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f6074421-9d59-447d-b730-a811431ce7de
Commits

Reviewing files that changed from the base of the PR and between d9b5b81 and bfa8832.

Files selected for processing: 3
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.ts
  • src/renderer/src/lib/pane-manager/terminal-forced-refresh-window.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

…bmitted

Review feedback (CodeRabbit): the bound was applied when a write claimed a slot at
submission, but xterm buffers writes and invokes callbacks later. Under backlog,
two submissions a window apart drain together, so both forced repairs ran
back-to-back — the helper limited claims, not repairs.

Move the slot check and timestamp into the parse callback that runs
settleForegroundRender, so the window is measured between repairs. The
parse-in-flight bookkeeping stays at submission, since it still has to hold off
replay resets and the trailing repair, and a rejected repair still records the
obligation.

Adds a delayed-callback regression test: two submissions a window apart draining
together produce one repair, not two.
@OrcaWin

OrcaWin commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Closing: the main problem is already fixed on main. The synchronous foreground repair now runs only on Windows (the win32 gate in write-pty-output-to-xterm.ts, from the merged #39462), so macOS and Linux no longer paint the DOM panes twice. This branch's measurements predate that fix. What remains is a 100 ms throttle on the Windows ConPTY repair that fixes stale cells, which has no Windows measurement, adds a timer state machine of about 270 lines, and has tests that count refresh calls, which the repo's test policy does not allow. A narrower Windows-only change with a measurement on top of current main would be welcome.

@OrcaWin OrcaWin closed this Nov 8, 2026
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] Opencode tui slows down running multiple agents

2 participants