Skip to content

Stop terminal flicker during active Claude Code sessions - #7540

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/sta-1365-claude-code-terminal-flicker
Jul 6, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/sta-1365-claude-code-terminal-flicker

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

What changes

While an agent (Claude Code, or any alternate-screen TUI) streams output inside an Orca terminal, the terminal area no longer flickers. The flash was a real, measurable redraw storm — not a perception issue.

Root cause: xterm's WebGL renderer keeps a module-global glyph atlas shared by all same-config terminals. Orca ran a recovery that clears that shared atlas and repaints every pane. One caller drove it from terminal output: on every alternate-screen in-place-rewrite chunk (standalone \r / \b / erase-line) and every CJK/"renderer-risk" chunk, it re-armed a coalescer that fired the global clear+repaint burst repeatedly. A streaming agent emits such a chunk on essentially every frame, so during an active session the whole terminal cleared and repainted several times a second, and stopped the instant output went static — exactly the report.

Fix: debounce the terminal-output recovery to the trailing edge. A sustained redraw stream coalesces into a single clear+refresh that runs only after 200 ms of quiet, so no atlas clear ever lands during visible streaming. A resumed stream re-arms (and cancels) the one debounce timer, so a pause-then-resume can't leak a clear mid-stream.

What does NOT change: tab-reveal recovery keeps its own immediate burst (deliberately decoupled from the streaming debounce so a background stream can't defer a just-revealed tab's atlas rebuild); the image-paste, OS/window-wake, and WebGL context-loss recovery paths are unchanged and still immediate.

Reproduction / evidence (macOS)

Instrumented the recovery with a fire-timestamp counter and drove a synthetic alternate-screen redraw stream (~20 fps in-place rewrites) in a real Orca terminal:

  • Before: 39 global atlas-clear + all-pane repaints during ~8.5 s of streaming (median gap 120 ms); 0 once idle.
  • After: 0 fires during the streaming window; exactly 1 clear+refresh at the settle edge (~200 ms after output stopped). Tab-reveal recovery still fires its immediate burst.

(Flicker is a sub-frame temporal artifact; the fire-count is the authoritative before/after measurement. Screenshots of the streaming state and the settled state are attached to the PR conversation.)

Design approach & review

Trailing-edge debounce, keeping a single settle-edge recovery (not a 3-stage burst) so a clear can only ever run after global quiet. Design was reviewed through Brennan's PR process (design-review loop → implementation → completeness verify → perf → two-reviewer code-review loop → live validation). The design-review loop raised and resolved: a burst-cancelation hole (eliminated by the single-recovery choice), a hidden-output shared-timer analysis, and a required Windows/CJK validation item.

Consistency across recovery surfaces

Compared every caller of the shared atlas recovery: streaming output (fixed), light-tab resume (moved to the immediate reveal path so it is NOT debounced), image paste (immediate, unchanged), hidden→visible reveal / OS-wake / context-loss (unchanged). No user-visible surface loses recovery; only the streaming path changed cadence.

Headline behavior: implemented

The production path (pty-connection foreground/hidden write → scheduleTerminalWebglAtlasRecovery) is debounced, verified live (0 mid-stream fires).

Risks / non-goals

  • Accepted residual (approved): because the debounce timer is module-global, a visible idle pane's output-driven stale-glyph cleanup can defer while a sibling or hidden background agent streams. Rare and Orca-specific; every other recovery trigger (reveal/resume/wake/paste/context-loss) stays immediate. Follow-up signal noted if a visible idle pane is ever seen holding a stale glyph while a sibling streams.
  • Non-goal: the background-transparency re-blend flicker (STA-912, only with opacity < 1) — different mechanism, separate work.
  • Isolated (non-streaming) stale-glyph recovery latency goes from ~1 frame to ≤200 ms — imperceptible for a cleanup repaint.

Provider / platform

