TypeScript
perf(web): stop rendering hidden terminals (#9718)
Theo Browne5eab021a5185
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex c8c89131773..368e43d5e06 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1154,6 +1154,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra});interface PersistentThreadTerminalPanelProps {+ visible: boolean;threadRef: ScopedThreadRef;surface: Extract<RightPanelSurface, { kind: "terminal" }>;launchContext: PersistentTerminalLaunchContext | null;@@ -1172,6 +1173,7 @@ interface PersistentThreadTerminalPanelProps {}const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({+ visible,threadRef,surface,launchContext,@@ -1287,6 +1289,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanereturn (<ThreadTerminalDrawermode="panel"+ visible={visible}threadRef={threadRef}threadId={threadRef.threadId}cwd={cwd}@@ -7549,6 +7552,7 @@ export default function ChatView(props: ChatViewProps) {</Suspense>) : renderedRightPanelSurface?.kind === "terminal" ? (<PersistentThreadTerminalPanel+ visible={rightPanelOpen}threadRef={activeThreadRef}surface={renderedRightPanelSurface}launchContext={activeTerminalLaunchContext ?? null}diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex 98717646694..89cdc3649ac 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -33,6 +33,7 @@ import {useCallback,useEffect,useEffectEvent,+ useLayoutEffect,useMemo,useRef,useState,@@ -295,6 +296,7 @@ interface TerminalViewportProps {onAddTerminalContext: (selection: TerminalContextSelection) => void;focusRequestId: number;autoFocus: boolean;+ visible: boolean;resizeEpoch: number;drawerHeight: number;keybindings: ResolvedKeybindingsConfig;@@ -319,12 +321,14 @@ export function TerminalViewport({onAddTerminalContext,focusRequestId,autoFocus,+ visible,resizeEpoch,drawerHeight,keybindings,}: TerminalViewportProps) {const containerRef = useRef<HTMLDivElement>(null);const terminalRef = useRef<GhosttyTerminalSurface | null>(null);+ const visibleRef = useRef(visible);const environmentId = threadRef.environmentId;const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));const openInPreferredEditor = useOpenInPreferredEditor(@@ -434,6 +438,11 @@ export function TerminalViewport({keybindingsRef.current = keybindings;}, [keybindings]);+ useLayoutEffect(() => {+ visibleRef.current = visible;+ terminalRef.current?.setVisible(visible);+ }, [visible]);+useEffect(() => {const current = terminalFontRef.current;if (current.family === terminalFontFamily && current.size === terminalFontSize) return;@@ -457,6 +466,9 @@ export function TerminalViewport({const terminalOptions: GhosttyTerminalSurfaceOptions = {theme: terminalThemeFromApp(mount),font: terminalFontOptions(setupFont.family, setupFont.size),+ get visible() {+ return visibleRef.current;+ },onData: (data) => handleData(data),onResize: (cols, rows) => void resizeTerminal(cols, rows),onSelectionChange: () => handleSelectionChange(),@@ -474,6 +486,7 @@ export function TerminalViewport({terminal.dispose();return null;}+ terminal.setVisible(visibleRef.current);// The theme observer is not installed yet, so re-read the theme in case// the app toggled light/dark while the WASM surface was loading.terminal.setTheme(terminalThemeFromApp(mount));@@ -503,7 +516,7 @@ export function TerminalViewport({// never started, so only "exited" triggers the message — as with xterm.)synchronizedStatusRef.current = "closed";synchronizeTerminalStatus(terminal, latestSession.status);- if (autoFocus) window.requestAnimationFrame(() => terminal.focus());+ if (autoFocus && visibleRef.current) window.requestAnimationFrame(() => terminal.focus());const dismissSelectionAction = (supersede = false) => {const ownsMenu =@@ -891,7 +904,7 @@ export function TerminalViewport({writeSystemMessage(terminal, current.error);}- if (previous.version === 0 && autoFocus) {+ if (previous.version === 0 && autoFocus && visibleRef.current) {window.requestAnimationFrame(() => {terminal.focus();});@@ -900,7 +913,7 @@ export function TerminalViewport({}, [autoFocus, terminalOutput, terminalError, terminalStatus, terminalVersion]);useEffect(() => {- if (!autoFocus) return;+ if (!autoFocus || !visible) return;const terminal = terminalRef.current;if (!terminal) return;const frame = window.requestAnimationFrame(() => {@@ -909,15 +922,16 @@ export function TerminalViewport({return () => {window.cancelAnimationFrame(frame);};- }, [autoFocus, focusRequestId]);+ }, [autoFocus, focusRequestId, visible]);useEffect(() => {const terminal = terminalRef.current;- if (!terminal) return;+ if (!terminal || !visibleRef.current) return;const wasAtBottom = terminal.isAtBottom();// The surface reports grid changes through onResize, which is the single// channel for PTY resize RPCs; fitting here only refreshes the layout.const frame = window.requestAnimationFrame(() => {+ if (!visibleRef.current) return;terminal.fit();if (wasAtBottom) {terminal.scrollToBottom();@@ -1493,6 +1507,7 @@ export default function ThreadTerminalDrawer({onAddTerminalContext={onAddTerminalContext}focusRequestId={focusRequestId}autoFocus={terminalId === resolvedActiveTerminalId}+ visible={visible}resizeEpoch={resizeEpoch}drawerHeight={drawerHeight}keybindings={keybindings}@@ -1522,6 +1537,7 @@ export default function ThreadTerminalDrawer({onAddTerminalContext={onAddTerminalContext}focusRequestId={focusRequestId}autoFocus+ visible={visible}resizeEpoch={resizeEpoch}drawerHeight={drawerHeight}keybindings={keybindings}diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.tsindex 11b3cc890fd..e9933cdb4b7 100644--- a/apps/web/src/terminal/ghostty/surface.test.ts+++ b/apps/web/src/terminal/ghostty/surface.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it, vi } from "vite-plus/test";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";-import type { GhosttyCell, GhosttyRow } from "./core";+import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";import {DEFAULT_TERMINAL_FONT_FAMILY,DEFAULT_TERMINAL_FONT_SIZE,@@ -31,8 +31,328 @@ import {terminalFontSize,terminalWheelArrowData,terminalWheelDeltaRows,+ GhosttyTerminalSurface,+ type GhosttyTerminalSurfaceOptions,} from "./surface";+vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({+ default: (await import("./vendor/ghostty-vt.wasm?inline")).default,+}));+vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({+ default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,+}));++describe("GhosttyTerminalSurface visibility", () => {+ const surfaces = new Set<GhosttyTerminalSurface>();++ // Keep the real surface, renderer, and WASM core. Only browser layout and+ // scheduling are replaced so tests can count work while the terminal is hidden.+ function createHarness() {+ vi.useFakeTimers();+ const frames = new Map<number, FrameRequestCallback>();+ const resizeCallbacks = new Set<() => void>();+ const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});+ let frameId = 0;+ const requestFrame = vi.fn((callback: FrameRequestCallback) => {+ frames.set(++frameId, callback);+ return frameId;+ });++ class TerminalTestElement extends EventTarget {+ style: Record<string, string> = {};+ parentElement: TerminalTestElement | null = null;+ clientWidth = 168;+ clientHeight = 104;+ width = 300;+ height = 150;+ value = "";+ private readonly captures = new Set<number>();++ setAttribute() {}+ append(...children: TerminalTestElement[]) {+ for (const child of children) child.parentElement = this;+ }+ replaceChildren(...children: TerminalTestElement[]) {+ this.append(...children);+ }+ remove() {+ this.parentElement = null;+ }+ getContext() {+ return context;+ }+ focus() {+ this.dispatchEvent(new Event("focus"));+ }+ setPointerCapture(pointerId: number) {+ this.captures.add(pointerId);+ }+ hasPointerCapture(pointerId: number) {+ return this.captures.has(pointerId);+ }+ releasePointerCapture(pointerId: number) {+ this.captures.delete(pointerId);+ }+ getBoundingClientRect() {+ return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };+ }+ }++ const canvas = new TerminalTestElement();+ const mount = new TerminalTestElement();+ const context = {+ canvas,+ beginPath() {},+ clip() {},+ rect() {},+ resetTransform() {},+ restore() {},+ save() {},+ setTransform() {},+ fillRect: (...args: number[]) => paint("fillRect", args),+ strokeRect: (...args: number[]) => paint("strokeRect", args),+ fillText: (...args: [string, number, number, number?]) => paint("fillText", args),+ measureText: (text: string) => ({+ width: text.length * 8,+ actualBoundingBoxAscent: 9,+ actualBoundingBoxDescent: 3,+ }),+ };+ vi.stubGlobal("document", {+ createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),+ fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),+ });+ vi.stubGlobal(+ "window",+ Object.assign(new EventTarget(), {+ devicePixelRatio: 1,+ requestAnimationFrame: requestFrame,+ cancelAnimationFrame: (id: number) => frames.delete(id),+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ matchMedia: () => Object.assign(new EventTarget(), { matches: false }),+ }),+ );+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(private readonly callback: () => void) {+ resizeCallbacks.add(callback);+ }+ observe() {}+ disconnect() {+ resizeCallbacks.delete(this.callback);+ }+ },+ );+ const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");+ const onData = vi.fn<(data: string) => void>();++ return {+ mount,+ frames,+ paint,+ requestFrame,+ snapshot,+ onData,+ get renderedSnapshot() {+ const result = snapshot.mock.results.at(-1);+ if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");+ return result.value;+ },+ flushFrame() {+ const queued = [...frames.values()];+ frames.clear();+ for (const callback of queued) callback(0);+ },+ resize() {+ for (const callback of resizeCallbacks) callback();+ },+ pointer(type: string, clientX: number, buttons: number) {+ canvas.dispatchEvent(+ Object.assign(new Event(type, { cancelable: true }), {+ clientX,+ clientY: 5,+ pointerId: 1,+ button: 0,+ buttons,+ }),+ );+ },+ async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {+ const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {+ theme: {+ foreground: { r: 255, g: 255, b: 255 },+ background: { r: 0, g: 0, b: 0 },+ cursor: { r: 255, g: 255, b: 255 },+ },+ onData,+ onResize() {},+ onSelectionChange() {},+ beforeKey: () => false,+ onLinkActivate() {},+ ...options,+ get visible() {+ return options.visible ?? true;+ },+ });+ surfaces.add(surface);+ return surface;+ },+ };+ }++ afterEach(() => {+ for (const surface of surfaces) surface.dispose();+ surfaces.clear();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {+ const harness = createHarness();+ const surface = await harness.create();+ surface.focus();+ surface.write("ready\x1b[1 q");+ harness.flushFrame();+ vi.advanceTimersByTime(500);+ harness.flushFrame();+ surface.write("queued");+ expect(harness.frames.size).toBe(1);+ surface.setVisible(false);+ expect(harness.frames.size).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ harness.snapshot.mockClear();+ harness.paint.mockClear();+ harness.requestFrame.mockClear();++ surface.write("\x1b[2J\x1b[H\x1b[3");+ surface.write("1mhidden");+ surface.write("界🙂\x1b[0m\x1b[5n\x1b[6n");+ surface.fit();+ vi.advanceTimersByTime(2_000);+ harness.flushFrame();++ expect(harness.onData.mock.calls).toEqual([["\x1b[0n"], ["\x1b[1;11R"]]);+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.paint).not.toHaveBeenCalled();+ expect(harness.requestFrame).not.toHaveBeenCalled();++ surface.setVisible(true);+ expect(harness.snapshot).toHaveBeenCalledTimes(1);+ expect(harness.renderedSnapshot).toMatchObject({ cursorX: 10, cursorY: 0 });+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("hidden");+ expect(harness.paint.mock.calls).toContainEqual(["fillRect", [84, 4, 8, 16]]);+ expect(harness.frames.size).toBe(0);+ });++ it("keeps the selection on reveal and applies a hidden selection clear", async () => {+ const harness = createHarness();+ const surface = await harness.create();+ surface.write("hello world");+ harness.flushFrame();+ harness.pointer("pointerdown", 5, 1);+ harness.pointer("pointermove", 37, 1);+ harness.pointer("pointerup", 37, 0);+ harness.flushFrame();+ expect(surface.getSelection()).toBe("hello");+ const position = surface.getSelectionPosition();++ surface.setVisible(false);+ harness.snapshot.mockClear();+ surface.setVisible(true);+ expect(harness.snapshot).toHaveBeenCalledTimes(1);+ expect(surface.getSelectionPosition()).toEqual(position);+ expect(+ harness.renderedSnapshot.rowData[0]?.cells.slice(0, 5).every((cell) => cell.selected),+ ).toBe(true);++ surface.setVisible(false);+ harness.snapshot.mockClear();+ surface.clearSelection();+ surface.write("!");+ expect(harness.snapshot).not.toHaveBeenCalled();+ surface.setVisible(true);+ expect(harness.snapshot).toHaveBeenCalledTimes(1);+ expect(surface.getSelection()).toBe("");+ expect(surface.getSelectionPosition()).toBeNull();+ expect(harness.renderedSnapshot.rowData[0]?.cells.some((cell) => cell.selected)).toBe(false);+ });++ it("stops zero-size mounts and repaints when the same size returns", async () => {+ const harness = createHarness();+ const surface = await harness.create();+ surface.focus();+ surface.write("visible");+ harness.flushFrame();+ harness.snapshot.mockClear();+ harness.paint.mockClear();+ harness.mount.clientWidth = 0;+ surface.write("!");+ harness.flushFrame();+ harness.requestFrame.mockClear();+ for (let index = 0; index < 8; index += 1) surface.write("x");+ vi.advanceTimersByTime(2_000);++ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.paint).not.toHaveBeenCalled();+ expect(harness.requestFrame).not.toHaveBeenCalled();+ harness.mount.clientWidth = 168;+ harness.resize();+ expect(harness.snapshot).toHaveBeenCalledTimes(1);+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("visible!xxxxxxxx");+ expect(harness.paint).toHaveBeenCalled();+ });++ it.each([false, true])(+ "uses visibility %s if it changes while WASM initializes",+ async (visible) => {+ const harness = createHarness();+ let markCreated!: () => void;+ const created = new Promise<void>((resolve) => {+ markCreated = resolve;+ });+ let finishLoading!: () => void;+ const release = new Promise<void>((resolve) => {+ finishLoading = resolve;+ });+ const create = GhosttyTerminalCore.create;+ vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {+ const core = await create(...args);+ markCreated();+ await release;+ return core;+ });+ let currentVisible = !visible;+ const pending = harness.create({+ get visible() {+ return currentVisible;+ },+ });+ await created;+ currentVisible = visible;+ harness.paint.mockClear();+ finishLoading();+ const surface = await pending;++ expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);+ if (!visible) expect(harness.paint).not.toHaveBeenCalled();+ surface.write("ready\x1b[5n");+ expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");+ if (!visible) {+ expect(harness.frames.size).toBe(0);+ surface.setVisible(true);+ } else {+ harness.flushFrame();+ }+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");+ },+ );+});+const cell = (text: string): GhosttyCell => ({text,wide: 0,diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.tsindex 84e59e10f50..826dcd01405 100644--- a/apps/web/src/terminal/ghostty/surface.ts+++ b/apps/web/src/terminal/ghostty/surface.ts@@ -532,6 +532,8 @@ export interface GhosttySelectionPosition {export interface GhosttyTerminalSurfaceOptions {readonly theme: GhosttyTheme;readonly font?: GhosttyTerminalFont;+ /** Read after font and WASM loading. Hosts can supply a getter for the latest value. */+ readonly visible?: boolean;readonly onData: (data: string) => void;readonly onResize: (cols: number, rows: number) => void;readonly onSelectionChange: () => void;@@ -556,6 +558,8 @@ export class GhosttyTerminalSurface {private readonly context: CanvasRenderingContext2D;private readonly core: GhosttyTerminalCore;private readonly options: GhosttyTerminalSurfaceOptions;+ private visible: boolean;+ private hasSize = false;private metrics: GhosttyCellMetrics;private fontFamily: string;private requestedFontFamily: string | undefined;@@ -643,6 +647,7 @@ export class GhosttyTerminalSurface {this.mouseAnyEventTracking = core.isMouseAnyEventTracking();this.metrics = metrics;this.options = options;+ this.visible = options.visible ?? true;this.theme = options.theme;this.fontFamily = fontFamily;this.requestedFontFamily = options.font?.family;@@ -725,10 +730,24 @@ export class GhosttyTerminalSurface {options,);surface.fit();- surface.requestRender();return surface;}+ /** Pause canvas work without interrupting output parsing or terminal replies. */+ setVisible(visible: boolean): void {+ if (this.disposed || this.visible === visible) return;+ this.visible = visible;+ this.cursorOn = true;+ this.forceFullRender = true;+ this.scrollbarDirty = true;+ if (!visible) {+ this.cancelRender();+ this.setSelectionAutoscroll(0);+ return;+ }+ this.fit();+ }+write(data: string): void {if (this.disposed) return;this.core.write(data);@@ -824,10 +843,16 @@ export class GhosttyTerminalSurface {};fit(): boolean {- if (this.disposed) return false;+ if (this.disposed || !this.visible) return false;const width = this.mount.clientWidth;const height = this.mount.clientHeight;- if (width <= 0 || height <= 0) return false;+ if (width <= 0 || height <= 0) {+ this.hasSize = false;+ this.forceFullRender = true;+ this.cancelRender();+ return false;+ }+ this.hasSize = true;const ratio = window.devicePixelRatio || 1;const pixelWidth = Math.max(1, Math.round(width * ratio));const pixelHeight = Math.max(1, Math.round(height * ratio));@@ -864,7 +889,7 @@ export class GhosttyTerminalSurface {// Rendering synchronously keeps the repaint inside the same frame as the// layout change: ResizeObserver fires before paint, so the browser never// composites the old backing store stretched into the new element box.- if (shouldRender) this.renderFrame();+ if (shouldRender || this.forceFullRender) this.renderFrame();return true;}@@ -883,6 +908,7 @@ export class GhosttyTerminalSurface {}focus(): void {+ if (this.disposed || !this.visible) return;this.input.focus({ preventScroll: true });}@@ -982,8 +1008,7 @@ export class GhosttyTerminalSurface {// the surface unmounts inside the debounce window.this.options.onResize(this.cols, this.rows);}- if (this.frame !== 0) window.cancelAnimationFrame(this.frame);- if (this.cursorTimer !== null) window.clearTimeout(this.cursorTimer);+ this.cancelRender();if (this.compositionSuppressionTimer !== null) {window.clearTimeout(this.compositionSuppressionTimer);}@@ -1676,19 +1701,39 @@ export class GhosttyTerminalSurface {}private requestRender(): void {- if (this.disposed || this.frame !== 0) return;+ if (this.disposed || !this.visible || !this.hasSize || this.frame !== 0) return;this.frame = window.requestAnimationFrame(() => {this.frame = 0;this.renderFrame();});}+ private cancelRender(): void {+ if (this.frame !== 0) {+ window.cancelAnimationFrame(this.frame);+ this.frame = 0;+ }+ if (this.cursorTimer !== null) {+ window.clearTimeout(this.cursorTimer);+ this.cursorTimer = null;+ }+ }+private renderFrame(): void {- if (this.disposed) return;+ if (this.disposed || !this.visible) return;if (this.frame !== 0) {window.cancelAnimationFrame(this.frame);this.frame = 0;}+ // Hidden thread drawers stay mounted so switching back is instant, but a+ // display:none canvas has nothing to show. Ghostty keeps parsing; the+ // ResizeObserver refits and repaints in full once the mount has a size.+ if (this.mount.clientWidth === 0 || this.mount.clientHeight === 0) {+ this.hasSize = false;+ this.forceFullRender = true;+ this.cancelRender();+ return;+ }this.snapshot = this.core.snapshot();// A cursor that is not blinking right now must be drawn, never caught in an// off phase left behind by a blink that has since been turned off.@@ -1754,7 +1799,7 @@ export class GhosttyTerminalSurface {private blinkEnabled(): boolean {const snapshot = this.snapshot;- if (!snapshot) return false;+ if (!snapshot || !this.visible || !this.hasSize) return false;return shouldBlinkTerminalCursor({focused: this.focused,cursorBlinking: snapshot.cursorBlinking,