diff --git a/src/renderer/src/components/standalone-terminal/input/preview-terminal-paste.ts b/src/renderer/src/components/standalone-terminal/input/preview-terminal-paste.ts index 9738737750e2..a5ddbdf8a6f8 100644 --- a/src/renderer/src/components/standalone-terminal/input/preview-terminal-paste.ts +++ b/src/renderer/src/components/standalone-terminal/input/preview-terminal-paste.ts @@ -7,6 +7,7 @@ import { TERMINAL_PASTE_MAX_BYTES } from '@/components/terminal-pane/input/paste import { pasteTerminalText } from '@/components/terminal-pane/input/paste/terminal-bracketed-paste' import { isTerminalPanePasteFocusCurrent } from '@/components/terminal-pane/input/paste/terminal-paste-target-state' import type { DashboardCardTerminalInput } from '../../../../../shared/agent-status/presentation/dashboard-snapshot' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' export type PreviewTerminalPasteSource = 'keyboard' | 'app-menu' | 'right-click' @@ -62,7 +63,11 @@ export function createPreviewClipboardPaster(deps: { }) await executeTerminalPastePlan(plan, { pasteText: (text, options) => pasteTerminalText(pasteTerminal, text, options), - writePty: (data) => deps.writeInput(data), + writePty: (data) => { + // Chunked pastes skip xterm's onData; they still hold atlas rebuilds like typing. + noteTerminalWebglAtlasTyping() + return deps.writeInput(data) + }, isTargetCurrent: targetIsCurrent, // Why: if focus changes mid-bracketed paste, the closing marker must still reach the live PTY. canContinue: () => true diff --git a/src/renderer/src/components/standalone-terminal/open-standalone-terminal.ts b/src/renderer/src/components/standalone-terminal/open-standalone-terminal.ts index dfe68a813511..d2fe6f616515 100644 --- a/src/renderer/src/components/standalone-terminal/open-standalone-terminal.ts +++ b/src/renderer/src/components/standalone-terminal/open-standalone-terminal.ts @@ -8,6 +8,7 @@ import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { useAppStore } from '@/store/index' import type { MacOptionAsAlt } from '@/components/terminal-pane/input/keyboard/terminal-option-shortcut-policy' import { subscribeToTerminalUserInput } from '@/components/terminal-pane/input/terminal-user-input-signal' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' import { installTerminalNativeCopyGutterTrim } from '@/components/terminal-pane/clipboard/terminal-native-copy-gutter' import { isWindowsUserAgent } from '@/app-shell/platform/user-agent-platform' import type { PreviewTerminalLinkHandlers } from './rendering/preview-terminal-links' @@ -70,6 +71,8 @@ export function openStandaloneTerminal(args: StandaloneTerminalArgs): Standalone const signaledUserInput = pendingUserInputSignals > 0 if (signaledUserInput) { pendingUserInputSignals-- + // Typing here holds atlas rebuilds of the pane terminals mounted behind this view. + noteTerminalWebglAtlasTyping() } // Why: core's signal distinguishes real input from parser replies, so typing survives live replay without forwarding synthetic CPR/DA bytes. if (!args.answersQueries && (userInputDisposable ? !signaledUserInput : replayDepth > 0)) { diff --git a/src/renderer/src/components/terminal-pane/chat/NativeChatPaneCover.tsx b/src/renderer/src/components/terminal-pane/chat/NativeChatPaneCover.tsx index 96d53db2f2bf..a534ef0693c6 100644 --- a/src/renderer/src/components/terminal-pane/chat/NativeChatPaneCover.tsx +++ b/src/renderer/src/components/terminal-pane/chat/NativeChatPaneCover.tsx @@ -1,8 +1,9 @@ -import { useRef, type ReactNode } from 'react' +import { useLayoutEffect, useRef, type ReactNode } from 'react' import { isEditableTarget } from '@/lib/text-input/focus/editable-target' import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types' import { useCoveredTerminalFocusHandoff } from './use-covered-terminal-focus-handoff' import { requestNativeChatCoverPaste } from '../input/paste/native-chat-cover-paste' +import { restoreWebglAfterChatCover } from '@/lib/pane-manager/terminal-rendering/pane-webgl-reattach' /** The cover owns focus and paste for its pane until a chat input can take them. */ export function NativeChatPaneCover({ @@ -14,6 +15,8 @@ export function NativeChatPaneCover({ }): React.JSX.Element { const coverRef = useRef(null) useCoveredTerminalFocusHandoff(coverRef, pane.terminal) + // An atlas rebuild leaves covered panes detached; reattach once the terminal shows again. + useLayoutEffect(() => () => restoreWebglAfterChatCover(pane.terminal), [pane.terminal]) return (
@@ -12,6 +13,9 @@ export function writeTerminalPastePtyInput( if (!transport) { return false } + if (inputKind === 'driving') { + noteTerminalWebglAtlasTyping() + } // sendInput only queues writes; await sendInputAccepted so paste chunking respects PTY backpressure. const accepted = signal ? transport.sendInputAccepted?.(data, inputKind, { signal }) diff --git a/src/renderer/src/components/terminal-pane/input/terminal-input-activity.ts b/src/renderer/src/components/terminal-pane/input/terminal-input-activity.ts index b9a84b15231c..dff98e336821 100644 --- a/src/renderer/src/components/terminal-pane/input/terminal-input-activity.ts +++ b/src/renderer/src/components/terminal-pane/input/terminal-input-activity.ts @@ -1,7 +1,9 @@ import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { useAppStore } from '@/store/index' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' export function recordTerminalUserInputForLeaf(tabId: string, leafId: string): void { + noteTerminalWebglAtlasTyping() try { // Hibernation must observe authorized writes that bypass xterm.onData. useAppStore.getState().recordTerminalInput(makePaneKey(tabId, leafId)) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-input-forward.ts b/src/renderer/src/components/terminal-pane/pty-connection/input/pty-input-forward.ts index f528d7abd221..14a0dc70a326 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-input-forward.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/input/pty-input-forward.ts @@ -18,9 +18,13 @@ import { isCodexPaneStale } from './codex-pane-stale' import { installTerminalSelectionFitGuard } from '../../viewport/terminal-selection-fit-guard' import type { ConnectPanePtySession } from '../connect-pane-pty-session' import { recordAdmittedTerminalUserInput } from '@/diagnostics/telemetry/telemetry' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' export function installPtyInputForward(session: ConnectPanePtySession): void { session.forwardPtyInput = (data: string, wasUserInput = false): void => { + if (wasUserInput) { + noteTerminalWebglAtlasTyping() + } // During replay, drop query replies and pointer-generated mouse/arrows but preserve typing; stale TUI modes could send reports or recall history in the fresh shell (replay-guard.ts). if ( isPaneReplaying(session.deps.replayingPanesRef, session.pane.id) && diff --git a/src/renderer/src/lib/pane-manager/pane-manager-registry.ts b/src/renderer/src/lib/pane-manager/pane-manager-registry.ts index 758ec26696fc..52f3cb81816b 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-registry.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-registry.ts @@ -12,9 +12,12 @@ type RegisteredPaneManager = { getPanes?: (limit?: number) => { id: number; terminal: unknown }[] getPaneCount?: () => number isVisibleForAtlasRecovery?: () => boolean + containsElement?: (element: Element) => boolean } const liveManagers = new Set() +// Kept at visibility changes so atlas recovery never walks hidden managers. +const visibleManagers = new Set() const managerIds = new WeakMap() /** Detaches a manager's WebGL renderers and returns the step that reattaches them. */ type WebglRendererDetacher = () => () => void @@ -32,10 +35,20 @@ export function registerLivePaneManager( webglRendererDetachers.set(manager, detachWebglRenderers) } liveManagers.add(manager) + notePaneManagerVisibility(manager) } export function unregisterLivePaneManager(manager: RegisteredPaneManager): void { liveManagers.delete(manager) + visibleManagers.delete(manager) +} + +export function notePaneManagerVisibility(manager: RegisteredPaneManager): void { + if (liveManagers.has(manager) && manager.isVisibleForAtlasRecovery?.() !== false) { + visibleManagers.add(manager) + } else { + visibleManagers.delete(manager) + } } export function resetAndRefreshAllTerminalWebglAtlases( @@ -109,6 +122,16 @@ export function rebuildAllTerminalWebglRenderers(reason: string): void { } } +/** Whether an element sits inside an on-screen manager; checks only visible managers' roots, never their panes. */ +export function isElementInVisiblePaneManager(element: Element): boolean { + for (const manager of visibleManagers) { + if (manager.containsElement?.(element)) { + return true + } + } + return false +} + /** Report each pane’s WebGL/DOM state so freeze reports distinguish missed repaint from atlas corruption/context loss. */ export function getAllPaneRenderingDiagnostics(): PaneRenderingDiagnostics[] { const all: PaneRenderingDiagnostics[] = [] diff --git a/src/renderer/src/lib/pane-manager/pane-manager.ts b/src/renderer/src/lib/pane-manager/pane-manager.ts index 4c52a5994615..15255893f847 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager.ts @@ -32,7 +32,11 @@ import { suspendPaneRendering } from './terminal-rendering/pane-rendering-control' import type { TerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' -import { registerLivePaneManager, unregisterLivePaneManager } from './pane-manager-registry' +import { + notePaneManagerVisibility, + registerLivePaneManager, + unregisterLivePaneManager +} from './pane-manager-registry' import { releaseHiddenWebglRetention } from './terminal-rendering/terminal-webgl-hidden-retention' import { schedulePaneRevealPresent, @@ -270,6 +274,11 @@ export class PaneManager { setAtlasRecoveryVisible(visible: boolean): void { this.atlasRecoveryVisible = visible + notePaneManagerVisibility(this) + } + + containsElement(element: Element): boolean { + return this.root.contains(element) } isVisibleForAtlasRecovery(): boolean { diff --git a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-flusher.ts b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-flusher.ts index 617d06d14393..6e8355b1c4ac 100644 --- a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-flusher.ts +++ b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-flusher.ts @@ -87,7 +87,8 @@ export function flushTerminalOutputImpl( terminal, queuedWrite.onParsed, ackCreditsParsed, - undefined + undefined, + queuedWrite.data ), onWriteFailure: composeWriteFailureCallback(terminal, ackCreditsParsed) } @@ -95,7 +96,13 @@ export function flushTerminalOutputImpl( : writeBackgroundTerminalChunk( terminal, queuedWrite.data, - composeParsedCallback(terminal, queuedWrite.onParsed, ackCreditsParsed, undefined), + composeParsedCallback( + terminal, + queuedWrite.onParsed, + ackCreditsParsed, + undefined, + queuedWrite.data + ), composeWriteFailureCallback(terminal, ackCreditsParsed) ) if (!writeAccepted) { diff --git a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-pipeline.ts b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-pipeline.ts index c896522df88d..1792a76da59c 100644 --- a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-pipeline.ts +++ b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-pipeline.ts @@ -10,6 +10,7 @@ import { } from './terminal-write-pipeline-health' import { removeTransientCursorShowSequences } from './pane-terminal-cursor-sequencing' import { takeQueuedChunk } from './pane-terminal-output-queue-chunks' +import { noteTerminalWebglAtlasOutput } from '../terminal-rendering/terminal-webgl-atlas-memory-rebuild' import { recordTerminalOutputQueueDebugPressure } from './pane-terminal-output-scheduler-debug' import { clearForegroundRelease } from './pane-terminal-foreground-queue-state' import { @@ -72,7 +73,8 @@ export function composeParsedCallback( terminal: ForegroundTerminalOutputTarget, onParsed: TerminalOutputParsedCallback | undefined, ackCreditsParsed: (() => void) | undefined, - pacer: (() => void) | undefined + pacer: (() => void) | undefined, + parsedData: string ): TerminalOutputParsedCallback { // Always provide completion: it settles pipeline health, avoiding a needless probe round-trip for every healthy idle pane. return () => { @@ -82,6 +84,10 @@ export function composeParsedCallback( ackCreditsParsed?.() pacer?.() settleTerminalWriteStallWatch(terminal) + if (parsedData) { + // At parse, so output queued before an atlas rebuild re-arms the atlas it actually grew. + noteTerminalWebglAtlasOutput(terminal) + } } } } @@ -134,7 +140,8 @@ export function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' entry.terminal, queuedWrite.onParsed, ackCreditsParsed, - pacer + pacer, + queuedWrite.data ), onWriteFailure: composeWriteFailureCallback(entry.terminal, ackCreditsParsed) } @@ -142,7 +149,13 @@ export function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' : writeBackgroundTerminalChunk( entry.terminal, queuedWrite.data, - composeParsedCallback(entry.terminal, queuedWrite.onParsed, ackCreditsParsed, pacer), + composeParsedCallback( + entry.terminal, + queuedWrite.onParsed, + ackCreditsParsed, + pacer, + queuedWrite.data + ), composeWriteFailureCallback(entry.terminal, ackCreditsParsed) ) if (!writeAccepted) { diff --git a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-writer.ts b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-writer.ts index c58d4c81226f..64d860653fd3 100644 --- a/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-writer.ts +++ b/src/renderer/src/lib/pane-manager/terminal-output/pane-terminal-output-writer.ts @@ -215,7 +215,13 @@ export function writeTerminalOutputImpl( followupViewportRefresh: options.followupForegroundRefresh === true, shouldRefreshViewportSynchronously: options.shouldRefreshForegroundSynchronously ?? ALWAYS_REFRESH_FOREGROUND_SYNCHRONOUSLY, - onParsed: composeParsedCallback(terminal, options.onParsed, ackCreditsParsed, undefined), + onParsed: composeParsedCallback( + terminal, + options.onParsed, + ackCreditsParsed, + undefined, + data + ), onWriteFailure: composeWriteFailureCallback(terminal, ackCreditsParsed) } ) diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.performance.test.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.performance.test.ts new file mode 100644 index 000000000000..f712cace1e20 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.performance.test.ts @@ -0,0 +1,224 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ManagedPaneInternal } from '../pane-manager-types' + +// Guards #43465: an atlas rebuild recreates at most one WebGL context per frame, decides each pane on its own frame, never leaves a shown pane on the DOM renderer or paints mid-frame, and pauses while the user interacts. +const attaches = { count: 0 } +const interactionHold = { ms: 0 } +const parked: { value: boolean; resume: (() => void) | null } = { value: false, resume: null } +type Verdict = 'now' | 'wait' | 'skip' +let rebuilder: + | (( + panes: ManagedPaneInternal[], + shouldReattach: (pane: ManagedPaneInternal) => boolean, + verdict: (pane: ManagedPaneInternal) => Verdict + ) => void) + | null = null + +type FakeAddon = { clears: number; clearTextureAtlas: () => void } +const newAddon = (): FakeAddon => { + const addon = { + clears: 0, + clearTextureAtlas: () => { + addon.clears++ + } + } + return addon +} + +vi.mock('./pane-webgl-renderer', () => ({ + attachWebgl: (pane: { webglAddon: unknown }) => { + attaches.count++ + pane.webglAddon = newAddon() + }, + disposeWebgl: (pane: { webglAddon: unknown }) => { + pane.webglAddon = null + }, + clearTerminalWebglAttachBackoff: () => {} +})) +vi.mock('./terminal-webgl-atlas-memory-rebuild', () => ({ + setTerminalWebglAtlasRebuilder: (next: typeof rebuilder) => { + rebuilder = next + }, + takeCoveredDetachedPane: () => undefined +})) +vi.mock('./terminal-webgl-atlas-rebuild-interaction', () => ({ + terminalWebglAtlasInteractionHoldMs: () => interactionHold.ms, + isTerminalWebglAtlasRebuildParked: () => parked.value, + whenTerminalWebglAtlasRebuildUnparked: (resume: () => void) => { + parked.resume = resume + } +})) +vi.mock('./terminal-render-pause-release', () => ({ paintReplacementCanvasNow: () => {} })) + +type RawPane = { + webglAddon: FakeAddon | null + container: { isConnected: boolean } + terminal: { modes: { synchronizedOutputMode: boolean } } +} + +function fakePane(): { pane: ManagedPaneInternal; raw: RawPane } { + const raw = { + webglAddon: newAddon(), + webglDisabledAfterContextLoss: false, + webglAttachmentDeferred: false, + container: { isConnected: true }, + terminal: { modes: { synchronizedOutputMode: false } } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rebuilder reads only the addon, deferral and context-loss flags, the container's connection and the terminal's modes, all supplied here. + const pane = raw as unknown as ManagedPaneInternal + return { pane, raw } +} + +const run = ( + fakes: { pane: ManagedPaneInternal }[], + verdict: (pane: ManagedPaneInternal) => Verdict = () => 'now', + shown: (pane: ManagedPaneInternal) => boolean = () => true +): void => + rebuilder?.( + fakes.map((fake) => fake.pane), + shown, + verdict + ) + +describe('atlas-rebuild context recreation', () => { + beforeEach(async () => { + vi.useFakeTimers() + vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 16)) + attaches.count = 0 + interactionHold.ms = 0 + parked.value = false + parked.resume = null + vi.resetModules() + await import('./pane-webgl-reattach') + }) + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('recreates one context per frame, starting on a frame of its own, without ever dropping a shown pane to DOM', async () => { + const fakes = Array.from({ length: 6 }, fakePane) + run(fakes) + expect(attaches.count).toBe(0) + for (let frame = 1; frame <= 6; frame++) { + expect(fakes.every((fake) => fake.raw.webglAddon)).toBe(true) + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(frame) + } + }) + + it('creates no context while the user types, clicks or scrolls, then resumes', async () => { + const fakes = Array.from({ length: 3 }, fakePane) + run(fakes) + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(1) + interactionHold.ms = 2_000 + await vi.advanceTimersByTimeAsync(1_000) + expect(attaches.count).toBe(1) + // Held panes keep their old context meanwhile. + expect(fakes.every((fake) => fake.raw.webglAddon)).toBe(true) + interactionHold.ms = 0 + // The hold ends 2 s after the frame that saw it (t = 32 ms), then waits one more frame. + await vi.advanceTimersByTimeAsync(1_040) + expect(attaches.count).toBe(2) + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(3) + }) + + it('decides each pane on its own frame: hidden ones drop their context, one revealed meanwhile gets a new one', async () => { + const [shown, hidden, revealed] = Array.from({ length: 3 }, fakePane) + const onScreen = new Set([shown.pane]) + run( + [shown, hidden, revealed], + (pane) => (onScreen.has(pane) ? 'now' : 'skip'), + (pane) => onScreen.has(pane) + ) + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(1) + onScreen.add(revealed.pane) + await vi.advanceTimersByTimeAsync(16 * 2) + expect(hidden.raw.webglAddon).toBeNull() + expect(revealed.raw.webglAddon).toBeTruthy() + expect(attaches.count).toBe(2) + }) + + it('lets panes behind one mid synchronized-output frame go first, and recreates it once its frame closes', async () => { + const [framed, plain] = Array.from({ length: 2 }, fakePane) + framed.raw.terminal.modes.synchronizedOutputMode = true + run([framed, plain], (pane) => (pane.terminal.modes.synchronizedOutputMode ? 'wait' : 'now')) + await vi.advanceTimersByTimeAsync(16) + // The waiting pane went to the back; the plain one was recreated in its place. + expect(attaches.count).toBe(1) + expect(plain.raw.webglAddon).toBeTruthy() + await vi.advanceTimersByTimeAsync(1_000) + expect(attaches.count).toBe(1) + // It keeps its old context while it waits. + expect(framed.raw.webglAddon).toBeTruthy() + framed.raw.terminal.modes.synchronizedOutputMode = false + await vi.advanceTimersByTimeAsync(300) + expect(attaches.count).toBe(2) + }) + + it('never paints a pane mid-frame: after 10 s of an open frame it keeps its old context and the queue ends', async () => { + const [framed] = Array.from({ length: 1 }, fakePane) + framed.raw.terminal.modes.synchronizedOutputMode = true + run([framed], () => 'wait') + await vi.advanceTimersByTimeAsync(11_000) + expect(attaches.count).toBe(0) + expect(framed.raw.webglAddon).toBeTruthy() + expect(vi.getTimerCount()).toBe(0) + }) + + it('touches no context while the window is hidden or unfocused, and resumes when it is back', async () => { + const fakes = Array.from({ length: 3 }, fakePane) + run(fakes) + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(1) + parked.value = true + await vi.advanceTimersByTimeAsync(5_000) + expect(attaches.count).toBe(1) + expect(fakes.every((fake) => fake.raw.webglAddon)).toBe(true) + expect(vi.getTimerCount()).toBe(0) + parked.value = false + parked.resume?.() + await vi.advanceTimersByTimeAsync(16 * 2) + expect(attaches.count).toBe(3) + }) + + it('runs overlapping rebuilds through one queue: still one context per frame', async () => { + const first = Array.from({ length: 3 }, fakePane) + const second = Array.from({ length: 3 }, fakePane) + run(first) + run(second) + for (let frame = 1; frame <= 6; frame++) { + await vi.advanceTimersByTimeAsync(16) + expect(attaches.count).toBe(frame) + } + }) + + it.each([300, 3_000])( + 'checks a waiting pane once per frame however many closed panes sit ahead of it (%i)', + async (count) => { + const fakes = Array.from({ length: count }, fakePane) + let verdicts = 0 + run(fakes, () => { + verdicts++ + return 'wait' + }) + for (const fake of fakes.slice(0, -1)) { + fake.raw.container.isConnected = false + } + await vi.advanceTimersByTimeAsync(16) + expect(verdicts).toBe(1) + } + ) + + it('skips a pane that closed or lost its renderer before its frame', async () => { + const [first, closed, lost] = Array.from({ length: 3 }, fakePane) + run([first, closed, lost]) + closed.raw.container.isConnected = false + lost.raw.webglAddon = null + await vi.advanceTimersByTimeAsync(16 * 4) + expect(attaches.count).toBe(1) + }) +}) diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts index 345b75ebdf69..2d9b4f53fce7 100644 --- a/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-reattach.ts @@ -1,6 +1,18 @@ import type { ManagedPaneInternal } from '../pane-manager-types' import { attachWebgl, clearTerminalWebglAttachBackoff, disposeWebgl } from './pane-webgl-renderer' import { canRetryPaneWebglAfterContextLoss } from './pane-webgl-context-loss-policy' +import { + setTerminalWebglAtlasRebuilder, + takeCoveredDetachedPane, + type DeferredReattachVerdict +} from './terminal-webgl-atlas-memory-rebuild' +import { + isTerminalWebglAtlasRebuildParked, + terminalWebglAtlasInteractionHoldMs, + whenTerminalWebglAtlasRebuildUnparked +} from './terminal-webgl-atlas-rebuild-interaction' +import { isXtermInstanceDisposed } from '../terminal-output/xterm-instance-disposed' +import { paintReplacementCanvasNow } from './terminal-render-pause-release' export function clearPaneWebglContextLossForRetry(pane: ManagedPaneInternal): boolean { if (!pane.webglDisabledAfterContextLoss) { @@ -38,18 +50,151 @@ export function rebuildAttachedWebgl(pane: ManagedPaneInternal): void { reattachDetachedWebgl(pane) } -/** Detaches every renderer and returns the reattach step, so no pane can keep a shared atlas alive. */ -export function detachPanesWebglForRebuild(panes: Iterable): () => void { +/** Gives WebGL back to a pane an atlas rebuild left detached under a chat cover that is now closing. */ +export function restoreWebglAfterChatCover(terminal: ManagedPaneInternal['terminal']): void { + const pane = takeCoveredDetachedPane(terminal) + if ( + pane && + !pane.webglAddon && + !isXtermInstanceDisposed(pane.terminal) && + pane.container.isConnected + ) { + reattachWebglIfNeeded(pane) + } +} + +/** Detaches every renderer; returns those to reattach. */ +function detachPanesWebgl( + panes: Iterable, + shouldReattach?: (pane: ManagedPaneInternal) => boolean +): ManagedPaneInternal[] { const reattach: ManagedPaneInternal[] = [] for (const pane of panes) { if (!pane.webglAddon || pane.webglDisabledAfterContextLoss) { continue } disposeWebgl(pane) - // Retained hidden panes must drop their atlas too; resume reattaches them. - if (!pane.webglAttachmentDeferred) { + // Retained hidden panes must drop their atlas too; resume reattaches them, and panes kept off screen heal on reveal or their next fit. + if (!pane.webglAttachmentDeferred && (shouldReattach?.(pane) ?? true)) { reattach.push(pane) } } + return reattach +} + +/** Detaches every renderer and returns the reattach step, so no pane can keep a shared atlas alive. */ +export function detachPanesWebglForRebuild(panes: Iterable): () => void { + const reattach = detachPanesWebgl(panes) return () => reattach.forEach(reattachDetachedWebgl) } + +// A pane mid synchronized-output frame keeps its old context and goes to the back of the queue; when only waiting panes remain the queue rechecks this often, and drops a pane still waiting after the cap (it keeps its old context). +const SYNC_WAIT_RECHECK_MS = 250 +const SYNC_WAIT_CAP_MS = 10_000 + +// One queue for every rebuild, so overlapping batches still recreate at most one context per frame; weak, so a pane closed while queued is never kept alive. +const rebuildQueue: WeakRef[] = [] +const queuedPanes = new WeakSet() +let queueVerdict: (pane: ManagedPaneInternal) => DeferredReattachVerdict = () => 'skip' +let queueRunning = false +const waitingSince = new WeakMap() + +/** The queue's first pane if it is still live; otherwise drops that entry and returns undefined. */ +function liveQueueHead(): ManagedPaneInternal | undefined { + const pane = rebuildQueue[0]?.deref() + // The pane may have closed, lost its renderer or its DOM since it was queued. + if ( + pane?.webglAddon && + !pane.webglDisabledAfterContextLoss && + pane.container.isConnected && + !isXtermInstanceDisposed(pane.terminal) + ) { + return pane + } + if (pane) { + queuedPanes.delete(pane) + } + rebuildQueue.shift() + return undefined +} + +/** One pane per frame, so no frame pays for more than one context; user input holds the rest, which keep rendering on their old context meanwhile. */ +function runRebuildQueue(): void { + if (isTerminalWebglAtlasRebuildParked()) { + // Hidden or unfocused mid-rebuild: the rest keep their old contexts until the window is back. + whenTerminalWebglAtlasRebuildUnparked(() => requestAnimationFrame(runRebuildQueue)) + return + } + const hold = terminalWebglAtlasInteractionHoldMs() + if (hold > 0) { + setTimeout(() => requestAnimationFrame(runRebuildQueue), hold) + return + } + // Waiting panes rotate to the back, so one stuck frame never blocks the panes behind it. + let recreated = false + // Every entry, dropped or rotated, uses one look, so no pane is checked twice in a frame. + for (let looked = rebuildQueue.length; looked > 0 && rebuildQueue.length > 0; looked--) { + const candidate = liveQueueHead() + if (!candidate) { + continue + } + // Decided on its own frame: a tab revealed or a chat cover closed since the rebuild started gets a new context, not a dropped one. + const verdict = queueVerdict(candidate) + if (verdict !== 'wait') { + recreated = true + rebuildQueue.shift() + queuedPanes.delete(candidate) + waitingSince.delete(candidate) + if (verdict === 'skip') { + // Off screen or chat-covered: drop its context now; reveal, fit, resume or the cover closing gives it a new one. + disposeWebgl(candidate) + } else { + // Dispose and attach in one task, so the pane never shows the DOM renderer. + rebuildAttachedWebgl(candidate) + if (candidate.webglAddon) { + paintReplacementCanvasNow(candidate.terminal) + } + } + break + } + const entry = rebuildQueue.shift() + const since = waitingSince.get(candidate) ?? performance.now() + if (performance.now() - since >= SYNC_WAIT_CAP_MS) { + // A frame that never closes: leave this pane on its old context rather than paint it mid-frame or hold the queue. + queuedPanes.delete(candidate) + waitingSince.delete(candidate) + } else if (entry) { + waitingSince.set(candidate, since) + rebuildQueue.push(entry) + } + } + if (rebuildQueue.length === 0) { + queueRunning = false + return + } + // One context per frame; when every remaining pane is mid-frame, look again a little later. + if (recreated) { + requestAnimationFrame(runRebuildQueue) + } else { + setTimeout(() => requestAnimationFrame(runRebuildQueue), SYNC_WAIT_RECHECK_MS) + } +} + +setTerminalWebglAtlasRebuilder((panes, shouldReattach, verdictOnItsFrame) => { + queueVerdict = verdictOnItsFrame + // Shown panes first; the atlas module already emptied each atlas in place, so every recreated context joins a small one. + const steps = panes + .filter((pane) => pane.webglAddon && !pane.webglDisabledAfterContextLoss) + .sort((a, b) => Number(shouldReattach(b)) - Number(shouldReattach(a))) + for (const pane of steps) { + if (!queuedPanes.has(pane)) { + queuedPanes.add(pane) + rebuildQueue.push(new WeakRef(pane)) + } + } + if (!queueRunning) { + queueRunning = true + // Starts on a frame of its own, so the first step never shares one with the second. + requestAnimationFrame(runRebuildQueue) + } +}) diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts index 9b9f90df4eb3..026e34d866a0 100644 --- a/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/pane-webgl-renderer.ts @@ -27,6 +27,12 @@ import { setTerminalWebglAddonLoadHandlers } from './terminal-webgl-addon-loader' import { watchTerminalSymbolsFontLoad } from './terminal-symbols-font' +import { + handleTerminalWebglAtlasPage, + noteTerminalWebglAtlasChange, + trackTerminalWebglAtlasPane, + untrackTerminalWebglAtlasPane +} from './terminal-webgl-atlas-memory-rebuild' export const ENABLE_WEBGL_RENDERER = true let suggestedRendererType: 'dom' | undefined @@ -118,6 +124,7 @@ export function disposeWebgl( ): void { cancelPendingWebglRefresh(pane) panesAwaitingWebglAddon.delete(pane) + untrackTerminalWebglAtlasPane(pane) if (!pane.webglAddon) { return } @@ -276,8 +283,11 @@ export function attachWebgl(pane: ManagedPaneInternal): void { pane.webglDisabledAfterContextLoss = true disposeWebgl(pane, { refreshDimensions: true }) }) + addon.onAddTextureAtlasCanvas((page) => handleTerminalWebglAtlasPage(page, pane)) + addon.onChangeTextureAtlas(() => noteTerminalWebglAtlasChange(pane)) pane.terminal.loadAddon(addon) pane.webglAddon = addon + trackTerminalWebglAtlasPane(pane) const canvas = getXtermWebglCanvas(addon) if (canvas) { // Why: panes of a hidden worktree surface keep their backing so switching worktrees never pays a reallocation. @@ -295,6 +305,7 @@ export function attachWebgl(pane: ManagedPaneInternal): void { } pane.webglAttachFailedSinceRecovery = true console.warn('[terminal] WebGL unavailable for pane', pane.id, '— using DOM renderer:', err) + untrackTerminalWebglAtlasPane(pane) try { webglAddon?.dispose() } catch {} diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-render-pause-release.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-render-pause-release.ts index 8c015ae2fd98..ce5978f9ddf2 100644 --- a/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-render-pause-release.ts +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-render-pause-release.ts @@ -9,6 +9,7 @@ type MaybePausableRenderService = { _needsFullRefresh?: boolean _pausedResizeTask?: { flush?: () => void } | null refreshRows?: (start: number, end: number, sync?: boolean) => void + _renderDebouncer?: { _rowStart?: number; _rowEnd?: number } _renderer?: { value?: MaybeWebglRenderer | null } | MaybeWebglRenderer | null } @@ -150,6 +151,31 @@ export function isSynchronizedOutputHeld(terminal: unknown): boolean { ) } +/** Paints an unpaused viewport now: a replacement canvas is blank until it paints, and a DEC 2026 frame parsed before a scheduled paint would hold it blank until the frame closes. */ +export function paintReplacementCanvasNow(terminal: unknown): void { + const service = getRenderService(terminal) + const rows = (terminal as TerminalWithRenderService | null)?.rows + if (!service || service._isPaused === true || typeof rows !== 'number' || rows < 1) { + return + } + // This paint covers the full refresh attach queued; drop it first so the next frame repaints only what the paint itself requests (selection restore, later output). + const debouncer = service._renderDebouncer + const queued = debouncer && { start: debouncer._rowStart, end: debouncer._rowEnd } + if (debouncer) { + debouncer._rowStart = undefined + debouncer._rowEnd = undefined + } + try { + service.refreshRows(0, rows - 1, true) + } catch { + // A pane disposed mid-rebuild keeps its scheduled refresh. + if (debouncer && queued) { + debouncer._rowStart = queued.start + debouncer._rowEnd = queued.end + } + } +} + /** A new or resized WebGL canvas holds no frame to keep, so DEC 2026 must not leave it blank until the frame closes. A paused one paints on its reveal present instead. */ export function presentEmptiedCanvas(terminal: unknown): boolean { const service = getRenderService(terminal) diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.performance.test.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.performance.test.ts new file mode 100644 index 000000000000..b48a80c88ab3 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.performance.test.ts @@ -0,0 +1,384 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ManagedPaneInternal } from '../pane-manager-types' +import type * as AtlasMemoryRebuild from './terminal-webgl-atlas-memory-rebuild' + +// Guards #43465: atlas-memory rebuilds need PTY output into the grown atlas, wait for it and user input to pause, stay ≥60 s apart and only touch that atlas's panes. +const QUIET = 2_000 +const INTERVAL = 60_000 +const MAC_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Electron' +const LARGE_PAGE = { width: 4096 } + +const rebuilds: ManagedPaneInternal[][] = [] +const reattached: ManagedPaneInternal[][] = [] +const visibleContainers = new Set() +const visibilityScans = { count: 0 } +vi.mock('../pane-manager-registry', () => ({ + isElementInVisiblePaneManager: (element: unknown) => { + visibilityScans.count++ + return visibleContainers.has(element) + } +})) + +type AtlasModule = typeof AtlasMemoryRebuild + +type FakeAtlas = { readonly pages: unknown[]; clears: number; clearTexture: () => void } +const newAtlas = (): FakeAtlas => { + const atlas = { + pages: [], + clears: 0, + clearTexture: () => { + atlas.clears++ + } + } + return atlas +} + +function fakePane( + atlasModule: AtlasModule, + atlas: FakeAtlas, + visible = true, + displayed = true, + covered = false +) { + const terminal = { modes: { synchronizedOutputMode: false } } + const container = { + getClientRects: () => (displayed ? [{}] : []), + querySelector: () => (covered ? {} : null) + } + if (visible) { + visibleContainers.add(container) + } + const renderer = { _charAtlas: atlas } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the module reads only terminal modes, container rects, chat cover and the addon's atlas identity, all supplied here. + const pane = { + terminal, + container, + webglAddon: { _renderer: renderer } + } as unknown as ManagedPaneInternal + atlasModule.trackTerminalWebglAtlasPane(pane) + return { + pane, + terminal, + renderer, + output: () => atlasModule.noteTerminalWebglAtlasOutput(pane.terminal) + } +} + +async function loadModule(navigatorStub: { userAgent: string; maxTouchPoints?: number }) { + vi.resetModules() + vi.stubGlobal('navigator', navigatorStub) + const atlas = await import('./terminal-webgl-atlas-memory-rebuild') + const interaction = await import('./terminal-webgl-atlas-rebuild-interaction') + atlas.setTerminalWebglAtlasRebuilder((panes, shouldReattach) => { + rebuilds.push(panes) + reattached.push(panes.filter(shouldReattach)) + }) + return { ...atlas, ...interaction } +} + +describe('terminal WebGL atlas-memory rebuild', () => { + beforeEach(() => { + vi.useFakeTimers() + rebuilds.length = 0 + reattached.length = 0 + visibleContainers.clear() + visibilityScans.count = 0 + }) + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('never rebuilds an atlas that grew without PTY output into it', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const { pane } = fakePane(atlas, newAtlas()) + for (let i = 0; i < 20; i++) { + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, pane) + await vi.advanceTimersByTimeAsync(60_000) + } + expect(rebuilds).toHaveLength(0) + }) + + it('counts output that arrives before or after the large page', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const first = fakePane(atlas, newAtlas()) + first.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, first.pane) + await vi.advanceTimersByTimeAsync(QUIET) + const second = fakePane(atlas, newAtlas()) + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, second.pane) + second.output() + await vi.advanceTimersByTimeAsync(INTERVAL) + expect(rebuilds).toEqual([[first.pane], [second.pane]]) + }) + + it('waits for output into the atlas to pause', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const busy = fakePane(atlas, newAtlas()) + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, busy.pane) + for (let i = 0; i < 20; i++) { + busy.output() + await vi.advanceTimersByTimeAsync(500) + } + expect(rebuilds).toHaveLength(0) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[busy.pane]]) + }) + + it('holds the rebuild while the user types or interacts', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const busy = fakePane(atlas, newAtlas()) + busy.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, busy.pane) + for (let i = 0; i < 180; i++) { + atlas.noteTerminalWebglAtlasTyping() + await vi.advanceTimersByTimeAsync(500) + } + expect(rebuilds).toHaveLength(0) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[busy.pane]]) + }) + + it('never rebuilds while output into the atlas never pauses, with one pending timer at most', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const busy = fakePane(atlas, newAtlas()) + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, busy.pane) + for (let i = 0; i < 3_000; i++) { + busy.output() + await vi.advanceTimersByTimeAsync(100) + } + expect(rebuilds).toHaveLength(0) + expect(vi.getTimerCount()).toBeLessThanOrEqual(1) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[busy.pane]]) + }) + + it('rebuilds only the panes that share the grown atlas, re-armed only by their own output', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const grown = newAtlas() + const a = fakePane(atlas, grown) + const b = fakePane(atlas, grown, false) + const other = fakePane(atlas, newAtlas()) + a.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, a.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[a.pane, b.pane]]) + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, a.pane) + for (let i = 0; i < 6; i++) { + other.output() + await vi.advanceTimersByTimeAsync(INTERVAL) + } + expect(rebuilds).toHaveLength(1) + }) + + it('rebuilds a quiet pane that switched onto the grown atlas', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const grown = newAtlas() + const busy = fakePane(atlas, grown) + const quiet = fakePane(atlas, newAtlas()) + // A font zoom moves the quiet pane onto the grown atlas after its large page, with no output. + atlas.noteTerminalWebglAtlasChange(quiet.pane) + // xterm assigns the new atlas after firing the change event. + quiet.renderer._charAtlas = grown + busy.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, busy.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[busy.pane, quiet.pane]]) + }) + + it('waits for an on-screen synchronized-output frame to close, looking again every 250 ms', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const visible = fakePane(atlas, newAtlas()) + visible.terminal.modes.synchronizedOutputMode = true + visible.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, visible.pane) + await vi.advanceTimersByTimeAsync(QUIET + 1_000) + expect(rebuilds).toHaveLength(0) + visible.terminal.modes.synchronizedOutputMode = false + await vi.advanceTimersByTimeAsync(250) + expect(rebuilds).toEqual([[visible.pane]]) + }) + + it('gives up on a frame held open past the watchdog until output into the atlas re-arms it', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const visible = fakePane(atlas, newAtlas()) + visible.terminal.modes.synchronizedOutputMode = true + visible.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, visible.pane) + await vi.advanceTimersByTimeAsync(QUIET + 10 * INTERVAL) + expect(rebuilds).toHaveLength(0) + // Nine looks (eight 250 ms retries, then the give-up), then nothing stays scheduled. + expect(visibilityScans.count).toBeLessThanOrEqual(9) + expect(vi.getTimerCount()).toBe(0) + visible.terminal.modes.synchronizedOutputMode = false + visible.output() + await vi.advanceTimersByTimeAsync(INTERVAL) + expect(rebuilds).toEqual([[visible.pane]]) + }) + + it('visits only the due atlas owners on each attempt, however many terminals are attached', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const atlasReads = { count: 0 } + for (let i = 0; i < 300; i++) { + const { pane } = fakePane(atlas, newAtlas()) + const addon = pane.webglAddon + Object.defineProperty(pane, 'webglAddon', { + get: () => { + atlasReads.count++ + return addon + } + }) + } + const visible = fakePane(atlas, newAtlas()) + visible.terminal.modes.synchronizedOutputMode = true + visible.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, visible.pane) + await vi.advanceTimersByTimeAsync(QUIET + 3 * INTERVAL) + expect(rebuilds).toHaveLength(0) + expect(atlasReads.count).toBe(0) + }) + + it('ignores a hidden pane mid synchronized-output frame', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const hidden = fakePane(atlas, newAtlas(), false) + hidden.terminal.modes.synchronizedOutputMode = true + hidden.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, hidden.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[hidden.pane]]) + }) + + it('reattaches only panes on screen', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const grown = newAtlas() + const shown = fakePane(atlas, grown) + const hiddenTab = fakePane(atlas, grown, false) + const expandedSibling = fakePane(atlas, grown, true, false) + expandedSibling.terminal.modes.synchronizedOutputMode = true + shown.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, shown.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[shown.pane, hiddenTab.pane, expandedSibling.pane]]) + expect(reattached).toEqual([[shown.pane]]) + }) + + it('leaves a chat-covered pane detached until its cover closes', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const grown = newAtlas() + const shown = fakePane(atlas, grown) + const covered = fakePane(atlas, grown, true, true, true) + covered.terminal.modes.synchronizedOutputMode = true + shown.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, shown.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[shown.pane, covered.pane]]) + expect(reattached).toEqual([[shown.pane]]) + expect(atlas.takeCoveredDetachedPane(covered.pane.terminal)).toBe(covered.pane) + expect(atlas.takeCoveredDetachedPane(covered.pane.terminal)).toBeUndefined() + }) + + it('rebuilds nothing while the window is hidden, and goes ahead once it is shown', async () => { + const parkVisibility = { visible: false, listeners: new Set<() => void>() } + vi.doMock('../../window-activity/window-park-visibility', () => ({ + getWindowParkVisible: () => parkVisibility.visible, + subscribeWindowParkVisibility: (onChange: () => void) => { + parkVisibility.listeners.add(onChange) + return () => parkVisibility.listeners.delete(onChange) + } + })) + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const shown = fakePane(atlas, newAtlas()) + shown.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, shown.pane) + await vi.advanceTimersByTimeAsync(QUIET + 8 * INTERVAL) + expect(rebuilds).toHaveLength(0) + // Hidden and idle: nothing polls. + expect(vi.getTimerCount()).toBe(0) + parkVisibility.visible = true + parkVisibility.listeners.forEach((listener) => listener()) + // Coming back counts as interaction, so the 2 s quiet starts then. + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[shown.pane]]) + vi.doUnmock('../../window-activity/window-park-visibility') + }) + + it('parks while focus is inside an embedded browser page, and goes ahead once focus is back on the host page', async () => { + const focusin = new Set<() => void>() + const activeElement = { tagName: 'WEBVIEW' } + vi.stubGlobal('document', { hasFocus: () => true, activeElement }) + vi.stubGlobal('window', { + addEventListener: (type: string, listener: () => void) => { + if (type === 'focusin') { + focusin.add(listener) + } + }, + removeEventListener: (_type: string, listener: () => void) => focusin.delete(listener) + }) + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const shown = fakePane(atlas, newAtlas()) + shown.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, shown.pane) + await vi.advanceTimersByTimeAsync(QUIET + 2 * INTERVAL) + expect(rebuilds).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + activeElement.tagName = 'DIV' + focusin.forEach((listener) => listener()) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[shown.pane]]) + }) + + it('does not strand an atlas that came due while the rebuild queue was parked', async () => { + const parkVisibility = { visible: false, listeners: new Set<() => void>() } + vi.doMock('../../window-activity/window-park-visibility', () => ({ + getWindowParkVisible: () => parkVisibility.visible, + subscribeWindowParkVisibility: (onChange: () => void) => { + parkVisibility.listeners.add(onChange) + return () => parkVisibility.listeners.delete(onChange) + } + })) + const atlas = await loadModule({ userAgent: MAC_AGENT }) + // The queue of an earlier rebuild parks first. + atlas.whenTerminalWebglAtlasRebuildUnparked(() => {}) + const late = fakePane(atlas, newAtlas()) + late.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, late.pane) + parkVisibility.visible = true + parkVisibility.listeners.forEach((listener) => listener()) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[late.pane]]) + vi.doUnmock('../../window-activity/window-park-visibility') + }) + + it('empties each due atlas in place before its owners are recreated', async () => { + const atlas = await loadModule({ userAgent: MAC_AGENT }) + const first = newAtlas() + const second = newAtlas() + const a = fakePane(atlas, first) + const b = fakePane(atlas, second) + a.output() + b.output() + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, a.pane) + atlas.handleTerminalWebglAtlasPage(LARGE_PAGE, b.pane) + await vi.advanceTimersByTimeAsync(QUIET) + expect(rebuilds).toEqual([[a.pane, b.pane]]) + expect([first.clears, second.clears]).toEqual([1, 1]) + }) + + it('ignores other page sizes, touch Apple devices and other platforms', async () => { + const mac = await loadModule({ userAgent: MAC_AGENT }) + const macPane = fakePane(mac, newAtlas()) + macPane.output() + mac.handleTerminalWebglAtlasPage({ width: 2048 }, macPane.pane) + mac.handleTerminalWebglAtlasPage({ width: 16384 }, macPane.pane) + const ipad = await loadModule({ userAgent: MAC_AGENT, maxTouchPoints: 5 }) + const ipadPane = fakePane(ipad, newAtlas()) + ipadPane.output() + ipad.handleTerminalWebglAtlasPage(LARGE_PAGE, ipadPane.pane) + const windows = await loadModule({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' }) + const windowsPane = fakePane(windows, newAtlas()) + windowsPane.output() + windows.handleTerminalWebglAtlasPage(LARGE_PAGE, windowsPane.pane) + await vi.advanceTimersByTimeAsync(60_000) + expect(rebuilds).toHaveLength(0) + }) +}) diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.ts new file mode 100644 index 000000000000..a12ff93edb75 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-memory-rebuild.ts @@ -0,0 +1,320 @@ +import type { ManagedPaneInternal } from '../pane-manager-types' +import type { ForegroundTerminalOutputTarget } from '../terminal-output/pane-terminal-foreground-render-settle' +import { recordTerminalWebglDiagnostic } from '../../../../../shared/terminal/diagnostics/terminal-webgl-diagnostics' +import { isElementInVisiblePaneManager } from '../pane-manager-registry' +import { getWindowParkVisible } from '../../window-activity/window-park-visibility' +import { + isTerminalWebglAtlasRebuildParked, + rebuildingTerminalWebglAtlasParkWatch, + terminalWebglAtlasInteractionEndsAt, + whenTerminalWebglAtlasRebuildUnparked +} from './terminal-webgl-atlas-rebuild-interaction' +import { paneIsCoveredByNativeChat } from '@/components/terminal-pane/chat/native-chat-covered-pane' + +// A 4096² merged page means the shared atlas reached ~64 MiB; on Apple GPUs each context keeps its upload memory until the context is destroyed (GiBs across panes). +const ATLAS_REBUILD_PAGE_SIZE = 4096 +const ATLAS_REBUILD_MIN_INTERVAL_MS = 60_000 +// A rebuild recreates its atlas's contexts one per frame, so it waits for output into that atlas to pause and for user input to stop; output that never pauses keeps the memory, as before this change. +const ATLAS_REBUILD_QUIET_MS = 2_000 +// A quiet atlas blocked by an on-screen synchronized-output frame looks again this soon; xterm's watchdog closes a frame within a second. +const ATLAS_REBUILD_FRAME_RETRY_MS = 250 +const ATLAS_REBUILD_MAX_FRAME_RETRIES = 8 +// Only macOS was measured retaining it (desktop app and Mac browsers); elsewhere a mass context recreate risks the driver's context budget. Touch excludes iPadOS desktop-mode agents. +const ATLAS_MEMORY_REBUILD_ENABLED = + typeof navigator !== 'undefined' && + navigator.userAgent.includes('Macintosh') && + !(navigator.maxTouchPoints > 0) + +// xterm's shared TextureAtlas, read from the addon's private renderer: its identity, and clearTexture to empty it in place. +type GlyphAtlas = { readonly pages: readonly unknown[]; clearTexture?: () => void } +type PaneFilter = (pane: ManagedPaneInternal) => boolean +/** Rechecked on each pane's own frame: 'skip' leaves it detached until reveal, 'wait' holds it a frame. */ +export type DeferredReattachVerdict = 'now' | 'wait' | 'skip' +type AtlasRebuilder = ( + panes: ManagedPaneInternal[], + shouldReattach: PaneFilter, + verdictOnItsFrame: (pane: ManagedPaneInternal) => DeferredReattachVerdict +) => void + +let rebuildPanes: AtlasRebuilder | null = null +let rebuildTimer: ReturnType | null = null +// Successful or deferred, attempts stay an interval apart so per-chunk output can't drive repeated scans. +let lastAttemptAt = Number.NEGATIVE_INFINITY +// Per atlas, so one atlas's output never re-arms another; weak so a retired atlas is never kept alive. +const atlasesWithLargePage = new WeakSet() +const atlasesWithOutput = new WeakSet() +const lastOutputAt = new WeakMap() +const frameRetryAt = new WeakMap() +const frameRetries = new WeakMap() +const attachedPanes = new Map() +// Owners indexed per atlas, so an attempt visits only the due atlases' panes, never every terminal. +const atlasOwners = new WeakMap>() +const paneAtlases = new WeakMap() +// Strong only until rebuilt or ownerless. +const dueAtlases = new Set() +// Chat-covered panes a rebuild left detached; the cover's unmount gives them WebGL back. +const coveredDetachedPanes = new WeakMap() + +function atlasOf(pane: ManagedPaneInternal): GlyphAtlas | undefined { + const addon = pane.webglAddon + if (!addon || !('_renderer' in addon)) { + return undefined + } + const renderer = addon._renderer + if (typeof renderer !== 'object' || renderer === null || !('_charAtlas' in renderer)) { + return undefined + } + return isGlyphAtlas(renderer._charAtlas) ? renderer._charAtlas : undefined +} + +function isGlyphAtlas(value: unknown): value is GlyphAtlas { + return ( + typeof value === 'object' && value !== null && 'pages' in value && Array.isArray(value.pages) + ) +} + +function forgetOwner(pane: ManagedPaneInternal): void { + const previous = paneAtlases.get(pane) + if (!previous) { + return + } + paneAtlases.delete(pane) + const owners = atlasOwners.get(previous) + owners?.delete(pane) + if (!owners?.size) { + forgetDue(previous) + } +} + +/** Files the pane under its current atlas; xterm swaps atlases on font or theme changes. */ +function indexOwner(pane: ManagedPaneInternal): GlyphAtlas | undefined { + const atlas = atlasOf(pane) + if (paneAtlases.get(pane) === atlas) { + return atlas + } + forgetOwner(pane) + if (!atlas) { + return undefined + } + paneAtlases.set(pane, atlas) + const owners = atlasOwners.get(atlas) + if (owners) { + owners.add(pane) + } else { + atlasOwners.set(atlas, new Set([pane])) + } + return atlas +} + +function markIfDue(atlas: GlyphAtlas): void { + if (atlasesWithLargePage.has(atlas) && atlasesWithOutput.has(atlas)) { + dueAtlases.add(atlas) + scheduleRebuild() + } +} + +/** When the atlas may rebuild: its output paused and user input stopped. */ +function readyAt(atlas: GlyphAtlas): number { + const quiet = (lastOutputAt.get(atlas) ?? Number.NEGATIVE_INFINITY) + ATLAS_REBUILD_QUIET_MS + const frameRetry = frameRetryAt.get(atlas) ?? Number.NEGATIVE_INFINITY + return Math.max(terminalWebglAtlasInteractionEndsAt(), quiet, frameRetry) +} + +function forgetDue(atlas: GlyphAtlas): void { + dueAtlases.delete(atlas) + frameRetryAt.delete(atlas) + frameRetries.delete(atlas) +} + +/** Wired by the reattach module, which owns detaching and reattaching pane renderers. */ +export function setTerminalWebglAtlasRebuilder(rebuilder: AtlasRebuilder): void { + rebuildPanes = rebuilder +} + +/** Shown: window shown, tab shown, and the pane laid out (not an expanded split's hidden sibling). */ +function shownPaneFilter(): PaneFilter { + if (!getWindowParkVisible()) { + return () => false + } + return (pane) => + isElementInVisiblePaneManager(pane.container) && pane.container.getClientRects().length > 0 +} + +/** A pane hidden, covered or mid synchronized-output frame since the rebuild must not get its context yet. */ +function deferredReattachVerdict(pane: ManagedPaneInternal): DeferredReattachVerdict { + if (!shownPaneFilter()(pane)) { + return 'skip' + } + if (paneIsCoveredByNativeChat(pane)) { + coveredDetachedPanes.set(pane.terminal, pane) + return 'skip' + } + return pane.terminal.modes.synchronizedOutputMode ? 'wait' : 'now' +} + +function rebuildDueAtlases(): void { + rebuildTimer = null + if (dueAtlases.size === 0) { + return + } + if (isTerminalWebglAtlasRebuildParked()) { + // Hidden or unfocused: sleep until the window is shown and focused, instead of dropping contexts or polling on output. + whenTerminalWebglAtlasRebuildUnparked(scheduleRebuild) + return + } + const now = performance.now() + const ready = [...dueAtlases].filter((atlas) => readyAt(atlas) <= now) + if (ready.length === 0) { + scheduleRebuild() + return + } + const shown = shownPaneFilter() + const onScreen: PaneFilter = (pane) => shown(pane) && !paneIsCoveredByNativeChat(pane) + const panes: ManagedPaneInternal[] = [] + let retry = false + let attempted = false + for (const atlas of ready) { + const atlasPanes = [...(atlasOwners.get(atlas) ?? [])].filter( + (pane) => attachedPanes.get(pane.terminal) === pane && atlasOf(pane) === atlas + ) + // A new canvas paints straight from the buffer, so an on-screen pane mid synchronized-output (DEC 2026) frame would show it half drawn; that atlas waits for the frame to close. + if (atlasPanes.some((pane) => onScreen(pane) && pane.terminal.modes.synchronizedOutputMode)) { + retry = true + const retries = frameRetries.get(atlas) ?? 0 + if (retries < ATLAS_REBUILD_MAX_FRAME_RETRIES) { + frameRetries.set(atlas, retries + 1) + frameRetryAt.set(atlas, now + ATLAS_REBUILD_FRAME_RETRY_MS) + } else { + // A frame held open past xterm's watchdog: give up until output into this atlas (such as the frame closing) re-arms it, so a stuck frame never keeps an idle renderer waking. + forgetDue(atlas) + atlasesWithOutput.delete(atlas) + attempted = true + } + continue + } + attempted = true + // Emptied in place, so every recreated context joins a small atlas; destroying each old context frees what it retained. It rebuilds again only after a new large page and new output. + atlas.clearTexture?.() + forgetDue(atlas) + atlasesWithLargePage.delete(atlas) + atlasesWithOutput.delete(atlas) + panes.push(...atlasPanes) + } + if (attempted) { + lastAttemptAt = now + } + if (retry || dueAtlases.size > 0) { + scheduleRebuild() + } + if (panes.length === 0) { + return + } + // Decided before any detach: detaching changes layout, and reading rects afterwards forces one layout per pane. + const reattach = new Set() + for (const pane of panes) { + if (!shown(pane)) { + continue + } + if (paneIsCoveredByNativeChat(pane)) { + coveredDetachedPanes.set(pane.terminal, pane) + } else { + reattach.add(pane) + } + } + // Every owner of a due atlas detaches before any reattaches, or a remaining owner keeps it alive; only on-screen owners reattach now. + const startedAt = performance.now() + rebuildPanes?.(panes, (pane) => reattach.has(pane), deferredReattachVerdict) + recordTerminalWebglDiagnostic('webgl-renderer-rebuild', { + panes: panes.length, + reattached: reattach.size, + reason: 'atlas-memory', + durationMs: Math.round(performance.now() - startedAt) + }) +} + +function scheduleRebuild(): void { + if (rebuildTimer !== null) { + return + } + // Parked (by this scheduler or the queue): output must not restart the timer; the window coming back does. + if (rebuildingTerminalWebglAtlasParkWatch()) { + whenTerminalWebglAtlasRebuildUnparked(scheduleRebuild) + return + } + // One timer, set to the earliest due atlas; output arriving later just moves that atlas's time, checked when the timer fires. + let at = Number.POSITIVE_INFINITY + for (const atlas of dueAtlases) { + at = Math.min(at, readyAt(atlas)) + } + // Also leaves xterm's atlas callback first; the rebuild disposes renderers mid-render. + const delay = Math.max( + 0, + lastAttemptAt + ATLAS_REBUILD_MIN_INTERVAL_MS - performance.now(), + at - performance.now() + ) + rebuildTimer = setTimeout(rebuildDueAtlases, delay) +} + +/** Tracks an attached WebGL pane for the renderer's lifetime. */ +export function trackTerminalWebglAtlasPane(pane: ManagedPaneInternal): void { + coveredDetachedPanes.delete(pane.terminal) + if (ATLAS_MEMORY_REBUILD_ENABLED) { + attachedPanes.set(pane.terminal, pane) + indexOwner(pane) + } +} + +/** The pane a rebuild left detached under this chat cover, if it is still shown and should get WebGL back now. */ +export function takeCoveredDetachedPane( + terminal: ManagedPaneInternal['terminal'] +): ManagedPaneInternal | undefined { + const pane = coveredDetachedPanes.get(terminal) + coveredDetachedPanes.delete(terminal) + return pane && shownPaneFilter()(pane) ? pane : undefined +} + +/** Forgets a detached pane so a closed pane is not kept alive. */ +export function untrackTerminalWebglAtlasPane(pane: ManagedPaneInternal): void { + attachedPanes.delete(pane.terminal) + forgetOwner(pane) +} + +/** Re-files a pane whose renderer swapped atlases (font, zoom or theme change), so a rebuild reaches every owner. */ +export function noteTerminalWebglAtlasChange(pane: ManagedPaneInternal): void { + // xterm fires this before it assigns the new atlas. + queueMicrotask(() => { + if (attachedPanes.get(pane.terminal) === pane) { + indexOwner(pane) + } + }) +} + +/** Marks PTY output for the pane's atlas; repaints, warm-up, reveals and empty parse barriers never come through here. */ +export function noteTerminalWebglAtlasOutput(terminal: ForegroundTerminalOutputTarget): void { + const pane = attachedPanes.get(terminal) + const atlas = pane ? indexOwner(pane) : undefined + if (!atlas) { + return + } + atlasesWithOutput.add(atlas) + lastOutputAt.set(atlas, performance.now()) + markIfDue(atlas) +} + +/** Requests a rebuild of the grown atlas's renderers, at most every 60 s, only after PTY output into that atlas, once it and user input pause. */ +export function handleTerminalWebglAtlasPage( + page: { width: number }, + pane: ManagedPaneInternal +): void { + if (!ATLAS_MEMORY_REBUILD_ENABLED || attachedPanes.get(pane.terminal) !== pane) { + return + } + // xterm forwards every page event to each renderer sharing the atlas, so this also completes the owner index. + const atlas = indexOwner(pane) + // Exact match: the larger oversized-glyph page comes back as soon as its glyph redraws, so a rebuild can't free it. + if (!atlas || page.width !== ATLAS_REBUILD_PAGE_SIZE) { + return + } + atlasesWithLargePage.add(atlas) + markIfDue(atlas) +} diff --git a/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction.ts b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction.ts new file mode 100644 index 000000000000..63a28139dc2d --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction.ts @@ -0,0 +1,108 @@ +import { + getWindowParkVisible, + subscribeWindowParkVisibility +} from '../../window-activity/window-park-visibility' + +// Atlas rebuilds stay out of the user's way: any input holds them this long, and they run only while the window is shown and focused. +const INTERACTION_QUIET_MS = 2_000 +let lastInteractionAt = Number.NEGATIVE_INFINITY + +/** User input (typing, pastes, clicks, scrolls); holds atlas rebuilds and their remaining per-frame steps. */ +export function noteTerminalWebglAtlasTyping(): void { + lastInteractionAt = performance.now() +} + +/** When user input stops holding atlas rebuilds. */ +export function terminalWebglAtlasInteractionEndsAt(): number { + return lastInteractionAt + INTERACTION_QUIET_MS +} + +/** How long a rebuild's remaining per-frame steps must still wait for user input to stop (0 when clear). */ +export function terminalWebglAtlasInteractionHoldMs(): number { + return Math.max(0, terminalWebglAtlasInteractionEndsAt() - performance.now()) +} + +// Clicks, wheel scrolls, keys and focus changes anywhere in the window (tab switches, scrolling, the chat composer, coming back to the window) count as input too, and so do clicks into an embedded browser page, which main reports, and the window being shown again. +if ( + typeof navigator !== 'undefined' && + navigator.userAgent.includes('Macintosh') && + !(navigator.maxTouchPoints > 0) && + typeof window !== 'undefined' && + window.addEventListener +) { + for (const type of ['pointerdown', 'wheel', 'keydown', 'focus'] as const) { + window.addEventListener(type, noteTerminalWebglAtlasTyping, { capture: true, passive: true }) + } + // A held pointer (text selection, divider drag) keeps counting while it moves. + window.addEventListener( + 'pointermove', + (event) => { + if (event.buttons !== 0) { + noteTerminalWebglAtlasTyping() + } + }, + { capture: true, passive: true } + ) + window.api?.ui?.onBrowserPagePointerDown?.(noteTerminalWebglAtlasTyping) + subscribeWindowParkVisibility(noteTerminalWebglAtlasTyping) +} + +// Rebuilds run only while the window is shown and the host page has focus: keys and wheel inside an embedded browser page (a ) or another app never reach this document, so focus there counts as the user being busy. +const unparkCallbacks = new Set<() => void>() +let stopWatchingWindow: (() => void) | null = null + +function focusIsInEmbeddedPage(): boolean { + const tag = document.activeElement?.tagName + return tag === 'WEBVIEW' || tag === 'IFRAME' +} + +/** True while the window is hidden, another app has focus, or focus is inside an embedded browser page. */ +export function isTerminalWebglAtlasRebuildParked(): boolean { + if (!getWindowParkVisible()) { + return true + } + if (typeof document === 'undefined' || typeof document.hasFocus !== 'function') { + return false + } + return !document.hasFocus() || focusIsInEmbeddedPage() +} + +/** Runs the callback once the window is shown and focused again; one shared watcher, no polling. */ +export function whenTerminalWebglAtlasRebuildUnparked(callback: () => void): void { + unparkCallbacks.add(callback) + if (stopWatchingWindow) { + return + } + const check = (): void => { + if (isTerminalWebglAtlasRebuildParked() || !stopWatchingWindow) { + return + } + stopWatchingWindow() + stopWatchingWindow = null + const callbacks = [...unparkCallbacks] + unparkCallbacks.clear() + for (const resume of callbacks) { + resume() + } + } + const stopVisibility = subscribeWindowParkVisibility(check) + const canListenToFocus = + typeof window !== 'undefined' && typeof window.addEventListener === 'function' + // focusin: focus leaving a browser page for the host page fires no window focus event. + if (canListenToFocus) { + window.addEventListener('focus', check) + window.addEventListener('focusin', check, true) + } + stopWatchingWindow = () => { + stopVisibility() + if (canListenToFocus) { + window.removeEventListener('focus', check) + window.removeEventListener('focusin', check, true) + } + } +} + +/** True while a parked rebuild is waiting for the window, so output can't restart its timer. */ +export function rebuildingTerminalWebglAtlasParkWatch(): boolean { + return stopWatchingWindow !== null +} diff --git a/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-input-send.ts b/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-input-send.ts index a04947cfaf5b..0ec83645de54 100644 --- a/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-input-send.ts +++ b/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-input-send.ts @@ -3,6 +3,7 @@ import { recordRuntimeTerminalInputForPtyId } from './runtime-terminal-input-rec import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' import { getRemoteRuntimePtyOwner } from '../identity/remote-runtime-pty-owner' import type { TerminalInputKind } from '../../../../../shared/terminal/input/terminal-input-kind' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' import type { RuntimeTerminalSend } from '../../../../../shared/terminal/runtime/runtime-terminal-send-contract' const DESKTOP_RUNTIME_CLIENT = { id: 'orca-desktop', type: 'desktop' } as const @@ -16,6 +17,10 @@ export function sendRuntimePtyInput( if (tooLarge === true) { return false } + if (inputKind === 'driving') { + // Native chat controls and other runtime writes are user input too; they hold atlas rebuilds like typing. + noteTerminalWebglAtlasTyping() + } if (tooLarge !== false) { // Yield before validating/dispatching fire-and-forget paste-sized input to avoid blocking renderer. void tooLarge diff --git a/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-verified-input.ts b/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-verified-input.ts index 988f1b0ad466..9f95724d6f61 100644 --- a/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-verified-input.ts +++ b/src/renderer/src/runtime/hosted-terminals/input/runtime-terminal-verified-input.ts @@ -1,5 +1,6 @@ import type { RuntimeTerminalSend } from '../../../../../shared/terminal/runtime/runtime-terminal-send-contract' import type { TerminalInputKind } from '../../../../../shared/terminal/input/terminal-input-kind' +import { noteTerminalWebglAtlasTyping } from '@/lib/pane-manager/terminal-rendering/terminal-webgl-atlas-rebuild-interaction' import { isTerminalInputTooLargeWithDeferredMeasurement } from '../../../../../shared/terminal/input/terminal-input' import { readTerminalSendAcknowledgment } from '../../../../../shared/terminal/pty/lifecycle/terminal-send-acknowledgment' import { classifyTerminalProcessInspectionFailure } from '../../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' @@ -23,6 +24,10 @@ export async function sendRuntimePtyInputVerified( if (typeof tooLarge === 'boolean' ? tooLarge : await tooLarge) { return false } + if (inputKind === 'driving') { + // Native chat controls and other runtime writes are user input too; they hold atlas rebuilds like typing. + noteTerminalWebglAtlasTyping() + } const owner = getRemoteRuntimePtyOwner(ptyId) if (!owner) { if (options?.requireWriteSettlement) {