Skip to content

fix(terminal): release an abandoned synchronized-output frame on reveal (STA-2694) - #10907

Merged
nwparker merged 10 commits into
mainfrom
neil/sta-2694-fix-ui-rendering-artifacts-when-switching-away-from-ai
Jul 27, 2026
Merged

nwparker merged 10 commits into
mainfrom
neil/sta-2694-fix-ui-rendering-artifacts-when-switching-away-from-ai

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes STA-2694 — "switch away to the desktop and come back, the terminal is garbled until I resize the window."

Proof (actual captures, not inference)

The defect and the fix are both captured on screen. This works where my earlier screenshot oracles were blind, and the reason is the mechanism itself: while synchronizedOutput is latched, refreshRows returns before reaching the renderer, so a compositor frame just re-composites the existing canvas texture. The stale pixels survive the screenshot instead of being healed by it. The earlier oracles failed because they compared a revealed pane against a "repaired" one and both ran the same repaint code.

Reproduced by tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts: paint a frame, latch mid-?2026h, write a full new frame the pane cannot paint, capture.

1 — before switching away. The agent's frame, painted normally.

1-before-hide.png

2 — on return. This is the bug. The screen still shows AGENT FRAME 1 and "original content" — byte-identical to shot 1 (28463 bytes both) — while xterm's buffer has fully advanced to frame 2:

### AGENT FRAME 2 — WHAT THE BUFFER NOW HOLDS ###
  line 1: UPDATED content ##############################
  ...

2-garbled-on-return.png

3 — after the fix's reveal repaint. The screen now matches the buffer.

3-after-fix.png

That byte-identity is the whole claim: the buffer advanced an entire frame and the canvas showed none of it. The spec asserts both halves — identical while latched, different after the repaint — so it fails if the defect stops reproducing or if the fix stops repairing it.

What is and isn't proven

Claim Evidence
The latch strands a pane with stale pixels Proven — captures above, plus 0 draw calls measured while latched
No watchdog is pending for an occluded pane Proven — asserted directly (_timeout === undefined)
The fix repaints it Proven — captures above; teeth-verified, removing the fix fails the test
The user's exact field incident is this mechanism Not proven — this reproduces the described symptom by the traced mechanism; I have not instrumented their machine

Root cause

Alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every repaint in DEC 2026 synchronized output — ?2026h … ?2026l — many times a second. Hide a pane mid-bracket (worktree switch, cold park, or OS-level occlusion all land there routinely) and xterm keeps decPrivateModes.synchronizedOutput latched.

RenderService.refreshRows checks that latch before rendering, so while it holds every repaint Orca owns is a no-op — the forced render-pause repaint, the plain refresh() fallback, and the shared glyph-atlas rebuild all render zero rows while the xterm buffer is perfectly correct. Exactly the reported shape.

The fix releases the latch at both reveal repaint entry points, before the repaint.

The window is unbounded (correcting my own earlier claim)

I originally scoped this as "closes a bounded ~1s window" because xterm arms a 1s watchdog. That was wrong, and it matters — it's the difference between a cosmetic blip and the reported bug.

The watchdog is armed only inside SynchronizedOutputHandler.bufferRows, and refreshRows returns at its _isPaused check first:

if (this._isPaused) { this._needsFullRefresh = true; return }   // occluded pane stops HERE
if (this._coreService.decPrivateModes.synchronizedOutput) {
  this._syncOutputHandler.bufferRows(start, end)               // only place the watchdog arms
  return
}

An occluded pane's IntersectionObserver sets _isPaused, so nothing ever reaches bufferRows and no timer is ever pending. The latch is stranded indefinitely. That also explains the specific workaround: a window resize makes the TUI repaint via SIGWINCH, and its closing ?2026l clears the latch.

A hypothesis I implemented, then refuted and reverted

I'd also shipped a "clear the render model on reveal" fix, reasoning that xterm's diff-based renderers skip cells whose model entry still matches the buffer. _updateModel really does early-continue per unchanged cell — but measured on a live pane:

Refresh updateCell calls instances drawn
diff-skipped 0 562
model cleared first 561 562

GlyphRenderer.render copies vertices for every row up to lineLengths[y] and issues one full-viewport draw. The diff decides how much vertex data is rewritten, never how much is drawn; the DOM renderer likewise replaceChildren()s every row unconditionally. So it could not change what reached the screen — and it had a real cost: _clearModel(true) zeroes every glyph vertex while RenderService.clear() fires no repaint of its own, opening a blank-viewport window. Reverted, and the refutation is pinned by a test so it can't come back as a "fix".

Why there's a new kind of test here

Every pixel oracle I built for this was blind, and I proved it by injecting the exact defect:

  1. Canvas-vs-buffer ink sampling — drawImage on a non-preserveDrawingBuffer WebGL canvas returns a re-rendered copy. Reported 0 missing cells against 5263 cells the canvas had never drawn.
  2. Screenshot vs. forced repaint — Playwright's screenshot drives a fresh compositor frame that heals the stale paint before capture.

Pixels are the wrong layer: reading them triggers the repaint that hides the bug. terminal-reveal-draw-command-probe.spec.ts instead wraps GlyphRenderer.updateCell and gl.drawElementsInstanced on the live pane and counts draw commands, which cannot be healed after the fact.