The trigger is client-side content analysis in the renderer, so behavior is identical across local / daemon / SSH / remote / WSL / mobile. The Windows CJK variant (STA-1385, #7475) funnels through the same debounced scheduler and is covered by this fix; a live Windows/CJK run is being done separately to confirm.

Validation

  • Unit: terminal-webgl-atlas-recovery.test.ts (no mid-stream recovery; single recovery at settle; no clear on pause-then-resume; reveal stays immediate; cross-caller single-timer) + terminal-visibility-resume.test.ts (reveal recovery immediate). Adjacent suites green: pty-connection.test.ts (323), pane-manager-registry.test.ts.
  • Perf: net reduction in render work (removes the repeated global clear/repaint from the per-chunk hot path); no new polling/IPC/listeners; single self-clearing timer, no leak.
  • Code review: two independent reviewers, converged clean (no P0/P1; the one P2 — resume coupling — was fixed by decoupling reveal recovery).
  • Live macOS: 39 → 0 mid-stream fires; reveal burst immediate.
  • oxlint + web typecheck clean.

Closes STA-1365. Related: STA-1385 / #7475 (same cause, Windows CJK).

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 03152d2e-9a30-44e5-ba71-0315ed7c2d82

📥 Commits

Reviewing files that changed from the base of the PR and between 9b6c106dfcd39dc34260409fc4d04ffc6ae30de6 and 5786193.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts

📝 Walkthrough

Walkthrough

The PR splits WebGL atlas recovery into a tab-reveal path and a terminal-output path. Tab reveal now uses scheduleTabRevealWebglAtlasRecovery() for immediate burst recovery, while terminal output uses scheduleTerminalWebglAtlasRecovery() with a 200ms quiet-window debounce. resumeTerminalVisibility now calls the tab-reveal function in the light-tab branch. Tests were updated to cover the new scheduling behavior, timer cleanup, and recovery timing invariants.

Changes

  • Added TERMINAL_OUTPUT_RECOVERY_QUIET_MS = 200.
  • Added scheduleTabRevealWebglAtlasRecovery().
  • Reworked terminal-output recovery to debounce on a timeout.
  • Updated light-tab resume wiring to use tab-reveal recovery.
  • Expanded tests for timing, coalescing, and timer cleanup.

Related issues: None referenced.
Related PRs: None referenced.
Suggested labels: renderer, terminal, tests
Suggested reviewers: None specified.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Concise and accurate: it clearly reflects the main behavior change, stopping terminal flicker during active Claude Code sessions.
Description check ✅ Passed Mostly complete: it covers the change, evidence, testing, review, and risks, but screenshots and a dedicated security-audit section are not explicit.
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

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.

🧹 Nitpick comments (2)
src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts (2)

5-11: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Comment blocks exceed the "one or two lines" guideline.

Several "Why" comments here run 5-8 lines (Lines 5-11, 48-54, 57-65). While the context is valuable, consider trimming to the essential non-obvious rationale and moving extended design discussion (e.g., "Brennan-approved", numeric fire-count history) to the PR description or a linked doc.

As per coding guidelines, **/*.{ts,tsx,js,jsx}: "Keep comments short — one or two lines, capturing only the non-obvious reason."

Also applies to: 48-54, 57-65

Source: Coding guidelines


57-72: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Pure trailing-edge debounce has no upper bound — verify unbounded deferral is intentional.

scheduleTerminalWebglAtlasRecovery re-arms on every call with no maxWait. If terminal output never leaves a 200ms gap (e.g., a long-running command with continuous output), resetAtlasesAndRefreshPanes() could be deferred for the entire duration, leaving stale/garbled glyphs uncorrected until the stream pauses. The PR's macOS validation (39→0 fires) suggests natural gaps exist in practice, but a hard-capped maxWait (similar to lodash debounce's maxWait option) would guard against pathological sustained-output cases without reintroducing flicker.

♻️ Optional maxWait guard
+const TERMINAL_OUTPUT_RECOVERY_MAX_WAIT_MS = 2000
+let terminalOutputRecoveryFirstPendingAt: number | null = null
+
 export function scheduleTerminalWebglAtlasRecovery(): void {
   if (terminalOutputRecoveryDebounceTimer != null) {
     globalThis.clearTimeout(terminalOutputRecoveryDebounceTimer)
   }
-  terminalOutputRecoveryDebounceTimer = globalThis.setTimeout(() => {
-    terminalOutputRecoveryDebounceTimer = null
-    resetAtlasesAndRefreshPanes()
-  }, TERMINAL_OUTPUT_RECOVERY_QUIET_MS)
+  const now = Date.now()
+  terminalOutputRecoveryFirstPendingAt ??= now
+  const remainingBudget = TERMINAL_OUTPUT_RECOVERY_MAX_WAIT_MS - (now - terminalOutputRecoveryFirstPendingAt)
+  const delay = Math.max(0, Math.min(TERMINAL_OUTPUT_RECOVERY_QUIET_MS, remainingBudget))
+  terminalOutputRecoveryDebounceTimer = globalThis.setTimeout(() => {
+    terminalOutputRecoveryDebounceTimer = null
+    terminalOutputRecoveryFirstPendingAt = null
+    resetAtlasesAndRefreshPanes()
+  }, delay)
 }

Could you confirm via web search or docs whether a maxWait-style cap is a common/recommended pattern for this kind of debounce, and whether unbounded deferral was an accepted tradeoff in the design discussion?


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 52f3f187-2802-443f-85cb-cec257ba818e

📥 Commits

Reviewing files that changed from the base of the PR and between 3b081c1 and 9b6c106dfcd39dc34260409fc4d04ffc6ae30de6.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts

…ecovery

An alternate-screen TUI (Claude Code, vim) emits an in-place-rewrite chunk on
every streaming frame, and the renderer-risk path does the same for CJK/
translated output. Each chunk requested a global WebGL glyph-atlas clear +
all-pane repaint, which during an active agent session fired several times a
second (measured 39 global repaints over 8.5s of streaming), reading as a
terminal-wide flicker that stops the moment output goes static.

Debounce the terminal-output recovery to the trailing edge: a sustained redraw
stream coalesces to a single clear+refresh that runs only after 200ms of quiet,
so no atlas clear ever lands during visible streaming. A resumed stream re-arms
(and cancels) the one debounce timer, so a pause-then-resume can't leak a clear
mid-stream. Tab-reveal recovery keeps its own immediate burst (decoupled from
the streaming debounce so a background stream can't defer a revealed tab's
rebuild); the image-paste, OS-wake and context-loss paths are unchanged.

STA-1365

Co-authored-by: Orca <[email protected]>
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-1365-claude-code-terminal-flicker branch from 9b6c106 to 5786193 Compare July 6, 2026 08:25
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Thanks @coderabbitai — addressed both:

Comment length: trimmed the three "Why" blocks in terminal-webgl-atlas-recovery.ts to 1–3 lines each, keeping only the non-obvious rationale (fire-count history / design-discussion detail lives in the PR description).

maxWait cap: intentionally not added — unbounded deferral during sustained output is the correct behavior here, not a gap. A maxWait would fire a global atlas-clear + all-pane repaint on a fixed interval during continuous streaming, which reintroduces exactly the flicker this PR removes (just at a lower frequency). It's safe to defer indefinitely because a continuously-redrawing TUI repaints its own cells every frame, so stale glyphs don't accumulate visibly while output is flowing; the staleness the recovery guards against only becomes visible once content stops changing — which is precisely when the trailing-edge debounce fires. In other words, "recover when output settles" is the invariant, and a hard cap would violate it. The one accepted consequence (a visible idle pane's output-driven cleanup can defer while a sibling/hidden agent streams) is disclosed in the PR body; all other recovery triggers (reveal/resume/OS-wake/paste/context-loss) remain immediate.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@brennanb2025 Thanks for the detailed explanation on both points.

On the comment trimming — appreciate the cleanup, keeping the rationale concise in-code while the fuller design discussion stays in the PR description is a reasonable trade-off.

On the maxWait cap — your reasoning holds up: since a continuously-redrawing TUI repaints its own cells every frame, stale glyphs don't become visibly stale until output actually stops, which is exactly when the trailing-edge debounce fires. A hard cap would just reintroduce periodic flicker during sustained streaming at a lower frequency, defeating the purpose of this fix. The disclosed trade-off (a visible idle pane's cleanup deferring while a sibling/hidden agent streams) is an acceptable, well-documented edge case given all other recovery paths remain immediate. I'm satisfied this was a deliberate design choice rather than a gap.

(=^・ω・^=) ノ


✏️ Learnings added
Learnt from: brennanb2025
URL: https://github.com/stablyai/orca/pull/7540

Timestamp: 2026-07-06T08:26:10.199Z
Learning: In src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts, the `scheduleTerminalWebglAtlasRecovery()` debounce (TERMINAL_OUTPUT_RECOVERY_QUIET_MS = 200ms trailing-edge debounce) is intentionally unbounded (no maxWait/cap) during sustained streaming output. This is a deliberate design decision, not a gap: a continuously-redrawing TUI (e.g., Claude Code) repaints its own cells every frame, so stale glyphs don't accumulate visibly while output is flowing. Staleness only becomes visible once content settles, which is precisely when the trailing-edge debounce fires. Adding a maxWait would force periodic global atlas-clear + full-pane repaints during continuous streaming, reintroducing the flicker this PR was designed to eliminate. The accepted trade-off (a visible idle pane's output-driven cleanup can defer while a sibling/hidden agent streams) is intentional and documented in the PR body. Do not suggest adding a maxWait cap to this debounce logic in future reviews.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

✅ Windows validation — mid-stream terminal flicker fix

Validated on Windows 11 against this branch (dev build, worktree 7540). Instrumented two points and streamed continuous CJK/translated output through a real ConPTY → xterm alternate-screen TUI (JP/KR/CN + emoji, ~120 in-place-rewrite frames over ~8 s), reproducing the Claude-Code-style redraw storm:

  • resetAtlasesAndRefreshPanes → counts actual atlas clears (fires)
  • scheduleTerminalWebglAtlasRecovery → counts recovery requests (calls)

Before / after (identical focused-window conditions)

Code recovery requests atlas clears during the ~8 s stream
pre-fix (HEAD~1) 115 42 — spread across the whole stream (~5/sec)
this branch (fix) 114–130 1 — a single settle ~200 ms after output goes quiet
  • Pre-fix reproduces the flicker storm: 42 global atlas clear + all-pane repaints during streaming (matches the commit message's documented "39 repaints over 8.5 s").
  • With the fix, zero clears land during visible streaming — the 120+ per-frame requests coalesce to exactly 1 trailing-edge clear+refresh. Reproduced across multiple runs (1 fire every time; last call → single fire 201 ms later).

Native rendering intact / no visible flicker

  • Frame-by-frame capture of the fixed-branch stream: every frame is fully painted and correct — 翻訳テスト…, 안녕하세요…, 这是一段中文…, mixed ASCII + emoji ✨ 🚀. No stale/garbled glyphs after redraws, no blanked frames.
  • The pre-fix code renders the same glyphs correctly too → the defect was purely flicker (rapid atlas clears), not broken rendering. The fix removes the clears without regressing ConPTY glyph rendering.
  • Harness sanity check passed: a one-shot tab-reveal burst fires exactly 3× (rAF + 120 ms + 500 ms), and a no-stream baseline fires 0×.

Note on automation artifact

When the Orca window is occluded/backgrounded under headless CDP automation, Chromium throttles renderer timers to ~1 Hz, batching PTY delivery so the debounce legitimately settles once per batch (~8 fires). Bringing the window to the foreground (real-world usage) gives the clean 1 fire. Either way the debounce coalesces correctly — the pre-fix burst path fires 3× per request regardless.

Verdict: fix works as designed on Windows — mid-stream flicker eliminated (42 → 1 atlas clear during streaming), native CJK/ConPTY rendering unaffected.

@brennanb2025
brennanb2025 merged commit fbaf3f7 into main Jul 6, 2026
1 check passed
@brennanb2025
brennanb2025 deleted the brennanb2025/sta-1365-claude-code-terminal-flicker branch July 6, 2026 17:11
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
74 commits from main, including the STA-1278 ai-vault transcript perf work,
terminal flicker fix (#7540), renderer V8 heap raise (#7531), scrollbar
position preservation (#7472), and the per-delivery debug-snapshot
allocation removal (#7541).

Conflict resolutions (our structure, main's semantics):
- agent-detection: kept the split-module barrel; grafted main's Gemini/Pi
  title-detection refinements (path-fragment false positives, legacy Pi
  synthetic titles) into agent-title-core, dropped the superseded
  PI_IDLE_PREFIX.
- orca-runtime wait-blocked detection: kept the throttled
  scheduleWaitBlockedCheck (branch §1 optimization) and ported it to main's
  new cached TerminalTailWaitState API; main's per-chunk cached scan stays
  on the leaf mismatch path where it auto-merged. pty.tailWaitState is
  deliberately never populated on this branch (throttle owns the pty
  record), so the leaf mirror copy invalidates rather than shares — the
  fromTail exactness contract is never violated by stale state.
- recordPtyRendererDeliveryPressure: took main's allocation-free peak
  update (#7541) and derived per-pty in-flight from this branch's
  cumulative sent/acked accounting instead of the removed
  rendererInFlightCharsByPty map.
- rpc/methods/terminal detach: kept both sides — our
  flushAllAckPendingOutput and main's exitWaiterAbort release.
- pty-connection: kept our single-policy handleCommandFinished (invariant)
  alongside main's new sampleVisiblePaneForegroundAgent (bodies were
  byte-identical where they overlapped).
- e2e pressure scenarios: kept the Phase-4 hidden-gate contract assertions
  and the extracted pressure-script module; adopted main's
  MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS budget.

Also documents the renderer-pull delivery watchdog in the branch guide.

Gates: typecheck clean; ipc/daemon/terminal-pane/pane-manager suites 4256
passed; both fuzz suites pass.

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 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.

1 participant