Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): desktop terminal lagginess + resize flicker (PRD-7296, PRD-7316) (#2530)

serafin-garciaff893f0a7adf
diff --git a/.changeset/terminal-lag-fixes.md b/.changeset/terminal-lag-fixes.md
new file mode 100644
index 000000000..c70ff551a
--- /dev/null
+++ b/.changeset/terminal-lag-fixes.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix desktop terminal lagginess and resize flicker. Typing and scrolling no longer pay for xterm's screen-reader mode when no assistive tech is attached — the mode (which mirrors the whole viewport into a live accessibility DOM on every write and scroll) now follows the OS screen-reader signal, turning on the moment VoiceOver attaches and staying on for screen-reader users. Keystroke echo latency from output coalescing drops from 12ms to 5ms (VS Code's bufferer window), kept trailing-only so a TUI redraw burst always lands as one atomic push (no partial-frame tearing). Resizing sections with a terminal open no longer SIGWINCH-repaints the running TUI on every pointer frame — the PTY resize is throttled leading+trailing while the xterm grid fits per event. And resizing no longer flashes the terminal blank: setting a canvas's width clears its bitmap while xterm's repaint is rAF-scheduled (a frame late), and the WebGL addon's device-pixel observer re-clears a second time in the same frame when a fractional panel width snaps differently to device pixels — both clears now flush a synchronous repaint before the frame paints, verified frame-by-frame with screencast captures (32 blank frames per drag before, zero after).
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index 6178b1634..f7ae6b66a 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -42,10 +42,18 @@ class MockTerminal {
// 'DEFAULT' X10 = defer to xterm). Exposed via the `_core` getter below to
// mirror xterm's internal shape the production handler reads.
mouseEncoding = 'SGR' as string;
+ // Captures the synchronous render-debouncer flush the resize path invokes to
+ // repaint in the same frame (the WebGL canvas is cleared on resize; without
+ // the flush the glyphs land one frame late — a visible blank flash).
+ renderFlush = mock(() => {});
+ refresh = mock((_start: number, _end: number) => {});
get _core() {
return {
coreMouseService: { activeEncoding: this.mouseEncoding },
- _renderService: { dimensions: { css: { cell: { width: 10, height: 17 } } } },
+ _renderService: {
+ dimensions: { css: { cell: { width: 10, height: 17 } } },
+ _renderDebouncer: { _innerRefresh: this.renderFlush },
+ },
};
}
// The wheel handler reads `term.element` to hit-test the pointer's cell for
@@ -57,7 +65,15 @@ class MockTerminal {
keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
wheelHandler: ((e: WheelEvent) => boolean) | null = null;
options: Record<string, unknown>;
- open = mock(() => {});
+ // Builds the minimal WebGL-renderer DOM (.xterm-screen > canvas) so the
+ // panel's device-pixel canvas observer — the second-clear repaint hook —
+ // has a canvas to find, matching real xterm's structure.
+ open = mock((container: HTMLElement) => {
+ const screen = document.createElement('div');
+ screen.className = 'xterm-screen';
+ screen.appendChild(document.createElement('canvas'));
+ container.appendChild(screen);
+ });
focus = mock(() => {});
dispose = mock(() => {});
write = mock((_data: string, cb?: () => void) => {
@@ -107,14 +123,22 @@ let mockResolvedTheme: string | undefined = 'dark';
// Capturing ResizeObserver — the jsdom preload installs a no-op one whose
// callback never fires, so override it to drive the resize path explicitly.
let roCallback: (() => void) | null = null;
-let lastRO: MockResizeObserver | null = null;
+// Every constructed observer, so tests can find a specific one by its
+// observed target (e.g. the device-pixel canvas observer vs the container
+// refit observer — `roCallback` only tracks the most recent construction).
+let allROs: MockResizeObserver[] = [];
class MockResizeObserver {
- observe = mock(() => {});
+ cb: () => void;
+ observed: Array<{ el: Element; opts?: ResizeObserverOptions }> = [];
+ observe = mock((el: Element, opts?: ResizeObserverOptions) => {
+ this.observed.push({ el, opts });
+ });
unobserve = mock(() => {});
disconnect = mock(() => {});
constructor(cb: () => void) {
+ this.cb = cb;
roCallback = cb;
- lastRO = this;
+ allROs.push(this);
}
}
@@ -199,8 +223,8 @@ describe('TerminalPanel', () => {
beforeEach(() => {
lastTerm = null;
lastFit = null;
- lastRO = null;
roCallback = null;
+ allROs = [];
webglThrows = false;
mockResolvedTheme = 'dark';
(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
@@ -216,6 +240,8 @@ describe('TerminalPanel', () => {
const region = screen.getByRole('region', { name: 'Terminal' });
expect(region).toBeTruthy();
+ // No `accessibility` surface on this bridge → the fail-accessible default:
+ // screen-reader mode stays ON when the assistive-tech signal is absent.
expect(lastTerm?.options.screenReaderMode).toBe(true);
expect(lastTerm?.options.minimumContrastRatio).toBe(4.5);
expect(lastTerm?.unicode.activeVersion).toBe('11');
@@ -230,6 +256,59 @@ describe('TerminalPanel', () => {
expect(terminal.create).toHaveBeenCalledWith({ cols: 80, rows: 24 });
});
+ test('screen-reader mode follows the assistive-tech signal: off when inactive, live-toggled on attach', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ const a11ySubs: Array<(active: boolean) => void> = [];
+ const a11yUnsub = mock(() => {});
+ const withA11y = {
+ ...(bridge as unknown as Record<string, unknown>),
+ accessibility: {
+ isScreenReaderActive: () => false,
+ onScreenReaderChanged: (cb: (active: boolean) => void) => {
+ a11ySubs.push(cb);
+ return a11yUnsub;
+ },
+ },
+ } as unknown as OkDesktopBridge;
+ const { unmount } = render(<TerminalPanel bridge={withA11y} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+
+ // No assistive tech detected → xterm skips its a11y DOM mirror (the
+ // dominant typing/scrolling cost when no screen reader is attached).
+ expect(lastTerm?.options.screenReaderMode).toBe(false);
+
+ // A screen reader attaching mid-session re-skins the live terminal in
+ // place — no restart, the PTY and scrollback survive.
+ act(() => {
+ for (const f of a11ySubs) f(true);
+ });
+ expect(lastTerm?.options.screenReaderMode).toBe(true);
+ act(() => {
+ for (const f of a11ySubs) f(false);
+ });
+ expect(lastTerm?.options.screenReaderMode).toBe(false);
+
+ // The subscription is released with the panel — a leaked listener would
+ // keep touching a disposed terminal on later attach/detach flips.
+ act(() => unmount());
+ expect(a11yUnsub).toHaveBeenCalledTimes(1);
+ });
+
+ test('the smoke suite pins screen-reader mode on even with no assistive tech (assertions read the a11y tree)', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ const smokeBridge = {
+ ...(bridge as unknown as Record<string, unknown>),
+ config: { e2eSmoke: true },
+ accessibility: {
+ isScreenReaderActive: () => false,
+ onScreenReaderChanged: () => () => {},
+ },
+ } as unknown as OkDesktopBridge;
+ render(<TerminalPanel bridge={smokeBridge} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ expect(lastTerm?.options.screenReaderMode).toBe(true);
+ });
+
test('reload rehydration: adopts a surviving session instead of spawning a fresh one', async () => {
const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-fresh' });
render(<TerminalPanel bridge={bridge} adoptPtyId="pty-survivor" />);
@@ -495,6 +574,79 @@ describe('TerminalPanel', () => {
expect(terminal.resize).toHaveBeenCalledWith('pty-1', 80, 24);
});
+ test('a resize burst fits per event (no flicker) but coalesces PTY resizes: one leading, one trailing', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(roCallback).toBeTruthy());
+
+ const fitsBefore = lastFit?.fit.mock.calls.length ?? 0;
+ const resizesBefore = terminal.resize.mock.calls.length;
+ // Simulate a section drag: a stream of ResizeObserver callbacks inside one
+ // throttle interval. Every event fits — the grid stays glued to the panel
+ // edge (throttling the fit made it visibly step/flicker) — but only the
+ // leading PTY resize goes out; unthrottled, each one SIGWINCHes the
+ // running TUI into a full repaint per pointer frame.
+ act(() => {
+ roCallback?.();
+ roCallback?.();
+ roCallback?.();
+ });
+ expect((lastFit?.fit.mock.calls.length ?? 0) - fitsBefore).toBe(3);
+ expect(terminal.resize.mock.calls.length - resizesBefore).toBe(1);
+
+ // The trailing PTY resize lands after the interval so the shell settles at
+ // the final drag size (PTY_RESIZE_THROTTLE_MS = 100).
+ await waitFor(() => expect(terminal.resize.mock.calls.length - resizesBefore).toBe(2), {
+ timeout: 1000,
+ });
+ });
+
+ test('a grid-changing fit repaints synchronously in the same frame (no blank-frame flash)', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(roCallback).toBeTruthy());
+
+ // A resize that does NOT cross a cell boundary leaves the canvas bitmap
+ // intact — no forced repaint.
+ act(() => roCallback?.());
+ expect(lastTerm?.renderFlush).not.toHaveBeenCalled();
+
+ // A fit that changes the grid resizes the WebGL canvas, which clears its
+ // bitmap; xterm's own repaint is rAF-scheduled (one frame LATE, after the
+ // browser paints the cleared canvas). The panel must queue a full refresh
+ // and flush the render debouncer synchronously so the glyphs are back
+ // before this frame paints.
+ lastFit?.fit.mockImplementation(() => {
+ if (lastTerm) lastTerm.cols = 100;
+ });
+ act(() => roCallback?.());
+ expect(lastTerm?.refresh).toHaveBeenCalled();
+ expect(lastTerm?.renderFlush).toHaveBeenCalledTimes(1);
+ });
+
+ test("the WebGL canvas's device-pixel re-clear also repaints in the same frame", async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+
+ // The panel wires its own device-pixel-content-box observer on the WebGL
+ // canvas: the addon's sibling observer re-sets canvas.width (a SECOND
+ // bitmap clear, after the fit-path repaint) whenever a fractional CSS
+ // width snaps differently to device pixels, and its own redraw is a frame
+ // late. Find the observer whose target is the canvas.
+ const canvas = document.querySelector('.xterm-screen canvas');
+ expect(canvas).toBeTruthy();
+ const canvasRO = allROs.find((ro) => ro.observed.some((o) => o.el === canvas));
+ expect(canvasRO).toBeTruthy();
+ expect(canvasRO?.observed[0]?.opts).toEqual({ box: 'device-pixel-content-box' });
+
+ // Firing it (the addon just cleared the bitmap) must flush a repaint
+ // synchronously so the blank canvas is never painted.
+ const flushesBefore = lastTerm?.renderFlush.mock.calls.length ?? 0;
+ act(() => canvasRO?.cb());
+ expect((lastTerm?.renderFlush.mock.calls.length ?? 0) - flushesBefore).toBe(1);
+ });
+
test('cancels the browser default for Shift+Tab only; every other key (incl. Escape) reaches the PTY', async () => {
const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
render(<TerminalPanel bridge={bridge} />);
@@ -741,14 +893,19 @@ describe('TerminalPanel', () => {
await waitFor(() => expect(roCallback).toBeTruthy());
const term = lastTerm;
- const ro = lastRO;
+ const ros = allROs.slice();
+ // Two observers per session: the container refit observer and the
+ // device-pixel canvas observer (the second-clear repaint hook).
+ expect(ros.length).toBe(2);
act(() => unmount());
expect(term?.dispose).toHaveBeenCalledTimes(1);
expect(terminal.kill).toHaveBeenCalledWith('pty-1');
expect(unsubData).toHaveBeenCalledTimes(1);
expect(unsubExit).toHaveBeenCalledTimes(1);
- expect(ro?.disconnect).toHaveBeenCalledTimes(1);
+ // EVERY observer disconnects — a surviving canvas observer would keep
+ // flushing renders into a disposed terminal.
+ for (const ro of ros) expect(ro.disconnect).toHaveBeenCalledTimes(1);
});
test('degrades to the DOM renderer when WebGL is unavailable instead of failing the mount', async () => {
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 146d3e88f..98c0b2fda 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -21,9 +21,21 @@ import { filesFromExternalDrop, isExternalFileDrag } from './file-tree-adapter';
import { TerminalCliMissingBanner } from './TerminalCliMissingBanner';
import { type TerminalExitInfo, TerminalExitNotice } from './TerminalExitNotice';
import { TerminalRefusalNotice } from './TerminalRefusalNotice';
+import { createSameFrameRepaint } from './terminal-render-flush';
+import { createResizeThrottle } from './terminal-resize-throttle';
import { xtermThemeForMode } from './terminal-theme';
import { nextWheelReports, sgrWheelReport, wheelReportPosition } from './terminal-wheel';
+/**
+ * Interval for the PTY-resize throttle (see terminal-resize-throttle.ts).
+ * Bounds the SIGWINCH → full-TUI-repaint → output-flood loop to ~10×/s during
+ * a section drag; the trailing call lands the final size. The xterm fit itself
+ * is NOT throttled — stepping it made the grid visibly jump ("flicker") during
+ * drags, and it is cheap per event (FitAddon only reflows when a cell boundary
+ * is actually crossed).
+ */
+const PTY_RESIZE_THROTTLE_MS = 100;
+
interface TerminalPanelProps {
/** Desktop bridge — the panel is rendered only on the Electron host, where
* `window.okDesktop` is present. */
@@ -196,9 +208,20 @@ function TerminalSession({
let unsubExit: (() => void) | undefined;
let titleDisposable: { dispose(): void } | undefined;
let observer: ResizeObserver | undefined;
-
+ let canvasPixelObserver: ResizeObserver | undefined;
+ let ptyResizeThrottle: ReturnType<typeof createResizeThrottle> | undefined;
+
+ // xterm's screen-reader mode mirrors the viewport into a live a11y DOM on
+ // every write and scroll — "a significant performance drop" per xterm's own
+ // docs, and the largest single cost on the typing/scrolling path. Gate it
+ // on the OS assistive-tech signal (the VS Code model): screen-reader users
+ // get the full a11y tree, everyone else gets native-feeling latency. An
+ // absent bridge surface fails accessible (mode on). The smoke suite pins it
+ // on — its assertions read the .xterm-accessibility tree.
+ const screenReaderModeAtMount =
+ bridge.config.e2eSmoke === true || (bridge.accessibility?.isScreenReaderActive() ?? true);
const term = new Terminal({
- screenReaderMode: true,
+ screenReaderMode: screenReaderModeAtMount,
minimumContrastRatio: 4.5,
allowProposedApi: true,
cursorBlink: true,
@@ -267,6 +290,38 @@ function TerminalSession({
fit.fit();
+ // Same-frame repaint after anything clears the canvas bitmap — see
+ // terminal-render-flush.ts for the full why (canvas resize clears by
+ // spec; xterm's own repaint is a frame late).
+ const repaintSameFrame = createSameFrameRepaint(term);
+
+ // The WebGL addon watches its canvas with a device-pixel-content-box
+ // ResizeObserver and, when the device-pixel snap of a fractional CSS width
+ // differs from the bitmap the grid resize set, re-sets canvas.width — a
+ // SECOND clear that lands in a later RO delivery iteration of the same
+ // frame (deeper target), i.e. AFTER the fit-path repaint. Observing the
+ // same canvas with the same box, registered after the addon, puts this
+ // callback after the addon's in that iteration, so the flush repaints
+ // after its clear. Drawing to the bitmap changes no layout, so this adds
+ // no further RO iterations. The DOM renderer path has no canvas and never
+ // wires this.
+ const webglCanvas = container.querySelector<HTMLCanvasElement>('.xterm-screen canvas');
+ if (webglCanvas !== null) {
+ canvasPixelObserver = new ResizeObserver(() => repaintSameFrame());
+ try {
+ canvasPixelObserver.observe(webglCanvas, { box: 'device-pixel-content-box' });
+ } catch (err) {
+ // Electron is always Chromium, which supports device-pixel-content-box
+ // — so any throw here is unexpected (detached canvas, a future API
+ // change), and it silently disables the flicker fix. Surface it so the
+ // symptom (resize flicker returns) is correlatable in logs; the addon's
+ // own sibling observer degrades the same way, so wiring stays off.
+ console.warn('[terminal] device-pixel canvas observe failed:', err);
+ canvasPixelObserver.disconnect();
+ canvasPixelObserver = undefined;
+ }
+ }
+
// Surface OSC 0/2 title changes the running program emits (shell prompt,
// `vim`, the `claude` TUI) so the dock can label the tab with what the
// program reports. Kept latest-ref so a new callback identity does not
@@ -418,9 +473,24 @@ function TerminalSession({
onExitRef.current?.({ exitCode: msg.exitCode, signal: msg.signal });
});
+ // Fit runs on every resize event so the grid stays glued to the panel
+ // edge (throttling it steps the canvas — visible flicker during drags);
+ // it is cheap per event since FitAddon reflows only when a cell boundary
+ // is crossed. The PTY resize is the throttled half: unthrottled, a drag
+ // SIGWINCHes the running TUI into a full repaint whose output floods
+ // back through IPC + render on every pointer frame — the drag lag users
+ // hit with a terminal open. Leading call keeps a lone resize instant;
+ // the trailing call always lands the final size (the kernel skips the
+ // SIGWINCH when dimensions are unchanged, so redundant sends are inert).
+ ptyResizeThrottle = createResizeThrottle(() => {
+ if (ptyId) bridge.terminal.resize(ptyId, term.cols, term.rows);
+ }, PTY_RESIZE_THROTTLE_MS);
observer = new ResizeObserver(() => {
+ const colsBefore = term.cols;
+ const rowsBefore = term.rows;
fit.fit();
- if (ptyId) bridge.terminal.resize(ptyId, term.cols, term.rows);
+ if (term.cols !== colsBefore || term.rows !== rowsBefore) repaintSameFrame();
+ ptyResizeThrottle?.request();
});
observer.observe(container);
@@ -614,6 +684,8 @@ function TerminalSession({
onPtyIdRef.current?.(null);
termRef.current = null;
observer?.disconnect();
+ canvasPixelObserver?.disconnect();
+ ptyResizeThrottle?.cancel();
unsubData?.();
unsubExit?.();
titleDisposable?.dispose();
@@ -637,6 +709,20 @@ function TerminalSession({
term.options.theme = xtermThemeForMode(resolvedTheme);
}, [resolvedTheme]);
+ // Follow assistive-tech attach/detach in place: toggling
+ // `term.options.screenReaderMode` builds or tears down xterm's a11y DOM
+ // mirror without touching the PTY, so a screen reader started mid-session
+ // gets the accessible tree without a restart. The smoke suite pins the mode
+ // on (see the mount option above), so it never subscribes.
+ useEffect(() => {
+ const accessibility = bridge.accessibility;
+ if (accessibility == null || bridge.config.e2eSmoke === true) return;
+ return accessibility.onScreenReaderChanged((active) => {
+ const term = termRef.current;
+ if (term !== null) term.options.screenReaderMode = active;
+ });
+ }, [bridge]);
+
// Drop a file onto the terminal -> insert its shell-escaped absolute path at
// the prompt (VS Code / Cursor / JetBrains parity). We deliberately do NOT try
// to attach images inline the way the `claude` TUI does over its own escape
diff --git a/packages/app/src/components/terminal-render-flush.test.ts b/packages/app/src/components/terminal-render-flush.test.ts
new file mode 100644
index 000000000..a3f800c0a
--- /dev/null
+++ b/packages/app/src/components/terminal-render-flush.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, mock, test } from 'bun:test';
+import { createSameFrameRepaint, type RepaintableTerminal } from './terminal-render-flush';
+
+function makeTerm(withDebouncer: boolean) {
+ const refresh = mock((_start: number, _end: number) => {});
+ const innerRefresh = mock(() => {});
+ const term = {
+ rows: 24,
+ refresh,
+ ...(withDebouncer
+ ? { _core: { _renderService: { _renderDebouncer: { _innerRefresh: innerRefresh } } } }
+ : {}),
+ } as unknown as RepaintableTerminal;
+ return { term, refresh, innerRefresh };
+}
+
+describe('createSameFrameRepaint', () => {
+ test('queues a full-viewport refresh then flushes the render debouncer synchronously', () => {
+ const { term, refresh, innerRefresh } = makeTerm(true);
+ const warn = mock((_m: string) => {});
+ const repaint = createSameFrameRepaint(term, warn);
+ repaint();
+ expect(refresh).toHaveBeenCalledWith(0, 23);
+ expect(innerRefresh).toHaveBeenCalledTimes(1);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ test('warns once (not per call) when an xterm bump moves the debouncer internal', () => {
+ const { term, refresh } = makeTerm(false);
+ const warn = mock((_m: string) => {});
+ const repaint = createSameFrameRepaint(term, warn);
+ repaint();
+ repaint();
+ repaint();
+ // Degrades to xterm's own next-frame repaint: the public refresh still
+ // queues the range, only the same-frame flush is unavailable.
+ expect(refresh).toHaveBeenCalledTimes(3);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0]?.[0]).toContain('render-debouncer internal not found');
+ });
+});
diff --git a/packages/app/src/components/terminal-render-flush.ts b/packages/app/src/components/terminal-render-flush.ts
new file mode 100644
index 000000000..e2b9b1674
--- /dev/null
+++ b/packages/app/src/components/terminal-render-flush.ts
@@ -0,0 +1,49 @@
+/**
+ * Same-frame repaint after anything clears the terminal's canvas bitmap.
+ *
+ * Setting a canvas's width — which xterm does on every grid resize, and which
+ * the WebGL addon's device-pixel observer does a second time when a fractional
+ * CSS width snaps differently to device pixels — clears the bitmap by spec,
+ * while xterm's own repaint is rAF-scheduled. ResizeObserver callbacks run
+ * after rAF in the frame lifecycle, so without intervention the browser paints
+ * one frame with an empty canvas: the text blinks out per resize step during a
+ * section drag (frame captures showed a full blank frame every few steps).
+ *
+ * The returned repaint queues a full refresh through the public API, then
+ * flushes xterm's render debouncer so the glyphs are back before this frame's
+ * paint — the resize-and-redraw-in-one-frame behavior GPU-native terminals
+ * (Zed) get for free.
+ *
+ * The debouncer reach is a private xterm internal (like TerminalPanel's wheel
+ * handler cell-height read) — it warns once if an xterm bump moves it, so the
+ * regression shows up in QA rather than as a silent return of the flicker.
+ */
+
+/** Structural subset of xterm's Terminal the repaint drives. */
+export interface RepaintableTerminal {
+ readonly rows: number;
+ refresh(start: number, end: number): void;
+}
+
+export function createSameFrameRepaint(
+ term: RepaintableTerminal,
+ warn: (message: string) => void = console.warn,
+): () => void {
+ let warnedMissingRenderFlush = false;
+ return () => {
+ term.refresh(0, term.rows - 1);
+ const debouncer = (
+ term as unknown as {
+ _core?: { _renderService?: { _renderDebouncer?: { _innerRefresh?: () => void } } };
+ }
+ )._core?._renderService?._renderDebouncer;
+ if (typeof debouncer?._innerRefresh === 'function') {
+ debouncer._innerRefresh();
+ } else if (!warnedMissingRenderFlush) {
+ warnedMissingRenderFlush = true;
+ warn(
+ '[terminal] xterm render-debouncer internal not found; resize repaint deferring to the next frame. An xterm upgrade may have moved _core._renderService._renderDebouncer.',
+ );
+ }
+ };
+}
diff --git a/packages/app/src/components/terminal-resize-throttle.test.ts b/packages/app/src/components/terminal-resize-throttle.test.ts
new file mode 100644
index 000000000..26b5a2383
--- /dev/null
+++ b/packages/app/src/components/terminal-resize-throttle.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, test } from 'bun:test';
+import { createResizeThrottle, type ResizeThrottleTimers } from './terminal-resize-throttle';
+
+function makeHarness(intervalMs = 100) {
+ const timers: Array<(() => void) | null> = [];
+ const fakeTimers: ResizeThrottleTimers = {
+ setTimer: (cb) => {
+ timers.push(cb);
+ return timers.length - 1;
+ },
+ clearTimer: (token) => {
+ if (typeof token === 'number') timers[token] = null;
+ },
+ };
+ let applies = 0;
+ const throttle = createResizeThrottle(
+ () => {
+ applies += 1;
+ },
+ intervalMs,
+ fakeTimers,
+ );
+ const runTimers = (): void => {
+ const snapshot = timers.slice();
+ for (let i = 0; i < snapshot.length; i += 1) {
+ const cb = snapshot[i];
+ if (cb) {
+ timers[i] = null;
+ cb();
+ }
+ }
+ };
+ const liveTimerCount = (): number => timers.filter((t) => t !== null).length;
+ return {
+ throttle,
+ runTimers,
+ liveTimerCount,
+ get applies() {
+ return applies;
+ },
+ };
+}
+
+describe('createResizeThrottle', () => {
+ test('a lone request applies immediately (leading edge)', () => {
+ const h = makeHarness();
+ h.throttle.request();
+ expect(h.applies).toBe(1);
+ });
+
+ test('requests during the interval coalesce into one trailing apply', () => {
+ const h = makeHarness();
+ h.throttle.request(); // leading
+ h.throttle.request();
+ h.throttle.request();
+ expect(h.applies).toBe(1);
+ h.runTimers();
+ expect(h.applies).toBe(2); // one trailing apply for the coalesced burst
+ });
+
+ test('an interval that expires idle does not apply and closes the window', () => {
+ const h = makeHarness();
+ h.throttle.request();
+ h.runTimers(); // no request landed inside the interval
+ expect(h.applies).toBe(1);
+ // Window closed — the next request is leading again.
+ h.throttle.request();
+ expect(h.applies).toBe(2);
+ });
+
+ test('a continuous stream applies once per interval, ending with a trailing settle', () => {
+ const h = makeHarness();
+ // Simulate a drag: request, tick, request, tick, ...
+ h.throttle.request(); // leading apply
+ h.throttle.request();
+ h.runTimers(); // trailing apply, window renewed
+ h.throttle.request();
+ h.runTimers(); // trailing apply again
+ expect(h.applies).toBe(3);
+ // The renewed window with nothing pending expires silently.
+ h.runTimers();
+ expect(h.applies).toBe(3);
+ });
+
+ test('cancel drops the pending trailing apply and clears the timer', () => {
+ const h = makeHarness();
+ h.throttle.request();
+ h.throttle.request(); // pending trailing
+ h.throttle.cancel();
+ h.runTimers();
+ expect(h.applies).toBe(1);
+ expect(h.liveTimerCount()).toBe(0);
+ });
+});
diff --git a/packages/app/src/components/terminal-resize-throttle.ts b/packages/app/src/components/terminal-resize-throttle.ts
new file mode 100644
index 000000000..939797876
--- /dev/null
+++ b/packages/app/src/components/terminal-resize-throttle.ts
@@ -0,0 +1,76 @@
+/**
+ * Leading+trailing throttle for the terminal's PTY resize.
+ *
+ * A section-drag with the terminal docked resizes its container on every
+ * pointer frame. The xterm fit itself must run per event — stepping it makes
+ * the grid visibly jump (flicker) during drags, and it is cheap per event
+ * since FitAddon only reflows when a cell boundary is actually crossed. But
+ * forwarding every step to the PTY SIGWINCHes the running program into a
+ * full-screen repaint whose output floods straight back through IPC + render
+ * — at pointer frequency that is the drag lag users hit with a terminal open.
+ *
+ * Leading+trailing keeps the first resize instant (a lone resize — dock
+ * open, window resize — reaches the shell immediately) while a continuous
+ * stream applies at most once per interval, with one trailing call so the
+ * PTY always settles at the final size.
+ */
+
+export interface ResizeThrottleTimers {
+ /** `setTimeout` in production; captured in tests. */
+ setTimer(cb: () => void, ms: number): unknown;
+ /** `clearTimeout` in production. */
+ clearTimer(token: unknown): void;
+}
+
+export interface ResizeThrottle {
+ /** Request a resize apply. Leading call applies immediately; calls landing inside
+ * the interval coalesce into one trailing apply at its end. */
+ request(): void;
+ /** Drop any pending trailing apply and cancel the interval timer. */
+ cancel(): void;
+}
+
+const defaultTimers: ResizeThrottleTimers = {
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
+};
+
+export function createResizeThrottle(
+ apply: () => void,
+ intervalMs: number,
+ timers: ResizeThrottleTimers = defaultTimers,
+): ResizeThrottle {
+ let windowToken: unknown = null;
+ let trailingPending = false;
+
+ function openWindow(): void {
+ windowToken = timers.setTimer(() => {
+ windowToken = null;
+ if (trailingPending) {
+ trailingPending = false;
+ apply();
+ // The trailing apply starts a fresh interval so a continuous stream
+ // (an active drag) stays bounded at one apply per interval.
+ openWindow();
+ }
+ }, intervalMs);
+ }
+
+ return {
+ request(): void {
+ if (windowToken !== null) {
+ trailingPending = true;
+ return;
+ }
+ apply();
+ openWindow();
+ },
+ cancel(): void {
+ if (windowToken !== null) {
+ timers.clearTimer(windowToken);
+ windowToken = null;
+ }
+ trailingPending = false;
+ },
+ };
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 9f5d84099..c68e19a95 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -1340,6 +1340,17 @@ export interface OkDesktopBridge {
rewireClaudeMcp(): Promise<ClaudeReadiness>;
};
+ /**
+ * OS assistive-tech signal gating xterm's `screenReaderMode`. Canonical
+ * JSDoc in `bridge-contract.ts`. Optional in this mirror: session-only
+ * bridges (and test doubles) omit it — consumers treat an absent surface
+ * as screen-reader-active (fail-accessible).
+ */
+ accessibility?: {
+ isScreenReaderActive(): boolean;
+ onScreenReaderChanged(cb: (active: boolean) => void): OkUnsubscribe;
+ };
+
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
/**
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 5ecf158ed..4eab3218d 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1582,6 +1582,17 @@ export interface OkDesktopBridge {
rewireClaudeMcp(): Promise<ClaudeReadiness>;
};
+ /**
+ * OS assistive-tech signal gating xterm's `screenReaderMode`. Canonical
+ * JSDoc in `bridge-contract.ts`. Optional in this mirror: session-only
+ * bridges omit it, and consumers treat an absent surface as
+ * screen-reader-active (fail-accessible).
+ */
+ accessibility?: {
+ isScreenReaderActive(): boolean;
+ onScreenReaderChanged(cb: (active: boolean) => void): OkUnsubscribe;
+ };
+
/** Current platform — `process.platform` reported by preload. */
readonly platform: 'darwin' | 'win32' | 'linux';
/** Electron app version (from main's `app.getVersion()`). */
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index dfd56b87d..4f8001383 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -901,7 +901,15 @@ function withDebugFlagIfAllowed(args: readonly string[]): string[] {
// (vs a blanket --disable-gpu) keeps Electron GPU acceleration on, so the
// suite doesn't trigger whole-app software rendering that starves CPU on
// constrained CI runners. See TerminalPanel's WebGL gate.
- return process.env.OK_DESKTOP_E2E_SMOKE === '1' ? [...withDebug, '--ok-e2e-smoke=1'] : withDebug;
+ const withSmoke =
+ process.env.OK_DESKTOP_E2E_SMOKE === '1' ? [...withDebug, '--ok-e2e-smoke=1'] : withDebug;
+ // Cold-start assistive-tech signal for the preload's live mirror (see
+ // `ok:accessibility:changed` in ipc-events.ts): the terminal gates xterm's
+ // costly `screenReaderMode` on it. Read per window creation so a window
+ // opened after VoiceOver attaches starts with the right posture.
+ return app.isAccessibilitySupportEnabled()
+ ? [...withSmoke, '--ok-screen-reader-active=1']
+ : withSmoke;
}
function ensureDebugIpc(): DebugIpcHandle {
@@ -4716,6 +4724,17 @@ function bootPrimaryInstance(): void {
attachRendererConsoleCapture(contents);
});
+ // Assistive-tech flips (e.g. VoiceOver, NVDA attach/detach) fan out to every window so
+ // the preload's live mirror stays current and an open terminal can toggle
+ // xterm's `screenReaderMode` in place. Cold-start value rides window
+ // creation via `--ok-screen-reader-active` (see withDebugFlagIfAllowed).
+ app.on('accessibility-support-changed', (_event, screenReaderActive) => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (win.webContents.isDestroyed()) continue;
+ sendToRenderer(win.webContents, 'ok:accessibility:changed', { screenReaderActive });
+ }
+ });
+
// URL-scheme handler — register BEFORE `whenReady` so macOS cold-start
// `open-url` Apple Events are caught even if they fire before the ready hook.
// Listener registration is synchronous; the actual routing defers URLs into a
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
index 75bcfd29c..b5155dcd8 100644
--- a/packages/desktop/src/main/terminal-manager.ts
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -9,8 +9,10 @@
* - routes `input` / `resize` / `kill` / `drain` to the addressed session
* within the host, dropping an unknown ptyId so a stale renderer can't
* drive a sibling or successor PTY;
- * - coalesces each session's `data` reads on a short timer and pushes one
- * combined UTF-8 string per tick (the renderer-freeze guard);
+ * - coalesces each session's `data` reads on a short trailing timer (5ms,
+ * VS Code's bufferer window) and pushes one combined UTF-8 string per
+ * tick — the renderer-freeze guard, and it keeps a TUI redraw burst
+ * (erase + repaint) in one push so partial states never render as tearing;
* - bounds each session's in-flight bytes with a high/low-water
* `pause()`/`resume()` loop driven by the renderer's `drain` acks (the
* backpressure seam) — a flood in one tab pauses only its PTY;
@@ -53,7 +55,7 @@ export interface TerminalManagerDeps {
setTimer: (cb: () => void, ms: number) => TimerToken;
/** Cancel a scheduled flush. `clearTimeout` in production. */
clearTimer: (token: TimerToken) => void;
- /** Coalesce window in ms (8-16ms keeps pushes bounded by tick rate). Default 12. */
+ /** Coalesce window in ms. Default `DEFAULT_COALESCE_MS` (5, VS Code's bufferer window). */
coalesceMs?: number;
/** Pause the host once un-drained in-flight bytes exceed this. Default 1 MiB. */
highWaterBytes?: number;
@@ -170,7 +172,16 @@ interface PtyWindowHandle {
sessions: Map<string, SessionState>;
}
-const DEFAULT_COALESCE_MS = 12;
+/**
+ * Trailing coalesce window per session. 5ms matches VS Code's terminal data
+ * bufferer: short enough that keystroke echo latency is imperceptible, long
+ * enough that a TUI redraw burst (erase + repaint) usually lands in ONE push —
+ * splitting a burst across pushes renders the erased/partial intermediate
+ * state for a frame (visible tearing/flicker). Delivery is deliberately NOT
+ * leading-edge for the same reason: the first read of a redraw burst would
+ * flush alone.
+ */
+const DEFAULT_COALESCE_MS = 5;
const DEFAULT_HIGH_WATER = 1024 * 1024;
const DEFAULT_LOW_WATER = 256 * 1024;
/**
@@ -295,11 +306,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
deps.sendExit(handle.webContents, payload);
}
- function flush(windowId: number, ptyId: string): void {
- const handle = handles.get(windowId);
- const session = handle?.sessions.get(ptyId);
- if (!handle || !session) return;
- session.flushToken = null;
+ /**
+ * Push the session's buffered outbound to the renderer, with backpressure
+ * accounting. Delivery only — never touches the flush timer; callers own
+ * scheduling.
+ */
+ function deliver(handle: PtyWindowHandle, ptyId: string, session: SessionState): void {
// pushData skips the send on a destroyed WebContents; bail before touching
// pendingBytes so backpressure accounting doesn't drift on bytes that were
// never delivered.
@@ -317,9 +329,17 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
}
}
+ function flushTick(windowId: number, ptyId: string): void {
+ const handle = handles.get(windowId);
+ const session = handle?.sessions.get(ptyId);
+ if (!handle || !session) return;
+ session.flushToken = null;
+ deliver(handle, ptyId, session);
+ }
+
function scheduleFlush(windowId: number, ptyId: string, session: SessionState): void {
if (session.flushToken !== null) return;
- session.flushToken = deps.setTimer(() => flush(windowId, ptyId), coalesceMs);
+ session.flushToken = deps.setTimer(() => flushTick(windowId, ptyId), coalesceMs);
}
function clearFlush(session: SessionState): void {
@@ -386,7 +406,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
// the window's other tabs (and a later restart).
const { ptyId } = message;
clearFlush(session);
- flush(windowId, ptyId);
+ deliver(handle, ptyId, session);
maybeRecordSession(session);
handle.sessions.delete(ptyId);
deps.recordShellExit?.({ crashed: false });
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 0666e4e8a..1ff370673 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -237,6 +237,19 @@ function readConfigFromArgv(): OkDesktopConfig {
});
}
+// Live assistive-tech mirror: seeded from the window-creation arg (main reads
+// `app.isAccessibilitySupportEnabled()` at createWindow time) and kept current
+// by the `ok:accessibility:changed` broadcast — so `isScreenReaderActive()` is
+// a synchronous read that is correct even for a terminal mounted long after a
+// screen reader attached. A method (not the frozen config) because
+// `contextBridge` captures plain values at exposure time; a closure read stays
+// live (electron/electron#25516).
+let screenReaderActive = parseArg('screen-reader-active') === '1';
+// biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ipcRenderer.on('ok:accessibility:changed', (_event, info: { screenReaderActive: boolean }) => {
+ screenReaderActive = info.screenReaderActive === true;
+});
+
const bridge: OkDesktopBridge = {
config: readConfigFromArgv(),
@@ -694,6 +707,17 @@ const bridge: OkDesktopBridge = {
rewireClaudeMcp: () => invoke('ok:terminal:claude-assist', { action: 'rewire' }),
},
+ accessibility: {
+ isScreenReaderActive: () => screenReaderActive,
+ onScreenReaderChanged(cb) {
+ const listener = (_event: IpcRendererEvent, info: { screenReaderActive: boolean }) =>
+ cb(info.screenReaderActive === true);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:accessibility:changed', listener);
+ return () => ipcRenderer.removeListener('ok:accessibility:changed', listener);
+ },
+ },
+
platform: process.platform as 'darwin' | 'win32' | 'linux',
appVersion: parseArg('app-version') ?? '0.0.0',
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index e2e2f1199..1a74427e0 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -1901,6 +1901,28 @@ export interface OkDesktopBridge {
rewireClaudeMcp(): Promise<ClaudeReadiness>;
};
+ /**
+ * OS assistive-tech signal — Electron's `app.isAccessibilitySupportEnabled()`,
+ * true while a screen reader (VoiceOver, NVDA) is attached. The terminal gates
+ * xterm's `screenReaderMode` on it: the mode mirrors the viewport into a live
+ * accessibility DOM on every write/scroll — a significant rendering cost per
+ * xterm's own docs — so it stays off until assistive tech is detected (the
+ * VS Code model), and screen-reader users still get the full a11y tree.
+ *
+ * `isScreenReaderActive` is a synchronous read of the preload's live mirror
+ * (seeded from the `--ok-screen-reader-active` window arg, updated by
+ * `ok:accessibility:changed`), so the terminal can set its a11y posture at
+ * construction with no async flash. The subscription re-skins an already-open
+ * terminal in place when a screen reader attaches or detaches mid-session.
+ *
+ * Structurally mirrored in the app bridge copy, where it is OPTIONAL —
+ * consumers treat an absent surface as screen-reader-active (fail-accessible).
+ */
+ accessibility: {
+ isScreenReaderActive(): boolean;
+ onScreenReaderChanged(cb: (active: boolean) => void): OkUnsubscribe;
+ };
+
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 3d0f729bd..bf0f21764 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -269,10 +269,11 @@ export interface EventChannels {
/**
* Main → renderer coalesced PTY output. Main batches the utilityProcess's
- * node-pty reads on an 8-16ms timer and pushes one combined UTF-8 string
- * per tick. node-pty's StringDecoder keeps multibyte sequences intact per
- * read, and main only ever concatenates whole reads (never slices a
- * string), so codepoints never split across a coalesce boundary.
+ * node-pty reads on a 5ms trailing timer (VS Code's bufferer window; see
+ * `DEFAULT_COALESCE_MS` in terminal-manager.ts) and pushes one combined
+ * UTF-8 string per tick. node-pty's StringDecoder keeps multibyte sequences
+ * intact per read, and main only ever concatenates whole reads (never
+ * slices a string), so codepoints never split across a coalesce boundary.
*/
'ok:pty:data': { payload: OkPtyData };
/**
@@ -281,4 +282,13 @@ export interface EventChannels {
* normal exit carries `exitCode`/`signal`.
*/
'ok:pty:exit': { payload: OkPtyExit };
+ /**
+ * Main → every window when Electron's assistive-tech signal flips
+ * (`app.on('accessibility-support-changed')` — a screen reader such as
+ * VoiceOver attached or detached). The cold-start value rides window
+ * creation as the `--ok-screen-reader-active=1` argv flag; this event keeps
+ * the preload's live mirror current so an already-open terminal can toggle
+ * xterm's `screenReaderMode` in place.
+ */
+ 'ok:accessibility:changed': { payload: { screenReaderActive: boolean } };
}
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 437eee50a..600e0f37d 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -112,7 +112,8 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {
sent.filter((s) => s.channel === 'ok:pty:data').map((s) => s.payload.data as string);
const exits = (): Array<Record<string, unknown>> =>
sent.filter((s) => s.channel === 'ok:pty:exit').map((s) => s.payload);
- return { mgr, sent, forked, warns, runTimers, dataPayloads, exits };
+ const liveTimerCount = (): number => timers.filter((t) => t !== null).length;
+ return { mgr, sent, forked, warns, runTimers, dataPayloads, exits, liveTimerCount };
}
const PROJECT = '/Users/me/project';
@@ -234,6 +235,9 @@ describe('createTerminalManager — coalescing + UTF-8 integrity', () => {
cols: 80,
rows: 24,
});
+ // Trailing-only on purpose: a TUI redraw burst (erase + repaint) must land
+ // as ONE push — a leading-edge flush would deliver the erase fragment
+ // alone and render the partial state for a frame (visible tearing).
h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'a' });
h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'b' });
h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'c' });
@@ -472,6 +476,20 @@ describe('createTerminalManager — destroyed-window guard', () => {
h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
expect(h.sent).toEqual([]);
});
+
+ test('a dead page does not spin the flush timer: a tick that delivered nothing stays disarmed', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });
+ // The page dies with output buffered inside the coalesce window.
+ wc.destroyed = true;
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'a' });
+ h.runTimers();
+ // Nothing deliverable → no re-arm (a dead page must not tick a timer
+ // forever). The buffered output stays put for a later adopt's replay path.
+ expect(h.liveTimerCount()).toBe(0);
+ expect(h.dataPayloads()).toEqual([]);
+ });
});
describe('createTerminalManager — lifecycle reap', () => {
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index 7cbcce135..8927fde73 100644
--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -201,7 +201,11 @@ const readinessBanner = (page: Page) => page.getByTestId('terminal-readiness-ban
/** Open the dock (via the real menu toggle) and wait for the panel to mount. */
async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {
- await clickViewTerminalItem(app);
+ const clicked = await clickViewTerminalItem(app);
+ // Fail loud when the menu item is missing — otherwise the click silently
+ // no-ops and the failure surfaces 15s later as an unrelated-looking
+ // "Terminal section not visible" timeout.
+ expect(clicked, 'View menu should expose a Show/Hide Terminal item').not.toBe(false);
await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
}
@@ -392,6 +396,54 @@ test.describe('Docked terminal — live Electron', () => {
.toContain('OK_E2E_MARKER_123');
});
+ // Resize storm at real-PTY fidelity: a section/window drag resizes the
+ // terminal container on every pointer frame; the panel fits xterm per event
+ // but coalesces the PTY resize (leading + trailing throttle), so a storm
+ // must (1) never wedge the shell and (2) always settle the PTY at the final
+ // fitted grid — a dropped trailing resize would leave the shell's winsize at
+ // a mid-drag width. The storm returns the window to its starting size, so
+ // `tput cols` before and after must agree.
+ test('a window-resize storm keeps the shell responsive and settles the PTY at the fitted grid', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('resize-storm', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ await typeInTerminal(page, 'echo BEFORE_COLS=$(tput cols)\r');
+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/BEFORE_COLS=\d+/);
+ const before = (await readTerminalText(page)).match(/BEFORE_COLS=(\d+)/)?.[1];
+
+ // Real window resizes from main — each one reflows the panel group and
+ // fires the terminal container's ResizeObserver, like a drag frame.
+ await app.evaluate(async ({ BrowserWindow }) => {
+ const win = BrowserWindow.getAllWindows()[0];
+ if (!win) throw new Error('no window to resize');
+ const [w, h] = win.getSize();
+ for (let i = 0; i < 24; i++) {
+ const dw = (i % 2 === 0 ? -1 : 1) * (8 + (i % 5) * 6);
+ win.setSize(w + dw, h, false);
+ await new Promise((r) => setTimeout(r, 40));
+ }
+ win.setSize(w, h, false);
+ });
+
+ // The shell still echoes (no wedged PTY, no dead renderer), and its
+ // winsize settled back to the pre-storm width — the trailing throttled
+ // resize landed. Polled: the trailing PTY resize lands within ~100ms of
+ // the last step, but the storm's queued SIGWINCH redraws drain async.
+ await typeInTerminal(page, 'echo AFTER_COLS=$(tput cols)\r');
+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/AFTER_COLS=\d+/);
+ expect(before).toBeTruthy();
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 10_000 })
+ .toContain(`AFTER_COLS=${before}`);
+ });
+
// Dock controls — the click toggle replaced the drag grip. This asserts the UI
// shape (dock-toggle + collapse present, no grip) in the live build. The default
// dock is the right column, so the toggle offers "Dock terminal to the bottom".