Teeth-verified: deleting the releaseAbandonedSynchronizedOutput line makes the stranded-latch test fail with "the reveal repaint did not release the stranded latch, so the pane stays frozen".

Leads closed by measurement

  • Dimension staleness (the leading suspect for "why a resize specifically"): across a real hide()/show(), canvas backing store 1272×1104 matched the renderer's computed dimensions exactly, char metrics stayed 8.65×16, _isAttached and screen-element connection held. Ruled out.
  • Lagging atlas bindings: bound texture version does lag right after reveal (1297 vs 1366), but bindings are lazy and one repaint levels them (1366/1366). Normal — judge bindings only after a draw.

Performance

Measured, not asserted. The production delta is 2 call sites plus one O(1) function — no new allocations, timers, listeners, or caches (grep for new/setTimeout/setInterval/addEventListener in the fix returns nothing).

The reason this needed measuring rather than hand-waving: releaseAbandonedSynchronizedOutput sits inside resetWebglTextureAtlas, which a streaming alt-screen TUI can reach through the terminal-output atlas recovery path (pty-connection.ts:5754), not only on reveal. So it is on a path a flooding agent TUI can touch.

tests/e2e/terminal-synchronized-output-release-perf.spec.ts pins both directions:

Scenario Result
Steady state — 200 fully-bracketed frames from a healthy TUI 0 releases, 0 extra draw calls, ~0.03ms per full atlas-reset call
Worst case — every reveal finds a latched frame (50 latched atlas resets) 0.08ms each (4.0ms total)

Why steady state is free: the function returns at its first property read unless a frame was genuinely abandoned. A TUI that closes every ?2026l it opens never reaches the assignment. The ~0.03ms above is the cost of the whole recovery (atlas clear + refresh), not the release — the release's own contribution is what the zero draw counts demonstrate. Reveal is a one-shot user action, so even the full path has enormous headroom.

(Correction: an earlier revision of this section quoted an unmeasurable 0.000ms. That number came from a test timing a hand-copied mirror of the early-out rather than the shipped code — caught in review, now fixed to drive the real path.)

Both bounds are set at ~10x measured (< 0.4ms/call steady state, < 20ms/reveal worst case) so they act as regression guards — catching a future change that makes this scan the buffer per pane — rather than flaking on machine speed.

It removes a timer rather than adding one: the flush() call clears xterm's pending synchronized-output watchdog setTimeout when one exists.

Project perf-budget suite re-run against this branch — 10 passed (terminal-typing-latency, terminal-foreground-redraw-freeze, terminal-output-scheduler, terminal-hidden-tui-visual-restore), covering typing echo latency, OpenCode/OpenTUI redraw floods, background drain scheduling, and hidden-TUI restore.

Checked and clear on the other axes: no polling, no subprocess, no IPC, no persistence writes, no store subscriptions, no list/tree work, no listSessions() in a hot path, and no change to hidden-pane gating or read pagination.

Testing

  • 8 unit tests across 2 files; 16 headless e2e pass (8.2m) covering the oracle, alt-screen convergence (worktree switch, cold park, idle agent), paused-render recovery, and visibility/WebGL recovery; headful desktop-hide passes (22.6s)
  • typecheck:web exit 0; full oxlint clean
  • Full unit suite: 37069 passed. 4 failures are unrelated and pre-existing — src/relay/agent-exec-handler.test.ts fails identically at the merge base; the other two pass in isolation (load-related flakes). None are in files this branch touches.

Residual risk

The oracle proves the repaint is issued; it doesn't photograph the user's screen. If a report survives this, the remaining suspects are below the draw call (GPU-process/compositor content loss), where the in-app render-desync sentinel on real hardware is the tool — procedure documented in the handoff doc.

Made with Orca 🐋

nwparker and others added 6 commits July 27, 2026 00:53
Alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every repaint
in `?2026h … ?2026l`. Hiding a pane mid-bracket — which a worktree switch or
cold-park lands on routinely, since these brackets are written many times a
second — leaves xterm's `decPrivateModes.synchronizedOutput` latched.

RenderService.refreshRows checks that latch *before* rendering, so while it
holds, every repaint Orca owns is a no-op: the forced render-pause repaint,
the plain `refresh()` fallback, and the shared glyph-atlas rebuild all render
zero rows while the xterm buffer is perfectly correct. Release the latch at
the two reveal repaint entry points so those repaints actually paint.

Also adds an OpenCode-shaped alt-screen e2e fixture and spec. The existing
inline-TUI convergence spec covers the normal-buffer shape (live block glued
to the bottom, history scrolling into scrollback); this covers the
full-screen alternate-buffer shape, where nothing scrolls and so no row ever
self-heals through the scroll path.

Scope note: xterm arms a 1s watchdog that clears this latch on its own, so
this closes a bounded window rather than the whole STA-2694 report. The e2e
spec passes with and without the production change for that reason; the unit
tests are what pin the behavior. Refs STA-2694.
`schedulePaneRevealPresent` — the atlas-preserving path a plain window
refocus takes — only called `terminal.refresh()`. xterm's renderers are
diff-based: `_updateModel` early-continues on any cell whose code/fg/bg/ext
still match the cached model, so a refresh repaints nothing for a pane whose
buffer never changed. When an occluded window loses its canvas contents while
that model stays populated, the refresh skips exactly the cells that went
stale and the pane keeps compositing pre-hide pixels — until a window resize
reallocates the model, which is the repair users find by hand.

