diff --git a/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md b/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md deleted file mode 100644 index 5b68ea029..000000000 --- a/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md +++ /dev/null @@ -1,213 +0,0 @@ -# STA-2694 — garbled terminal after switching away from an AI workspace - -Handoff snapshot: 2026-07-27, branch -`neil/sta-2694-fix-ui-rendering-artifacts-when-switching-away-from-ai`. - -## The report - -> When I use an AI tool—such as OpenCode—and switch away to the desktop or -> another task, the page appears garbled or distorted upon returning; I have to -> resize the window to restore the display. - -Reporter hints: related to terminal parking / workspace switching; also happens -with Claude Code and probably grok. - -## Status - -**One defect, root-caused and fixed, with a mechanism-level test that fails -without the fix.** The garble window is *unbounded*, not the ~1s I originally -claimed — see [the correction](#correction-the-window-is-unbounded). - -A second hypothesis was implemented, then **refuted by measurement and -reverted**. That refutation is the other half of the value here: it rules out a -whole class of "just force a fuller repaint" fixes, and it is pinned by a test so -it cannot be reintroduced. - -| | | -|---|---| -| Fix | `ed1eaf55f1` — release an abandoned synchronized-output frame on reveal | -| Refuted + reverted | `0f7ec4458d`, reverted in `8d5eacecb4` | -| Oracle + scope correction | `3ccffc17ec` | -| Unit tests | 8 passing across 2 files | -| e2e | 5 draw-command oracle + 10 headless convergence + 1 headful | -| Teeth-verified | Yes — removing the fix fails the stranded-latch test | - -## The defect - -Alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every repaint in -DEC 2026 synchronized output — `\x1b[?2026h … \x1b[?2026l` — many times a second. -Hide a pane mid-bracket (a worktree switch, a cold park, or an OS-level occlusion -lands there routinely) and xterm keeps -`decPrivateModes.synchronizedOutput` latched `true`. - -`RenderService.refreshRows` checks that latch **before** rendering -(`RenderService.ts:162`), 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 against a perfectly correct buffer. - -The fix (`terminal-synchronized-output-release.ts`) clears the latch and flushes -the handler's buffered row range at both reveal repaint entry points, before the -repaint. Both reveal paths reach it: - -- `schedulePaneRevealPresent` (plain refocus / desktop return) -- `resetWebglTextureAtlas` (worktree switch, cold park, tab reveal — also reached - from `resetAndRefreshAllTerminalWebglAtlases` via the light tab-resume path) - -### Correction: the window is unbounded - -`ed1eaf55f1`'s commit message says this "closes a bounded window rather than the -whole STA-2694 report", because xterm arms a 1s watchdog that clears the latch. -**That was wrong.** The watchdog is armed only inside -`SynchronizedOutputHandler.bufferRows`, and `refreshRows` returns at its -`_isPaused` check *first*: - -```ts -public refreshRows(start, end, sync = false, isRedrawOnly = false): void { - 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 - } - ... -``` - -While a pane is occluded its `IntersectionObserver` sets `_isPaused`, so nothing -ever reaches `bufferRows` and **no timer is ever pending**. A pane hidden -mid-frame holds the latch with no watchdog behind it, indefinitely — which is the -indefinite garble the report describes. `terminal-reveal-draw-command-probe.spec.ts` -asserts exactly this: latch set, `_timeout === undefined`, and a repaint drawing -0 instances. - -This also explains the specific workaround: resizing the window makes the TUI -repaint via SIGWINCH, and that repaint's closing `?2026l` clears the latch. - -## The refuted hypothesis (do not reimplement) - -The idea: xterm's renderers are diff-based, so a reveal `refresh()` skips cells -whose model entry still matches the buffer, leaving an occluded canvas showing -pre-hide pixels until a resize rebuilds the model. It is a *plausible* reading — -`WebglRenderer._updateModel` really does early-continue per unchanged cell. - -It is wrong, measured on a live pane: - -| Refresh | `updateCell` calls | instances drawn | -|---|---|---| -| diff-skipped (model matches buffer) | 0 | 562 | -| model cleared first | 561 | 562 | - -`GlyphRenderer.render` copies vertices for **every** row up to `lineLengths[y]` -into the active buffer and issues **one** full-viewport `drawElementsInstanced`. -The diff only decides how much *vertex data* is rewritten, never how much is -*drawn*. The DOM renderer likewise `replaceChildren()`s every row -unconditionally. So clearing the model cannot change what reaches the screen. - -Worse, it has a cost: `_clearModel(true)` zeroes every glyph vertex, and -`RenderService.clear()` fires no repaint of its own — so any paint landing between -the clear and the repopulating refresh draws an **empty** viewport (0 instances, -also asserted in the spec). On a reveal that refresh is debounced through a RAF -and can itself be swallowed, which would turn a merely-stale pane into a blank -one. Reverted in `8d5eacecb4`. - -The first test in the oracle spec pins the refutation so this cannot come back as -a "fix". - -## Why pixel oracles failed, and what replaced them - -The field defect is "the buffer is correct but the compositor shows pre-hide -pixels". Two pixel oracles were built and **both were proven blind** by injecting -that exact defect (freeze `RenderService.refreshRows`, then write new content): - -1. **Canvas-vs-buffer ink sampling.** `drawImage` on a - non-`preserveDrawingBuffer` WebGL canvas hands back a *re-rendered* copy — it - reported 0 missing cells against 5263 cells of text the canvas had never - drawn. -2. **Screenshot vs. a forced repaint.** Playwright's screenshot drives a fresh - compositor frame, which *heals* the stale paint before capture; and the - "repair" ran the same code the reveal already ran, so a shared defect cancels - out. - -An earlier resize-referenced oracle was also unsound: resizing shifts alt-screen -rows, so its 4.4% pixel diff measured legitimate reflow. - -**Pixels are the wrong layer** — anything that reads them can trigger the repaint -that hides the bug. `tests/e2e/terminal-reveal-draw-command-probe.spec.ts` -instead wraps `GlyphRenderer.updateCell` and `gl.drawElementsInstanced` on the -live pane and counts draw commands. A draw command cannot be healed after the -fact, so "did the reveal repaint?" is directly observable — and falsifiable, -which is how the second hypothesis got refuted. - -Use that spec for **paint** questions; -`terminal-opencode-altscreen-reveal-artifacts.spec.ts` for **buffer, geometry and -PTY-size convergence** (worktree switch, cold park, idle agent, headful desktop -hide). The idle-agent case matters: every earlier test kept the TUI streaming -across the reveal, so live frames repainted whatever the reveal got wrong and the -defect healed itself before any assertion ran. - -## Leads closed by measurement - -Both were live suspects in the previous handoff; both are now ruled out. - -- **Dimension staleness.** Every dimension-rebuilding path in `WebglRenderer` is - behind an unchanged/zero-sized early exit that a hidden pane trips, and - `performSafeFit` early-returns at unchanged geometry — so nothing on the reveal - path re-runs `handleResize()`. Measured across a real `window.hide()` / - `show()`: canvas backing store `1272×1104` matched the renderer's computed - dimensions exactly, char metrics stayed `8.65×16`, `_isAttached` stayed true, - the screen element stayed connected. No staleness. -- **Lagging atlas page bindings.** Right after a reveal the bound texture version - *does* lag the atlas page (e.g. 1297 vs 1366) — but bindings are lazy and - `GlyphRenderer.render` rebinds any page whose version moved, so one repaint - brings them level (1366/1366). Normal, not a defect. Judge bindings only - *after* a draw. - -## Residual risk - -The oracle proves the repaint is *issued*; it does not photograph the user's -screen. If a report survives this fix, the remaining suspects are below the draw -call — GPU-process/compositor-level content loss — where the in-app sentinel on -real hardware is the tool: - -```js -localStorage.setItem('orca:render-desync-sentinel', '1') // then reload -``` - -Reproduce, then **⌘-click** (Ctrl-click off Mac) in the garbled pane. That starts -a 10s burst at 250ms intervals; a trip needs the same cells missing across 2 -consecutive samples, ≥200 text cells, ≥8% missing. It writes `corrupt.png` + -`corrupt.json` to `/terminal-render-desync-evidence//`, then -runs atlas recovery and captures the healed frame. Armed at import when the flag -is set (`terminal-freeze-breadcrumbs.ts:45`). - -## Verification commands - -```bash -npx vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/ -npx tsc --noEmit -p config/tsconfig.tc.web.json -npx playwright test tests/e2e/terminal-reveal-draw-command-probe.spec.ts \ - tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts \ - tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts \ - --config tests/playwright.config.ts --project=electron-headless --workers=1 -SKIP_BUILD=1 npx playwright test tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts \ - --config tests/playwright.config.ts --project=electron-headful --workers=1 -``` - -To confirm the fix still has teeth, delete the -`releaseAbandonedSynchronizedOutput(pane.terminal)` line from -`schedulePaneRevealPresent` and re-run the oracle: the stranded-latch test fails -with "the reveal repaint did not release the stranded latch, so the pane stays -frozen". - -## Files - -Production: - -- `src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts` (the fix) -- `src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts` (`schedulePaneRevealPresent`) -- `src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts` (`resetWebglTextureAtlas`) - -Tests: - -- `terminal-synchronized-output-release.test.ts`, `reveal-repaint-synchronized-output.test.ts` -- `tests/e2e/terminal-reveal-draw-command-probe.spec.ts` (the oracle) -- `tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts`, - `tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs` diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index c87c25cbd..4fc153c01 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -100,7 +100,6 @@ import { import { captureForceParkedWorktreeBuffers } from './terminal-pane/force-park-buffer-capture' import { warnTerminalLifecycleAnomaly } from './terminal-pane/terminal-lifecycle-diagnostics' import { getTerminalParkingPolicyOverrides } from './terminal-pane/terminal-parking-e2e-overrides' -import { useColdParkedTerminalPresentation } from './terminal-pane/use-cold-parked-terminal-presentation' import { selectEvictionExemptTerminalTabIds } from './terminal-pane/terminal-eviction-exempt-tabs' import { canWatcherCoverParkedTerminalTab, @@ -1258,32 +1257,6 @@ function Terminal(): React.JSX.Element | null { groupsByWorktree, activeGroupIdByWorktree ) - const desiredPresentedWorktree = useMemo( - () => - new Map([['terminal-worktree', activeView === 'terminal' ? renderedActiveWorktreeId : null]]), - [activeView, renderedActiveWorktreeId] - ) - const availablePresentedWorktreeIds = useMemo( - () => new Set(workspaceSurfaces.map((workspace) => workspace.id)), - [workspaceSurfaces] - ) - const coldWorktreePresentationTargets = useMemo( - () => - activeView === 'terminal' && activeTabType === 'terminal' - ? effectiveParkedTerminalWorktreeIds - : new Set(), - [activeTabType, activeView, effectiveParkedTerminalWorktreeIds] - ) - const { - presentationByScope: worktreePresentationByScope, - settleTarget: settleWorktreePresentation - } = useColdParkedTerminalPresentation({ - desiredTargetByScope: desiredPresentedWorktree, - coldParkedTargetIds: coldWorktreePresentationTargets, - availableTargetIds: availablePresentedWorktreeIds - }) - const presentedWorktreeId = - worktreePresentationByScope.get('terminal-worktree')?.presentedTargetId ?? null // Why: legacy (non-split) host owns watcher reconciliation; split mode's overlay layers own theirs, so only dispose worktrees with no overlay layer. useEffect(() => { pruneParkedTerminalWatchers(new Set(workspaceSurfaces.map((workspace) => workspace.id))) @@ -2335,7 +2308,6 @@ function Terminal(): React.JSX.Element | null { // Why: strict '=== terminal' (not !== settings) so the terminal/browser surface hides on the tasks page too. const isVisible = activeView === 'terminal' && workspace.id === renderedActiveWorktreeId - const isPresented = workspace.id === presentedWorktreeId const shouldMeasureHiddenWorktree = !isVisible && measurableBackgroundWorktreeIdsRef.current.has(workspace.id) const shouldColdParkTerminalPanes = @@ -2350,7 +2322,6 @@ function Terminal(): React.JSX.Element | null { layout={layout} focusedGroupId={activeGroupIdByWorktree[workspace.id]} isVisible={isVisible} - isPresented={isPresented} shouldMeasureHiddenWorktree={shouldMeasureHiddenWorktree} shouldColdParkTerminalPanes={shouldColdParkTerminalPanes} isForceParked={forceParkedTerminalWorktreeIds.has(workspace.id)} @@ -2361,7 +2332,6 @@ function Terminal(): React.JSX.Element | null { activationDeferredMountTabIds={ activationDeferredMountTabIdsByWorktreeRef.current.get(workspace.id) ?? null } - onInitialTerminalRenderSettled={() => settleWorktreePresentation(workspace.id)} /> ) })} @@ -2388,7 +2358,6 @@ function Terminal(): React.JSX.Element | null { // Why: strict '=== terminal' (not !== settings) so the terminal/browser surface hides on the tasks page too. const isVisible = activeView === 'terminal' && workspace.id === renderedActiveWorktreeId - const isPresented = workspace.id === presentedWorktreeId const shouldMeasureHiddenWorktree = !isVisible && measurableBackgroundWorktreeIdsRef.current.has(workspace.id) const shouldColdParkTerminalPanes = @@ -2399,16 +2368,15 @@ function Terminal(): React.JSX.Element | null {
- + {(tabsByWorktree[workspace.id] ?? []) .filter((tab) => shouldMountBackgroundWorktreeTab( @@ -2424,9 +2392,6 @@ function Terminal(): React.JSX.Element | null { const isActivityPortalTab = activityTerminalPortal !== null const isActiveTerminalTab = isVisible && tab.id === activeTabId && activeTabType === 'terminal' - const isPresentedTerminalTab = - isPresented && - (isActiveTerminalTab || tab.id === activeTabIdByWorktree[workspace.id]) // Why: parking unmounts the view but keeps the PTY; an Activity portal stays // mounted as a visible consumer, and a force-parked worktree's eviction-exempt // tabs stay mounted because a remount would orphan their live pty. @@ -2444,22 +2409,16 @@ function Terminal(): React.JSX.Element | null { worktreeId={workspace.id} cwd={tab.startupCwd ?? workspace.path} isActive={ - (isActiveTerminalTab && isPresented) || - activityTerminalPortal?.active === true + isActiveTerminalTab || activityTerminalPortal?.active === true } // Why: keep isVisible true for the portaled tab so xterm fits/streams while the workspace surface stays hidden. - isVisible={isPresentedTerminalTab || isActivityPortalTab} + isVisible={isActiveTerminalTab || isActivityPortalTab} // Why: inactive tabs here are tab-hidden (not worktree-hidden), so they need the same light resume path as split-group overlays. - isWorktreeActive={isVisible || isPresented || isActivityPortalTab} + isWorktreeActive={isVisible || isActivityPortalTab} // Why: isolate the portaled Activity leaf so split siblings stay hidden; workspace renders pass null. isolatedPaneKey={activityTerminalPortal?.paneKey ?? null} onPtyExit={(ptyId) => handlePtyExit(tab.id, ptyId)} onCloseTab={() => handleCloseTab(tab.id)} - onInitialRenderSettled={ - isActiveTerminalTab - ? () => settleWorktreePresentation(workspace.id) - : undefined - } /> ) if (activityTerminalPortal) { @@ -2629,28 +2588,24 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ layout, focusedGroupId, isVisible, - isPresented, shouldMeasureHiddenWorktree, shouldColdParkTerminalPanes, isForceParked, activityTerminalPortals, backgroundMountTabIds, - activationDeferredMountTabIds, - onInitialTerminalRenderSettled + activationDeferredMountTabIds }: { worktreeId: string worktreePath: string layout: TabGroupLayoutNode focusedGroupId?: string isVisible: boolean - isPresented: boolean shouldMeasureHiddenWorktree: boolean shouldColdParkTerminalPanes: boolean isForceParked: boolean activityTerminalPortals: ActivityTerminalPortalTarget[] backgroundMountTabIds: ReadonlySet | null activationDeferredMountTabIds: ReadonlySet | null - onInitialTerminalRenderSettled: (tabId: string) => void }): React.JSX.Element { const browserPageIds = useAppStore( useShallow((state) => @@ -2667,46 +2622,38 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ return (
- + {isVisible || backgroundMountTabIds === null ? ( <> - - + + ) : null} diff --git a/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx b/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx index 1da822d7c..20e5f9906 100644 --- a/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx @@ -7,12 +7,22 @@ import type { ActivityTerminalPortalTarget } from '../activity/activity-terminal import TerminalPane from './TerminalPane' import { closeTerminalTab } from '../terminal/terminal-tab-actions' import { shouldDeferParkedPtyExitTabClose } from './terminal-parked-tab-watchers' -import { - FALLBACK_RECT_MIN_CHANGE_PX, - MIN_OVERLAY_FIT_HEIGHT_PX, - MIN_OVERLAY_FIT_WIDTH_PX, - shouldUseCssAnchorPositioning -} from './terminal-overlay-positioning' + +const HAS_CSS_ANCHOR_POSITIONING = + typeof CSS !== 'undefined' && + CSS.supports('position-anchor', '--orca-terminal-overlay-probe') && + CSS.supports('top', 'anchor(--orca-terminal-overlay-probe top)') && + CSS.supports('width', 'anchor-size(--orca-terminal-overlay-probe width)') +const MIN_OVERLAY_FIT_WIDTH_PX = 48 +const MIN_OVERLAY_FIT_HEIGHT_PX = 24 +const FALLBACK_RECT_MIN_CHANGE_PX = 1 + +function shouldUseCssAnchorPositioning(): boolean { + return ( + HAS_CSS_ANCHOR_POSITIONING && + (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ !== true + ) +} type MeasuredFallbackRect = { top: number @@ -29,15 +39,12 @@ type TerminalOverlaySlotProps = { startupCwd: string | undefined groupId: string | undefined isWorktreeActive: boolean - isWorktreePresented: boolean isVisible: boolean - isPresented: boolean isActive: boolean activityTerminalPortal: ActivityTerminalPortalTarget | null onFocusOwningGroup: ((groupId: string) => void) | undefined consumeSuppressedPtyExit: (ptyId: string) => boolean leaveWorktreeIfEmpty: () => void - onInitialRenderSettled?: () => void } export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ @@ -48,15 +55,12 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ startupCwd, groupId, isWorktreeActive, - isWorktreePresented, isVisible, - isPresented, isActive, activityTerminalPortal, onFocusOwningGroup, consumeSuppressedPtyExit, - leaveWorktreeIfEmpty, - onInitialRenderSettled + leaveWorktreeIfEmpty }: TerminalOverlaySlotProps): React.JSX.Element { const anchorName = groupId !== undefined ? tabGroupBodyAnchorName(groupId) : undefined const overlayRef = useRef(null) @@ -165,8 +169,6 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ } }, [anchorName, isVisible, measuredFallbackRect]) - const showPresentedTerminal = isPresented && (isWorktreeActive || isWorktreePresented) - const isInteractive = isVisible && isPresented && isWorktreePresented const style: React.CSSProperties = useMemo( () => anchorName && shouldUseCssAnchorPositioning() @@ -177,10 +179,9 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ left: `anchor(${anchorName} left)`, width: `anchor-size(${anchorName} width)`, height: `anchor-size(${anchorName} height)`, - display: - isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none', - opacity: showPresentedTerminal ? 1 : 0, - pointerEvents: isInteractive ? 'auto' : 'none' + display: isVisible || shouldMeasureHiddenStartup ? 'flex' : 'none', + opacity: isVisible ? 1 : 0, + pointerEvents: isVisible ? 'auto' : 'none' } : anchorName ? { @@ -192,10 +193,9 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ left: measuredFallbackRect?.left ?? 0, width: measuredFallbackRect?.width ?? '100%', height: measuredFallbackRect?.height ?? 'calc(100% - 32px)', - display: - isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none', - opacity: showPresentedTerminal ? 1 : 0, - pointerEvents: isInteractive ? 'auto' : 'none' + display: isVisible || shouldMeasureHiddenStartup ? 'flex' : 'none', + opacity: isVisible ? 1 : 0, + pointerEvents: isVisible ? 'auto' : 'none' } : { position: 'absolute', @@ -206,14 +206,7 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ display: 'none', pointerEvents: 'none' }, - [ - anchorName, - isInteractive, - isVisible, - measuredFallbackRect, - shouldMeasureHiddenStartup, - showPresentedTerminal - ] + [anchorName, isVisible, measuredFallbackRect, shouldMeasureHiddenStartup] ) const focusGroup = useCallback(() => { if (groupId !== undefined && onFocusOwningGroup) { @@ -227,14 +220,12 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ tabId={terminalTabId} worktreeId={worktreeId} cwd={startupCwd ?? worktreePath} - isActive={ - (isActive && isPresented && isWorktreePresented) || activityTerminalPortal?.active === true - } + isActive={isActive || activityTerminalPortal?.active === true} // Why: split-group changes reparent TabGroupPanel subtrees. Keeping the // TerminalPane mounted here preserves alt-screen TUI state while this // flag still lets hidden tabs throttle rendering. - isVisible={isVisible || showPresentedTerminal || activityTerminalPortal !== null} - isWorktreeActive={isWorktreeActive || isWorktreePresented || activityTerminalPortal !== null} + isVisible={isVisible || activityTerminalPortal !== null} + isWorktreeActive={isWorktreeActive || activityTerminalPortal !== null} isolatedPaneKey={activityTerminalPortal?.paneKey ?? null} onPtyExit={(ptyId) => { if (consumeSuppressedPtyExit(ptyId)) { @@ -258,7 +249,6 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ // store.closeTab was the path that closed pinned terminals silently. closeTerminalTab(terminalTabId, { onClosed: leaveWorktreeIfEmpty }) }} - onInitialRenderSettled={onInitialRenderSettled} /> ) @@ -275,9 +265,6 @@ export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ ref={overlayRef} style={style} data-terminal-overlay-tab-id={terminalTabId} - data-terminal-overlay-presented={showPresentedTerminal ? 'true' : 'false'} - inert={!isInteractive} - aria-hidden={!isInteractive} onPointerDown={focusGroup} onFocusCapture={focusGroup} > diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index d52b1dc30..2cd4d3c0d 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -250,7 +250,6 @@ type TerminalPaneProps = { showSplitButton?: boolean onPtyExit: (ptyId: string) => void onCloseTab: () => void - onInitialRenderSettled?: () => void } export type TerminalPaneHandle = { @@ -298,8 +297,7 @@ function TerminalPane( isolatedPaneKey = null, showSplitButton = true, onPtyExit, - onCloseTab, - onInitialRenderSettled + onCloseTab }: TerminalPaneProps, ref: React.ForwardedRef ): React.JSX.Element { @@ -330,8 +328,6 @@ function TerminalPane( const isRendererVisible = isVisible && isWorktreeActive const isVisibleRef = useRef(isRendererVisible) isVisibleRef.current = isRendererVisible - const onInitialRenderSettledRef = useRef(onInitialRenderSettled) - onInitialRenderSettledRef.current = onInitialRenderSettled const sshReconnectTargetId = useAppStore((store) => { const connectionId = getConnectionIdFromState(store, worktreeId) // Why: runtime-owned SSH targets are internal plumbing users can't connect to, so a reconnect prompt would mislead. @@ -1485,8 +1481,7 @@ function TerminalPane( setPaneCount, setPaneLayoutRevision, resolveExternalPaneDropTarget, - onExternalPaneDrop: handleExternalPaneDrop, - onInitialRenderSettledRef + onExternalPaneDrop: handleExternalPaneDrop }) useEffect(() => { diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.react185.test.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.react185.test.tsx index 5803dd54b..b3ed18faa 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.react185.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.react185.test.tsx @@ -72,9 +72,7 @@ function renderSlot(): void { startupCwd={undefined} groupId={GROUP_ID} isWorktreeActive - isWorktreePresented isVisible - isPresented isActive activityTerminalPortal={null} onFocusOwningGroup={vi.fn()} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx index dac0b7f70..5dbc1482a 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx @@ -8,10 +8,14 @@ import { } from '../activity/activity-terminal-portal' import { shouldMountBackgroundWorktreeTab } from '../terminal/background-terminal-worktree-mount' import { useNativeChatToggleShortcut } from '../native-chat/use-native-chat-toggle-shortcut' -import { useTerminalTabColdParking } from './use-terminal-tab-cold-parking' -import { useTerminalOverlayPresentation } from './use-terminal-overlay-presentation' -import { buildTerminalOverlayAssignments } from './terminal-overlay-assignments' import { TerminalOverlaySlot } from './TerminalOverlaySlot' +import { useTerminalTabColdParking } from './use-terminal-tab-cold-parking' + +type TerminalOverlayAssignment = { + unifiedTabId: string + groupId: string + isActiveInGroup: boolean +} const EMPTY_TERMINAL_TABS: readonly TerminalTab[] = [] const EMPTY_UNIFIED_TABS: readonly Tab[] = [] @@ -22,31 +26,25 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ worktreeId, worktreePath, isWorktreeActive, - isWorktreePresented = isWorktreeActive, coldParkTerminalPanes = false, isForceParked = false, shouldMeasureHiddenWorktree = false, activityTerminalPortals = EMPTY_ACTIVITY_PORTALS, backgroundMountTabIds = null, - activationDeferredMountTabIds = null, - onInitialTerminalRenderSettled + activationDeferredMountTabIds = null }: { worktreeId: string worktreePath: string isWorktreeActive: boolean - isWorktreePresented?: boolean coldParkTerminalPanes?: boolean - /** Retention-budget force-park (C1 slice B): eviction-exempt tabs keep their mounted panes. */ + /** Retention-budget force-park keeps eviction-exempt tabs mounted. */ isForceParked?: boolean shouldMeasureHiddenWorktree?: boolean activityTerminalPortals?: ActivityTerminalPortalTarget[] - /** Non-null for targeted background mounts: only these terminal tabs get a - * TerminalPane, so waking one slept agent does not connect every saved tab. */ + /** Targeted mounts connect only these terminal tabs. */ backgroundMountTabIds?: ReadonlySet | null - /** Only cold-activation deferred tabs receive immediate parked watcher - * coverage; targeted mounts keep their existing delayed parking policy. */ + /** Cold-activation deferred tabs receive immediate parked watcher coverage. */ activationDeferredMountTabIds?: ReadonlySet | null - onInitialTerminalRenderSettled?: (tabId: string) => void }): React.JSX.Element | null { const { terminalTabs, unifiedTabs, groups, activeGroupId } = useAppStore( useShallow((state) => ({ @@ -63,11 +61,6 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ useNativeChatToggleShortcut(worktreeId, isWorktreeActive) - // Why: legacy TabGroupPanel routed terminal closes through - // commands.closeItem → leaveWorktreeIfEmpty, which deselected the worktree - // when the last renderable tab closed and sent the user back to Landing. - // Run this only after the guarded close resolves; a pending/cancelled pinned - // close must leave the worktree and paired-web mirror selected. const leaveWorktreeIfEmpty = useCallback(() => { const state = useAppStore.getState() if (state.activeWorktreeId !== worktreeId) { @@ -84,12 +77,30 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ [focusGroup, worktreeId] ) - const assignments = useMemo( - () => buildTerminalOverlayAssignments(groups, unifiedTabs), - [groups, unifiedTabs] - ) + const groupActiveTabById = useMemo(() => { + const lookup: Record = {} + for (const group of groups) { + lookup[group.id] = group.activeTabId + } + return lookup + }, [groups]) - const { parkedTerminalTabIds, coldParkedTerminalTabIds } = useTerminalTabColdParking({ + const assignments = useMemo(() => { + const entries = new Map() + for (const tab of unifiedTabs) { + if (tab.contentType !== 'terminal') { + continue + } + entries.set(tab.entityId, { + unifiedTabId: tab.id, + groupId: tab.groupId, + isActiveInGroup: groupActiveTabById[tab.groupId] === tab.id + }) + } + return entries + }, [groupActiveTabById, unifiedTabs]) + + const parkedTerminalTabIds = useTerminalTabColdParking({ worktreeId, terminalTabs, assignments, @@ -100,16 +111,6 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ activityTerminalPortals, activationDeferredMountTabIds }) - const { presentedTerminalTabIdByGroup: presentationByScope, handleInitialRenderSettled } = - useTerminalOverlayPresentation({ - groups, - terminalTabs, - assignments, - coldParkedTerminalTabIds, - isWorktreeActive, - activeGroupId, - onInitialTerminalRenderSettled - }) if (!worktreePath) { return null @@ -123,17 +124,12 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ ) .map((terminalTab) => { const assignment = assignments.get(terminalTab.id) - const isVisible = Boolean(isWorktreeActive && assignment && assignment.isActiveInGroup) - const isActive = Boolean(isVisible && assignment && assignment.groupId === activeGroupId) - const isPresented = Boolean( - assignment && presentationByScope.get(assignment.groupId) === terminalTab.id - ) + const isVisible = Boolean(isWorktreeActive && assignment?.isActiveInGroup) + const isActive = Boolean(isVisible && assignment?.groupId === activeGroupId) const activityTerminalPortal = findActivityTerminalPortal(activityTerminalPortals, { worktreeId, tabId: terminalTab.id }) - // Why: parking unmounts only the view; the parked watcher owns exit - // and side-effect handling until this tab is eligible to remount. if (parkedTerminalTabIds.has(terminalTab.id)) { return null } @@ -147,15 +143,12 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ startupCwd={terminalTab.startupCwd} groupId={assignment?.groupId} isWorktreeActive={isWorktreeActive} - isWorktreePresented={isWorktreePresented} isVisible={isVisible} - isPresented={isPresented} isActive={isActive} activityTerminalPortal={activityTerminalPortal} onFocusOwningGroup={focusOwningGroup} consumeSuppressedPtyExit={consumeSuppressedPtyExit} leaveWorktreeIfEmpty={leaveWorktreeIfEmpty} - onInitialRenderSettled={() => handleInitialRenderSettled(terminalTab.id)} /> ) })} diff --git a/src/renderer/src/components/terminal-pane/apply-terminal-visibility-transition.ts b/src/renderer/src/components/terminal-pane/apply-terminal-visibility-transition.ts deleted file mode 100644 index 4b884329b..000000000 --- a/src/renderer/src/components/terminal-pane/apply-terminal-visibility-transition.ts +++ /dev/null @@ -1,99 +0,0 @@ -import type { PaneManager } from '@/lib/pane-manager/pane-manager' -import type { ScrollState } from '@/lib/pane-manager/pane-manager-types' -import { - hideTerminalVisibility, - resumeTerminalVisibility, - type TerminalHiddenReason, - type TerminalVisibilityPostPaintRecovery -} from './terminal-visibility-resume' - -export type TerminalVisibilityBookkeepingRefs = { - wasVisibleRef: { current: boolean } - wasWorktreeActiveRef: { current: boolean } - hasCompletedVisibleResumeRef: { current: boolean } - renderingSuspendedByVisibilityRef: { current: boolean } - hiddenReasonRef: { current: TerminalHiddenReason | null } -} - -type ApplyTerminalVisibilityTransitionArgs = TerminalVisibilityBookkeepingRefs & { - manager: PaneManager | null - rendererVisible: boolean - isActive: boolean - isWorktreeActive: boolean - captureViewportPositions: (useRememberedSnapshots: boolean) => Map - withSuppressedScrollTracking: (callback: () => void) => void - applyPendingFollowOutputRequests: () => void -} - -// Record visible mounts before PaneManager exists so first tab hide stays light. -export function applyTerminalVisibilityTransition( - args: ApplyTerminalVisibilityTransitionArgs -): TerminalVisibilityPostPaintRecovery | null { - const { - manager, - rendererVisible, - isActive, - isWorktreeActive, - wasVisibleRef, - wasWorktreeActiveRef, - hasCompletedVisibleResumeRef, - renderingSuspendedByVisibilityRef, - hiddenReasonRef, - captureViewportPositions, - withSuppressedScrollTracking, - applyPendingFollowOutputRequests - } = args - - if (!manager) { - if (rendererVisible) { - wasVisibleRef.current = true - wasWorktreeActiveRef.current = isWorktreeActive - hasCompletedVisibleResumeRef.current = true - renderingSuspendedByVisibilityRef.current = false - hiddenReasonRef.current = null - } else { - wasVisibleRef.current = false - wasWorktreeActiveRef.current = isWorktreeActive - } - return null - } - - const wasVisible = wasVisibleRef.current - const wasWorktreeActive = wasWorktreeActiveRef.current - if (rendererVisible) { - const shouldUseLightTabResume = - isWorktreeActive && - hasCompletedVisibleResumeRef.current && - !renderingSuspendedByVisibilityRef.current && - (wasVisible || hiddenReasonRef.current === 'tab') - const postPaintRecovery = resumeTerminalVisibility({ - manager, - isActive, - wasVisible, - shouldUseLightTabResume, - captureViewportPositions, - withSuppressedScrollTracking - }) - renderingSuspendedByVisibilityRef.current = false - wasVisibleRef.current = true - wasWorktreeActiveRef.current = isWorktreeActive - hasCompletedVisibleResumeRef.current = true - hiddenReasonRef.current = null - applyPendingFollowOutputRequests() - return postPaintRecovery - } - - const hiddenState = hideTerminalVisibility({ - manager, - wasVisible, - wasWorktreeActive, - isWorktreeActive, - hasCompletedVisibleResume: hasCompletedVisibleResumeRef.current, - captureViewportPositions - }) - renderingSuspendedByVisibilityRef.current = hiddenState.renderingSuspended - hiddenReasonRef.current = hiddenState.hiddenReason - wasVisibleRef.current = false - wasWorktreeActiveRef.current = isWorktreeActive - return null -} diff --git a/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.test.ts b/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.test.ts deleted file mode 100644 index 0fca4abd5..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { scheduleTerminalInitialRenderSettled } from './terminal-initial-render-settle' - -vi.mock('@/lib/pane-manager/pane-terminal-output-scheduler', () => ({ - waitForTerminalOutputParsed: vi.fn(() => Promise.resolve()) -})) - -describe('scheduleTerminalInitialRenderSettled', () => { - const frames: FrameRequestCallback[] = [] - - beforeEach(() => { - frames.length = 0 - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - frames.push(callback) - return frames.length - }) - vi.stubGlobal('cancelAnimationFrame', vi.fn()) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('waits for replay and content before two frames paint', async () => { - let replaySettled = false - let contentReady = false - const onSettled = vi.fn() - scheduleTerminalInitialRenderSettled({ - manager: { getPanes: () => [] }, - isCurrent: () => true, - isReplaySettled: () => replaySettled, - isContentReady: () => contentReady, - onSettled - }) - await Promise.resolve() - - frames.shift()?.(0) - replaySettled = true - frames.shift()?.(16) - contentReady = true - frames.shift()?.(32) - expect(onSettled).not.toHaveBeenCalled() - - frames.shift()?.(48) - expect(onSettled).toHaveBeenCalledOnce() - }) - - it('ignores queued work after cancellation', async () => { - const onSettled = vi.fn() - const cancel = scheduleTerminalInitialRenderSettled({ - manager: { getPanes: () => [] }, - isCurrent: () => true, - isReplaySettled: () => true, - isContentReady: () => true, - onSettled - }) - await Promise.resolve() - cancel() - - frames.shift()?.(0) - expect(onSettled).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.ts b/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.ts deleted file mode 100644 index f0dbfe6ea..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-initial-render-settle.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { Terminal } from '@xterm/xterm' -import { waitForTerminalOutputParsed } from '@/lib/pane-manager/pane-terminal-output-scheduler' - -type InitialRenderPaneManager = { - getPanes(): { terminal: Terminal }[] -} - -export function scheduleTerminalInitialRenderSettled(args: { - manager: InitialRenderPaneManager - isCurrent: () => boolean - isReplaySettled: () => boolean - isContentReady: () => boolean - onSettled: () => void -}): () => void { - let cancelled = false - let frameId: number | null = null - let replaySettledFrameObserved = false - const scheduleFrame = (): void => { - frameId = requestAnimationFrame(() => { - frameId = null - if (cancelled || !args.isCurrent()) { - return - } - if (!args.isReplaySettled() || !args.isContentReady()) { - replaySettledFrameObserved = false - scheduleFrame() - return - } - if (!replaySettledFrameObserved) { - replaySettledFrameObserved = true - scheduleFrame() - return - } - args.onSettled() - }) - } - void Promise.all( - args.manager.getPanes().map((pane) => waitForTerminalOutputParsed(pane.terminal)) - ).then(() => { - if (cancelled || !args.isCurrent()) { - return - } - scheduleFrame() - }) - return () => { - cancelled = true - if (frameId !== null) { - cancelAnimationFrame(frameId) - } - } -} diff --git a/src/renderer/src/components/terminal-pane/terminal-overlay-assignments.ts b/src/renderer/src/components/terminal-pane/terminal-overlay-assignments.ts deleted file mode 100644 index 36cb7d0d8..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-overlay-assignments.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { Tab, TabGroup } from '../../../../shared/types' - -export type TerminalOverlayAssignment = { - groupId: string - isActiveInGroup: boolean -} - -export function buildTerminalOverlayAssignments( - groups: readonly TabGroup[], - unifiedTabs: readonly Tab[] -): Map { - const activeTabByGroupId = new Map(groups.map((group) => [group.id, group.activeTabId])) - const assignments = new Map() - for (const tab of unifiedTabs) { - if (tab.contentType === 'terminal') { - assignments.set(tab.entityId, { - groupId: tab.groupId, - isActiveInGroup: activeTabByGroupId.get(tab.groupId) === tab.id - }) - } - } - return assignments -} diff --git a/src/renderer/src/components/terminal-pane/terminal-overlay-positioning.ts b/src/renderer/src/components/terminal-pane/terminal-overlay-positioning.ts deleted file mode 100644 index 706c579ed..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-overlay-positioning.ts +++ /dev/null @@ -1,16 +0,0 @@ -const HAS_CSS_ANCHOR_POSITIONING = - typeof CSS !== 'undefined' && - CSS.supports('position-anchor', '--orca-terminal-overlay-probe') && - CSS.supports('top', 'anchor(--orca-terminal-overlay-probe top)') && - CSS.supports('width', 'anchor-size(--orca-terminal-overlay-probe width)') - -export const MIN_OVERLAY_FIT_WIDTH_PX = 48 -export const MIN_OVERLAY_FIT_HEIGHT_PX = 24 -export const FALLBACK_RECT_MIN_CHANGE_PX = 1 - -export function shouldUseCssAnchorPositioning(): boolean { - return ( - HAS_CSS_ANCHOR_POSITIONING && - (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ !== true - ) -} diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.test.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.test.ts deleted file mode 100644 index 3520975c7..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getTerminalVisibilityEffectPhase } from './terminal-visibility-effect-phase' - -describe('terminal visibility effect phase', () => { - it('runs pre-paint only on macOS', () => { - expect(getTerminalVisibilityEffectPhase('darwin')).toBe('layout') - expect(getTerminalVisibilityEffectPhase('win32')).toBe('passive') - expect(getTerminalVisibilityEffectPhase('linux')).toBe('passive') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.ts deleted file mode 100644 index dcf959331..000000000 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-effect-phase.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type TerminalVisibilityEffectPhase = 'layout' | 'passive' - -export function getTerminalVisibilityEffectPhase( - platform: NodeJS.Platform -): TerminalVisibilityEffectPhase { - return platform === 'darwin' ? 'layout' : 'passive' -} diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts index 28ed449ee..300a381c0 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts @@ -117,67 +117,11 @@ describe('resumeTerminalVisibility reveal repaint', () => { it('schedules the repaint after rendering resumes on a heavy reveal', () => { const order: string[] = [] const manager = createManager(order) - const recovery = resumeTerminalVisibility(resumeArgs(manager, false)) + resumeTerminalVisibility(resumeArgs(manager, false)) - expect(order).toEqual(['resume-rendering', 'fit-reveal']) - - recovery?.run(manager as never as PaneManager) expect(order).toEqual(['resume-rendering', 'fit-reveal', 'reveal-repaint']) }) - it('defers backlog and shared atlas recovery until after resume and fit', async () => { - // On macOS resume before flush avoids DOM bold flash; fit before flush avoids - // writing TUI backlog onto the transient DOM↔WebGL one-column-off grid. - const order: string[] = [] - const manager = createManager(order) - manager.getPanes.mockReturnValue([{ terminal: { name: 'pane' } }]) - const { flushTerminalOutput, requestTerminalBacklogRecovery } = vi.mocked( - await import('@/lib/pane-manager/pane-terminal-output-scheduler') - ) - const { resetAndRefreshAllTerminalWebglAtlases } = vi.mocked( - await import('@/lib/pane-manager/pane-manager-registry') - ) - flushTerminalOutput.mockImplementation(() => { - order.push('flush') - }) - requestTerminalBacklogRecovery.mockImplementation(() => { - order.push('backlog') - }) - - const recovery = resumeTerminalVisibility(resumeArgs(manager, false)) - - expect(order).toEqual(['resume-rendering', 'fit-reveal']) - expect(resetAndRefreshAllTerminalWebglAtlases).not.toHaveBeenCalled() - recovery?.run(manager as never as PaneManager) - expect(order.slice(0, 4)).toEqual(['resume-rendering', 'fit-reveal', 'backlog', 'flush']) - expect(resetAndRefreshAllTerminalWebglAtlases).toHaveBeenCalledTimes(1) - // Why: no flush may land between resume and the corrective reveal fit. - const resumeIdx = order.indexOf('resume-rendering') - const fitIdx = order.indexOf('fit-reveal') - const flushIdx = order.indexOf('flush') - expect(resumeIdx).toBeLessThan(fitIdx) - expect(fitIdx).toBeLessThan(flushIdx) - }) - - it('retargets post-paint recovery to a replacement manager', async () => { - const oldManager = createManager() - const newTerminal = { name: 'replacement' } - const newManager = createManager() - newManager.getPanes.mockReturnValue([{ terminal: newTerminal }]) - const { flushTerminalOutput } = vi.mocked( - await import('@/lib/pane-manager/pane-terminal-output-scheduler') - ) - const recovery = resumeTerminalVisibility(resumeArgs(oldManager, false)) - - recovery?.run(newManager as never as PaneManager) - - expect(flushTerminalOutput).toHaveBeenCalledWith(newTerminal, { - maxChars: 256 * 1024 - }) - expect(newManager.scheduleRevealRepaint).toHaveBeenCalledTimes(1) - expect(oldManager.scheduleRevealRepaint).not.toHaveBeenCalled() - }) - it('routes a heavy reveal through fitAllRevealedPanes, not the sync fit', () => { // Regression: the sync reveal fit applied a transient one-column DOM↔WebGL grid, garbling grok on restore. const manager = createManager() @@ -207,55 +151,6 @@ describe('resumeTerminalVisibility reveal repaint', () => { expect(manager.fitAllPanes).not.toHaveBeenCalled() }) - it('latches viewport intent before WebGL resume on window wake', async () => { - // Why: resume/fit can move viewportY; syncing after reattach would re-latch - // a pinned viewport as followOutput and jump the user to the bottom. - const terminal = { name: 'pinned-wake' } - const manager = createManager() - manager.getPanes.mockReturnValue([{ terminal }]) - const { enforceTerminalCurrentScrollIntent, syncTerminalScrollIntentFromViewport } = vi.mocked( - await import('@/lib/pane-manager/terminal-scroll-intent') - ) - - recoverVisibleTerminalWindowWake({ - manager: manager as never as PaneManager, - isActive: true, - clearGlyphAtlases: false - }) - - expect(syncTerminalScrollIntentFromViewport).toHaveBeenCalledWith(terminal) - expect(syncTerminalScrollIntentFromViewport.mock.invocationCallOrder[0]).toBeLessThan( - manager.resumeRendering.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY - ) - expect(manager.resumeRendering.mock.invocationCallOrder[0]).toBeLessThan( - manager.fitAllRevealedPanes.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY - ) - // One pre-resume latch only; no same-tick post-flush re-sync (flush is async). - expect(syncTerminalScrollIntentFromViewport).toHaveBeenCalledTimes(1) - expect(enforceTerminalCurrentScrollIntent.mock.invocationCallOrder[0]).toBeGreaterThan( - manager.fitAllRevealedPanes.mock.invocationCallOrder[0] ?? Number.NEGATIVE_INFINITY - ) - }) - - it('does not re-sync viewport intent after heavy resume reattaches WebGL', async () => { - // Outer resumeTerminalVisibility already latched intent pre-resume; a - // same-tick post-flush re-sync would read pre-parse geometry (flush only - // queues terminal.write) and could overwrite a pin with resume/fit wobble. - const terminal = { name: 'pinned-heavy' } - const manager = createManager() - manager.getPanes.mockReturnValue([{ terminal }]) - const { syncTerminalScrollIntentFromViewport } = vi.mocked( - await import('@/lib/pane-manager/terminal-scroll-intent') - ) - - resumeTerminalVisibility(resumeArgs(manager, false)) - - expect(syncTerminalScrollIntentFromViewport).toHaveBeenCalledTimes(1) - expect(syncTerminalScrollIntentFromViewport.mock.invocationCallOrder[0]).toBeLessThan( - manager.resumeRendering.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY - ) - }) - it('resets each pane linkifier hover cache on window wake recovery so links recover without a scroll', () => { const first = { name: 'pane-a' } const second = { name: 'pane-b' } diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts index 8dcbb6e93..641c99258 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts @@ -30,10 +30,6 @@ type ResumeTerminalVisibilityArgs = { withSuppressedScrollTracking: (callback: () => void) => void } -export type TerminalVisibilityPostPaintRecovery = { - run: (manager: PaneManager) => void -} - type HideTerminalVisibilityArgs = { manager: PaneManager wasVisible: boolean @@ -61,7 +57,7 @@ export function resumeTerminalVisibility({ shouldUseLightTabResume, captureViewportPositions, withSuppressedScrollTracking -}: ResumeTerminalVisibilityArgs): TerminalVisibilityPostPaintRecovery | null { +}: ResumeTerminalVisibilityArgs): void { // Why: hiding the surface fired mouseleave, which cleared xterm's current // link but left its hover cell cache; without this reset a link stays dead // until a scroll when the pointer returns to the same cell on reveal. @@ -89,28 +85,19 @@ export function resumeTerminalVisibility({ focusActivePane(manager) } } else { - resumeTerminalVisibilityBeforePaint(manager, isActive) + resumeTerminalVisibilityHeavy(manager, isActive) } enforceTerminalViewportIntents(manager) - if (shouldUseLightTabResume) { - manager.scheduleRevealRepaint() + if (!shouldUseLightTabResume) { + // Why: this clear wipes the glyph atlas shared with other same-config + // terminals; refresh after reset so rebuilt atlases repaint from xterm. + resetAndRefreshAllTerminalWebglAtlases() } + // Why: the synchronous recovery above can fire before the revealed pane is + // attached and laid out, where the WebGL renderer drops redraw requests + // without retry. Follow up with a settled-frame, pane-scoped repaint. + manager.scheduleRevealRepaint() }) - if (shouldUseLightTabResume) { - return null - } - return { - run: (currentManager) => { - withSuppressedScrollTracking(() => { - drainVisibleTerminalBacklog(currentManager) - enforceTerminalViewportIntents(currentManager) - // Why: the shared atlas reset repaints every live manager, so keep it - // out of the reveal's pre-paint critical path. - resetAndRefreshAllTerminalWebglAtlases() - currentManager.scheduleRevealRepaint() - }) - } - } } export function hideTerminalVisibility({ @@ -128,6 +115,8 @@ export function hideTerminalVisibility({ captureViewportPositions(false) } if (!isWorktreeActive && (wasVisible || surfaceBecameHidden)) { + // Suspend WebGL when going hidden. xterm.write() continues to land in the + // DOM-renderer fallback terminal; the suspend is purely a GPU resource decision. manager.suspendRendering() return { hiddenReason: 'surface', renderingSuspended: true } } @@ -154,13 +143,6 @@ export function recoverVisibleTerminalWindowWake({ }: RecoverVisibleTerminalWindowWakeArgs): void { // Why: macOS screensaver/display wake can leave xterm visible but with a // stale renderer/input surface; Orca's own hidden-state resume never runs. - // Order: latch intent → resume WebGL → fit metrics → drain → enforce. - // Intent must be captured before resume/fit (they can move viewportY and - // would re-latch a pin as followOutput). Fit must precede flush so backlog - // does not land on the transient DOM↔WebGL one-column-off grid. - syncTerminalViewportIntents(manager) - manager.resumeRendering() - manager.fitAllRevealedPanes() for (const pane of manager.getPanes()) { requestTerminalBacklogRecovery(pane.terminal) flushTerminalOutput(pane.terminal, { maxChars: WINDOW_WAKE_FLUSH_CHARS }) @@ -172,10 +154,10 @@ export function recoverVisibleTerminalWindowWake({ resetTerminalLinkifierHoverState(pane.terminal) } } - // Why no post-flush re-sync: flushTerminalOutput only submits terminal.write and - // returns before parse callbacks, so a same-tick re-sync would read pre-parse - // geometry (possibly disturbed by resume/fit) and overwrite the pre-resume pin. - // Enforce the pre-resume latched intent instead. + syncTerminalViewportIntents(manager) + manager.resumeRendering() + // Why: wake re-attaches WebGL — same transient cell-metric wobble guard as the heavy resume. + manager.fitAllRevealedPanes() if (isActive) { focusActivePane(manager) } @@ -201,19 +183,28 @@ function requestLightTabBacklogRecovery(manager: PaneManager): void { } } -function resumeTerminalVisibilityBeforePaint(manager: PaneManager, isActive: boolean): void { - manager.resumeRendering() - manager.fitAllRevealedPanes() - if (isActive) { - focusActivePane(manager) - } -} - -function drainVisibleTerminalBacklog(manager: PaneManager): void { +function resumeTerminalVisibilityHeavy(manager: PaneManager, isActive: boolean): void { + // Why: hidden panes can accumulate large PTY bursts while Chromium is + // occluded. Drain a bounded slice before fitting; the scheduler keeps + // ordering and continues the rest asynchronously so return-to-app does + // not beachball behind an entire backlog. for (const pane of manager.getPanes()) { requestTerminalBacklogRecovery(pane.terminal) flushTerminalOutput(pane.terminal, { maxChars: VISIBLE_RESUME_FLUSH_CHARS }) } + syncTerminalViewportIntents(manager) + // Resume WebGL immediately so the terminal shows its last-known state + // on the first painted frame. macOS context creation is ~5 ms; on + // Windows (ANGLE -> D3D11) it can be 100-500 ms but a deferred resume + // would paint a stretched DOM-fallback flash, which is worse UX. + manager.resumeRendering() + // Why: resumeRendering just re-attached WebGL, whose cell metrics briefly differ + // from the DOM renderer's; a raw fit here reflows on a transient one-column-off + // grid and garbles diff-painting inline TUIs (grok minimize→restore). + manager.fitAllRevealedPanes() + if (isActive) { + focusActivePane(manager) + } } function enforceTerminalViewportIntents(manager: PaneManager): void { diff --git a/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.test.ts b/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.test.ts deleted file mode 100644 index d1a2f2089..000000000 --- a/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - COLD_PARKED_PRESENTATION_FALLBACK_MS, - useColdParkedTerminalPresentation -} from './use-cold-parked-terminal-presentation' - -type HookProps = { - desiredTargetId: string | null - coldParkedTargetIds: ReadonlySet -} - -const availableTargetIds = new Set(['a', 'b', 'c']) - -function renderPresentationHook(initialProps: HookProps) { - return renderHook( - ({ desiredTargetId, coldParkedTargetIds }: HookProps) => - useColdParkedTerminalPresentation({ - desiredTargetByScope: new Map([['scope', desiredTargetId]]), - coldParkedTargetIds, - availableTargetIds - }), - { initialProps } - ) -} - -function presentedTargetId( - result: ReturnType['result'] -): string | null | undefined { - return result.current.presentationByScope.get('scope')?.presentedTargetId -} - -describe('useColdParkedTerminalPresentation', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('presents a warm target immediately', () => { - const hook = renderPresentationHook({ - desiredTargetId: 'a', - coldParkedTargetIds: new Set() - }) - - hook.rerender({ desiredTargetId: 'b', coldParkedTargetIds: new Set() }) - - expect(presentedTargetId(hook.result)).toBe('b') - }) - - it('clears the terminal presentation when the group activates non-terminal content', () => { - const hook = renderPresentationHook({ - desiredTargetId: 'a', - coldParkedTargetIds: new Set() - }) - - hook.rerender({ desiredTargetId: null, coldParkedTargetIds: new Set() }) - - expect(presentedTargetId(hook.result)).toBeNull() - }) - - it('retains the prior target until a cold target settles', () => { - const hook = renderPresentationHook({ - desiredTargetId: 'a', - coldParkedTargetIds: new Set() - }) - - hook.rerender({ desiredTargetId: 'b', coldParkedTargetIds: new Set(['b']) }) - hook.rerender({ desiredTargetId: 'b', coldParkedTargetIds: new Set() }) - - expect(presentedTargetId(hook.result)).toBe('a') - act(() => hook.result.current.settleTarget('b')) - expect(presentedTargetId(hook.result)).toBe('b') - }) - - it('ignores a stale settle after another switch', () => { - const hook = renderPresentationHook({ - desiredTargetId: 'a', - coldParkedTargetIds: new Set() - }) - - hook.rerender({ desiredTargetId: 'b', coldParkedTargetIds: new Set(['b']) }) - hook.rerender({ desiredTargetId: 'c', coldParkedTargetIds: new Set() }) - act(() => hook.result.current.settleTarget('b')) - - expect(presentedTargetId(hook.result)).toBe('c') - }) - - it('falls back when a cold target never settles', () => { - vi.useFakeTimers() - const hook = renderPresentationHook({ - desiredTargetId: 'a', - coldParkedTargetIds: new Set() - }) - - hook.rerender({ desiredTargetId: 'b', coldParkedTargetIds: new Set(['b']) }) - act(() => vi.advanceTimersByTime(COLD_PARKED_PRESENTATION_FALLBACK_MS)) - - expect(presentedTargetId(hook.result)).toBe('b') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.ts b/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.ts deleted file mode 100644 index 400805638..000000000 --- a/src/renderer/src/components/terminal-pane/use-cold-parked-terminal-presentation.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' - -export const COLD_PARKED_PRESENTATION_FALLBACK_MS = 1_000 - -type PresentationEntry = { - presentedTargetId: string | null - pendingTargetId: string | null -} - -export type ColdParkedPresentationState = ReadonlyMap - -type PresentationInputs = { - desiredTargetByScope: ReadonlyMap - coldParkedTargetIds: ReadonlySet - availableTargetIds: ReadonlySet -} - -function haveSameEntries( - left: ColdParkedPresentationState, - right: ColdParkedPresentationState -): boolean { - if (left.size !== right.size) { - return false - } - for (const [scopeId, entry] of left) { - const other = right.get(scopeId) - if ( - !other || - entry.presentedTargetId !== other.presentedTargetId || - entry.pendingTargetId !== other.pendingTargetId - ) { - return false - } - } - return true -} - -export function createColdParkedPresentationState( - desiredTargetByScope: ReadonlyMap -): ColdParkedPresentationState { - return new Map( - Array.from(desiredTargetByScope, ([scopeId, targetId]) => [ - scopeId, - { presentedTargetId: targetId, pendingTargetId: null } - ]) - ) -} - -export function resolveColdParkedPresentation( - current: ColdParkedPresentationState, - inputs: PresentationInputs -): ColdParkedPresentationState { - const next = new Map() - for (const [scopeId, desiredTargetId] of inputs.desiredTargetByScope) { - const entry = current.get(scopeId) ?? { - presentedTargetId: null, - pendingTargetId: null - } - if (entry.pendingTargetId !== null && entry.pendingTargetId === desiredTargetId) { - next.set(scopeId, entry) - continue - } - const canRetainPresentedTarget = - entry.presentedTargetId !== null && inputs.availableTargetIds.has(entry.presentedTargetId) - const shouldWait = - desiredTargetId !== null && - desiredTargetId !== entry.presentedTargetId && - canRetainPresentedTarget && - inputs.coldParkedTargetIds.has(desiredTargetId) - next.set( - scopeId, - shouldWait - ? { presentedTargetId: entry.presentedTargetId, pendingTargetId: desiredTargetId } - : { presentedTargetId: desiredTargetId, pendingTargetId: null } - ) - } - return haveSameEntries(current, next) ? current : next -} - -function settlePresentationTarget( - current: ColdParkedPresentationState, - desiredTargetByScope: ReadonlyMap, - targetId: string -): ColdParkedPresentationState { - let changed = false - const next = new Map(current) - for (const [scopeId, entry] of current) { - if (entry.pendingTargetId !== targetId || desiredTargetByScope.get(scopeId) !== targetId) { - continue - } - next.set(scopeId, { presentedTargetId: targetId, pendingTargetId: null }) - changed = true - } - return changed ? next : current -} - -export function useColdParkedTerminalPresentation( - inputs: PresentationInputs, - fallbackMs = COLD_PARKED_PRESENTATION_FALLBACK_MS -): { - presentationByScope: ColdParkedPresentationState - settleTarget: (targetId: string) => void -} { - const [committed, setCommitted] = useState(() => - createColdParkedPresentationState(inputs.desiredTargetByScope) - ) - const latestInputsRef = useRef(inputs) - latestInputsRef.current = inputs - const presentationByScope = resolveColdParkedPresentation(committed, inputs) - - useLayoutEffect(() => { - setCommitted((current) => resolveColdParkedPresentation(current, latestInputsRef.current)) - }, [presentationByScope]) - - const settleTarget = useCallback((targetId: string) => { - setCommitted((current) => { - const latest = latestInputsRef.current - const resolved = resolveColdParkedPresentation(current, latest) - return settlePresentationTarget(resolved, latest.desiredTargetByScope, targetId) - }) - }, []) - - useEffect(() => { - const timers = new Set() - const pendingTargetIds = new Set( - Array.from(presentationByScope.values(), (entry) => entry.pendingTargetId).filter( - (targetId): targetId is string => targetId !== null - ) - ) - for (const targetId of pendingTargetIds) { - timers.add(window.setTimeout(() => settleTarget(targetId), fallbackMs)) - } - return () => { - for (const timer of timers) { - window.clearTimeout(timer) - } - } - }, [fallbackMs, presentationByScope, settleTarget]) - - return { presentationByScope, settleTarget } -} diff --git a/src/renderer/src/components/terminal-pane/use-terminal-overlay-presentation.ts b/src/renderer/src/components/terminal-pane/use-terminal-overlay-presentation.ts deleted file mode 100644 index 856ac67e0..000000000 --- a/src/renderer/src/components/terminal-pane/use-terminal-overlay-presentation.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { useCallback, useMemo } from 'react' -import type { TabGroup, TerminalTab } from '../../../../shared/types' -import { useColdParkedTerminalPresentation } from './use-cold-parked-terminal-presentation' - -type TerminalOverlayAssignment = { - groupId: string - isActiveInGroup: boolean -} - -export function useTerminalOverlayPresentation(args: { - groups: readonly TabGroup[] - terminalTabs: readonly TerminalTab[] - assignments: ReadonlyMap - coldParkedTerminalTabIds: ReadonlySet - isWorktreeActive: boolean - activeGroupId: string | undefined - onInitialTerminalRenderSettled?: (tabId: string) => void -}): { - presentedTerminalTabIdByGroup: ReadonlyMap - handleInitialRenderSettled: (tabId: string) => void -} { - const { - groups, - terminalTabs, - assignments, - coldParkedTerminalTabIds, - isWorktreeActive, - activeGroupId, - onInitialTerminalRenderSettled - } = args - const desiredTerminalTabByGroup = useMemo(() => { - const desired = new Map() - for (const group of groups) { - desired.set(group.id, null) - } - for (const terminalTab of terminalTabs) { - const assignment = assignments.get(terminalTab.id) - if (assignment?.isActiveInGroup) { - desired.set(assignment.groupId, terminalTab.id) - } - } - return desired - }, [assignments, groups, terminalTabs]) - const availableTerminalTabIds = useMemo( - () => new Set(terminalTabs.map((terminalTab) => terminalTab.id)), - [terminalTabs] - ) - const { presentationByScope, settleTarget } = useColdParkedTerminalPresentation({ - desiredTargetByScope: desiredTerminalTabByGroup, - coldParkedTargetIds: coldParkedTerminalTabIds, - availableTargetIds: availableTerminalTabIds - }) - const presentedTerminalTabIdByGroup = useMemo( - () => - new Map( - Array.from(presentationByScope, ([groupId, entry]) => [groupId, entry.presentedTargetId]) - ), - [presentationByScope] - ) - const handleInitialRenderSettled = useCallback( - (tabId: string) => { - settleTarget(tabId) - const assignment = assignments.get(tabId) - if (isWorktreeActive && assignment?.isActiveInGroup && assignment.groupId === activeGroupId) { - onInitialTerminalRenderSettled?.(tabId) - } - }, - [activeGroupId, assignments, isWorktreeActive, onInitialTerminalRenderSettled, settleTarget] - ) - - return { - presentedTerminalTabIdByGroup, - handleInitialRenderSettled - } -} diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts index 4bf7faae2..f271ab092 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts @@ -30,8 +30,7 @@ const mocks = vi.hoisted(() => ({ const reactRefState = vi.hoisted(() => ({ slots: [] as { current: unknown }[], - index: 0, - effectPhase: null as 'layout' | 'passive' | null + index: 0 })) function beginHookRender(): void { @@ -49,21 +48,7 @@ vi.mock('react', async (importOriginal) => { ...actual, useCallback: unknown>(callback: T) => callback, useEffect: (effect: () => void | (() => void)) => { - reactRefState.effectPhase = 'passive' - try { - effect() - } finally { - reactRefState.effectPhase = null - } - }, - // macOS visibility suspend/resume runs here before reveal paint. - useLayoutEffect: (effect: () => void | (() => void)) => { - reactRefState.effectPhase = 'layout' - try { - effect() - } finally { - reactRefState.effectPhase = null - } + effect() }, useRef: (value: T) => { const index = reactRefState.index @@ -156,8 +141,7 @@ function useMountForFileDrop( isWorktreeActive?: boolean isSyncFitEnabled?: boolean paneCount?: number - } = {}, - useGlobalEffects: typeof useTerminalPaneGlobalEffects = useTerminalPaneGlobalEffects + } = {} ): { onFileDrop: DropCallback manager: { @@ -171,7 +155,6 @@ function useMountForFileDrop( fitAllRevealedPanes: ReturnType } paneTransports: Map - renderingEffectPhases: ('layout' | 'passive' | null)[] } { let onFileDrop: DropCallback = () => { throw new Error('onFileDrop callback was not registered') @@ -180,10 +163,9 @@ function useMountForFileDrop( onFileDrop = callback return vi.fn() }) - const renderingEffectPhases: ('layout' | 'passive' | null)[] = [] const manager = { getPanes: vi.fn(() => []), - resumeRendering: vi.fn(() => renderingEffectPhases.push(reactRefState.effectPhase)), + resumeRendering: vi.fn(), resetWebglTextureAtlases: vi.fn(), scheduleRevealRepaint: vi.fn(), scheduleRevealPresent: vi.fn(), @@ -194,7 +176,7 @@ function useMountForFileDrop( const paneTransports = new Map() beginHookRender() - useGlobalEffects({ + useTerminalPaneGlobalEffects({ tabId: options.tabId ?? 'tab-1', worktreeId: options.worktreeId ?? 'wt-1', cwd: options.cwd, @@ -211,7 +193,7 @@ function useMountForFileDrop( toggleExpandPane: vi.fn() }) - return { onFileDrop, manager, paneTransports, renderingEffectPhases } + return { onFileDrop, manager, paneTransports } } describe('useTerminalPaneGlobalEffects', () => { @@ -244,26 +226,6 @@ describe('useTerminalPaneGlobalEffects', () => { ;(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver }) - it.each([ - ['darwin', 'layout'], - ['win32', 'passive'], - ['linux', 'passive'] - ] as const)('runs visibility transitions in the %s effect phase', async (platform, phase) => { - window.api.platform = { - get: () => ({ platform, osRelease: 'test', displayServer: null }) - } - vi.resetModules() - const { useTerminalPaneGlobalEffects: usePlatformTerminalPaneGlobalEffects } = - await import('./use-terminal-pane-global-effects') - - const { renderingEffectPhases } = useMountForFileDrop( - { isActive: true, isVisible: true }, - usePlatformTerminalPaneGlobalEffects - ) - - expect(renderingEffectPhases).toEqual([phase]) - }) - afterEach(() => { for (const manager of registeredManagers.splice(0)) { unregisterLivePaneManager(manager) @@ -274,9 +236,7 @@ describe('useTerminalPaneGlobalEffects', () => { delete (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver }) - it('resumes WebGL and fits before flushing backlog so paint is GPU and grid is stable', () => { - // On macOS resume before flush avoids DOM bold flash; fit before flush avoids - // writing backlog onto the transient DOM↔WebGL one-column-off grid. + it('flushes visible terminal panes before resuming rendering and fitting', () => { const order: string[] = [] const terminalA = { name: 'terminal-a' } const terminalB = { name: 'terminal-b' } @@ -339,23 +299,18 @@ describe('useTerminalPaneGlobalEffects', () => { expect(order).toEqual([ 'capture:terminal-a', 'capture:terminal-b', - 'resume', - 'fit-reveal', - 'intent:terminal-a', - 'intent:terminal-b', 'recover:terminal-a', 'flush:terminal-a', 'recover:terminal-b', 'flush:terminal-b', + 'resume', + 'fit-reveal', 'intent:terminal-a', 'intent:terminal-b', 'reset-atlas', 'refresh', 'reveal-repaint' ]) - // Why: flush must not land between resume and the corrective reveal fit. - expect(order.indexOf('resume')).toBeLessThan(order.indexOf('fit-reveal')) - expect(order.indexOf('fit-reveal')).toBeLessThan(order.indexOf('flush:terminal-a')) expect(mocks.restoreScrollStateAfterLayout).not.toHaveBeenCalled() expect(mocks.flushTerminalOutput).toHaveBeenNthCalledWith(1, terminalA, { maxChars: 256 * 1024 @@ -368,62 +323,6 @@ describe('useTerminalPaneGlobalEffects', () => { expect(isVisibleRef.current).toBe(true) }) - it('records mount-visible completion before PaneManager exists so first tab hide stays light', () => { - // Why: PaneManager is created in a passive lifecycle effect after this layout - // pass. Bookkeeping must still mark hasCompletedVisibleResume so the first - // intra-worktree hide does not take the !hasCompleted suspend branch. - const terminal = { name: 'terminal-a' } - const manager = { - getPanes: vi.fn(() => [{ id: 1, terminal }]), - resumeRendering: vi.fn(), - resetWebglTextureAtlases: vi.fn(), - scheduleRevealRepaint: vi.fn(), - scheduleRevealPresent: vi.fn(), - refreshAllPanes: vi.fn(), - suspendRendering: vi.fn(), - fitAllPanes: vi.fn(), - fitAllRevealedPanes: vi.fn(), - getActivePane: vi.fn(() => null), - setActivePane: vi.fn() - } - registerManagerForReset(manager) - const managerRef: { current: typeof manager | null } = { current: null } - const baseArgs = { - tabId: 'tab-1', - worktreeId: 'wt-1', - managerRef: managerRef as never, - containerRef: { current: null }, - paneTransportsRef: { current: new Map() }, - isActiveRef: { current: false }, - isVisibleRef: { current: false }, - paneCount: 0, - isSyncFitEnabled: true, - isWorktreeActive: true, - toggleExpandPane: vi.fn() - } - - // Mount visible before the manager exists (layout before passive create). - beginHookRender() - useTerminalPaneGlobalEffects({ - ...baseArgs, - isActive: true, - isVisible: true - }) - expect(manager.resumeRendering).not.toHaveBeenCalled() - - // Manager appears; visibility unchanged so the layout effect does not re-run. - // First hide still must keep WebGL (light path). - managerRef.current = manager - beginHookRender() - useTerminalPaneGlobalEffects({ - ...baseArgs, - paneCount: 1, - isActive: false, - isVisible: false - }) - expect(manager.suspendRendering).not.toHaveBeenCalled() - }) - it('uses a light resume for tab switches while the worktree stays active', () => { vi.useFakeTimers() vi.stubGlobal( diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts index 4e81b820c..95f9198e7 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.ts @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useRef } from 'react' +import { useEffect, useRef } from 'react' import { FOCUS_TERMINAL_PANE_EVENT, PASTE_TERMINAL_TEXT_EVENT, @@ -16,23 +16,16 @@ import { useAppStore } from '@/store' import { useTerminalScrollVisibilityMemory } from './use-terminal-scroll-visibility-memory' import { useTerminalContainerFitSync } from './use-terminal-container-fit-sync' import { handleTerminalProgrammaticTextPaste } from './terminal-programmatic-text-paste' -import { applyTerminalVisibilityTransition } from './apply-terminal-visibility-transition' -import type { - TerminalHiddenReason, - TerminalVisibilityPostPaintRecovery +import { + hideTerminalVisibility, + resumeTerminalVisibility, + type TerminalHiddenReason } from './terminal-visibility-resume' import { useTerminalWindowWakeRecovery } from './use-terminal-window-wake-recovery' import { releaseRendererPtyVisibilityClaim, setRendererPtyVisibilityClaim } from './pty-renderer-delivery-claims' -import { getRendererAppPlatform } from '@/lib/renderer-app-platform' -import { getTerminalVisibilityEffectPhase } from './terminal-visibility-effect-phase' - -const useTerminalVisibilityEffect = - getTerminalVisibilityEffectPhase(getRendererAppPlatform()) === 'layout' - ? useLayoutEffect - : useEffect type UseTerminalPaneGlobalEffectsArgs = { tabId: string @@ -88,15 +81,22 @@ export function useTerminalPaneGlobalEffects({ worktreeIdRef.current = worktreeId const cwdRef = useRef(cwd) cwdRef.current = cwd - // Starts true so initially hidden tabs never allocate WebGL. + // Starts true so the first render with isVisible=false triggers a + // suspendRendering(). Background worktrees that mount hidden would + // otherwise leak WebGL contexts — openTerminal() unconditionally creates + // one — and exhaust Chromium's ~8-context budget across worktrees. const wasVisibleRef = useRef(true) const wasWorktreeActiveRef = useRef(isWorktreeActive) const hasCompletedVisibleResumeRef = useRef(false) const renderingSuspendedByVisibilityRef = useRef(false) const hiddenReasonRef = useRef(null) - const postPaintVisibilityRecoveryRef = useRef(null) const rendererVisible = isVisible && isWorktreeActive - // Why: rebind/active-leaf changes without visibility flips must re-report PTY. + // Why: the active pane can rebind to a new PTY (deferred reattach / eager + // adopt) or switch active leaf without isActive/isVisible/isWorktreeActive + // flipping. Derive the active leaf's live PTY reactively from the same + // leaf→PTY binding the reattach path writes, so the active-renderer-pty report + // below re-fires on rebind — otherwise main keeps the stale id and the live + // PTY loses its interactive reserve. const activeLeafPtyId = useAppStore((state) => { const layout = state.terminalLayoutsByTabId[tabId] const activeLeafId = layout?.activeLeafId @@ -137,37 +137,52 @@ export function useTerminalPaneGlobalEffects({ } }, [rendererVisible, paneTransportsRef]) - // macOS can rebuild WebGL pre-paint without blocking reveal on slow ANGLE paths. - useTerminalVisibilityEffect(() => { - isActiveRef.current = isActive - isVisibleRef.current = rendererVisible - postPaintVisibilityRecoveryRef.current = applyTerminalVisibilityTransition({ - manager: managerRef.current, - rendererVisible, - isActive, - isWorktreeActive, - wasVisibleRef, - wasWorktreeActiveRef, - hasCompletedVisibleResumeRef, - renderingSuspendedByVisibilityRef, - hiddenReasonRef, - captureViewportPositions, - withSuppressedScrollTracking, - applyPendingFollowOutputRequests - }) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isActive, isWorktreeActive, rendererVisible]) - useEffect(() => { - const recovery = postPaintVisibilityRecoveryRef.current - postPaintVisibilityRecoveryRef.current = null const manager = managerRef.current - if (!recovery || !isVisibleRef.current || !manager) { + if (!manager) { return } - // Why: lifecycle effects may replace the manager after layout but before this effect. - recovery.run(manager) - }, [isActive, isWorktreeActive, rendererVisible, isVisibleRef, managerRef]) + const wasVisible = wasVisibleRef.current + const wasWorktreeActive = wasWorktreeActiveRef.current + isActiveRef.current = isActive + isVisibleRef.current = rendererVisible + if (rendererVisible) { + const shouldUseLightTabResume = + isWorktreeActive && + hasCompletedVisibleResumeRef.current && + !renderingSuspendedByVisibilityRef.current && + (wasVisible || hiddenReasonRef.current === 'tab') + resumeTerminalVisibility({ + manager, + isActive, + wasVisible, + shouldUseLightTabResume, + captureViewportPositions, + withSuppressedScrollTracking + }) + renderingSuspendedByVisibilityRef.current = false + wasVisibleRef.current = true + wasWorktreeActiveRef.current = isWorktreeActive + hasCompletedVisibleResumeRef.current = true + hiddenReasonRef.current = null + applyPendingFollowOutputRequests() + return + } else { + const hiddenState = hideTerminalVisibility({ + manager, + wasVisible, + wasWorktreeActive, + isWorktreeActive, + hasCompletedVisibleResume: hasCompletedVisibleResumeRef.current, + captureViewportPositions + }) + renderingSuspendedByVisibilityRef.current = hiddenState.renderingSuspended + hiddenReasonRef.current = hiddenState.hiddenReason + } + wasVisibleRef.current = false + wasWorktreeActiveRef.current = isWorktreeActive + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isActive, isWorktreeActive, rendererVisible]) useEffect(() => { const ptyId = isActive && isVisible && isWorktreeActive ? activeLeafPtyId : null diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts index 639e4dece..4ad241c9f 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts @@ -63,7 +63,6 @@ import { replayTerminalLayout, restoreScrollbackBuffers } from './layout-serialization' -import { scheduleTerminalInitialRenderSettled } from './terminal-initial-render-settle' import { resolveTerminalLayoutActiveLeafId } from './terminal-layout-leaf-ids' import { makePaneKey } from '../../../../shared/stable-pane-id' import { applyExpandedLayoutTo, restoreExpandedLayoutFrom } from './expand-collapse' @@ -319,7 +318,6 @@ type UseTerminalPaneLifecycleDeps = { setPaneLayoutRevision: React.Dispatch> resolveExternalPaneDropTarget?: PaneExternalDropResolver onExternalPaneDrop?: PaneExternalDropHandler - onInitialRenderSettledRef: React.RefObject<(() => void) | undefined> } export function suppressIntentionalPaneCloseExit( @@ -568,8 +566,7 @@ export function useTerminalPaneLifecycle({ setPaneCount, setPaneLayoutRevision, resolveExternalPaneDropTarget, - onExternalPaneDrop, - onInitialRenderSettledRef + onExternalPaneDrop }: UseTerminalPaneLifecycleDeps): void { const terminalScrollbackRows = normalizeDesktopTerminalScrollbackRows( settings?.terminalScrollbackRows @@ -707,7 +704,6 @@ export function useTerminalPaneLifecycle({ initialLayoutRef.current = hydratedInitialScrollback.layout } let shouldPersistLayout = false - let cancelInitialRenderSettle: (() => void) | null = null const startupWithSetupSplitWait = startup && setupSplit ? { ...startup, waitForSetupSplitDirection: setupSplit.direction } @@ -1490,28 +1486,6 @@ export function useTerminalPaneLifecycle({ queueResizeAll(isActive) persistLayoutSnapshot() scheduleRuntimeGraphSync() - if (onInitialRenderSettledRef.current) { - cancelInitialRenderSettle = scheduleTerminalInitialRenderSettled({ - manager, - isCurrent: () => managerRef.current === manager, - isReplaySettled: () => replayingPanesRef.current.size === 0, - isContentReady: () => { - const terminal = (manager.getActivePane() ?? manager.getPanes()[0])?.terminal - if (!terminal) { - return false - } - const buffer = terminal.buffer.active - const viewportEnd = Math.min(buffer.length, buffer.viewportY + terminal.rows) - for (let row = buffer.viewportY; row < viewportEnd; row += 1) { - if (buffer.getLine(row)?.translateToString(true).trim()) { - return true - } - } - return false - }, - onSettled: () => onInitialRenderSettledRef.current?.() - }) - } // Why: deliver the startup command via the PTY connection path (waits for shell readiness), not terminal.paste() which can lose input before the shell reads stdin. function onCliSplitPane(event: Event): void { @@ -1582,7 +1556,6 @@ export function useTerminalPaneLifecycle({ window.addEventListener(CLOSE_TERMINAL_PANE_EVENT, onCliClosePane) return () => { - cancelInitialRenderSettle?.() window.removeEventListener(SPLIT_TERMINAL_PANE_EVENT, onCliSplitPane) window.removeEventListener(CLOSE_TERMINAL_PANE_EVENT, onCliClosePane) const currentWorktreeTabs = useAppStore.getState().tabsByWorktree[worktreeId] diff --git a/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts index 24ae41a77..e04f6c008 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts @@ -85,37 +85,37 @@ describe('useTerminalTabColdParking measure-clock contract', () => { (args: ReturnType) => useTerminalTabColdParking(args), { initialProps: hookArgs(false) } ) - expect(result.current.parkedTerminalTabIds.size).toBe(0) + expect(result.current.size).toBe(0) // Past hot-retain: tab-1 holds the last-active exemption, tab-2 parks. act(() => { vi.advanceTimersByTime(TERMINAL_TAB_HOT_RETAIN_MS + 1) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) // A measure window reveals every tab but must not clear the hidden clock. act(() => { rerender(hookArgs(true)) }) - expect(result.current.parkedTerminalTabIds.size).toBe(0) + expect(result.current.size).toBe(0) act(() => { vi.advanceTimersByTime(3_000) rerender(hookArgs(false)) }) // Measure just ended: the cool-down vetoes an instant re-park (the thrash). - expect(result.current.parkedTerminalTabIds.size).toBe(0) + expect(result.current.size).toBe(0) act(() => { vi.advanceTimersByTime(TERMINAL_TAB_COLD_PARK_DELAY_MS - 1) }) - expect(result.current.parkedTerminalTabIds.size).toBe(0) + expect(result.current.size).toBe(0) // One cool-down later tab-2 re-parks — proving hiddenSince survived the // measure (a cleared clock would demand a fresh 15-minute hot-retain). act(() => { vi.advanceTimersByTime(2) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) }) // Why: a measure window also ends when the user opens the worktree; the @@ -130,12 +130,12 @@ describe('useTerminalTabColdParking measure-clock contract', () => { act(() => { vi.advanceTimersByTime(TERMINAL_TAB_HOT_RETAIN_MS + 1) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) act(() => { rerender(hookArgs(true)) }) - expect(result.current.parkedTerminalTabIds.size).toBe(0) + expect(result.current.size).toBe(0) // Measure ends because the worktree went visible: tab-2 is still hidden // (no active group assignment) and re-parks on this very pass. @@ -143,7 +143,7 @@ describe('useTerminalTabColdParking measure-clock contract', () => { vi.advanceTimersByTime(3_000) rerender({ ...hookArgs(false), isWorktreeActive: true }) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) }) // Why: force-park is the only park that can contain unrestorable ptys, so its @@ -155,14 +155,14 @@ describe('useTerminalTabColdParking measure-clock contract', () => { useTerminalTabColdParking(args), { initialProps: { ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: true } } ) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) // The carve-out is scoped to force-parks: an ordinary worktree park has no // exempt tabs to protect, so it evicts both. act(() => { rerender({ ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: false }) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2'])) + expect(result.current).toEqual(new Set(['tab-1', 'tab-2'])) }) // Why: a split lands in the layout store, not in terminalTabs — a memo keyed @@ -174,14 +174,14 @@ describe('useTerminalTabColdParking measure-clock contract', () => { (args: typeof stableArgs) => useTerminalTabColdParking(args), { initialProps: stableArgs } ) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2'])) + expect(result.current).toEqual(new Set(['tab-1', 'tab-2'])) // Same tabs, same verdict: nothing the memo can see has moved yet. mocks.exemptTabIds = new Set(['tab-1']) act(() => { rerender(stableArgs) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2'])) + expect(result.current).toEqual(new Set(['tab-1', 'tab-2'])) // The split's leaf pty lands in the layout store and re-keys the memo. mocks.storeState.terminalLayoutsByTabId = { @@ -190,7 +190,7 @@ describe('useTerminalTabColdParking measure-clock contract', () => { act(() => { rerender(stableArgs) }) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) }) // Why: resolving an exemption re-reads the store and walks the layout tree per @@ -202,13 +202,13 @@ describe('useTerminalTabColdParking measure-clock contract', () => { (args: typeof stableArgs) => useTerminalTabColdParking(args), { initialProps: stableArgs } ) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) const callsAfterFirstRender = mocks.exemptSelectCalls act(() => { rerender({ ...stableArgs, isWorktreeActive: false }) }) expect(mocks.exemptSelectCalls).toBe(callsAfterFirstRender) - expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2'])) + expect(result.current).toEqual(new Set(['tab-2'])) }) }) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts b/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts index cbf128e78..85ea3e9e9 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts @@ -71,10 +71,7 @@ export function useTerminalTabColdParking(args: { /** Tabs cold activation keeps unmounted — parked-equivalent for watcher * purposes. Targeted background restrictions intentionally stay bounded. */ activationDeferredMountTabIds?: ReadonlySet | null -}): { - parkedTerminalTabIds: ReadonlySet - coldParkedTerminalTabIds: ReadonlySet -} { +}): ReadonlySet { const { worktreeId, terminalTabs, @@ -350,5 +347,5 @@ export function useTerminalTabColdParking(args: { useEffect(() => () => disposeParkedTerminalWatchersForWorktree(worktreeId), [worktreeId]) - return { parkedTerminalTabIds, coldParkedTerminalTabIds } + return parkedTerminalTabIds } diff --git a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts index 9aa24002b..9fb283782 100644 --- a/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts +++ b/src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts @@ -1,7 +1,6 @@ import type { ManagedPaneInternal } from './pane-manager-types' import { reattachWebglIfNeeded } from './pane-webgl-reattach' import { resetWebglTextureAtlas } from './pane-webgl-renderer' -import { releaseAbandonedSynchronizedOutput } from './terminal-synchronized-output-release' function scheduleSettledFrame(callback: () => void): void { if (typeof globalThis.requestAnimationFrame !== 'function') { @@ -61,10 +60,6 @@ export function schedulePaneRevealRepaint(getPanes: () => Iterable Iterable): void { forEachPaneOnSettledFrame(getPanes, (pane) => { reattachWebglIfNeeded(pane) - // Why before the refresh: while a TUI's synchronized-output frame is - // latched, RenderService buffers refreshes instead of rendering them, so - // this present would paint nothing. See terminal-synchronized-output-release. - releaseAbandonedSynchronizedOutput(pane.terminal) if (pane.terminal.rows > 0) { pane.terminal.refresh(0, pane.terminal.rows - 1) } diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts b/src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts index fe661327c..f2a07f875 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-refresh-lifecycle.test.ts @@ -121,7 +121,7 @@ describe('pane WebGL refresh lifecycle', () => { expect(pane.webglAddon).toBeNull() }) - it('disposes WebGL whenever rendering is suspended', () => { + it('disposes WebGL when rendering is suspended', () => { const dispose = vi.fn() const pane = createPane({ webglAddon: { dispose } as never }) diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts index f4f625a84..65e78c008 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts @@ -8,7 +8,6 @@ import { resetTerminalWebglAutoDecision } from './terminal-webgl-auto-policy' import { safeFitAndThen } from './pane-fit' -import { releaseAbandonedSynchronizedOutput } from './terminal-synchronized-output-release' export const ENABLE_WEBGL_RENDERER = true let suggestedRendererType: 'dom' | undefined @@ -130,10 +129,6 @@ export function resetWebglTextureAtlas(pane: ManagedPaneInternal): void { return } try { - // Why first: a TUI hidden mid-`?2026h` leaves synchronized output latched, - // and RenderService buffers every refresh while it holds — so the repaint - // below would render nothing at all. See terminal-synchronized-output-release. - releaseAbandonedSynchronizedOutput(pane.terminal) // Why: rapid TUI redraws can corrupt xterm's WebGL glyph atlas without a // context-loss event. Clearing the atlas preserves GPU rendering and forces // a fresh paint when the pane becomes visible/focused again. diff --git a/src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts b/src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts deleted file mode 100644 index 4d3519726..000000000 --- a/src/renderer/src/lib/pane-manager/reveal-repaint-synchronized-output.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -/** - * STA-2694: an alt-screen agent TUI (OpenCode/OpenTUI, Codex, grok) brackets - * every repaint in `?2026h … ?2026l`. Hiding the pane mid-bracket latches - * xterm's synchronizedOutput mode, and RenderService.refreshRows checks that - * latch BEFORE rendering — so on reveal the whole repaint arsenal renders zero - * rows and the canvas keeps compositing pre-hide pixels. - * - * These tests drive the real reveal entry points against a terminal double that - * mirrors xterm's gate order, so a regression that stops releasing the latch - * shows up as "reveal repainted nothing". - */ -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import { schedulePaneRevealPresent } from './pane-reveal-repaint' -import { resetWebglTextureAtlas } from './pane-webgl-renderer' -import type { ManagedPaneInternal } from './pane-manager-types' - -type GateState = { synchronizedOutput: boolean; rendered: number } - -// Mirrors RenderService.refreshRows: paused first, then the synchronized-output -// buffer gate, then the actual render. This double can drift from xterm on an -// upgrade, so the gate order it encodes is independently pinned against the real -// renderer in tests/e2e/terminal-reveal-draw-command-probe.spec.ts. -function createGatedPane(options: { synchronizedOutput: boolean }): { - pane: ManagedPaneInternal - gate: GateState -} { - const gate: GateState = { synchronizedOutput: options.synchronizedOutput, rendered: 0 } - const refreshRows = (): void => { - if (gate.synchronizedOutput) { - return - } - gate.rendered += 1 - } - const terminal = { - rows: 24, - cols: 80, - refresh: refreshRows, - _core: { - coreService: { - get decPrivateModes() { - return gate - } - }, - _renderService: { - _isPaused: false, - _needsFullRefresh: false, - refreshRows, - _syncOutputHandler: { flush: vi.fn() } - } - } - } - const pane = { - id: 1, - terminal, - gpuRenderingEnabled: false, - webglAddon: null, - webglAttachmentDeferred: false, - webglDisabledAfterContextLoss: false - } as unknown as ManagedPaneInternal - return { pane, gate } -} - -describe('reveal repaint under an abandoned synchronized-output frame', () => { - beforeEach(() => { - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - callback(0) - return 1 - }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('atlas-reset recovery repaints a pane hidden mid-synchronized-frame', () => { - const { pane, gate } = createGatedPane({ synchronizedOutput: true }) - - resetWebglTextureAtlas(pane) - - expect(gate.synchronizedOutput, 'the abandoned frame must be released').toBe(false) - expect(gate.rendered, 'reveal must actually repaint, not buffer').toBeGreaterThan(0) - }) - - it('atlas-preserving present repaints a pane hidden mid-synchronized-frame', () => { - const { pane, gate } = createGatedPane({ synchronizedOutput: true }) - - schedulePaneRevealPresent(() => [pane]) - - expect(gate.synchronizedOutput).toBe(false) - expect(gate.rendered).toBeGreaterThan(0) - }) - - it('leaves a pane that was not mid-frame exactly as before', () => { - const { pane, gate } = createGatedPane({ synchronizedOutput: false }) - - resetWebglTextureAtlas(pane) - - expect(gate.synchronizedOutput).toBe(false) - expect(gate.rendered).toBeGreaterThan(0) - }) -}) diff --git a/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.test.ts b/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.test.ts deleted file mode 100644 index e04efbd4d..000000000 --- a/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { releaseAbandonedSynchronizedOutput } from './terminal-synchronized-output-release' - -function createTerminal(options: { - synchronizedOutput?: boolean | undefined - withoutCore?: boolean - withoutModes?: boolean - flush?: () => unknown -}): unknown { - if (options.withoutCore) { - return {} - } - return { - _core: { - coreService: options.withoutModes - ? {} - : { decPrivateModes: { synchronizedOutput: options.synchronizedOutput } }, - _renderService: { _syncOutputHandler: { flush: options.flush } } - } - } -} - -describe('releaseAbandonedSynchronizedOutput', () => { - it('clears a latched synchronized-output frame and flushes its buffered rows', () => { - const flush = vi.fn() - const terminal = createTerminal({ synchronizedOutput: true, flush }) - - expect(releaseAbandonedSynchronizedOutput(terminal)).toBe(true) - expect( - (terminal as { _core: { coreService: { decPrivateModes: { synchronizedOutput: boolean } } } }) - ._core.coreService.decPrivateModes.synchronizedOutput - ).toBe(false) - // The buffered range dies with the latch; the caller's own full refresh - // repaints those rows, and leaving it armed keeps xterm's 1s timer alive. - expect(flush).toHaveBeenCalledTimes(1) - }) - - it('leaves an unlatched terminal untouched', () => { - const flush = vi.fn() - expect( - releaseAbandonedSynchronizedOutput(createTerminal({ synchronizedOutput: false, flush })) - ).toBe(false) - expect( - releaseAbandonedSynchronizedOutput(createTerminal({ synchronizedOutput: undefined, flush })) - ).toBe(false) - expect(flush).not.toHaveBeenCalled() - }) - - it('degrades to a no-op when xterm internals are unavailable', () => { - expect(releaseAbandonedSynchronizedOutput(createTerminal({ withoutCore: true }))).toBe(false) - expect(releaseAbandonedSynchronizedOutput(createTerminal({ withoutModes: true }))).toBe(false) - expect(releaseAbandonedSynchronizedOutput(null)).toBe(false) - expect(releaseAbandonedSynchronizedOutput(undefined)).toBe(false) - }) - - it('still clears the latch when the buffered-row flush throws', () => { - const terminal = createTerminal({ - synchronizedOutput: true, - flush: () => { - throw new Error('disposed mid-frame') - } - }) - - expect(releaseAbandonedSynchronizedOutput(terminal)).toBe(true) - expect( - (terminal as { _core: { coreService: { decPrivateModes: { synchronizedOutput: boolean } } } }) - ._core.coreService.decPrivateModes.synchronizedOutput - ).toBe(false) - }) - - it('unblocks the repaint that xterm would otherwise swallow', () => { - // Mirrors RenderService.refreshRows' gate order: the synchronizedOutput - // check precedes rendering, so a latched frame turns every reveal repaint - // into a no-op — the STA-2694 failure. - const modes = { synchronizedOutput: true } - let rendered = 0 - const refreshRows = (): void => { - if (modes.synchronizedOutput) { - return - } - rendered += 1 - } - const terminal = { - _core: { coreService: { decPrivateModes: modes }, _renderService: {} } - } - - refreshRows() - expect(rendered, 'a latched frame swallows the repaint').toBe(0) - - releaseAbandonedSynchronizedOutput(terminal) - refreshRows() - expect(rendered, 'releasing the latch lets the repaint through').toBe(1) - }) -}) diff --git a/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts b/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts deleted file mode 100644 index c8999aa27..000000000 --- a/src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Releases a DEC 2026 (synchronized output) frame that a TUI left open across a - * hide, so reveal repaints are not silently swallowed. - * - * Why: alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every - * repaint in `?2026h … ?2026l`. If the pane is hidden mid-bracket — the exact - * moment a worktree switch or cold-park lands, since the fixture writes these - * brackets many times a second — xterm keeps `decPrivateModes.synchronizedOutput` - * latched. RenderService.refreshRows then buffers instead of rendering, and it - * checks that BEFORE the sync flag, so on reveal 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. The canvas keeps - * compositing pre-hide pixels while xterm's buffer is perfectly correct. - * - * xterm's 1s safety timeout does NOT bound this: 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-frame holds the latch with no watchdog behind it, - * indefinitely. (terminal-reveal-draw-command-probe.spec.ts asserts exactly - * this: latch set, `_timeout === undefined`, and a repaint drawing 0 instances.) - * Resizing the window "fixes" it because SIGWINCH makes the TUI repaint, and - * that repaint's closing `?2026l` clears the latch — exactly the workaround - * users report (STA-2694). - * - * Reveal is a safe place to drop the latch: a frame opened before the pane was - * hidden can no longer be completed atomically, and its content is already in - * the buffer. Clearing it costs at most one extra repaint of a frame the TUI - * was mid-way through, versus a terminal that stays visibly corrupted. - * - * All access is behind typeof guards: an xterm upgrade that renames these - * internals degrades to a no-op rather than throwing into a render frame. - */ - -type MaybeSynchronizedOutputModes = { - synchronizedOutput?: boolean -} - -type TerminalWithSynchronizedOutput = { - _core?: { - coreService?: { decPrivateModes?: MaybeSynchronizedOutputModes } - _renderService?: { _syncOutputHandler?: { flush?: () => unknown } } - } -} - -function getDecPrivateModes(terminal: unknown): MaybeSynchronizedOutputModes | null { - const modes = (terminal as TerminalWithSynchronizedOutput | null)?._core?.coreService - ?.decPrivateModes - return modes && typeof modes === 'object' ? modes : null -} - -/** - * Clears a synchronized-output latch left open across a hide. - * - * Returns true when a latch was actually released, so callers can treat it as - * "this pane needs a repaint now" — the buffered rows are dropped with the - * latch, and the caller's own full refresh is what repaints them. - */ -export function releaseAbandonedSynchronizedOutput(terminal: unknown): boolean { - const modes = getDecPrivateModes(terminal) - if (modes?.synchronizedOutput !== true) { - return false - } - modes.synchronizedOutput = false - try { - // Why: drop the handler's buffered row range with the latch. Leaving it - // armed would let a later flush widen an unrelated refresh to rows this - // pane is about to repaint in full anyway, and keeps its 1s timer alive. - const handler = (terminal as TerminalWithSynchronizedOutput)._core?._renderService - ?._syncOutputHandler - handler?.flush?.() - } catch { - // The latch is already cleared; a failed flush must not block the repaint. - } - return true -} diff --git a/src/shared/worktree-card-properties.test.ts b/src/shared/worktree-card-properties.test.ts index 68e433114..6a24606c1 100644 --- a/src/shared/worktree-card-properties.test.ts +++ b/src/shared/worktree-card-properties.test.ts @@ -17,7 +17,6 @@ describe('worktree card properties', () => { expect(props).not.toContain('branch') expect(props).toContain('pr') expect(props).toContain('automation') - expect(props).toContain('cli') expect(props).toEqual(DEFAULT_WORKTREE_CARD_PROPERTIES) }) diff --git a/tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs b/tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs deleted file mode 100644 index 1e9ed7932..000000000 --- a/tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs +++ /dev/null @@ -1,174 +0,0 @@ -// OpenCode/OpenTUI-shaped ALT-SCREEN TUI: a full-screen frame repainted every -// tick inside synchronized-output brackets, with a wide glyph inventory (box -// drawing, emoji, CJK) so each repaint exercises the shared WebGL glyph atlas. -// -// Why a second TUI fixture: codex-inline-live-block-fixture.cjs models the -// INLINE shape (normal buffer, live block glued to the bottom). OpenCode runs -// full-screen on the alternate buffer and repaints absolutely-positioned rows, -// which is the shape that leaves stale/garbled pixels after a hidden stretch — -// nothing scrolls, so no row ever self-heals through the scroll path. -// -// argv[2] = heartbeat file path (latest frame number, rewritten every tick) -// argv[3] = ticks per second (default 16) -// The stream never stops on its own; tests hide/park/reveal around it. -const fs = require('node:fs') - -const heartbeatPath = process.argv[2] -const TICKS_PER_SECOND = Math.max(1, Number(process.argv[3]) || 16) -const TICK_MS = Math.max(1, Math.round(1000 / TICKS_PER_SECOND)) - -// Why a rotating inventory: a single repeated glyph set stays resident in the -// atlas after one rasterization. Rotating forces fresh glyph uploads on most -// frames, which is what grows atlas pages and drives the page-merge path. -const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] -const BADGES = ['🟢', '🟡', '🔵', '🟣', '🟠'] -const CJK = ['実行中', '生成中', '待機中', '完了', '解析中'] - -let frame = 0 - -function rows() { - return process.stdout.rows || 24 -} - -function cols() { - return process.stdout.columns || 80 -} - -function bodyRow(index) { - const spin = SPINNER[(frame + index) % SPINNER.length] - const badge = BADGES[(frame + index) % BADGES.length] - const cjk = CJK[(frame + index) % CJK.length] - const bar = '█'.repeat((frame + index) % 12).padEnd(12, '░') - return ( - `│ ${spin} ${badge} row ${String(index).padStart(3, '0')} ${cjk} ${bar} ` + - `tok ${String((frame * 7 + index) % 100000).padStart(6, '0')} λ∑√≈∂ ` - ) -} - -// A full-screen absolute repaint: home, then one absolutely-positioned write -// per row. No scrolling, so a row that paints wrong stays wrong. -function fullFrame() { - const width = Math.max(20, Math.min(cols() - 2, 100)) - const height = rows() - const lines = [ - `╭─ OPENCODE_FRAME_${String(frame).padStart(6, '0')} ${'─'.repeat(Math.max(0, width - 30))}╮` - ] - for (let index = 0; index < Math.max(0, height - 3); index += 1) { - lines.push(`${bodyRow(index).slice(0, width).padEnd(width, ' ')}│`) - } - lines.push( - `╰─ status: streaming · OPENCODE_TAIL_${String(frame).padStart(6, '0')} ${'─'.repeat(Math.max(0, width - 46))}╯` - ) - let out = '' - for (const [index, line] of lines.entries()) { - out += `\x1b[${index + 1};1H\x1b[K${line}` - } - return out -} - -function tick() { - frame += 1 - // Synchronized output around every repaint, exactly like OpenTUI. - process.stdout.write(`\x1b[?2026h\x1b[?25l${fullFrame()}\x1b[?25h\x1b[?2026l`) - if (heartbeatPath) { - try { - // Why write-then-rename: writeFileSync truncates before writing, so a - // concurrent reader can see '' and read it as frame 0. - fs.writeFileSync(`${heartbeatPath}.tmp`, String(frame)) - fs.renameSync(`${heartbeatPath}.tmp`, heartbeatPath) - } catch { - // heartbeat is best-effort; the stream itself is the product - } - } -} - -// OpenCode-shaped startup: capability queries, alt screen, mouse reporting. -process.stdout.write('\x1b[c\x1b[6n\x1b]10;?\x07\x1b]11;?\x07') -process.stdout.write('\x1b[?1049h\x1b[2J\x1b[H') -process.stdout.write('\x1b[?1002h\x1b[?1006h') - -let tickTimer = setInterval(tick, TICK_MS) -let frozen = false - -// Freeze: stop producing new frames but STAY on the alt screen holding the last -// painted frame. Tests need this to compare pixels — a live stream would differ -// between two shots for legitimate reasons, and quitting would leave a shell -// prompt. A frozen fixture also stops answering SIGWINCH, so only Orca's own -// render path can repair the display, which is what's under test. -// -// `midFrame` models the STA-2694 hazard directly: the TUI opens a synchronized -// frame (`?2026h`), paints it, and is interrupted before writing the closing -// `?2026l`. That is what a hide lands on many times a second in the field, and -// it leaves xterm's synchronizedOutput mode latched — which makes every reveal -// repaint a no-op until something clears it. -function freeze(options) { - if (frozen) { - return - } - frozen = true - clearInterval(tickTimer) - tickTimer = null - if (options && options.midFrame) { - process.stdout.write(`\x1b[?2026h\x1b[?25l${fullFrame()}`) - } -} - -// A real TUI repaints on SIGWINCH. Keep that for realism while live — tests must -// converge WITHOUT relying on it, since needing a resize IS the bug under test. -process.stdout.on('resize', () => { - if (frozen) { - return - } - process.stdout.write(`\x1b[?2026h\x1b[?25l${fullFrame()}\x1b[?25h\x1b[?2026l`) -}) -process.stdin.resume() -if (process.stdin.isTTY) { - process.stdin.setRawMode(true) -} - -let stopping = false -function stop() { - if (stopping) { - return - } - stopping = true - if (tickTimer) { - clearInterval(tickTimer) - } - if (process.stdin.isTTY) { - process.stdin.setRawMode(false) - } - // Why: the e2e sends Ctrl+C while raw mode is active, so Node receives a byte - // instead of SIGINT; explicitly restore modes and terminate the fixture. - process.stdout.write('\x1b[?1002l\x1b[?1006l\x1b[?25h\x1b[?2026l\x1b[?1049l', () => - process.exit(0) - ) -} -// Why a multi-byte sentinel and not a single key: at startup this fixture emits -// DA1/CPR/OSC-10/OSC-11 queries, and the terminal's replies arrive on stdin — -// an OSC color reply ("rgb:ffff/...") contains 'f', so a single-letter trigger -// froze the fixture against its own startup handshake before frame 1. -const FREEZE_SENTINEL = 'ORCA_FREEZE_NOW' -const FREEZE_MID_FRAME_SENTINEL = 'ORCA_FREEZE_MID_FRAME' -const MAX_SENTINEL_LEN = Math.max(FREEZE_SENTINEL.length, FREEZE_MID_FRAME_SENTINEL.length) -let stdinTail = '' -process.stdin.on('data', (chunk) => { - if (chunk.includes(0x03)) { - stop() - return - } - stdinTail = `${stdinTail}${chunk.toString('latin1')}`.slice(-2 * MAX_SENTINEL_LEN) - // Why check mid-frame first: both share the 'ORCA_FREEZE_' prefix, so testing - // the longer sentinel first keeps a partial read from picking the wrong mode. - if (stdinTail.includes(FREEZE_MID_FRAME_SENTINEL)) { - stdinTail = '' - freeze({ midFrame: true }) - return - } - if (stdinTail.includes(FREEZE_SENTINEL)) { - stdinTail = '' - freeze() - } -}) -process.on('SIGINT', stop) -process.on('SIGTERM', stop) diff --git a/tests/e2e/terminal-hidden-view-parking.spec.ts b/tests/e2e/terminal-hidden-view-parking.spec.ts index b103964b6..9f31d6932 100644 --- a/tests/e2e/terminal-hidden-view-parking.spec.ts +++ b/tests/e2e/terminal-hidden-view-parking.spec.ts @@ -181,87 +181,6 @@ async function activateTerminalTab(page: Page, tabId: string): Promise { .toBe(tabId) } -type TerminalPresentationFrame = { - previousPresented: boolean - targetPresented: boolean - targetBufferContainsMarker: boolean -} - -async function startTerminalPresentationObservation( - page: Page, - previousTabId: string, - targetTabId: string, - targetMarker: string -): Promise { - await page.evaluate( - ({ previousTabId, targetTabId, targetMarker }) => { - const observedWindow = window as Window & { - __terminalPresentationFrames?: TerminalPresentationFrame[] - __terminalPresentationObservationDone?: boolean - } - const frames: TerminalPresentationFrame[] = [] - observedWindow.__terminalPresentationFrames = frames - observedWindow.__terminalPresentationObservationDone = false - const findOverlay = (tabId: string): HTMLElement | null => - document.querySelector(`[data-terminal-overlay-tab-id="${CSS.escape(tabId)}"]`) - const isPresented = (tabId: string): boolean => { - const overlay = findOverlay(tabId) - return ( - overlay?.dataset.terminalOverlayPresented === 'true' && - getComputedStyle(overlay).display !== 'none' && - getComputedStyle(overlay).opacity !== '0' - ) - } - const sample = (): void => { - const targetPane = - window.__paneManagers?.get(targetTabId)?.getActivePane?.() ?? - window.__paneManagers?.get(targetTabId)?.getPanes?.()[0] - const frame = { - previousPresented: isPresented(previousTabId), - targetPresented: isPresented(targetTabId), - targetBufferContainsMarker: - targetPane?.serializeAddon?.serialize?.().includes(targetMarker) === true - } - frames.push(frame) - if (frame.targetPresented) { - observedWindow.__terminalPresentationObservationDone = true - return - } - requestAnimationFrame(sample) - } - sample() - }, - { previousTabId, targetTabId, targetMarker } - ) -} - -async function readTerminalPresentationObservation( - page: Page -): Promise { - await expect - .poll( - () => - page.evaluate( - () => - ( - window as Window & { - __terminalPresentationObservationDone?: boolean - } - ).__terminalPresentationObservationDone === true - ), - { timeout: 5_000, message: 'terminal presentation handoff did not settle' } - ) - .toBe(true) - return page.evaluate( - () => - ( - window as Window & { - __terminalPresentationFrames?: TerminalPresentationFrame[] - } - ).__terminalPresentationFrames ?? [] - ) -} - async function createActiveTerminalTab(page: Page, worktreeId: string): Promise { const tabId = await page.evaluate((worktreeId) => { const store = window.__store @@ -392,16 +311,6 @@ test.describe('Terminal hidden view parking', () => { expect(tabBState.hasManager).toBe(true) expect(tabBState.paneCount).toBeGreaterThan(0) - const previouslyPresentedTabId = await getActiveTabId(orcaPage) - if (!previouslyPresentedTabId) { - throw new Error('parking reveal had no previously presented terminal tab') - } - await startTerminalPresentationObservation( - orcaPage, - previouslyPresentedTabId, - tabAId, - finalMarker - ) await activateTerminalTab(orcaPage, tabAId) await waitForActiveTerminalManager(orcaPage, 30_000) const revealedSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) @@ -417,20 +326,6 @@ test.describe('Terminal hidden view parking', () => { }) .toContain(finalMarker) - const presentationFrames = await readTerminalPresentationObservation(orcaPage) - const firstTargetFrame = presentationFrames.findIndex((frame) => frame.targetPresented) - expect(firstTargetFrame).toBeGreaterThan(0) - expect( - presentationFrames[firstTargetFrame]?.targetBufferContainsMarker, - JSON.stringify(presentationFrames) - ).toBe(true) - expect( - presentationFrames - .slice(0, firstTargetFrame) - .every((frame) => frame.previousPresented && !frame.targetPresented), - JSON.stringify(presentationFrames) - ).toBe(true) - const content = await getTerminalContent(orcaPage, 12_000) expect(content).toContain(`Frame ${String(PARKED_FRAME_COUNT - 1).padStart(3, '0')}`) expect(content).toContain('╭') diff --git a/tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts b/tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts deleted file mode 100644 index d6a2a89a8..000000000 --- a/tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts +++ /dev/null @@ -1,821 +0,0 @@ -/** - * STA-2694 repro attempt: switching away from a workspace running an alt-screen - * AI TUI (OpenCode/OpenTUI, also Claude Code and grok) and returning later shows - * a garbled/distorted terminal that only a manual window resize repairs. - * - * Why this spec exists next to terminal-inline-tui-reveal-convergence.spec.ts: - * that one drives the INLINE shape (normal buffer, live block glued to the - * bottom, history scrolling into scrollback). OpenCode runs FULL-SCREEN on the - * alternate buffer and repaints absolutely-positioned rows — nothing scrolls, so - * no row ever self-heals through the scroll path. These tests cover that shape - * across the hide/reveal boundaries (worktree switch, cold park, idle agent, - * desktop hide) and guard the convergence properties we CAN observe: the buffer - * converges to the live frame, the pane stays on the alt screen, and xterm's - * grid, the fit proposal, and the PTY-applied size all agree without a resize. - * - * ⚠ These tests do NOT observe the CANVAS. Two pixel oracles were tried here and - * both were proven blind by injecting the exact defect (freeze - * RenderService.refreshRows, then write new content, so the buffer advances - * while the canvas cannot): - * - * 1. Canvas-vs-buffer ink sampling (the render-desync sentinel's method). - * `drawImage` on a non-preserveDrawingBuffer WebGL canvas hands back a - * re-rendered copy, so it reported 0 missing cells against 5263 cells of - * text the canvas had never drawn. - * 2. Screenshot comparison against a forced repaint. Playwright's screenshot - * drives a fresh compositor frame, which HEALS the stale paint before it - * is captured; and the "repair" calls the same repaint code the reveal - * already ran, so a defect shared by both shots cancels out. - * - * Pixels are the wrong layer for this: anything that reads them can trigger the - * repaint that hides the bug. terminal-reveal-draw-command-probe.spec.ts solves - * that by counting the WebGL draw commands a repaint issues, which cannot be - * healed after the fact — use it for paint questions and this spec for buffer, - * geometry, and PTY-size convergence. - */ -import { readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { PNG } from 'pngjs' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { compareTerminalScreenshots } from './terminal-screenshot-diff' -import { - ensureTerminalVisible, - getActiveTabId, - switchToOtherWorktree, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - sendToTerminal, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForTabParked } from './helpers/terminal-hidden-parking' - -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -const FIXTURE_PATH = path.join(__dirname, 'fixtures', 'opencode-altscreen-live-fixture.cjs') -const FRAME_RE = /OPENCODE_FRAME_(\d+)/g -const TAIL_RE = /OPENCODE_TAIL_(\d+)/g -// The fixture ticks ~16x/s; allow generous parse/delivery lag while still -// rejecting a frame frozen from before the hide. -const MAX_VISIBLE_FRAME_LAG = 60 - -type RevealProbe = { - ptyId: string | null - cols: number - rows: number - bufferType: string - proposed: { cols: number; rows: number } | null - appliedPtySize: { cols: number; rows: number } | null - screenRows: string[] -} - -function latestMatch(text: string, pattern: RegExp): number { - let latest = -1 - for (const match of text.matchAll(pattern)) { - latest = Math.max(latest, Number(match[1])) - } - return latest -} - -function heartbeatFrame(heartbeatPath: string): number { - try { - return Number(readFileSync(heartbeatPath, 'utf8').trim()) - } catch { - return -1 - } -} - -async function probeRevealedPane(page: Page, tabId: string): Promise { - return page.evaluate( - async ({ tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - const ptyId = pane.container.dataset.ptyId ?? null - const terminal = pane.terminal - const buffer = terminal.buffer.active - const screenRows: string[] = [] - for (let i = 0; i < terminal.rows; i += 1) { - const line = buffer.getLine(buffer.viewportY + i) - screenRows.push(line ? line.translateToString(true) : '') - } - let proposed: { cols: number; rows: number } | null = null - try { - proposed = pane.fitAddon.proposeDimensions() ?? null - } catch { - proposed = null - } - let appliedPtySize: { cols: number; rows: number } | null = null - try { - appliedPtySize = ptyId ? ((await window.api.pty.getSize(ptyId)) ?? null) : null - } catch { - appliedPtySize = null - } - return { - ptyId, - cols: terminal.cols, - rows: terminal.rows, - bufferType: buffer.type, - proposed, - appliedPtySize, - screenRows - } - }, - { tabId } - ) -} - -function describeProbe(probe: RevealProbe | null): string { - if (!probe) { - return 'pane not mounted' - } - return JSON.stringify( - { - cols: probe.cols, - rows: probe.rows, - bufferType: probe.bufferType, - proposed: probe.proposed, - appliedPtySize: probe.appliedPtySize, - screenHead: probe.screenRows.slice(0, 4), - screenTail: probe.screenRows.slice(-4) - }, - null, - 1 - ) -} - -async function forceWebglOnActiveTab(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { ...state.settings, terminalGpuAcceleration: 'on' } - }) - const worktreeId = state.activeWorktreeId - const tabId = - state.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - window.__paneManagers?.get(tabId ?? '')?.setTerminalGpuAcceleration?.('on') - }) -} - -async function hasWebglPane(page: Page, tabId: string): Promise { - return page.evaluate( - (tabId) => - (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( - (diagnostic) => diagnostic.hasWebgl - ), - tabId - ) -} - -async function paneClipRect( - page: Page, - tabId: string -): Promise<{ x: number; y: number; width: number; height: number } | null> { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - const rect = pane.container.getBoundingClientRect() - if (rect.width < 10 || rect.height < 10) { - return null - } - return { x: rect.x, y: rect.y, width: rect.width, height: rect.height } - }, tabId) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((targetTabId) => { - const store = window.__store - if (!store) { - throw new Error('activateTerminalTab: window.__store is unavailable') - } - const state = store.getState() - state.setActiveTabType('terminal') - state.setActiveTab(targetTabId) - }, tabId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: `terminal tab ${tabId} did not become active` - }) - .toBe(tabId) -} - -async function createActiveTerminalTab(page: Page, worktreeId: string): Promise { - const tabId = await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('createActiveTerminalTab: window.__store is unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal') - return tab.id - }, worktreeId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'newly created terminal tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - return tabId -} - -async function withCpuThrottle(page: Page, rate: number, run: () => Promise): Promise { - const session = await page.context().newCDPSession(page) - try { - await session.send('Emulation.setCPUThrottlingRate', { rate }) - return await run() - } finally { - await session.send('Emulation.setCPUThrottlingRate', { rate: 1 }).catch(() => {}) - await session.detach().catch(() => {}) - } -} - -type StreamingTabSetup = { - worktreeId: string - tabId: string - ptyId: string - heartbeatPath: string - stop: () => Promise -} - -// Why agent-marked: a real OpenCode tab carries launchAgent/telemetry, which -// flips the reveal into the live-agent reattach branches (mode-preserving -// resets, hidden startup query grammar, post-replay focus-in) — the branches -// the field bug lives behind. -async function startStreamingAltScreenTui( - page: Page, - testInfo: TestInfo, - options: { ticksPerSecond?: number } = {} -): Promise { - await waitForSessionReady(page) - const worktreeId = await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - const heartbeatPath = testInfo.outputPath(`opencode-altscreen-heartbeat-${Date.now()}.txt`) - const command = `node ${JSON.stringify(FIXTURE_PATH)} ${JSON.stringify(heartbeatPath)} ${options.ticksPerSecond ?? 16}` - const tabId = await page.evaluate( - ({ worktreeId, command }) => { - const store = window.__store - if (!store) { - throw new Error('startStreamingAltScreenTui: window.__store is unavailable') - } - const state = store.getState() - // Why 'codex' and not 'opencode': the agent marker exists only to take the - // live-agent reattach branches, and codex is the kind the e2e environment - // reliably launches (same choice as the inline-TUI convergence spec). The - // TUI *shape* under test comes from the fixture, not from this marker. - const tab = state.createTab(worktreeId, undefined, undefined, { launchAgent: 'codex' }) - state.queueTabStartupCommand(tab.id, { - command, - launchAgent: 'codex', - telemetry: { - agent_kind: 'codex', - launch_source: 'tab_bar_quick_launch', - request_kind: 'new' - } - }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal') - return tab.id - }, - { worktreeId, command } - ) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'agent-marked streaming tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - // WebGL on: the paint-layer seams under test (atlas wipes, render-pause - // release) only exist on the GPU renderer path. - await forceWebglOnActiveTab(page) - await expect - .poll( - async () => - latestMatch((await probeRevealedPane(page, tabId))?.screenRows.join('\n') ?? '', FRAME_RE), - { - timeout: 20_000, - message: 'alt-screen TUI fixture did not start streaming in the visible pane' - } - ) - .toBeGreaterThan(5) - const ptyId = (await probeRevealedPane(page, tabId))?.ptyId - if (!ptyId) { - throw new Error('streaming tab did not bind a PTY') - } - return { - worktreeId, - tabId, - ptyId, - heartbeatPath, - stop: async () => { - await sendToTerminal(page, ptyId, '\x03').catch(() => {}) - await page.waitForTimeout(100) - } - } -} - -// Buffer-level convergence: xterm parsed the live frames. This is necessary but -// NOT sufficient — the field bug shows a correct buffer behind garbled pixels. -async function assertBufferConverged( - page: Page, - testInfo: TestInfo, - setup: StreamingTabSetup, - label: string -): Promise { - const { tabId, heartbeatPath } = setup - expect(heartbeatFrame(heartbeatPath), 'fixture stopped streaming while hidden').toBeGreaterThan(5) - - let lastProbe: RevealProbe | null = null - await expect - .poll( - async () => { - lastProbe = await probeRevealedPane(page, tabId) - if (!lastProbe) { - return 'pane-not-mounted' - } - if (lastProbe.bufferType !== 'alternate') { - return `not-alt-screen bufferType=${lastProbe.bufferType}` - } - const screen = lastProbe.screenRows.join('\n') - const visibleFrame = latestMatch(screen, FRAME_RE) - const visibleTail = latestMatch(screen, TAIL_RE) - if (visibleTail < 0) { - return 'status-row-missing' - } - const liveFrame = heartbeatFrame(heartbeatPath) - if (visibleFrame < 0 || liveFrame - visibleFrame > MAX_VISIBLE_FRAME_LAG) { - return `stale-frame visible=${visibleFrame} live=${liveFrame}` - } - return 'converged' - }, - { - timeout: 20_000, - message: `${label}: revealed buffer did not converge to the live alt-screen TUI` - } - ) - .toBe('converged') - .catch(async (error) => { - testInfo.annotations.push({ - type: `${label}-buffer-divergence`, - description: describeProbe(lastProbe) - }) - throw error - }) - - const probe = await probeRevealedPane(page, tabId) - expect(probe, `${label}: pane disappeared after convergence`).not.toBeNull() - // Geometry: no stale-grid leg — xterm, fit proposal, and PTY must agree - // without any manual resize. - expect(probe!.proposed, `${label}: fit proposal diverges: ${describeProbe(probe)}`).toEqual({ - cols: probe!.cols, - rows: probe!.rows - }) - expect( - probe!.appliedPtySize, - `${label}: PTY applied size diverges: ${describeProbe(probe)}` - ).toEqual({ cols: probe!.cols, rows: probe!.rows }) - return probe! -} - -/** - * SECONDARY, WEAK check: geometry-stable repaint equivalence. - * - * Freeze the TUI, screenshot, force a clean rebuild in-app (atlas clear + full - * refresh), screenshot again, and require the two to match. - * - * Why weak, despite looking decisive: the "repair" runs the same repaint code - * the reveal already ran, so a defect present in BOTH shots cancels out and the - * comparison reports success. Injecting a frozen renderer proved that blind - * spot. Treat a green result as "the reveal did not leave a repaint-visible - * difference", never as proof the canvas painted correctly. - * - * The sound paint oracles live elsewhere: terminal-reveal-draw-command-probe - * counts WebGL draw commands (unhealable after the fact), and - * terminal-reveal-latch-visual-evidence captures the stale pixels directly. - */ -async function assertRevealPixelsNeedNoRepair( - page: Page, - testInfo: TestInfo, - setup: StreamingTabSetup, - label: string -): Promise { - const { tabId, ptyId } = setup - // Freeze the fixture in place: it stops emitting frames but stays on the alt - // screen holding its last frame. Quitting would leave a shell prompt, and a - // live stream would differ between the two shots for legitimate reasons. - await sendToTerminal(page, ptyId, 'ORCA_FREEZE_NOW').catch(() => {}) - await page.waitForTimeout(2_000) - - // Guard against a vacuous comparison: both shots must show a real TUI frame. - const frozenProbe = await probeRevealedPane(page, tabId) - expect( - frozenProbe?.bufferType, - `${label}: fixture left the alt screen before the paint check: ${describeProbe(frozenProbe)}` - ).toBe('alternate') - expect( - latestMatch(frozenProbe?.screenRows.join('\n') ?? '', FRAME_RE), - `${label}: no TUI frame on screen for the paint check: ${describeProbe(frozenProbe)}` - ).toBeGreaterThan(0) - - const clip = await paneClipRect(page, tabId) - expect(clip, `${label}: pane rect unavailable for paint check`).not.toBeNull() - const revealed = await page.screenshot({ clip: clip! }) - - // The in-app equivalent of the user's manual resize repair, with the geometry - // untouched: clear the glyph atlas and force a full repaint from the buffer. - const rebuilt = await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - if (!manager) { - return false - } - manager.resetWebglTextureAtlases?.() - manager.refreshAllPanes?.() - return true - }, tabId) - expect(rebuilt, `${label}: could not force a clean repaint`).toBe(true) - await page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) - await page.waitForTimeout(600) - - const repairedClip = await paneClipRect(page, tabId) - expect(repairedClip, `${label}: pane rect unavailable after repaint`).not.toBeNull() - // Geometry must be identical, or the comparison is not apples-to-apples. - expect(repairedClip, `${label}: pane geometry moved during the repaint`).toEqual(clip) - const repaired = await page.screenshot({ clip: repairedClip! }) - - writeFileSync(testInfo.outputPath(`${label}-revealed.png`), revealed) - writeFileSync(testInfo.outputPath(`${label}-after-clean-repaint.png`), repaired) - - // Anti-vacuity: a blank-vs-blank comparison would "match" trivially. The - // repainted shot is the known-good reference, so require real glyph ink. - const repairedInk = measureInkRatio(repaired) - expect( - repairedInk, - `${label}: repainted pane has no glyphs (ink ${repairedInk.toFixed(4)}) — ` + - 'the screenshot is not capturing terminal content, so the comparison is vacuous' - ).toBeGreaterThan(0.01) - - const diff = compareTerminalScreenshots(repaired, revealed) - expect( - diff.matches, - `${label}: revealed canvas did not match a clean repaint of its own buffer ` + - `(diff ${diff.diffPixels}px, ratio ${diff.diffRatio.toFixed(4)}) — this is STA-2694` - ).toBe(true) -} - -// Fraction of pixels differing from the dominant (background) color. -function measureInkRatio(screenshot: Buffer): number { - const png = PNG.sync.read(screenshot) - const counts = new Map() - for (let offset = 0; offset < png.data.length; offset += 4) { - const key = - ((png.data[offset] ?? 0) << 16) | - ((png.data[offset + 1] ?? 0) << 8) | - (png.data[offset + 2] ?? 0) - counts.set(key, (counts.get(key) ?? 0) + 1) - } - let backgroundKey = 0 - let backgroundCount = -1 - for (const [key, count] of counts) { - if (count > backgroundCount) { - backgroundKey = key - backgroundCount = count - } - } - const backgroundRed = (backgroundKey >> 16) & 0xff - const backgroundGreen = (backgroundKey >> 8) & 0xff - const backgroundBlue = backgroundKey & 0xff - let ink = 0 - let total = 0 - for (let offset = 0; offset < png.data.length; offset += 4) { - const distance = - Math.abs((png.data[offset] ?? 0) - backgroundRed) + - Math.abs((png.data[offset + 1] ?? 0) - backgroundGreen) + - Math.abs((png.data[offset + 2] ?? 0) - backgroundBlue) - total += 1 - if (distance > 48) { - ink += 1 - } - } - return total > 0 ? ink / total : 0 -} - -// Reads xterm's live DEC 2026 latch for the pane. While true, RenderService -// buffers every refresh instead of rendering it. -async function readSynchronizedOutputLatch(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const modes = ( - pane?.terminal as unknown as - | { _core?: { coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } } - | undefined - )?._core?.coreService?.decPrivateModes - return modes ? modes.synchronizedOutput === true : null - }, tabId) -} - -async function freezeMidFrameAndSwitchWorktree( - page: Page, - setup: StreamingTabSetup -): Promise { - return page.evaluate( - ({ currentWorktreeId, ptyId, tabId }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is unavailable') - } - const otherWorktree = Object.values(store.getState().worktreesByRepo) - .flat() - .find((worktree) => worktree.id !== currentWorktreeId) - if (!otherWorktree) { - return null - } - - window.api.pty.write(ptyId, 'ORCA_FREEZE_MID_FRAME') - return new Promise((resolve, reject) => { - const deadline = performance.now() + 5_000 - const switchWhenLatched = (): void => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const synchronizedOutput = ( - pane?.terminal as unknown as - | { - _core?: { - coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - } - } - | undefined - )?._core?.coreService?.decPrivateModes?.synchronizedOutput - if (synchronizedOutput === true) { - store.getState().setActiveWorktree(otherWorktree.id) - resolve(otherWorktree.id) - return - } - if (performance.now() >= deadline) { - reject(new Error('fixture did not leave a synchronized-output frame open')) - return - } - setTimeout(switchWhenLatched, 0) - } - switchWhenLatched() - }) - }, - { - currentWorktreeId: setup.worktreeId, - ptyId: setup.ptyId, - tabId: setup.tabId - } - ) -} - -async function streamWhileHidden(setup: StreamingTabSetup, minFrames: number): Promise { - const heartbeatBefore = heartbeatFrame(setup.heartbeatPath) - await expect - .poll(() => heartbeatFrame(setup.heartbeatPath), { - timeout: 60_000, - message: 'fixture did not keep streaming while hidden/parked' - }) - .toBeGreaterThan(heartbeatBefore + minFrames) -} - -test.describe('OpenCode alt-screen reveal artifacts (STA-2694)', () => { - test('worktree switch away and back paints correctly without a manual resize', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(180_000) - const setup = await startStreamingAltScreenTui(orcaPage, testInfo) - try { - test.skip( - !(await hasWebglPane(orcaPage, setup.tabId)), - 'WebGL renderer unavailable in this environment' - ) - // The field action: switch away to another workspace (suspends rendering - // and releases WebGL), let the agent keep streaming, then come back. - const otherWorktreeId = await switchToOtherWorktree(orcaPage, setup.worktreeId) - test.skip(!otherWorktreeId, 'test session has a single worktree; cannot surface-hide') - await streamWhileHidden(setup, 120) - - await withCpuThrottle(orcaPage, 6, async () => { - await switchToWorktree(orcaPage, setup.worktreeId) - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(2_000) - }) - - await assertBufferConverged(orcaPage, testInfo, setup, 'worktree-return') - await assertRevealPixelsNeedNoRepair(orcaPage, testInfo, setup, 'worktree-return') - } finally { - await setup.stop() - } - }) - - test('parked tab reveal paints correctly without a manual resize', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(240_000) - const setup = await startStreamingAltScreenTui(orcaPage, testInfo, { ticksPerSecond: 20 }) - try { - test.skip( - !(await hasWebglPane(orcaPage, setup.tabId)), - 'WebGL renderer unavailable in this environment' - ) - // Tab B hides tab A; the decoy then hides B so B takes the last-active - // exemption and tab A genuinely cold-parks (renderer torn down). - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await waitForTabParked(orcaPage, setup.tabId, { parkDelayMs: PARKING_DELAY_MS }) - await streamWhileHidden(setup, 150) - - await withCpuThrottle(orcaPage, 6, async () => { - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(3_000) - }) - - await assertBufferConverged(orcaPage, testInfo, setup, 'parked-reveal') - await assertRevealPixelsNeedNoRepair(orcaPage, testInfo, setup, 'parked-reveal') - } finally { - await setup.stop() - } - }) - - // The field condition the other tests miss: the agent is IDLE when you come - // back. Every test above keeps the TUI streaming across the reveal, so live - // frames repaint whatever the reveal got wrong — the defect heals itself - // before any assertion runs. A real OpenCode session sits waiting for input, - // so nothing arrives to heal it, and whatever the reveal painted is what the - // user stares at until they resize the window. - test('parked reveal of an IDLE alt-screen agent paints without a manual repair', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(240_000) - const setup = await startStreamingAltScreenTui(orcaPage, testInfo) - try { - test.skip( - !(await hasWebglPane(orcaPage, setup.tabId)), - 'WebGL renderer unavailable in this environment' - ) - // Go idle BEFORE hiding, cleanly between brackets — a settled agent - // holding its last full-screen frame. - await sendToTerminal(orcaPage, setup.ptyId, 'ORCA_FREEZE_NOW').catch(() => {}) - await orcaPage.waitForTimeout(2_000) - const idleFrame = latestMatch( - (await probeRevealedPane(orcaPage, setup.tabId))?.screenRows.join('\n') ?? '', - FRAME_RE - ) - expect(idleFrame, 'fixture never painted a frame before going idle').toBeGreaterThan(0) - - // Cold-park the idle tab: renderer torn down, so the reveal must restore - // and repaint entirely from the snapshot with no live output to help. - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await waitForTabParked(orcaPage, setup.tabId, { parkDelayMs: PARKING_DELAY_MS }) - await orcaPage.waitForTimeout(3_000) - - await withCpuThrottle(orcaPage, 6, async () => { - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(3_000) - }) - - // The same frame must still be on screen — the agent produced nothing new. - const revealedProbe = await probeRevealedPane(orcaPage, setup.tabId) - expect( - revealedProbe?.bufferType, - `idle-parked-reveal: pane is not on the alt screen: ${describeProbe(revealedProbe)}` - ).toBe('alternate') - expect( - latestMatch(revealedProbe?.screenRows.join('\n') ?? '', FRAME_RE), - `idle-parked-reveal: idle frame lost across the park: ${describeProbe(revealedProbe)}` - ).toBeGreaterThan(0) - - await assertRevealPixelsNeedNoRepair(orcaPage, testInfo, setup, 'idle-parked-reveal') - } finally { - await setup.stop() - } - }) - - // The LITERAL user action: "switch away to the desktop". That is an OS-level - // window hide/occlusion, not in-app navigation — it flips - // document.visibilityState, releases the WebGL context, and comes back - // through the window-wake recovery path rather than the worktree-reveal path. - // The pane never unmounts and its worktree never changes, so none of the - // reveal-repaint machinery the other tests exercise even runs. - test('@headful desktop switch away and back paints an idle agent without a manual repair', async ({ - orcaPage, - electronApp - }, testInfo) => { - test.setTimeout(240_000) - const setup = await startStreamingAltScreenTui(orcaPage, testInfo) - try { - test.skip( - !(await hasWebglPane(orcaPage, setup.tabId)), - 'WebGL renderer unavailable in this environment' - ) - // Idle agent holding a full-screen frame — the field state on return. - await sendToTerminal(orcaPage, setup.ptyId, 'ORCA_FREEZE_NOW').catch(() => {}) - await orcaPage.waitForTimeout(2_000) - - // Switch away to the desktop: hide the window entirely. - await electronApp.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No Electron window') - } - window.hide() - }) - await orcaPage.waitForTimeout(4_000) - - // ...and come back to it. - await electronApp.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No Electron window') - } - window.show() - window.focus() - }) - await orcaPage.waitForTimeout(3_000) - - const revealedProbe = await probeRevealedPane(orcaPage, setup.tabId) - expect( - revealedProbe?.bufferType, - `desktop-return: pane is not on the alt screen: ${describeProbe(revealedProbe)}` - ).toBe('alternate') - - await assertRevealPixelsNeedNoRepair(orcaPage, testInfo, setup, 'desktop-return') - } finally { - await electronApp - .evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.show()) - .catch(() => {}) - await setup.stop() - } - }) - - // The mechanism behind STA-2694: OpenTUI-style TUIs bracket every repaint in - // `?2026h … ?2026l`, so a hide can land inside an open bracket. xterm then - // keeps synchronizedOutput latched, and RenderService checks that latch - // BEFORE rendering — so on reveal the forced repaint, the plain refresh - // fallback, and the glyph-atlas rebuild all render zero rows while the buffer - // is perfectly correct. A window resize "fixes" it only because SIGWINCH - // makes the TUI emit the closing `?2026l`. - test('reveal repaints a pane hidden inside an unclosed synchronized-output frame', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(180_000) - const setup = await startStreamingAltScreenTui(orcaPage, testInfo) - try { - // Switch in the renderer task that observes the latch; CI round trips can - // otherwise outlast xterm's one-second safety watchdog. - const otherWorktreeId = await freezeMidFrameAndSwitchWorktree(orcaPage, setup) - test.skip(!otherWorktreeId, 'test session has a single worktree; cannot surface-hide') - test.skip( - !(await readSynchronizedOutputLatch(orcaPage, setup.tabId)), - 'the watchdog cleared the latch before the hide, so this run proves nothing' - ) - await orcaPage.waitForTimeout(2_500) - await switchToWorktree(orcaPage, setup.worktreeId) - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(2_500) - - // The reveal must not leave the pane wedged behind the stale latch: while - // it holds, nothing this pane can do repaints a single row. - expect( - await readSynchronizedOutputLatch(orcaPage, setup.tabId), - 'reveal left a stale synchronized-output latch, so every repaint is swallowed' - ).toBe(false) - await assertRevealPixelsNeedNoRepair(orcaPage, testInfo, setup, 'mid-frame-hide') - } finally { - await setup.stop() - } - }) -}) diff --git a/tests/e2e/terminal-reveal-draw-command-probe.spec.ts b/tests/e2e/terminal-reveal-draw-command-probe.spec.ts deleted file mode 100644 index c5d286926..000000000 --- a/tests/e2e/terminal-reveal-draw-command-probe.spec.ts +++ /dev/null @@ -1,558 +0,0 @@ -/** - * STA-2694 draw-command oracle. - * - * Every pixel-level oracle tried for this bug 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. This spec sidesteps pixels entirely and counts the - * WebGL draw commands the repaint actually issues, by wrapping - * `GlyphRenderer.updateCell` and `gl.drawElementsInstanced` on the live pane. - * - * A draw command cannot be healed after the fact, so "did the reveal repaint?" - * becomes directly observable — and falsifiable, which is how this spec refuted - * one hypothesis outright (see the first test). - */ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { waitForActiveTerminalManager } from './helpers/terminal' - -type DrawStats = { - updateCellCalls: number - drawCalls: number - instancesDrawn: number - rows: number - cols: number -} - -type RendererGeometry = { - canvasWidth: number - canvasHeight: number - modelCanvasWidth: number - modelCanvasHeight: number - charWidth: number - charHeight: number - isAttached: boolean - synchronizedOutput: boolean - isPaused: boolean - atlasPageVersions: number[] - boundTextureVersions: number[] - screenConnected: boolean -} - -async function setUpWebglPane(page: Page): Promise { - await waitForSessionReady(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { ...state.settings, terminalGpuAcceleration: 'on' } - }) - for (const manager of window.__paneManagers?.values() ?? []) { - ;( - manager as { setTerminalGpuAcceleration?: (mode: string) => void } - ).setTerminalGpuAcceleration?.('on') - } - }) - const gotWebgl = await page - .waitForFunction( - () => { - for (const manager of window.__paneManagers?.values() ?? []) { - const diagnostics = - ( - manager as { getRenderingDiagnostics?: () => { hasWebgl: boolean }[] } - ).getRenderingDiagnostics?.() ?? [] - if (diagnostics.some((diagnostic) => diagnostic.hasWebgl)) { - return true - } - } - return false - }, - { timeout: 20_000 } - ) - .then(() => true) - .catch(() => false) - if (!gotWebgl) { - return false - } - // Stable text so lineLengths (and therefore drawn instances) are non-zero. - await page.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const terminal = (pane as { terminal?: { write?: (data: string) => void } }).terminal - terminal?.write?.(`${'STA2694-PROBE '.repeat(40)}\r\n`) - } - } - }) - await page.waitForTimeout(1_500) - return true -} - -/** Wraps updateCell + drawElementsInstanced on the live pane's WebGL renderer. */ -async function instrumentDrawCommands(page: Page): Promise { - await page.evaluate(() => { - const win = window as unknown as { - __paneManagers?: Map unknown[] }> - __drawProbe?: unknown - } - // getPanes() returns a public view without webglAddon, so reach the live - // renderer through the render service instead. - let renderer: Record | null = null - for (const manager of win.__paneManagers?.values() ?? []) { - for (const candidate of manager.getPanes?.() ?? []) { - const active = ( - candidate as { - terminal?: { _core?: { _renderService?: { _renderer?: { value?: unknown } } } } - } - ).terminal?._core?._renderService?._renderer?.value as Record | undefined - if (active?._gl) { - renderer = active - } - } - } - if (!renderer) { - throw new Error('no WebGL pane to instrument') - } - const glyphRenderer = (renderer._glyphRenderer as { value?: Record })?.value - if (!glyphRenderer) { - throw new Error('renderer has no glyph renderer') - } - const gl = renderer._gl as WebGL2RenderingContext - const probe = { - updateCellCalls: 0, - drawCalls: 0, - instancesDrawn: 0, - reset(): void { - probe.updateCellCalls = 0 - probe.drawCalls = 0 - probe.instancesDrawn = 0 - } - } - win.__drawProbe = probe - - const originalUpdateCell = glyphRenderer.updateCell as (...args: unknown[]) => unknown - glyphRenderer.updateCell = function patched(...args: unknown[]): unknown { - probe.updateCellCalls++ - return originalUpdateCell.apply(this, args) - } - const originalDraw = gl.drawElementsInstanced.bind(gl) - gl.drawElementsInstanced = function patched( - mode: number, - count: number, - type: number, - offset: number, - instanceCount: number - ): void { - probe.drawCalls++ - probe.instancesDrawn += instanceCount - originalDraw(mode, count, type, offset, instanceCount) - } - }) -} - -type RefreshOptions = { clearModel?: boolean; latchSynchronizedOutput?: boolean } - -async function forceRefreshAndRead(page: Page, options: RefreshOptions = {}): Promise { - return page.evaluate((opts) => { - const win = window as unknown as { - __paneManagers?: Map unknown[] }> - __drawProbe?: { - updateCellCalls: number - drawCalls: number - instancesDrawn: number - reset: () => void - } - } - let found: unknown = null - for (const manager of win.__paneManagers?.values() ?? []) { - for (const candidate of manager.getPanes?.() ?? []) { - const candidateTerminal = ( - candidate as { - terminal?: { - _core?: { _renderService?: { _renderer?: { value?: { _gl?: unknown } } } } - } - } - ).terminal - if (candidateTerminal?._core?._renderService?._renderer?.value?._gl) { - found = candidateTerminal - } - } - } - const terminal = found as - | { - rows: number - cols: number - _core?: { - coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - _renderService?: { - clear?: () => void - refreshRows?: (s: number, e: number, sync?: boolean) => void - } - } - } - | undefined - const probe = win.__drawProbe - if (!terminal || !probe) { - throw new Error('probe or terminal missing') - } - if (opts.clearModel) { - terminal._core?._renderService?.clear?.() - } - const modes = terminal._core?.coreService?.decPrivateModes - if (opts.latchSynchronizedOutput && modes) { - modes.synchronizedOutput = true - } - probe.reset() - // Synchronous refresh so the counters are populated before we read them. - terminal._core?._renderService?.refreshRows?.(0, terminal.rows - 1, true) - return { - updateCellCalls: probe.updateCellCalls, - drawCalls: probe.drawCalls, - instancesDrawn: probe.instancesDrawn, - rows: terminal.rows, - cols: terminal.cols - } - }, options) -} - -async function readRendererGeometry(page: Page): Promise { - return page.evaluate(() => { - let renderer: Record | null = null - let terminal: Record | null = null - for (const manager of window.__paneManagers?.values() ?? []) { - for (const candidate of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const candidateTerminal = (candidate as { terminal?: Record }).terminal - const active = ( - candidateTerminal as - | { _core?: { _renderService?: { _renderer?: { value?: Record } } } } - | undefined - )?._core?._renderService?._renderer?.value - if (active?._gl) { - renderer = active - terminal = candidateTerminal as Record - } - } - } - if (!renderer || !terminal) { - throw new Error('no WebGL pane') - } - const canvas = renderer._canvas as HTMLCanvasElement - const dimensions = renderer.dimensions as { - device: { canvas: { width: number; height: number } } - } - const charSizeService = renderer._charSizeService as { width: number; height: number } - const core = terminal._core as { - screenElement?: HTMLElement - coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - _renderService?: { _isPaused?: boolean } - } - const atlas = renderer._charAtlas as { pages?: { version: number }[] } | undefined - const glyphRenderer = (renderer._glyphRenderer as { value?: Record })?.value - const boundTextures = (glyphRenderer?._atlasTextures as { version: number }[] | undefined) ?? [] - return { - canvasWidth: canvas.width, - canvasHeight: canvas.height, - modelCanvasWidth: dimensions.device.canvas.width, - modelCanvasHeight: dimensions.device.canvas.height, - charWidth: charSizeService.width, - charHeight: charSizeService.height, - isAttached: Boolean(renderer._isAttached), - synchronizedOutput: Boolean(core.coreService?.decPrivateModes?.synchronizedOutput), - isPaused: Boolean(core._renderService?._isPaused), - atlasPageVersions: (atlas?.pages ?? []).map((page) => page.version), - boundTextureVersions: boundTextures.map((texture) => texture?.version ?? -1), - screenConnected: Boolean(core.screenElement?.isConnected) - } - }) -} - -test.describe('reveal draw-command oracle (STA-2694)', () => { - // REFUTATION TEST. The hypothesis was: xterm's renderers are diff-based, so a - // reveal `refresh()` skips cells whose model entry still matches the buffer, - // leaving an occluded canvas showing pre-hide pixels until a resize rebuilds - // the model. `_updateModel` really does early-continue per unchanged cell — - // but `GlyphRenderer.render` then copies vertices for EVERY row up to - // `lineLengths[y]` and issues ONE full-viewport `drawElementsInstanced`. So - // the diff only decides how much VERTEX data is rewritten, never how much is - // DRAWN. This test pins that, so the refuted hypothesis cannot be - // reintroduced as a "fix". - test('a diff-skipped refresh draws exactly as much as a model-cleared one', async ({ - orcaPage - }) => { - test.setTimeout(120_000) - test.skip(!(await setUpWebglPane(orcaPage)), 'WebGL renderer unavailable in this environment') - await instrumentDrawCommands(orcaPage) - - // Model already matches the buffer, so every cell diff-skips. - const warm = await forceRefreshAndRead(orcaPage) - // Model cleared first, so every cell is re-sent through updateCell. - const cleared = await forceRefreshAndRead(orcaPage, { clearModel: true }) - - expect(warm.updateCellCalls, 'expected the warm pass to diff-skip its cells').toBe(0) - expect(cleared.updateCellCalls, 'expected the cleared pass to re-send cells').toBeGreaterThan(0) - // The decisive comparison: identical draw output despite a 0-vs-N split in - // vertex updates. Clearing the model cannot change what reaches the screen. - expect(warm.drawCalls, 'a diff-skipped refresh issued no draw at all').toBeGreaterThan(0) - expect( - warm.instancesDrawn, - 'a diff-skipped refresh drew fewer instances than a model-cleared one — ' + - 'the diff-based-staleness hypothesis would be back in play' - ).toBe(cleared.instancesDrawn) - }) - - // The COST of clearing the render model, which the refutation above shows buys - // nothing: `_clearModel(true)` zeroes every glyph vertex and resets - // `lineLengths`, and `RenderService.clear()` fires no repaint of its own. So - // any paint that lands between the clear and the repopulating refresh draws an - // EMPTY viewport. On a reveal the following refresh is debounced through a RAF - // and can additionally be swallowed (paused render, latched synchronized - // output), which would turn a merely-stale pane into a blank one. - test('clearing the render model without repopulating it draws an empty viewport', async ({ - orcaPage - }) => { - test.setTimeout(120_000) - test.skip(!(await setUpWebglPane(orcaPage)), 'WebGL renderer unavailable in this environment') - await instrumentDrawCommands(orcaPage) - - const populated = await forceRefreshAndRead(orcaPage) - expect(populated.instancesDrawn, 'baseline drew nothing').toBeGreaterThan(0) - - // Clear the model, then draw WITHOUT letting _updateModel repopulate it — - // exactly the window a debounced or swallowed refresh leaves open. - const blank = await orcaPage.evaluate(() => { - const win = window as unknown as { - __paneManagers?: Map unknown[] }> - __drawProbe?: { instancesDrawn: number; drawCalls: number; reset: () => void } - } - let renderer: Record | null = null - let model: unknown = null - for (const manager of win.__paneManagers?.values() ?? []) { - for (const candidate of manager.getPanes?.() ?? []) { - const active = ( - candidate as { - terminal?: { _core?: { _renderService?: { _renderer?: { value?: unknown } } } } - } - ).terminal?._core?._renderService?._renderer?.value as Record | undefined - if (active?._gl) { - renderer = active - model = active._model - } - } - } - const glyphRenderer = (renderer?._glyphRenderer as { value?: Record })?.value - const probe = win.__drawProbe - if (!renderer || !glyphRenderer || !probe) { - throw new Error('probe or renderer missing') - } - // What RenderService.clear() does to the renderer. - ;(renderer.clear as () => void).call(renderer) - probe.reset() - // Draw the cleared model directly, skipping _updateModel. - ;(glyphRenderer.render as (m: unknown) => void).call(glyphRenderer, model) - return { instancesDrawn: probe.instancesDrawn, drawCalls: probe.drawCalls } - }) - - expect( - blank.instancesDrawn, - 'a cleared model still drew content — the blank-pane window would not exist' - ).toBe(0) - // Restore the pane so the fixture teardown sees a painted terminal. - await forceRefreshAndRead(orcaPage, { clearModel: true }) - }) - - // The mechanism that IS real: while a TUI's synchronized-output frame is - // latched, RenderService returns before reaching the renderer, so a repaint - // draws literally nothing. Counting draw commands proves it directly instead - // of inferring it from pixels. - test('a latched synchronized-output frame drops the repaint entirely', async ({ orcaPage }) => { - test.setTimeout(120_000) - test.skip(!(await setUpWebglPane(orcaPage)), 'WebGL renderer unavailable in this environment') - await instrumentDrawCommands(orcaPage) - - const baseline = await forceRefreshAndRead(orcaPage) - expect(baseline.drawCalls, 'baseline refresh drew nothing').toBeGreaterThan(0) - - // Hide mid-`?2026h`: the latch stays set and every repaint is swallowed. - const latched = await forceRefreshAndRead(orcaPage, { latchSynchronizedOutput: true }) - expect( - latched.drawCalls, - 'a latched synchronized-output frame should swallow the repaint completely' - ).toBe(0) - - // What the production fix does at both reveal repaint entry points. - const released = await orcaPage.evaluate(() => { - let invoked = 0 - for (const manager of window.__paneManagers?.values() ?? []) { - const schedule = (manager as { scheduleRevealPresent?: () => void }).scheduleRevealPresent - if (typeof schedule === 'function') { - schedule.call(manager) - invoked++ - } - } - return invoked - }) - // Why count rather than assume: scheduleRevealPresent is optional-chained, - // so a missing test hook would otherwise surface below as "the fix did not - // release the latch" and misattribute the failure to production code. - expect(released, 'no pane manager exposed scheduleRevealPresent').toBeGreaterThan(0) - await orcaPage.waitForTimeout(500) - - const afterRelease = await forceRefreshAndRead(orcaPage) - expect( - afterRelease.drawCalls, - 'the reveal repaint left the latch set, so the pane still cannot paint' - ).toBeGreaterThan(0) - }) - - // The indefinite-garble case, and the reason the 1s watchdog does NOT bound - // it. `refreshRows` checks `_isPaused` BEFORE the synchronized-output latch - // and returns early, so while a pane is occluded nothing ever reaches - // `bufferRows` — which is the only place the watchdog arms. A pane hidden mid - // `?2026h` therefore holds the latch with NO timer pending, and stays that way - // until something clears the latch explicitly. That is unbounded, not 1s. - test('an occluded pane strands a latched frame with no watchdog to clear it', async ({ - orcaPage - }) => { - test.setTimeout(120_000) - test.skip(!(await setUpWebglPane(orcaPage)), 'WebGL renderer unavailable in this environment') - await instrumentDrawCommands(orcaPage) - - const stranded = await orcaPage.evaluate(() => { - let terminal: Record | null = null - for (const manager of window.__paneManagers?.values() ?? []) { - for (const candidate of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const candidateTerminal = (candidate as { terminal?: Record }).terminal - const active = ( - candidateTerminal as - | { _core?: { _renderService?: { _renderer?: { value?: { _gl?: unknown } } } } } - | undefined - )?._core?._renderService?._renderer?.value - if (active?._gl) { - terminal = candidateTerminal as Record - } - } - } - const core = terminal?._core as { - coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - _renderService?: { - _isPaused?: boolean - _syncOutputHandler?: { _timeout?: number; _isBuffering?: boolean } - refreshRows?: (s: number, e: number, sync?: boolean) => void - } - } - const service = core?._renderService - const modes = core?.coreService?.decPrivateModes - if (!service || !modes || !terminal) { - throw new Error('render service unavailable') - } - // Exactly the field state: the TUI opened a frame, then the pane was - // occluded (IntersectionObserver pauses rendering) before ?2026l arrived. - modes.synchronizedOutput = true - service._isPaused = true - service.refreshRows?.(0, (terminal.rows as number) - 1, true) - const armed = { - watchdogPending: service._syncOutputHandler?._timeout !== undefined, - buffering: service._syncOutputHandler?._isBuffering === true, - latched: modes.synchronizedOutput === true - } - // Reveal: the pane intersects again and the pause lifts. - service._isPaused = false - return armed - }) - - expect(stranded.latched, 'the latch should still be set while occluded').toBe(true) - // The decisive observation: no timer, so nothing will ever clear this latch. - expect( - stranded.watchdogPending, - 'a watchdog was armed, so the latch would self-clear in 1s and the window would be bounded' - ).toBe(false) - expect(stranded.buffering, 'the paused return happened before any row buffering').toBe(false) - - // A repaint now draws nothing, no matter how long the pane waits. - const whileLatched = await forceRefreshAndRead(orcaPage) - expect(whileLatched.drawCalls, 'expected the stranded latch to swallow the repaint').toBe(0) - - // The production fix, at the real reveal entry point. - const invokedReveal = await orcaPage.evaluate(() => { - let invoked = 0 - for (const manager of window.__paneManagers?.values() ?? []) { - const schedule = (manager as { scheduleRevealPresent?: () => void }).scheduleRevealPresent - if (typeof schedule === 'function') { - schedule.call(manager) - invoked++ - } - } - return invoked - }) - expect(invokedReveal, 'no pane manager exposed scheduleRevealPresent').toBeGreaterThan(0) - await orcaPage.waitForTimeout(600) - - const afterFix = await forceRefreshAndRead(orcaPage) - expect( - afterFix.drawCalls, - 'the reveal repaint did not release the stranded latch, so the pane stays frozen' - ).toBeGreaterThan(0) - expect(afterFix.instancesDrawn, 'the released repaint drew an empty viewport').toBeGreaterThan( - 0 - ) - }) - - // Tests the remaining live hypothesis: that a hidden pane's canvas backing - // store or char metrics go stale, so nothing re-runs handleResize() on - // reveal and only a real window resize repairs the display. - test('a hide/reveal cycle leaves canvas geometry and atlas bindings consistent', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - test.skip(!(await setUpWebglPane(orcaPage)), 'WebGL renderer unavailable in this environment') - - const before = await readRendererGeometry(orcaPage) - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0]?.hide() - }) - await orcaPage.waitForTimeout(4_000) - await electronApp.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - window?.show() - window?.focus() - }) - await orcaPage.waitForTimeout(3_000) - - await instrumentDrawCommands(orcaPage) - const afterReveal = await readRendererGeometry(orcaPage) - const afterDraw = await forceRefreshAndRead(orcaPage) - // Atlas page bindings are lazy: GlyphRenderer.render rebinds any page whose - // version moved. So the binding must be judged AFTER a draw — a lag that a - // render repairs on its own is normal, one that survives a render is not. - const after = await readRendererGeometry(orcaPage) - console.log('[probe] geometry before hide:', JSON.stringify(before)) - console.log('[probe] geometry right after reveal:', JSON.stringify(afterReveal)) - console.log('[probe] post-reveal draw:', JSON.stringify(afterDraw)) - console.log('[probe] geometry after a repaint:', JSON.stringify(after)) - - // The canvas backing store must still match the dimensions the renderer - // computes from the grid; a mismatch is exactly what a window resize fixes. - expect( - { width: after.canvasWidth, height: after.canvasHeight }, - `canvas backing store diverged from renderer dimensions after reveal: ${JSON.stringify(after)}` - ).toEqual({ width: after.modelCanvasWidth, height: after.modelCanvasHeight }) - expect(after.charWidth, 'char width went stale/zero across the hide').toBeGreaterThan(0) - expect(after.charHeight, 'char height went stale/zero across the hide').toBeGreaterThan(0) - expect(after.isAttached, 'renderer detached across the hide and never re-attached').toBe(true) - expect(after.screenConnected, 'screen element disconnected across the hide').toBe(true) - expect(after.synchronizedOutput, 'synchronized output left latched after reveal').toBe(false) - expect(after.isPaused, 'render service left paused after reveal').toBe(false) - // A glyph page whose bound texture version still lags AFTER a repaint - // renders stale/garbled glyphs — the shared-atlas half of the report. - expect( - after.boundTextureVersions.slice(0, after.atlasPageVersions.length), - `bound atlas textures still lag the atlas pages after a full repaint: ${JSON.stringify(after)}` - ).toEqual(after.atlasPageVersions) - expect(afterDraw.drawCalls, 'the pane cannot draw at all after a reveal').toBeGreaterThan(0) - }) -}) diff --git a/tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts b/tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts deleted file mode 100644 index 43fbe9c75..000000000 --- a/tests/e2e/terminal-reveal-latch-visual-evidence.spec.ts +++ /dev/null @@ -1,227 +0,0 @@ -/** - * STA-2694 visual evidence generator (not a pass/fail guard — see the oracle - * spec for that). - * - * Earlier screenshot oracles here were blind because they compared a revealed - * pane against a repaired one, and both ran the same repaint code. Capturing - * the defect directly works, because the mechanism is self-preserving: while - * `synchronizedOutput` is latched, `RenderService.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. - * - * So: latch the frame, write new content the pane cannot paint, and capture. - * Buffer says one thing, screen shows another — which is the field report. - * - * Run with ORCA_E2E_EVIDENCE_DIR=/path to collect the PNGs. - */ -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { waitForActiveTerminalManager } from './helpers/terminal' - -const EVIDENCE_DIR = process.env.ORCA_E2E_EVIDENCE_DIR ?? '/tmp/sta2694-evidence' - -async function activeWebglTerminalReady(page: Page): Promise { - await waitForSessionReady(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { ...state.settings, terminalGpuAcceleration: 'on' } - }) - for (const manager of window.__paneManagers?.values() ?? []) { - ;( - manager as { setTerminalGpuAcceleration?: (mode: string) => void } - ).setTerminalGpuAcceleration?.('on') - } - }) - return page - .waitForFunction( - () => { - for (const manager of window.__paneManagers?.values() ?? []) { - const diagnostics = - ( - manager as { getRenderingDiagnostics?: () => { hasWebgl: boolean }[] } - ).getRenderingDiagnostics?.() ?? [] - if (diagnostics.some((diagnostic) => diagnostic.hasWebgl)) { - return true - } - } - return false - }, - { timeout: 20_000 } - ) - .then(() => true) - .catch(() => false) -} - -/** Writes to the pane's xterm buffer directly, bypassing the PTY. */ -async function writeToPane(page: Page, data: string): Promise { - await page.evaluate((payload) => { - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - ;(pane as { terminal?: { write?: (d: string) => void } }).terminal?.write?.(payload) - } - } - }, data) - await page.waitForTimeout(600) -} - -async function paneClip( - page: Page -): Promise<{ x: number; y: number; width: number; height: number } | null> { - return page.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - const pane = (manager as { getPanes?: () => { container?: HTMLElement }[] }).getPanes?.()[0] - const rect = pane?.container?.getBoundingClientRect() - if (rect && rect.width > 10 && rect.height > 10) { - return { x: rect.x, y: rect.y, width: rect.width, height: rect.height } - } - } - return null - }) -} - -/** The visible screen text, as xterm's buffer believes it to be. */ -async function readScreenText(page: Page): Promise { - return page.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const terminal = ( - pane as { - terminal?: { - rows: number - buffer?: { - active?: { - viewportY: number - getLine: ( - i: number - ) => { translateToString: (trim: boolean) => string } | undefined - } - } - } - } - ).terminal - const active = terminal?.buffer?.active - if (!terminal || !active) { - continue - } - const lines: string[] = [] - for (let y = 0; y < terminal.rows; y++) { - lines.push(active.getLine(active.viewportY + y)?.translateToString(true) ?? '') - } - return lines.join('\n') - } - } - return '' - }) -} - -test.describe('STA-2694 visual evidence', () => { - test('a latched frame keeps stale pixels on screen, and the fix repaints them', async ({ - orcaPage - }) => { - test.setTimeout(180_000) - test.skip( - !(await activeWebglTerminalReady(orcaPage)), - 'WebGL renderer unavailable in this environment' - ) - mkdirSync(EVIDENCE_DIR, { recursive: true }) - - // 1. A settled "agent frame" on screen, painted normally. - await writeToPane( - orcaPage, - `\x1b[2J\x1b[H\x1b[1;32m### AGENT FRAME 1 — BEFORE SWITCHING AWAY ###\x1b[0m\r\n\r\n${Array.from( - { length: 8 }, - (_, i) => ` line ${i + 1}: original content ${'-'.repeat(30)}` - ).join('\r\n')}` - ) - const clip = await paneClip(orcaPage) - expect(clip, 'pane rect unavailable').not.toBeNull() - const beforeShot = await orcaPage.screenshot({ clip: clip! }) - writeFileSync(path.join(EVIDENCE_DIR, '1-before-hide.png'), beforeShot) - - // 2. Hide mid-`?2026h`: the TUI opened a frame that never closed, and the - // pane was occluded before it could. This is the field state. - await orcaPage.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const core = (pane as { terminal?: { _core?: unknown } }).terminal?._core as - | { coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } - | undefined - const modes = core?.coreService?.decPrivateModes - if (modes) { - modes.synchronizedOutput = true - } - } - } - }) - - // 3. The agent keeps working while hidden. The buffer advances; the canvas - // cannot follow, because refreshRows returns at the latch. - await writeToPane( - orcaPage, - `\x1b[2J\x1b[H\x1b[1;31m### AGENT FRAME 2 — WHAT THE BUFFER NOW HOLDS ###\x1b[0m\r\n\r\n${Array.from( - { length: 8 }, - (_, i) => ` line ${i + 1}: UPDATED content ${'#'.repeat(30)}` - ).join('\r\n')}` - ) - - const staleShot = await orcaPage.screenshot({ clip: clip! }) - writeFileSync(path.join(EVIDENCE_DIR, '2-garbled-on-return.png'), staleShot) - const bufferWhileStale = await readScreenText(orcaPage) - - // The buffer holds frame 2... - expect(bufferWhileStale, 'buffer never received frame 2').toContain('AGENT FRAME 2') - writeFileSync(path.join(EVIDENCE_DIR, 'buffer-while-garbled.txt'), bufferWhileStale, 'utf8') - // ...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) - - // 4. The reveal repaint Orca runs — the production fix. - await orcaPage.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - ;(manager as { scheduleRevealPresent?: () => void }).scheduleRevealPresent?.() - } - }) - await orcaPage.waitForTimeout(1_200) - const repairedShot = await orcaPage.screenshot({ clip: clip! }) - writeFileSync(path.join(EVIDENCE_DIR, '3-after-fix.png'), repairedShot) - - // The latch must be gone and the pane must now be painting. - const latchAfter = await orcaPage.evaluate(() => { - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const core = (pane as { terminal?: { _core?: unknown } }).terminal?._core as - | { coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } - | undefined - if (core?.coreService?.decPrivateModes?.synchronizedOutput) { - return true - } - } - } - return false - }) - expect(latchAfter, 'the reveal repaint left the latch set').toBe(false) - - // And the fix closes the gap: the repaired capture differs from the stale - // one, so the reveal repaint actually reached the screen. - expect( - Buffer.compare(staleShot, repairedShot), - 'the pre-fix and post-fix captures are byte-identical, so the fix repainted nothing' - ).not.toBe(0) - console.log(`[evidence] wrote PNGs to ${EVIDENCE_DIR}`) - }) -}) diff --git a/tests/e2e/terminal-synchronized-output-release-perf.spec.ts b/tests/e2e/terminal-synchronized-output-release-perf.spec.ts deleted file mode 100644 index 6d354c129..000000000 --- a/tests/e2e/terminal-synchronized-output-release-perf.spec.ts +++ /dev/null @@ -1,285 +0,0 @@ -/** - * Performance budget for the STA-2694 synchronized-output release (PR #10907). - * - * `releaseAbandonedSynchronizedOutput` runs inside `resetWebglTextureAtlas`, - * which a streaming alt-screen TUI can reach through the terminal-output atlas - * recovery path — not just on reveal. So it is worth proving, rather than - * asserting, that it does not add per-chunk work or extra repaints while an - * agent TUI floods output. - * - * Two things must hold: - * 1. Cost per call is O(1) — two property reads and, only when actually - * latched, one assignment plus a flush. No buffer/scrollback scan. - * 2. It adds NO repaints in steady state. The function returns early unless a - * frame was genuinely abandoned, so a healthy streaming TUI (which closes - * every `?2026l` it opens) must see zero releases and zero extra draws. - */ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { waitForActiveTerminalManager } from './helpers/terminal' - -async function webglTerminalReady(page: Page): Promise { - await waitForSessionReady(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { ...state.settings, terminalGpuAcceleration: 'on' } - }) - for (const manager of window.__paneManagers?.values() ?? []) { - ;( - manager as { setTerminalGpuAcceleration?: (mode: string) => void } - ).setTerminalGpuAcceleration?.('on') - } - }) - return page - .waitForFunction( - () => { - for (const manager of window.__paneManagers?.values() ?? []) { - const diagnostics = - ( - manager as { getRenderingDiagnostics?: () => { hasWebgl: boolean }[] } - ).getRenderingDiagnostics?.() ?? [] - if (diagnostics.some((diagnostic) => diagnostic.hasWebgl)) { - return true - } - } - return false - }, - { timeout: 20_000 } - ) - .then(() => true) - .catch(() => false) -} - -test.describe('synchronized-output release performance (STA-2694)', () => { - test('a healthy streaming TUI triggers no releases and no extra draws', async ({ orcaPage }) => { - test.setTimeout(180_000) - test.skip(!(await webglTerminalReady(orcaPage)), 'WebGL renderer unavailable') - - const result = await orcaPage.evaluate(async () => { - let terminal: Record | null = null - let renderer: Record | null = null - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const candidate = (pane as { terminal?: Record }).terminal - const active = ( - candidate as - | { _core?: { _renderService?: { _renderer?: { value?: { _gl?: unknown } } } } } - | undefined - )?._core?._renderService?._renderer?.value - if (active?._gl) { - terminal = candidate as Record - renderer = active as Record - } - } - } - if (!terminal || !renderer) { - throw new Error('no WebGL pane') - } - const gl = renderer._gl as WebGL2RenderingContext - let drawCalls = 0 - const originalDraw = gl.drawElementsInstanced.bind(gl) - gl.drawElementsInstanced = function counted( - mode: number, - count: number, - type: number, - offset: number, - instanceCount: number - ): void { - drawCalls++ - originalDraw(mode, count, type, offset, instanceCount) - } - - const write = (terminal as { write: (d: string, cb?: () => void) => void }).write.bind( - terminal - ) - const modes = ( - terminal._core as { coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } - ).coreService?.decPrivateModes - - // A well-behaved alt-screen TUI: 200 fully-bracketed frames. - const FRAMES = 200 - const frame = (n: number): string => - `\x1b[?2026h\x1b[H${Array.from( - { length: 20 }, - (_, row) => `row ${row} frame ${n} ${'x'.repeat(60)}` - ).join('\r\n')}\x1b[?2026l` - - const start = performance.now() - for (let i = 0; i < FRAMES; i++) { - write(frame(i)) - } - await new Promise((resolve) => { - write('', () => resolve()) - }) - const writeMs = performance.now() - start - const drawsAfterStream = drawCalls - if (!modes) { - throw new Error('decPrivateModes unavailable — the measurement would be vacuous') - } - - // Time the REAL production path in its steady state (nothing latched). - // Driving resetWebglTextureAtlases rather than a copy of the early-out is - // the point: a future change that makes the release scan the buffer shows - // up here instead of hiding behind a hand-written mirror. - const drawsBeforeIdleResets = drawCalls - const releaseStart = performance.now() - for (let i = 0; i < FRAMES; i++) { - for (const manager of window.__paneManagers?.values() ?? []) { - ;(manager as { resetWebglTextureAtlases?: () => void }).resetWebglTextureAtlases?.() - } - } - const releaseMs = performance.now() - releaseStart - const drawsDuringIdleResets = drawCalls - drawsBeforeIdleResets - - return { - writeMs, - releaseMs, - drawsAfterStream, - drawsDuringIdleResets, - latchedAfterStream: modes.synchronizedOutput === true, - frames: FRAMES - } - }) - - console.log( - `[perf] ${result.frames} bracketed frames written in ${result.writeMs.toFixed(1)}ms` - ) - console.log( - `[perf] ${result.frames} unlatched atlas resets took ${result.releaseMs.toFixed(3)}ms ` + - `(${((result.releaseMs / result.frames) * 1000).toFixed(2)}µs each)` - ) - console.log( - `[perf] draws during stream: ${result.drawsAfterStream}, ` + - `during idle resets: ${result.drawsDuringIdleResets}` - ) - - // A healthy TUI closes every frame it opens, so the latch is clear and the - // release is a pure early-out that changes nothing. - expect(result.latchedAfterStream, 'a fully-bracketed stream should leave no latch behind').toBe( - false - ) - // The title's "no extra draws" claim, actually asserted: a bracketed stream - // that never abandons a frame must not provoke synchronous repaints. - expect( - result.drawsAfterStream, - `a fully-bracketed stream forced ${result.drawsAfterStream} synchronous draws` - ).toBe(0) - // Measured ~0.04ms per full atlas-reset call on CI-class hardware. Note this - // is the cost of the WHOLE recovery (atlas clear + refresh), not the release - // alone — the release itself is the early-out that contributes ~nothing, as - // the zero draw counts above show. Bound at 10x measured so it catches a - // change that makes this scan the buffer per pane without flaking on speed. - expect( - result.releaseMs / result.frames, - `unlatched reset cost ${result.releaseMs / result.frames}ms per call, expected < 0.4ms` - ).toBeLessThan(0.4) - }) - - // Worst case: every reveal finds a latched frame, so the release does its full - // work (assignment + handler flush) and the caller repaints. This bounds the - // cost of the path the fix actually exists for. - test('the latched path stays bounded and repaints exactly once per reveal', async ({ - orcaPage - }) => { - test.setTimeout(180_000) - test.skip(!(await webglTerminalReady(orcaPage)), 'WebGL renderer unavailable') - - const result = await orcaPage.evaluate(async () => { - let terminal: Record | null = null - let renderer: Record | null = null - for (const manager of window.__paneManagers?.values() ?? []) { - for (const pane of (manager as { getPanes?: () => unknown[] }).getPanes?.() ?? []) { - const candidate = (pane as { terminal?: Record }).terminal - const active = ( - candidate as - | { _core?: { _renderService?: { _renderer?: { value?: { _gl?: unknown } } } } } - | undefined - )?._core?._renderService?._renderer?.value - if (active?._gl) { - terminal = candidate as Record - renderer = active as Record - } - } - } - if (!terminal || !renderer) { - throw new Error('no WebGL pane') - } - const gl = renderer._gl as WebGL2RenderingContext - let drawCalls = 0 - const originalDraw = gl.drawElementsInstanced.bind(gl) - gl.drawElementsInstanced = function counted( - mode: number, - count: number, - type: number, - offset: number, - instanceCount: number - ): void { - drawCalls++ - originalDraw(mode, count, type, offset, instanceCount) - } - ;(terminal as { write: (d: string) => void }).write(`\x1b[H${'content '.repeat(200)}`) - await new Promise((resolve) => setTimeout(resolve, 500)) - - const modes = ( - terminal._core as { coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } } - ).coreService?.decPrivateModes - if (!modes) { - // Without this the latch is never set, the recovery has nothing to do, - // and every assertion below passes without exercising the fix. - throw new Error('decPrivateModes unavailable — the latched path would be vacuous') - } - const REVEALS = 50 - drawCalls = 0 - const start = performance.now() - let latchSurvivedAReset = false - for (let i = 0; i < REVEALS; i++) { - modes.synchronizedOutput = true - for (const manager of window.__paneManagers?.values() ?? []) { - ;(manager as { resetWebglTextureAtlases?: () => void }).resetWebglTextureAtlases?.() - } - if (modes.synchronizedOutput) { - latchSurvivedAReset = true - } - } - const elapsedMs = performance.now() - start - return { - elapsedMs, - reveals: REVEALS, - drawCalls, - latchSurvivedAReset, - stillLatched: modes.synchronizedOutput === true - } - }) - - console.log( - `[perf] ${result.reveals} latched atlas resets in ${result.elapsedMs.toFixed(1)}ms ` + - `(${(result.elapsedMs / result.reveals).toFixed(2)}ms each), ${result.drawCalls} draw calls` - ) - - expect(result.stillLatched, 'the latch must be cleared by the recovery path').toBe(false) - // Every iteration must clear it, not just the last one. - expect( - result.latchSurvivedAReset, - 'a reset left the latch set, so the release did not run on every reveal' - ).toBe(false) - // "exactly once per reveal": the recovery repaints through the render-pause - // release, so draws must scale with reveals rather than multiplying per pane. - expect( - result.drawCalls, - `${result.drawCalls} draws across ${result.reveals} reveals exceeds one repaint each` - ).toBeLessThanOrEqual(result.reveals * 3) - // Reveal is a one-shot user action, so even the full path has ample headroom; - // this guards against a future change making it scan the buffer per pane. - expect( - result.elapsedMs / result.reveals, - `latched atlas reset cost ${result.elapsedMs / result.reveals}ms per reveal, expected < 20ms` - ).toBeLessThan(20) - }) -})