Clear the model first (`RenderService.clear()` → renderer `clear()` →
`_clearModel(true)`) so the refresh becomes a guaranteed full repaint. That
drops cached cells and glyph vertices but NOT the texture atlas, which is
shared by every same-config terminal and whose mid-stream wipe re-arms xterm's
page-merge garble race (xterm.js #4480) — the reason this path is
atlas-preserving in the first place.

Also covers the DOM-renderer fallback in `resetWebglTextureAtlas`:
`clearTextureAtlas()` is what invalidated the model on the WebGL path, so a
pane without an addon had nothing invalidate it and hit the same skip.

Scope note: the e2e spec guards buffer/geometry convergence across the
hide/reveal boundaries and adds idle-agent and headful desktop-hide cases, but
it cannot observe a stale canvas — both oracles built for that (canvas-vs-buffer
ink sampling, screenshot-vs-forced-repaint) were proven blind by injecting the
defect, and the spec header documents why. The unit tests pin the ordering and
the atlas-preservation invariant. Refs STA-2694.

Co-authored-by: Orca <[email protected]>
Records both fixed defects with their xterm mechanisms, the reveal/wake call
graph, why every e2e oracle for a stale canvas was proven blind, how to arm the
in-app render-desync sentinel on real hardware, and the one unverified lead
(dimension staleness) that would explain why a window resize specifically is
the repair users find. Refs STA-2694.

Co-authored-by: Orca <[email protected]>
…rrect the STA-2694 scope

Every pixel oracle tried for STA-2694 was blind: `drawImage` on a
non-preserveDrawingBuffer WebGL canvas returns a re-rendered copy, and
Playwright's screenshot drives a fresh compositor frame that heals a stale paint
before capture. Reading pixels is self-defeating here — the read triggers the
repaint that hides the bug.

Count the WebGL draw commands instead, by wrapping GlyphRenderer.updateCell and
gl.drawElementsInstanced on the live pane. A draw command cannot be healed after
the fact, so "did the reveal actually repaint?" becomes directly observable.
Teeth-verified: removing releaseAbandonedSynchronizedOutput from
schedulePaneRevealPresent fails the stranded-latch test.

Two findings, both of which change previously-committed claims:

1. The 1s watchdog does NOT bound the synchronized-output defect. It is armed
   only inside `bufferRows`, and `refreshRows` returns at its `_isPaused` check
   first — so while a pane is occluded nothing reaches `bufferRows` and no timer
   is ever pending. A pane hidden mid-`?2026h` holds the latch with no watchdog
   behind it, indefinitely. ed1eaf5's "closes a bounded window" scope note was
   wrong; this is the unbounded garble the report describes, and the fix closes
   it. Corrected in the module doc comment.

2. It refutes the diff-based-staleness hypothesis behind 0f7ec44 (reverted in
   8d5eace). `_updateModel` does early-continue per unchanged cell, but
   `GlyphRenderer.render` then copies vertices for EVERY row up to
   `lineLengths[y]` and issues ONE full-viewport draw — measured identical
   instance counts (562) for a diff-skipped and a model-cleared refresh, with
   updateCell at 0 vs 561. The DOM renderer likewise replaceChildren()s every
   row unconditionally. Clearing the model could not change what reached the
   screen, and `_clearModel(true)` zeroes every glyph vertex while
   `RenderService.clear()` fires no repaint of its own — so it opened a
   blank-viewport window (also asserted here) for no benefit.

Also keeps the idle-agent and headful desktop-hide cases from the reverted
commit, since those were independent of the refuted production change, and
rewrites the alt-screen spec header to point paint questions at this oracle.
Refs STA-2694.

Co-authored-by: Orca <[email protected]>
Records that the garble window is unbounded (the 1s watchdog never arms for an
occluded pane), that the diff-based-staleness hypothesis was refuted by
measurement and reverted, why pixel oracles are structurally blind here, and the
two leads now closed by measurement (dimension staleness, lazy atlas bindings).
Refs STA-2694.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds recovery for abandoned xterm synchronized-output latches in pane reveal presentation and WebGL atlas reset paths. Introduces unit tests for latch clearing, buffered-row flushing, missing internals, and repaint gating. Adds an animated alt-screen PTY fixture and Playwright coverage for buffer, geometry, PTY-size, pixel, performance, and draw-command convergence across reveal scenarios. Documents the defect mechanism, rejected hypotheses, oracle strategy, residual risks, and verification commands.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and is missing explicit Summary, Screenshots, AI Review Report, Security Audit, and Notes sections. Rewrite the PR description to match the repository template and add the missing sections, including screenshot note, AI review report, security audit, and notes.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main change: releasing abandoned synchronized-output state on reveal for STA-2694.
✨ 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.

Actionable comments posted: 4

🧹 Nitpick comments (4)
src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts (1)

1-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the duplicated incident narrative.

  • src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts#L1-L32: retain a short invariant describing why reveal clears DEC 2026.
  • src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.test.ts#L1-L11: replace the repeated mechanism with a one-line test intent.
  • src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts#L1-L11: replace the repeated mechanism with a one-line test intent.

Move the investigation detail to documentation. As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines

tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs (1)

138-143: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Exit depends solely on the stdout write callback.

If the write never flushes (closed/backpressured PTY), the fixture never exits and the re-entrancy guard makes a second SIGINT/SIGTERM a no-op. An unref'd fallback timer guarantees termination.

♻️ Optional hardening
   process.stdout.write('\x1b[?1002l\x1b[?1006l\x1b[?25h\x1b[?2026l\x1b[?1049l', () =>
     process.exit(0)
   )
+  setTimeout(() => process.exit(0), 500).unref()
tests/e2e/terminal-reveal-draw-command-probe.spec.ts (1)

95-155: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Instrumentation is never restored.

Patches on glyphRenderer.updateCell / gl.drawElementsInstanced persist for the life of the page; if orcaPage is shared across tests in a worker, wrappers stack per test. Counts stay correct (only the newest probe is read), but an afterEach restore would keep the renderer clean.

docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md (1)

43-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Pinned upstream line reference (RenderService.ts:162) will drift.

The quoted snippet carries the argument on its own; the line number goes stale on any xterm bump. Consider citing the version alongside it.

Also applies to: 64-72


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6d6cf5b-3704-4086-a1a8-08da04189d31

📥 Commits

Reviewing files that changed from the base of the PR and between fb26254 and dfa6804.

📒 Files selected for processing (9)
  • docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md
  • src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts
  • src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts
  • src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts
  • src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.test.ts
  • src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts
  • tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs
  • tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts
  • tests/e2e/terminal-reveal-draw-command-probe.spec.ts

nwparker and others added 2 commits July 27, 2026 13:15
The earlier screenshot oracles were blind because they compared a revealed pane
against a repaired one and both ran the same repaint code. Capturing the defect
directly works instead, because the mechanism is self-preserving: while
synchronizedOutput is latched, refreshRows returns before reaching the renderer,
so a compositor frame just re-composites the existing canvas texture and the
stale pixels survive the screenshot rather than being healed by it.

Latch a frame, write a full new frame the pane cannot paint, and capture. The
screenshot comes back byte-identical to the pre-hide one while the buffer holds
the new frame — the buffer/screen divergence users report — and differs after
the reveal repaint runs. Asserts both halves, so it fails if either the defect
stops reproducing or the fix stops repairing it.

Refs STA-2694.

Co-authored-by: Orca <[email protected]>
…real

The unit double encodes RenderService's paused-then-latch gate order, which can
drift on an xterm upgrade. Point at the e2e oracle that pins the same order
against the real renderer, so a future upgrade has a trail to the authoritative
check. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

@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

🧹 Nitpick comments (4)
tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts (4)

1-17: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Trim the file-header narrative; move extended rationale to the handoff doc.

This 17-line docblock is largely narrative reasoning rather than a single concise note. The stack already ships a dedicated handoff doc (docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md) for this exact purpose — consider linking to it and keeping the in-file comment to the essential non-obvious facts (latch → refreshRows short-circuit → stale texture).

As per coding guidelines, "Comments must be concise, limited to non-obvious information, preferably one line; do not explain obvious code or walk through implementation details."

Source: Coding guidelines


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

Hardcoded /tmp default isn't cross-platform.

'/tmp/sta2694-evidence' is a POSIX-specific default. Use path.join(os.tmpdir(), 'sta2694-evidence') so the fallback works when ORCA_E2E_EVIDENCE_DIR is unset on Windows CI/dev machines too.

🔧 Proposed fix
+import os from 'node:os'
...
-const EVIDENCE_DIR = process.env.ORCA_E2E_EVIDENCE_DIR ?? '/tmp/sta2694-evidence'
+const EVIDENCE_DIR = process.env.ORCA_E2E_EVIDENCE_DIR ?? path.join(os.tmpdir(), 'sta2694-evidence')
As per coding guidelines, "code, commands, and scripts must work on macOS, Linux, and Windows" and should "use path utilities such as `path.join` instead of hardcoded separators."

Source: Coding guidelines


39-124: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Duplicated unsafe-cast pane access; latch setter/getter can drift.

The for (const manager of window.__paneManagers?.values() ?? []) + deep as {...} cast pattern is repeated across activeWebglTerminalReady, writeToPane, paneClip, readScreenText, the latch-set block (153-165), and the latch-read block (204-216). Most concerning: the latch is set and later read via two independently-typed unsafe cast chains reaching terminal._core.coreService.decPrivateModes.synchronizedOutput. If xterm's internal shape ever changes, one path could silently stop matching while the other still compiles, undermining this test's core assertion without a visible failure signal. Extracting a single typed helper (e.g. forEachPane(page, fn) plus getSynchronizedOutputLatch/setSynchronizedOutputLatch) used by both call sites would remove the duplication and the drift risk.

Also applies to: 153-216


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

Fixed waitForTimeout sleeps risk CI flakiness.

writeToPane sleeps 600ms hoping xterm finished processing the write (no completion callback is awaited), and the reveal step sleeps 1200ms hoping the repaint completed. Under CI load either could be too short (flaky failure) or unnecessarily slow the suite. Prefer polling the actual condition (e.g. expect.poll(() => readScreenText(...)) for the write, and polling the latch/screenshot state for the repaint) instead of fixed delays.

Also applies to: 199-199


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6a276dbe-2289-4e72-a592-abdc2bef51be

📥 Commits

Reviewing files that changed from the base of the PR and between dfa6804 and 8397dfe.

📒 Files selected for processing (2)
  • src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts
  • tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts

Comment on lines +184 to +191
// ...while the SCREEN is byte-identical to the pre-hide capture. This is the
// defect itself: the buffer advanced a whole frame and the canvas shows
// none of it. It also proves the screenshot did not heal the pane, which is
// what made the earlier pixel oracles blind.
expect(
Buffer.compare(beforeShot, staleShot),
'the screen changed while the frame was latched, so no stale paint was captured'
).toBe(0)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate WebGL cursor rendering / blink handling to confirm it shares the refreshRows gate.
rg -nP -C3 'cursorBlink|blink' src/renderer/src/lib/pane-manager

Repository: stablyai/orca

Length of output: 1478


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate relevant files =="
git ls-files | rg 'tests/e2e/terminal-reveal-latch-visual-evidence|src/renderer/src/lib/pane-manager|renderer' | sed -n '1,200p'

echo
echo "== outline e2e file =="
ast-grep outline tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts --view expanded || true

echo
echo "== relevant e2e lines =="
sed -n '150,240p' tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts | cat -n -v

echo
echo "== blink/cursor search broader =="
rg -n -C2 'cursorBlink|blink|refreshRows|render.*rows|Renderer|renderer' src/renderer/src/lib/pane-manager src/renderer/src tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== e2e file around assertions =="
sed -n '150,235p' tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts | cat -n -v

echo
echo "== focused blink/render references =="
rg -n -C4 'cursorBlink|cursorBlinkTimeout|blink|refreshRows|requestRender|requestAnimationFrame|animationFrame|RAF|raf|setInterval|setTimeout' src/renderer/src lib node_modules 2>/dev/null \
  | rg -n -C4 'terminal-pane|renderer|RenderService|xterm|Webgl|webgl|cursor' \
  | sed -n '1,260p'

echo
echo "== package versions =="
if [ -f package.json ]; then
  node -e "const p=require('./package.json'); for (const s of ['dependencies','devDependencies']) if (p[s]) for (const [k,v] of Object.entries(p[s])) if (/xterm/.test(k)) console.log(s+': '+k+' '+v)"
fi

Repository: stablyai/orca

Length of output: 26821


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== all repository blink/render/timer references of interest =="
rg -n 'cursorBlink|cursorBlinkTimeout|blink|refreshRows|requestRender|requestAnimationFrame|animationFrame|setInterval|setTimeout|setTimeout\(' src/renderer src main tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts | sed -n '1,240p'

echo
echo "== deterministic blink timing semantics for modern xterm package if available =="
if [ -f package-lock.json ]; then
  node - <<'JS'
const lock = require('./package-lock.json')
for (const v of Object.values(lock.packages || {})) {
  if (v.name && (/xterm$/.test(v.name) || /@xterm\//.test(v.name))) console.log(v.name, v.version)
}
JS
fi

Repository: stablyai/orca

Length of output: 50369


🌐 Web query:

xterm.js WebGLRenderer Cursor blink implementation refreshRows cursorBlink requestAnimationFrame

💡 Result:

In xterm.js, the WebGLRenderer's cursor blinking implementation has evolved from using an external DOM-based layer to being rendered directly within the WebGL canvas [1][2]. Key aspects of the implementation include: 1. Evolution of Rendering: Previously, the WebGL renderer utilized a separate 'CursorRenderLayer' (a transparent 2D canvas) positioned over the WebGL canvas to handle the cursor [3][2][4]. This was replaced by an integrated approach where the cursor is drawn directly into the WebGL canvas, consolidating rendering logic and ensuring visual consistency [1]. 2. CursorBlinkStateManager: The terminal manages the blink state via the 'CursorBlinkStateManager' [5][6]. This manager handles the timing of the blink cycle and ensures that resources—specifically the interval timer—are properly disposed of when the terminal or renderer is disposed of [5][6]. Failure to properly register this disposable has historically been a source of memory leaks and unwanted background activity [5]. 3. Refresh mechanism: When the cursor needs to blink, the state change triggers a refresh. While the renderer uses efficient batch updates for terminal content, the cursor blink typically necessitates triggering a render cycle to update the cursor's visual state on the GPU [3]. Modern implementations optimize this by sharing the blink state manager between the core terminal and the WebGL renderer [1]. 4. Performance Considerations: Managing the blink state via 'requestAnimationFrame' is generally preferred over standard 'setInterval' when synchronization with screen repaints is required to prevent visual artifacts like flickering [7]. However, the 'CursorBlinkStateManager' specifically relies on an interval timer to toggle the blink state [5]. The WebGL renderer then renders the cursor as needed, often by updating the buffer or triggering a render pass [1][3]. By moving cursor rendering into the WebGL pipeline, the system avoids the overhead of managing an additional DOM layer, though it requires careful management of rendering cycles to balance responsiveness and power consumption [1][3][2].

Citations:


Avoid byte-exact blink-sensitive screenshot assertions.

Both synchronizedOutput and the WebGL cursor are independent visual gates on the canvas. A full-clip screenshot comparison can fail/pass based on cursor-phase blink timing instead of the latch bug. Match the same cursor phase with cursorBlinkTimeout, take screenshots through the same blink phase, or compare against a mask that excludes the cursor.

releaseAbandonedSynchronizedOutput runs inside resetWebglTextureAtlas, which a
streaming alt-screen TUI can reach through the terminal-output atlas recovery
path — not only on reveal. Measure rather than assert that this costs nothing.

Steady state (a TUI that closes every frame it opens): 200 bracketed frames
produce zero releases, zero extra draw calls, and an unmeasurable early-out
cost. Worst case (every reveal finds a latched frame): 50 latched atlas resets
at 0.08ms each. Both are asserted with headroom, so the guard catches a future
change that makes this scan the buffer per pane rather than flaking on machine
speed. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

@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: 3

🧹 Nitpick comments (2)
tests/e2e/terminal-synchronized-output-release-perf.spec.ts (2)

65-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated pane/renderer discovery + draw patch, and restore the patch when done.

Both tests repeat the same ~30 lines of internals walking and gl.drawElementsInstanced instrumentation, and neither restores the original function, leaving the counted wrapper installed on the live context for anything that runs afterwards in the same page. Consider a shared page-side probe in tests/e2e/helpers/terminal.ts that returns a restore callback invoked in a finally.

Also applies to: 182-214


215-216: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer the write completion callback over a fixed 500ms sleep.

Test 1 already uses write('', cb) for deterministic flushing; reusing it here removes an arbitrary wait.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 79db77c4-63f4-4ff4-b729-ded28f0aca6b

📥 Commits

Reviewing files that changed from the base of the PR and between 8397dfe and fe9a297.

📒 Files selected for processing (1)
  • tests/e2e/terminal-synchronized-output-release-perf.spec.ts

… gaps

CodeRabbit caught a genuine tautology in the perf budget: it timed a
hand-copied mirror of the early-out rather than the shipped function, so the
assertion would have held even if the real code grew a buffer scan. Driving
resetWebglTextureAtlases instead moved the measured cost from ~0 to ~0.03ms per
call, which is the honest number for the whole recovery; bound re-set to 0.4ms
(10x measured).

Other review fixes:
- Assert the draw counts both perf tests were measuring and logging but never
  checking, so the 'no extra draws' titles now mean something.
- Fail fast when decPrivateModes is unavailable; previously the latched test
  would pass without ever exercising the fix.
- Re-check the latch right after the worktree switch in the mid-frame test: the
  pane is visible until then, so the 1s watchdog can arm and clear it before the
  hide, making the run vacuous.
- Count scheduleRevealPresent invocations instead of returning a literal true,
  so a missing test hook no longer masquerades as a production failure.
- Assert the latch clears on every reveal iteration, not just the last.
- Make the fixture heartbeat write atomic (tmp + rename); writeFileSync
  truncates first, so a reader could see '' and read it as frame 0.
- Relabel assertRevealPixelsNeedNoRepair as the weak secondary check it is; it
  contradicted the file header by calling itself 'the decisive paint assertion'.

Refs STA-2694.

Co-authored-by: Orca <[email protected]>

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

⚠️ Outside diff range comments (1)
tests/e2e/terminal-synchronized-output-release-perf.spec.ts (1)

131-182: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

drawsDuringIdleResets is computed and logged but never asserted.

The test drives the real resetWebglTextureAtlases() path in its idle/unlatched steady state and computes drawsDuringIdleResets (Lines 131-139, 145, logged at 158-161), but no expect() constrains it. The inline rationale at Lines 174-177 explicitly claims "the release itself is the early-out that contributes ~nothing, as the zero draw counts above show" — but that specific claim about idle resets is never verified, only drawsAfterStream is asserted (Line 170-173). This mirrors the exact "measured but never asserted" pattern flagged and fixed elsewhere in this file (drawsAfterStream, drawCalls), just for a metric newly introduced in this diff.

🧪 Proposed fix
     expect(
       result.drawsAfterStream,
       `a fully-bracketed stream forced ${result.drawsAfterStream} synchronous draws`
     ).toBe(0)
+    // The idle release path (real resetWebglTextureAtlases, unlatched) must also
+    // be a pure early-out — no synchronous draws forced by a no-op reset.
+    expect(
+      result.drawsDuringIdleResets,
+      `${result.drawsDuringIdleResets} unlatched resets forced synchronous draws`
+    ).toBe(0)
     expect(
       result.releaseMs / result.frames,

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 23cdf4ce-d48a-4859-97e5-b60729bd75ca

📥 Commits

Reviewing files that changed from the base of the PR and between fe9a297 and 9ac18e8.

📒 Files selected for processing (4)
  • tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs
  • tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts
  • tests/e2e/terminal-reveal-draw-command-probe.spec.ts
  • tests/e2e/terminal-synchronized-output-release-perf.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts
  • tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs
  • tests/e2e/terminal-reveal-draw-command-probe.spec.ts

@nwparker
nwparker merged commit 97cb32c into main Jul 27, 2026
26 checks passed
nwparker added a commit that referenced this pull request Jul 29, 2026
…0907 (#11338)

* Revert "fix(terminal): avoid flash while restoring parked terminals (#10871)"

This reverts commit 5a6a9e0.

Reverted for terminal rendering regressions (flashing, lost content).
Conflict resolution preserves the forwardRef signature from #10433 and
drops the parked-presentation gating #11016 fed with its effective set.

Co-authored-by: Orca <[email protected]>

* Revert "fix(terminal): limit pre-paint WebGL resume to macOS (#10794)" and "fix(terminal): stop switch bold flash and Windows lag (#10692)"

This reverts commits 4681edb and
8f5a454.

#10794 was itself a partial revert of #10692, so both are reverted
together: the Windows retained-WebGL LRU and the macOS pre-paint
(layout-phase) visibility transition that survived it. Terminal
visibility resume returns to passive disposal and recreation on every
platform, and the WebGL context ceiling returns to a flat 128.

Co-authored-by: Orca <[email protected]>

* Revert "fix(terminal): release an abandoned synchronized-output frame on reveal (STA-2694) (#10907)"

This reverts commit 97cb32c.

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…al (STA-2694) (stablyai#10907)

* fix(terminal): release an abandoned synchronized-output frame on reveal

Alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every repaint
in `?2026h … ?2026l`. Hiding a pane mid-bracket — which a worktree switch or
cold-park lands on routinely, since these brackets are written many times a
second — leaves xterm's `decPrivateModes.synchronizedOutput` latched.

RenderService.refreshRows checks that latch *before* rendering, so while it
holds, every repaint Orca owns is a no-op: the forced render-pause repaint,
the plain `refresh()` fallback, and the shared glyph-atlas rebuild all render
zero rows while the xterm buffer is perfectly correct. Release the latch at
the two reveal repaint entry points so those repaints actually paint.

Also adds an OpenCode-shaped alt-screen e2e fixture and spec. The existing
inline-TUI convergence spec covers the normal-buffer shape (live block glued
to the bottom, history scrolling into scrollback); this covers the
full-screen alternate-buffer shape, where nothing scrolls and so no row ever
self-heals through the scroll path.

Scope note: xterm arms a 1s watchdog that clears this latch on its own, so
this closes a bounded window rather than the whole STA-2694 report. The e2e
spec passes with and without the production change for that reason; the unit
tests are what pin the behavior. Refs STA-2694.

* fix(terminal): clear the render model on the plain-refocus repaint path

`schedulePaneRevealPresent` — the atlas-preserving path a plain window
refocus takes — only called `terminal.refresh()`. xterm's renderers are
diff-based: `_updateModel` early-continues on any cell whose code/fg/bg/ext
still match the cached model, so a refresh repaints nothing for a pane whose
buffer never changed. When an occluded window loses its canvas contents while
that model stays populated, the refresh skips exactly the cells that went
stale and the pane keeps compositing pre-hide pixels — until a window resize
reallocates the model, which is the repair users find by hand.

Clear the model first (`RenderService.clear()` → renderer `clear()` →
`_clearModel(true)`) so the refresh becomes a guaranteed full repaint. That
drops cached cells and glyph vertices but NOT the texture atlas, which is
shared by every same-config terminal and whose mid-stream wipe re-arms xterm's
page-merge garble race (xterm.js stablyai#4480) — the reason this path is
atlas-preserving in the first place.

Also covers the DOM-renderer fallback in `resetWebglTextureAtlas`:
`clearTextureAtlas()` is what invalidated the model on the WebGL path, so a
pane without an addon had nothing invalidate it and hit the same skip.

Scope note: the e2e spec guards buffer/geometry convergence across the
hide/reveal boundaries and adds idle-agent and headful desktop-hide cases, but
it cannot observe a stale canvas — both oracles built for that (canvas-vs-buffer
ink sampling, screenshot-vs-forced-repaint) were proven blind by injecting the
defect, and the spec header documents why. The unit tests pin the ordering and
the atlas-preservation invariant. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* docs(terminal): hand off the STA-2694 reveal-artifact investigation

Records both fixed defects with their xterm mechanisms, the reveal/wake call
graph, why every e2e oracle for a stale canvas was proven blind, how to arm the
in-app render-desync sentinel on real hardware, and the one unverified lead
(dimension staleness) that would explain why a window resize specifically is
the repair users find. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* Revert "fix(terminal): clear the render model on the plain-refocus repaint path"

This reverts commit 0f7ec44.

* test(terminal): add a draw-command oracle for reveal repaints, and correct the STA-2694 scope

Every pixel oracle tried for STA-2694 was blind: `drawImage` on a
non-preserveDrawingBuffer WebGL canvas returns a re-rendered copy, and
Playwright's screenshot drives a fresh compositor frame that heals a stale paint
before capture. Reading pixels is self-defeating here — the read triggers the
repaint that hides the bug.

Count the WebGL draw commands instead, by wrapping GlyphRenderer.updateCell and
gl.drawElementsInstanced on the live pane. A draw command cannot be healed after
the fact, so "did the reveal actually repaint?" becomes directly observable.
Teeth-verified: removing releaseAbandonedSynchronizedOutput from
schedulePaneRevealPresent fails the stranded-latch test.

Two findings, both of which change previously-committed claims:

1. The 1s watchdog does NOT bound the synchronized-output defect. It is armed
   only inside `bufferRows`, and `refreshRows` returns at its `_isPaused` check
   first — so while a pane is occluded nothing reaches `bufferRows` and no timer
   is ever pending. A pane hidden mid-`?2026h` holds the latch with no watchdog
   behind it, indefinitely. ed1eaf5's "closes a bounded window" scope note was
   wrong; this is the unbounded garble the report describes, and the fix closes
   it. Corrected in the module doc comment.

2. It refutes the diff-based-staleness hypothesis behind 0f7ec44 (reverted in
   8d5eace). `_updateModel` does early-continue per unchanged cell, but
   `GlyphRenderer.render` then copies vertices for EVERY row up to
   `lineLengths[y]` and issues ONE full-viewport draw — measured identical
   instance counts (562) for a diff-skipped and a model-cleared refresh, with
   updateCell at 0 vs 561. The DOM renderer likewise replaceChildren()s every
   row unconditionally. Clearing the model could not change what reached the
   screen, and `_clearModel(true)` zeroes every glyph vertex while
   `RenderService.clear()` fires no repaint of its own — so it opened a
   blank-viewport window (also asserted here) for no benefit.

Also keeps the idle-agent and headful desktop-hide cases from the reverted
commit, since those were independent of the refuted production change, and
rewrites the alt-screen spec header to point paint questions at this oracle.
Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* docs(terminal): rewrite the STA-2694 handoff after the refutation

Records that the garble window is unbounded (the 1s watchdog never arms for an
occluded pane), that the diff-based-staleness hypothesis was refuted by
measurement and reverted, why pixel oracles are structurally blind here, and the
two leads now closed by measurement (dimension staleness, lazy atlas bindings).
Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* test(terminal): capture visual proof of the STA-2694 stale paint

The earlier screenshot oracles were blind because they compared a revealed pane
against a repaired one and both ran the same repaint code. Capturing the defect
directly works instead, because the mechanism is self-preserving: while
synchronizedOutput is latched, refreshRows returns before reaching the renderer,
so a compositor frame just re-composites the existing canvas texture and the
stale pixels survive the screenshot rather than being healed by it.

Latch a frame, write a full new frame the pane cannot paint, and capture. The
screenshot comes back byte-identical to the pre-hide one while the buffer holds
the new frame — the buffer/screen divergence users report — and differs after
the reveal repaint runs. Asserts both halves, so it fails if either the defect
stops reproducing or the fix stops repairing it.

Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* test(terminal): note where the xterm gate-order double is pinned for real

The unit double encodes RenderService's paused-then-latch gate order, which can
drift on an xterm upgrade. Point at the e2e oracle that pins the same order
against the real renderer, so a future upgrade has a trail to the authoritative
check. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* test(terminal): add a perf budget for the synchronized-output release

releaseAbandonedSynchronizedOutput runs inside resetWebglTextureAtlas, which a
streaming alt-screen TUI can reach through the terminal-output atlas recovery
path — not only on reveal. Measure rather than assert that this costs nothing.

Steady state (a TUI that closes every frame it opens): 200 bracketed frames
produce zero releases, zero extra draw calls, and an unmeasurable early-out
cost. Worst case (every reveal finds a latched frame): 50 latched atlas resets
at 0.08ms each. Both are asserted with headroom, so the guard catches a future
change that makes this scan the buffer per pane rather than flaking on machine
speed. Refs STA-2694.

Co-authored-by: Orca <[email protected]>

* test(terminal): address review — drive real code paths, close vacuity gaps

CodeRabbit caught a genuine tautology in the perf budget: it timed a
hand-copied mirror of the early-out rather than the shipped function, so the
assertion would have held even if the real code grew a buffer scan. Driving
resetWebglTextureAtlases instead moved the measured cost from ~0 to ~0.03ms per
call, which is the honest number for the whole recovery; bound re-set to 0.4ms
(10x measured).

Other review fixes:
- Assert the draw counts both perf tests were measuring and logging but never
  checking, so the 'no extra draws' titles now mean something.
- Fail fast when decPrivateModes is unavailable; previously the latched test
  would pass without ever exercising the fix.
- Re-check the latch right after the worktree switch in the mid-frame test: the
  pane is visible until then, so the 1s watchdog can arm and clear it before the
  hide, making the run vacuous.
- Count scheduleRevealPresent invocations instead of returning a literal true,
  so a missing test hook no longer masquerades as a production failure.
- Assert the latch clears on every reveal iteration, not just the last.
- Make the fixture heartbeat write atomic (tmp + rename); writeFileSync
  truncates first, so a reader could see '' and read it as frame 0.
- Relabel assertRevealPixelsNeedNoRepair as the weak secondary check it is; it
  contradicted the file header by calling itself 'the decisive paint assertion'.

Refs STA-2694.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#10871, and stablyai#10907 (stablyai#11338)

* Revert "fix(terminal): avoid flash while restoring parked terminals (stablyai#10871)"

This reverts commit 785158b.

Reverted for terminal rendering regressions (flashing, lost content).
Conflict resolution preserves the forwardRef signature from stablyai#10433 and
drops the parked-presentation gating stablyai#11016 fed with its effective set.

Co-authored-by: Orca <[email protected]>

* Revert "fix(terminal): limit pre-paint WebGL resume to macOS (stablyai#10794)" and "fix(terminal): stop switch bold flash and Windows lag (stablyai#10692)"

This reverts commits 5a5adaa and
0c09b5d.

stablyai#10794 was itself a partial revert of stablyai#10692, so both are reverted
together: the Windows retained-WebGL LRU and the macOS pre-paint
(layout-phase) visibility transition that survived it. Terminal
visibility resume returns to passive disposal and recreation on every
platform, and the WebGL context ceiling returns to a flat 128.

Co-authored-by: Orca <[email protected]>

* Revert "fix(terminal): release an abandoned synchronized-output frame on reveal (STA-2694) (stablyai#10907)"

This reverts commit 0520c27.

---------

Co-authored-by: Orca <[email protected]>
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