Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Keep Windows terminal scrollback across a row-growing move (#4918)

Nick Gomez216557f04231
diff --git a/.changeset/windows-terminal-scrollback-on-grow.md b/.changeset/windows-terminal-scrollback-on-grow.md
new file mode 100644
index 000000000..0a4fdd008
--- /dev/null
+++ b/.changeset/windows-terminal-scrollback-on-grow.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+On Windows, the terminal no longer loses recent output from its scrollback when it grows taller, such as when you move it to the right.
diff --git a/packages/app/src/components/TerminalPanel.resize-scrollback.dom.test.tsx b/packages/app/src/components/TerminalPanel.resize-scrollback.dom.test.tsx
new file mode 100644
index 000000000..0e9e02a79
--- /dev/null
+++ b/packages/app/src/components/TerminalPanel.resize-scrollback.dom.test.tsx
@@ -0,0 +1,424 @@
+import { randomUUID } from 'node:crypto';
+import { act, render, waitFor } from '@testing-library/react';
+import type { Terminal as XtermTerminal } from '@xterm/xterm';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import type { OkDesktopBridge, OkPtyData } from '@/lib/desktop-bridge-types';
+
+interface Geometry {
+ readonly cols: number;
+ readonly rows: number;
+}
+
+const DOCK_GEOMETRY: Geometry = { cols: 200, rows: 13 };
+const TALLER_DOCK_GEOMETRY: Geometry = { cols: DOCK_GEOMETRY.cols, rows: 48 };
+const NARROWED_DOCK_GEOMETRY: Geometry = { cols: 92, rows: DOCK_GEOMETRY.rows };
+const COLUMN_GEOMETRY: Geometry = {
+ cols: NARROWED_DOCK_GEOMETRY.cols,
+ rows: TALLER_DOCK_GEOMETRY.rows,
+};
+const SCROLL_LINE_COUNT = 120;
+
+const constructedTerminals: XtermTerminal[] = [];
+const laidOut: { geometry: Geometry | null } = { geometry: null };
+
+vi.doMock('@xterm/xterm', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@xterm/xterm')>();
+ class RecordedTerminal extends actual.Terminal {
+ constructor(...args: ConstructorParameters<typeof actual.Terminal>) {
+ super(...args);
+ constructedTerminals.push(this);
+ }
+ }
+ return { ...actual, Terminal: RecordedTerminal };
+});
+
+vi.doMock('@xterm/addon-fit', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@xterm/addon-fit')>();
+ class LaidOutFitAddon extends actual.FitAddon {
+ override proposeDimensions() {
+ return laidOut.geometry === null ? undefined : { ...laidOut.geometry };
+ }
+ }
+ return { ...actual, FitAddon: LaidOutFitAddon };
+});
+
+type ResizeCallback = (
+ entries: readonly { contentRect: { width: number; height: number } }[],
+) => void;
+
+const resizeObservers: LayoutResizeObserver[] = [];
+class LayoutResizeObserver {
+ readonly targets: Element[] = [];
+ readonly callback: ResizeCallback;
+ disconnected = false;
+ constructor(callback: ResizeCallback) {
+ this.callback = callback;
+ resizeObservers.push(this);
+ }
+ observe(target: Element) {
+ this.targets.push(target);
+ }
+ unobserve() {}
+ disconnect() {
+ this.disconnected = true;
+ }
+}
+vi.stubGlobal('ResizeObserver', LayoutResizeObserver);
+
+const { TerminalPanel } = await import('./TerminalPanel');
+
+const nextAnimationFrame = () =>
+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+afterEach(async () => {
+ await nextAnimationFrame();
+ await nextAnimationFrame();
+ constructedTerminals.length = 0;
+ resizeObservers.length = 0;
+ laidOut.geometry = null;
+});
+
+interface ModelledHost {
+ readonly platform: OkDesktopBridge['platform'];
+ readonly prompt: string;
+ repaintAfterResize(previous: Geometry, next: Geometry, screen: ScreenModel): string;
+}
+
+interface ScreenModel {
+ readonly rows: string[];
+ readonly cursorRow: number;
+ readonly cursorCol: number;
+}
+
+const conptyHost: ModelledHost = {
+ platform: 'win32',
+ prompt: 'PS C:\\Users\\runneradmin\\project> ',
+ repaintAfterResize(previous, next, screen) {
+ if (next.rows <= previous.rows) return '';
+ let repaint = '\x1b[H';
+ for (let row = 0; row < next.rows; row += 1) {
+ repaint += `\x1b[${row + 1};1H${screen.rows[row] ?? ''}\x1b[K`;
+ }
+ return `${repaint}\x1b[${screen.cursorRow + 1};${screen.cursorCol + 1}H`;
+ },
+};
+
+const unixPtyHost = (platform: 'darwin' | 'linux'): ModelledHost => ({
+ platform,
+ prompt: 'user@host project % ',
+ repaintAfterResize: () => '',
+});
+
+function hostSession(host: ModelledHost, token: string) {
+ const dataSubscribers: Array<(message: OkPtyData) => void> = [];
+ const pendingDrains: Array<() => void> = [];
+ const repaints: Promise<void>[] = [];
+ const ptyId = `pty-${token}`;
+ const outputLines: string[] = [''];
+ const state: { geometry: Geometry | null; replay: string | null } = {
+ geometry: null,
+ replay: null,
+ };
+
+ const screen = (): ScreenModel => {
+ const rows = state.geometry?.rows ?? 0;
+ const visible = outputLines.slice(-rows);
+ return {
+ rows: visible,
+ cursorRow: visible.length - 1,
+ cursorCol: visible.at(-1)?.length ?? 0,
+ };
+ };
+
+ const deliver = (data: string) =>
+ new Promise<void>((resolve) => {
+ pendingDrains.push(resolve);
+ for (const subscriber of dataSubscribers) subscriber({ ptyId, data });
+ });
+
+ const terminal = {
+ create: vi.fn(async (request: { cols: number; rows: number }) => {
+ state.geometry = { cols: request.cols, rows: request.rows };
+ return { ok: true as const, ptyId };
+ }),
+ start: vi.fn(async () => ({ ok: true as const, replay: '' })),
+ adopt: vi.fn(async () =>
+ state.replay === null
+ ? { ok: false as const, reason: 'unknown-session' as const }
+ : { ok: true as const, replay: state.replay },
+ ),
+ input: vi.fn(),
+ resize: vi.fn((_id: string, cols: number, rows: number) => {
+ const previous = state.geometry ?? { cols, rows };
+ const before = screen();
+ state.geometry = { cols, rows };
+ const repaint = host.repaintAfterResize(previous, { cols, rows }, before);
+ if (repaint !== '') repaints.push(deliver(repaint));
+ }),
+ kill: vi.fn(async () => {}),
+ drain: vi.fn(() => {
+ pendingDrains.shift()?.();
+ }),
+ onData: vi.fn((subscriber: (message: OkPtyData) => void) => {
+ dataSubscribers.push(subscriber);
+ return () => {};
+ }),
+ onExit: vi.fn(() => () => {}),
+ onNotice: vi.fn(() => () => {}),
+ claudePreflight: vi.fn(async () => ({ claude: 'present' as const })),
+ cliPreflight: vi.fn(async () => ({ onPath: 'present' as const })),
+ };
+
+ const bridge = {
+ terminal,
+ shell: {
+ openExternal: vi.fn(async () => {}),
+ openAsset: vi.fn(async () => ({ ok: true })),
+ revealAsset: vi.fn(async () => ({ ok: true })),
+ revealExternal: vi.fn(async () => ({ ok: true, outcome: 'revealed' })),
+ },
+ project: { checkTargetExists: vi.fn(async () => 'exists' as const) },
+ config: { e2eSmoke: true, projectPath: '/project' },
+ platform: host.platform,
+ getPathForFile: () => null,
+ } as unknown as OkDesktopBridge;
+
+ const record = (text: string) => {
+ const [first = '', ...rest] = text.split('\r\n');
+ outputLines[outputLines.length - 1] += first;
+ outputLines.push(...rest);
+ };
+
+ const print = async (text: string) => {
+ record(text);
+ await act(() => deliver(text));
+ };
+
+ const holdForAdoption = (text: string, geometry: Geometry) => {
+ record(text);
+ state.replay = text;
+ state.geometry = geometry;
+ };
+
+ return {
+ bridge,
+ ptyId,
+ terminal,
+ get geometry() {
+ return state.geometry;
+ },
+ print,
+ holdForAdoption,
+ repaintsDelivered: () => Promise.all(repaints),
+ get outputLines(): readonly string[] {
+ return outputLines;
+ },
+ };
+}
+
+function scrollbackFixture(token: string, prompt: string) {
+ const sentinel = `SENTINEL_${token}`;
+ const scrollStart = `SCROLL_START_${token}`;
+ const scrollLines = Array.from(
+ { length: SCROLL_LINE_COUNT },
+ (_, index) => `SCROLL_${token}_${String(index + 1).padStart(3, '0')}`,
+ );
+ const history = [sentinel, scrollStart, ...scrollLines];
+ const transcript = [`${prompt}print-scrollback-fixture`, ...history, prompt].join('\r\n');
+ const historyLine = new RegExp(`^(?:SENTINEL|SCROLL_START|SCROLL)_${token}(?:_\\d+)?$`);
+ return { history, transcript, historyLine };
+}
+
+function bufferLines(term: XtermTerminal): string[] {
+ const buffer = term.buffer.active;
+ return Array.from(
+ { length: buffer.length },
+ (_, index) => buffer.getLine(index)?.translateToString(true) ?? '',
+ );
+}
+
+function viewportLines(term: XtermTerminal): string[] {
+ const buffer = term.buffer.active;
+ return Array.from(
+ { length: term.rows },
+ (_, row) => buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '',
+ );
+}
+
+interface BufferRow {
+ readonly text: string;
+ readonly wrapped: boolean;
+}
+
+function bufferRows(term: XtermTerminal): BufferRow[] {
+ const buffer = term.buffer.active;
+ return Array.from({ length: buffer.length }, (_, index) => {
+ const line = buffer.getLine(index);
+ return { text: line?.translateToString(true) ?? '', wrapped: line?.isWrapped ?? false };
+ });
+}
+
+function filledLine(label: string, length: number): string {
+ return `${label}${'0123456789'.repeat(Math.ceil(length / 10))}`.slice(0, length);
+}
+
+function rowsOfWidth(line: string, cols: number): string[] {
+ return Array.from({ length: Math.ceil(line.length / cols) }, (_, index) =>
+ line.slice(index * cols, (index + 1) * cols),
+ );
+}
+
+type SessionEstablishment = 'created' | 'adopted';
+
+async function mountTerminalWithHistory(host: ModelledHost, establishment: SessionEstablishment) {
+ const token = randomUUID().replaceAll('-', '');
+ const session = hostSession(host, token);
+ const fixture = scrollbackFixture(token, host.prompt);
+ if (establishment === 'adopted') session.holdForAdoption(fixture.transcript, DOCK_GEOMETRY);
+ render(
+ <TerminalPanel
+ bridge={session.bridge}
+ adoptPtyId={establishment === 'adopted' ? session.ptyId : null}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(constructedTerminals).toHaveLength(1);
+ expect(document.querySelector('[data-terminal-status="running"]')).not.toBeNull();
+ });
+ const term = constructedTerminals[0];
+ if (term === undefined) throw new Error('TerminalPanel constructed no xterm Terminal');
+
+ const containerObserver = () => {
+ const observer = resizeObservers.find(
+ (candidate) =>
+ !candidate.disconnected &&
+ candidate.targets.some((target) => target.matches('[data-terminal-status]')),
+ );
+ if (observer === undefined) throw new Error('TerminalPanel observes no terminal container');
+ return observer;
+ };
+
+ const layOut = async (geometry: Geometry) => {
+ laidOut.geometry = geometry;
+ await act(async () => {
+ containerObserver().callback([
+ { contentRect: { width: geometry.cols, height: geometry.rows } },
+ ]);
+ });
+ await waitFor(() => {
+ expect(term.rows).toBe(geometry.rows);
+ expect(session.geometry).toEqual(geometry);
+ });
+ await session.repaintsDelivered();
+ };
+
+ await layOut(DOCK_GEOMETRY);
+ if (establishment === 'created') await session.print(fixture.transcript);
+
+ return { ...fixture, term, session, layOut };
+}
+
+describe.each([
+ { growth: 'the dock dragged taller', grown: TALLER_DOCK_GEOMETRY },
+ { growth: 'a move to the right column', grown: COLUMN_GEOMETRY },
+])('TerminalPanel row growth on a ConPTY-hosted shell (win32, $growth)', ({ grown }) => {
+ test.each([{ establishment: 'created' as const }, { establishment: 'adopted' as const }])(
+ 'growing the terminal keeps every scrollback line exactly once, in order, after the host repaints its view ($establishment session)',
+ async ({ establishment }) => {
+ const { history, historyLine, term, layOut } = await mountTerminalWithHistory(
+ conptyHost,
+ establishment,
+ );
+
+ expect(
+ bufferLines(term).filter((line) => historyLine.test(line)),
+ 'the scrollback held every emitted line before the resize',
+ ).toEqual(history);
+ expect(
+ term.buffer.active.baseY,
+ 'the dock-sized terminal holds more scrollback than the growth can pull back into view',
+ ).toBeGreaterThan(grown.rows - DOCK_GEOMETRY.rows);
+
+ await layOut(grown);
+
+ expect(
+ bufferLines(term).filter((line) => historyLine.test(line)),
+ 'a row-growing resize on a ConPTY host lost or duplicated scrollback',
+ ).toEqual(history);
+ },
+ );
+});
+
+describe('TerminalPanel line wrapping on a ConPTY-hosted shell (win32)', () => {
+ test('narrowing the terminal reflows a line longer than the new width into wrapped rows', async () => {
+ const { term, session, layOut } = await mountTerminalWithHistory(conptyHost, 'created');
+ const label = `REFLOW_${randomUUID().replaceAll('-', '')}_`;
+ const longLine = filledLine(label, DOCK_GEOMETRY.cols - 1);
+ await session.print(`\r\n${longLine}\r\n${conptyHost.prompt}`);
+ expect(
+ bufferRows(term).filter((row) => row.text.startsWith(label)),
+ 'the dock-width terminal holds the long line on one unwrapped row',
+ ).toEqual([{ text: longLine, wrapped: false }]);
+
+ await layOut(NARROWED_DOCK_GEOMETRY);
+ expect(term.cols, 'the terminal narrowed to the laid-out width').toBe(
+ NARROWED_DOCK_GEOMETRY.cols,
+ );
+
+ const rows = bufferRows(term);
+ const firstRow = rows.findIndex((row) => row.text.startsWith(label));
+ const reflowed: BufferRow[] = [
+ ...rowsOfWidth(longLine, NARROWED_DOCK_GEOMETRY.cols).map((text, index) => ({
+ text,
+ wrapped: index > 0,
+ })),
+ { text: conptyHost.prompt, wrapped: false },
+ ];
+ expect(
+ rows.slice(firstRow, firstRow + reflowed.length),
+ 'the long line reflowed into wrapped rows of the narrower width, ending before the prompt',
+ ).toEqual(reflowed);
+ });
+
+ test('a full-width line followed by a line break leaves the next row unwrapped', async () => {
+ const { term, session } = await mountTerminalWithHistory(conptyHost, 'created');
+ const token = randomUUID().replaceAll('-', '');
+ const fullWidthLine = filledLine(`FULL_${token}_`, term.cols);
+ const nextLine = `NEXT_${token}`;
+ await session.print(`\r\n${fullWidthLine}\r\n${nextLine}\r\n${conptyHost.prompt}`);
+
+ const rows = bufferRows(term);
+ const fullWidthRow = rows.findIndex((row) => row.text === fullWidthLine);
+ expect(fullWidthRow, 'the full-width line filled exactly one row').toBeGreaterThanOrEqual(0);
+ expect(
+ rows.slice(fullWidthRow, fullWidthRow + 2),
+ 'the row after a full-width line and a line break is not marked as its continuation',
+ ).toEqual([
+ { text: fullWidthLine, wrapped: false },
+ { text: nextLine, wrapped: false },
+ ]);
+ });
+});
+
+describe.each([{ platform: 'darwin' as const }, { platform: 'linux' as const }])(
+ 'TerminalPanel row growth on a Unix pty ($platform)',
+ ({ platform }) => {
+ test('growing the terminal brings the most recent scrollback back into view above the prompt', async () => {
+ const { history, historyLine, term, session, layOut } = await mountTerminalWithHistory(
+ unixPtyHost(platform),
+ 'created',
+ );
+ await layOut(TALLER_DOCK_GEOMETRY);
+
+ expect(
+ bufferLines(term).filter((line) => historyLine.test(line)),
+ 'a row-growing resize on a Unix pty lost or duplicated scrollback',
+ ).toEqual(history);
+ expect(
+ viewportLines(term),
+ 'the grown viewport shows the latest output with the prompt on its bottom row',
+ ).toEqual(session.outputLines.slice(-TALLER_DOCK_GEOMETRY.rows));
+ });
+ },
+);
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 54d8529bd..016285936 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -250,6 +250,7 @@ function TerminalSession({
scrollback: 10000,
smoothScrollDuration: 125,
scrollSensitivity: 3,
+ windowsPty: bridge.platform === 'win32' ? { backend: 'conpty' } : undefined,
linkHandler: {
activate: (_event, uri) => openUrl(uri),
},
diff --git a/packages/desktop/tests/smoke/_helpers/terminal-scrollback.test.ts b/packages/desktop/tests/smoke/_helpers/terminal-scrollback.test.ts
new file mode 100644
index 000000000..80a1c802d
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/terminal-scrollback.test.ts
@@ -0,0 +1,226 @@
+import { describe, expect, test } from 'vitest';
+import {
+ numberedScrollLine,
+ readScrollbackUpward,
+ type ScrollbackExpectation,
+} from './terminal-scrollback';
+import { terminalSmokeShellCommands } from './terminal-smoke-shell';
+
+const TOKEN = '0123456789abcdef0123456789abcdef';
+const SENTINEL = `SENTINEL_${TOKEN}`;
+const SCROLL_START = `SCROLL_START_${TOKEN}`;
+const LINE_PREFIX = `SCROLL_${TOKEN}_`;
+const LINE_COUNT = 120;
+const DOCK_ROWS = 13;
+const COLUMN_ROWS = 48;
+const PAGE_LIMIT = 40;
+const PROMPT = 'PS C:\\project> ';
+
+const expectation: ScrollbackExpectation = {
+ markers: [SENTINEL, SCROLL_START],
+ linePrefix: LINE_PREFIX,
+ lineCount: LINE_COUNT,
+};
+
+const scrollLines = Array.from({ length: LINE_COUNT }, (_, index) =>
+ numberedScrollLine(LINE_PREFIX, index + 1),
+);
+
+function transcript(platform: NodeJS.Platform, lines: readonly string[]): string[] {
+ const command = terminalSmokeShellCommands(platform).scroll(
+ SENTINEL,
+ SCROLL_START,
+ LINE_PREFIX,
+ LINE_COUNT,
+ );
+ return ['PowerShell 7.6.5', `${PROMPT}${command}`, SENTINEL, SCROLL_START, ...lines, PROMPT];
+}
+
+function renderedTerminal(
+ buffer: readonly string[],
+ rows: number,
+ startAt: 'bottom' | 'top' = 'bottom',
+) {
+ const bottomViewportY = Math.max(0, buffer.length - rows);
+ let viewportY = startAt === 'bottom' ? bottomViewportY : 0;
+ const view = () => buffer.slice(viewportY, viewportY + rows).join('');
+ return {
+ readSettledView: async () => view(),
+ pageUpFrom: async (_settledView: string) => {
+ viewportY = Math.max(0, viewportY - (rows - 1));
+ return view();
+ },
+ pageDownFrom: async (_settledView: string) => {
+ viewportY = Math.min(bottomViewportY, viewportY + (rows - 1));
+ return view();
+ },
+ };
+}
+
+function linesOverwrittenByDockToColumnGrowth(): string[] {
+ const rowsPulledIntoView = COLUMN_ROWS - DOCK_ROWS;
+ const firstPreGrowthViewportLine = LINE_COUNT - (DOCK_ROWS - 1);
+ return scrollLines.slice(
+ firstPreGrowthViewportLine - rowsPulledIntoView,
+ firstPreGrowthViewportLine,
+ );
+}
+
+function pagesToTop(bufferLength: number, rows: number): number {
+ return Math.ceil(Math.max(0, bufferLength - rows) / (rows - 1));
+}
+
+function pagesToCrossAndConfirmTheEnd(bufferLength: number, rows: number): number {
+ return pagesToTop(bufferLength, rows) + 1;
+}
+
+describe('reading terminal scrollback upward', () => {
+ test.each([
+ { platform: 'win32' as const, rows: DOCK_ROWS },
+ { platform: 'win32' as const, rows: COLUMN_ROWS },
+ { platform: 'linux' as const, rows: DOCK_ROWS },
+ ])(
+ 'accepts a $platform buffer of $rows rows that still holds every emitted line',
+ async ({ platform, rows }) => {
+ const terminal = renderedTerminal(transcript(platform, scrollLines), rows);
+
+ await expect(readScrollbackUpward(terminal, expectation, PAGE_LIMIT)).resolves.toEqual({
+ kind: 'complete',
+ });
+ },
+ );
+
+ test('names exactly the recent lines a row-growing resize overwrote, though the oldest markers survive', async () => {
+ const overwritten = linesOverwrittenByDockToColumnGrowth();
+ const survivors = scrollLines.filter((line) => !overwritten.includes(line));
+ const terminal = renderedTerminal(transcript('win32', survivors), DOCK_ROWS);
+
+ await expect(readScrollbackUpward(terminal, expectation, PAGE_LIMIT)).resolves.toEqual({
+ kind: 'lost',
+ pagesRead: expect.any(Number),
+ missingMarkers: [],
+ missingLines: overwritten,
+ });
+ });
+
+ test.each([
+ { platform: 'win32' as const, rows: DOCK_ROWS },
+ { platform: 'win32' as const, rows: COLUMN_ROWS },
+ { platform: 'linux' as const, rows: DOCK_ROWS },
+ { platform: 'linux' as const, rows: COLUMN_ROWS },
+ ])(
+ 'accepts a $platform buffer of $rows rows that holds every emitted line when the read starts from a view parked at its top',
+ async ({ platform, rows }) => {
+ const terminal = renderedTerminal(transcript(platform, scrollLines), rows, 'top');
+ expect(
+ await terminal.readSettledView(),
+ 'the parked view starts above the newest emitted line',
+ ).not.toContain(numberedScrollLine(LINE_PREFIX, LINE_COUNT));
+
+ await expect(readScrollbackUpward(terminal, expectation, PAGE_LIMIT)).resolves.toEqual({
+ kind: 'complete',
+ });
+ },
+ );
+
+ test.each([{ rows: COLUMN_ROWS }, { rows: DOCK_ROWS }])(
+ 'names exactly the lines a row-growing resize overwrote when the read starts from a view parked at the top of $rows rows',
+ async ({ rows }) => {
+ const overwritten = linesOverwrittenByDockToColumnGrowth();
+ const survivors = scrollLines.filter((line) => !overwritten.includes(line));
+ const terminal = renderedTerminal(transcript('win32', survivors), rows, 'top');
+ expect(
+ await terminal.readSettledView(),
+ 'the parked view starts above the newest emitted line',
+ ).not.toContain(numberedScrollLine(LINE_PREFIX, LINE_COUNT));
+
+ await expect(readScrollbackUpward(terminal, expectation, PAGE_LIMIT)).resolves.toEqual({
+ kind: 'lost',
+ pagesRead: expect.any(Number),
+ missingMarkers: [],
+ missingLines: overwritten,
+ });
+ },
+ );
+
+ test.each(['win32', 'linux'] as const)(
+ 'does not count the echoed %s scroll command as the lines it prints',
+ async (platform) => {
+ const terminal = renderedTerminal(transcript(platform, []), DOCK_ROWS);
+
+ const verdict = await readScrollbackUpward(terminal, expectation, PAGE_LIMIT);
+
+ expect(verdict).toMatchObject({ kind: 'lost', missingLines: scrollLines });
+ },
+ );
+
+ test('reports an unreached top, not a loss, when the page limit ends the read first', async () => {
+ const buffer = transcript('win32', scrollLines);
+ const terminal = renderedTerminal(buffer, DOCK_ROWS);
+ const tooFewPages = pagesToTop(buffer.length, DOCK_ROWS) - 1;
+
+ const verdict = await readScrollbackUpward(terminal, expectation, tooFewPages);
+
+ expect(verdict).toMatchObject({ kind: 'unreached', pagesRead: tooFewPages });
+ });
+
+ test('reports an unreached read, not a loss, when the page limit ends before the descent from a parked view confirms the bottom', async () => {
+ const overwritten = linesOverwrittenByDockToColumnGrowth();
+ const survivors = scrollLines.filter((line) => !overwritten.includes(line));
+ const buffer = transcript('win32', survivors);
+ const terminal = renderedTerminal(buffer, DOCK_ROWS, 'top');
+ const onePageShortOfConfirmingTheBottom =
+ pagesToCrossAndConfirmTheEnd(buffer.length, DOCK_ROWS) - 1;
+ expect(
+ await terminal.readSettledView(),
+ 'the parked view starts above the newest emitted line',
+ ).not.toContain(numberedScrollLine(LINE_PREFIX, LINE_COUNT));
+
+ const verdict = await readScrollbackUpward(
+ terminal,
+ expectation,
+ onePageShortOfConfirmingTheBottom,
+ );
+
+ expect(verdict).toMatchObject({
+ kind: 'unreached',
+ pagesRead: onePageShortOfConfirmingTheBottom,
+ });
+ });
+
+ test('charges the descent from a parked view to the same page limit as the ascent', async () => {
+ const overwritten = linesOverwrittenByDockToColumnGrowth();
+ const survivors = scrollLines.filter((line) => !overwritten.includes(line));
+ const buffer = transcript('win32', survivors);
+ const terminal = renderedTerminal(buffer, DOCK_ROWS, 'top');
+ const onePageShortOfBothLegs = 2 * pagesToCrossAndConfirmTheEnd(buffer.length, DOCK_ROWS) - 1;
+ expect(
+ await terminal.readSettledView(),
+ 'the parked view starts above the newest emitted line',
+ ).not.toContain(numberedScrollLine(LINE_PREFIX, LINE_COUNT));
+
+ const verdict = await readScrollbackUpward(terminal, expectation, onePageShortOfBothLegs);
+
+ expect(verdict).toMatchObject({ kind: 'unreached', pagesRead: onePageShortOfBothLegs });
+ });
+
+ test.each([{ rows: DOCK_ROWS }, { rows: COLUMN_ROWS }])(
+ 'leaves the view scrolled back above the newest line after a complete read from the bottom of $rows rows',
+ async ({ rows }) => {
+ const terminal = renderedTerminal(transcript('win32', scrollLines), rows);
+ const newestLine = numberedScrollLine(LINE_PREFIX, LINE_COUNT);
+ expect(
+ await terminal.readSettledView(),
+ 'the read starts from a view that shows the newest emitted line',
+ ).toContain(newestLine);
+
+ await expect(readScrollbackUpward(terminal, expectation, PAGE_LIMIT)).resolves.toEqual({
+ kind: 'complete',
+ });
+ expect(
+ await terminal.readSettledView(),
+ 'the read leaves the view scrolled back for the next move to keep',
+ ).not.toContain(newestLine);
+ },
+ );
+});
diff --git a/packages/desktop/tests/smoke/_helpers/terminal-scrollback.ts b/packages/desktop/tests/smoke/_helpers/terminal-scrollback.ts
new file mode 100644
index 000000000..3d35d22da
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/terminal-scrollback.ts
@@ -0,0 +1,68 @@
+export interface ScrollbackExpectation {
+ readonly markers: readonly string[];
+ readonly linePrefix: string;
+ readonly lineCount: number;
+}
+
+export type ScrollbackVerdict =
+ | { readonly kind: 'complete' }
+ | {
+ readonly kind: 'lost' | 'unreached';
+ readonly pagesRead: number;
+ readonly missingMarkers: readonly string[];
+ readonly missingLines: readonly string[];
+ };
+
+export function numberedScrollLine(linePrefix: string, lineNumber: number): string {
+ return `${linePrefix}${String(lineNumber).padStart(3, '0')}`;
+}
+
+export interface ScrollbackReader {
+ readonly readSettledView: () => Promise<string>;
+ readonly pageUpFrom: (settledView: string) => Promise<string>;
+ readonly pageDownFrom: (settledView: string) => Promise<string>;
+}
+
+export async function readScrollbackUpward(
+ { readSettledView, pageUpFrom, pageDownFrom }: ScrollbackReader,
+ expectation: ScrollbackExpectation,
+ pageLimit: number,
+): Promise<ScrollbackVerdict> {
+ const expectedLines = Array.from({ length: expectation.lineCount }, (_, index) =>
+ numberedScrollLine(expectation.linePrefix, index + 1),
+ );
+ const pendingMarkers = new Set(expectation.markers);
+ const pendingLines = new Set(expectedLines);
+ const absorb = (view: string) => {
+ for (const marker of pendingMarkers) if (view.includes(marker)) pendingMarkers.delete(marker);
+ for (const line of pendingLines) if (view.includes(line)) pendingLines.delete(line);
+ };
+ const complete = () => pendingMarkers.size === 0 && pendingLines.size === 0;
+
+ let view = await readSettledView();
+ let pagesRead = 0;
+ let reachedBottom = false;
+ while (!reachedBottom && pagesRead < pageLimit) {
+ const next = await pageDownFrom(view);
+ pagesRead += 1;
+ reachedBottom = next === view;
+ view = next;
+ }
+ absorb(view);
+ let reachedTop = false;
+ while (!complete() && !reachedTop && pagesRead < pageLimit) {
+ const next = await pageUpFrom(view);
+ pagesRead += 1;
+ reachedTop = next === view;
+ view = next;
+ absorb(view);
+ }
+
+ if (complete()) return { kind: 'complete' };
+ return {
+ kind: reachedTop ? 'lost' : 'unreached',
+ pagesRead,
+ missingMarkers: expectation.markers.filter((marker) => pendingMarkers.has(marker)),
+ missingLines: expectedLines.filter((line) => pendingLines.has(line)),
+ };
+}
diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
index 86222f95e..0aa155eb7 100644
--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import type { ElectronApplication, ElementHandle, Page } from '@playwright/test';
+import type { ElectronApplication, ElementHandle, JSHandle, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import {
@@ -19,6 +19,11 @@ import {
} from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
import { waitForShellReady } from './_helpers/terminal-ready';
+import {
+ numberedScrollLine,
+ readScrollbackUpward,
+ type ScrollbackExpectation,
+} from './_helpers/terminal-scrollback';
import {
seedTerminalShellProfiles,
terminalSmokeEnvironment,
@@ -38,6 +43,8 @@ const TARGET = resolveDesktopTarget();
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';
const SHELL_COMMANDS = terminalSmokeShellCommands();
+const SCROLLBACK_PAGE_LIMIT = 40;
+const SCROLL_SETTLE_FRAME_LIMIT = 60;
type TerminalHome = 'bottom' | 'right';
@@ -297,36 +304,45 @@ async function readActiveTerminal(page: Page): Promise<string> {
});
}
-async function expectScrollbackRetains(page: Page, ...markers: string[]): Promise<void> {
+async function expectScrollbackRetains(
+ page: Page,
+ expectation: ScrollbackExpectation,
+): Promise<void> {
await visibleTerminal(page).locator('.xterm-helper-textarea').focus();
- let text = await readTerminalRows(page);
- for (let step = 0; step < 40 && !markers.every((marker) => text.includes(marker)); step += 1) {
- await page.keyboard.press('Shift+PageUp');
- await page.evaluate(
- () =>
- new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- ),
- );
- text = await readTerminalRows(page);
- }
- for (const marker of markers) {
- expect(text, `terminal scrollback is missing ${marker}`).toContain(marker);
- }
- await settleScrollPosition(page);
+ const verdict = await readScrollbackUpward(
+ {
+ readSettledView: () => settleScrollPosition(page),
+ pageUpFrom: async (settledView) => {
+ await page.keyboard.press('Shift+PageUp');
+ return settleScrollPosition(page, settledView);
+ },
+ pageDownFrom: async (settledView) => {
+ await page.keyboard.press('Shift+PageDown');
+ return settleScrollPosition(page, settledView);
+ },
+ },
+ expectation,
+ SCROLLBACK_PAGE_LIMIT,
+ );
+ expect(verdict, 'terminal scrollback no longer holds every line the shell printed').toEqual({
+ kind: 'complete',
+ });
}
-async function settleScrollPosition(page: Page): Promise<void> {
+async function settleScrollPosition(page: Page, departFrom?: string): Promise<string> {
let previous = '';
let stable = 0;
- for (let step = 0; step < 60 && stable < 2; step += 1) {
+ let departed = departFrom === undefined;
+ for (let step = 0; step < SCROLL_SETTLE_FRAME_LIMIT && !(departed && stable >= 2); step += 1) {
await page.evaluate(
() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),
);
const current = await readTerminalRows(page);
+ departed ||= current !== departFrom;
stable = current === previous ? stable + 1 : 0;
previous = current;
}
+ return previous;
}
function waitForTerminalHome(page: Page, home: TerminalHome): Promise<void> {
@@ -401,6 +417,44 @@ async function expectTerminalMovedNotRebuilt(
});
}
+interface MenuActionTally {
+ count: number;
+ stop: () => void;
+}
+
+function tallyMenuActionDeliveries(
+ page: Page,
+ action: 'move-terminal',
+): Promise<JSHandle<MenuActionTally>> {
+ return page.evaluateHandle((counted) => {
+ const bridge = window.okDesktop;
+ if (!bridge) throw new Error('renderer desktop bridge is unavailable');
+ const tally: MenuActionTally = { count: 0, stop: () => {} };
+ tally.stop = bridge.onMenuAction((delivered) => {
+ if (delivered === counted) tally.count += 1;
+ });
+ return tally;
+ }, action);
+}
+
+function readBurstOutcome(
+ surface: ElementHandle<Element>,
+ deliveries: JSHandle<MenuActionTally>,
+ home: TerminalHome,
+) {
+ return surface.evaluate(
+ (element, { tally, containerId }) => ({
+ delivered: tally.count,
+ connected: element.isConnected,
+ atHome: element.closest(`#${containerId}`) !== null,
+ }),
+ {
+ tally: deliveries,
+ containerId: home === 'right' ? 'terminal-column' : 'terminal-dock-panel',
+ },
+ );
+}
+
async function readShellPid(page: Page, marker: string): Promise<number> {
await typeInActiveTerminal(page, `${SHELL_COMMANDS.processId(marker)}\r`);
let processId = 0;
@@ -478,43 +532,56 @@ test.describe('Terminal placement continuity — live Electron', () => {
const processMarker = `PROCESS_${token}`;
const sentinel = `SENTINEL_${token}`;
const scrollStart = `SCROLL_START_${token}`;
+ const scrollback: ScrollbackExpectation = {
+ markers: [sentinel, scrollStart],
+ linePrefix: `SCROLL_${token}_`,
+ lineCount: 120,
+ };
+ const newestScrollLine = numberedScrollLine(scrollback.linePrefix, scrollback.lineCount);
const processId = await readShellPid(page, processMarker);
await typeInActiveTerminal(
page,
- `${SHELL_COMMANDS.scroll(sentinel, scrollStart, `SCROLL_${token}_`, 120)}\r`,
+ `${SHELL_COMMANDS.scroll(sentinel, scrollStart, scrollback.linePrefix, scrollback.lineCount)}\r`,
);
await expect
.poll(() => readActiveTerminal(page), { timeout: 15_000 })
- .toContain(`SCROLL_${token}_120`);
- await expectScrollbackRetains(page, sentinel, scrollStart);
+ .toContain(newestScrollLine);
+ await expectScrollbackRetains(page, scrollback);
const liveSurface = await captureLiveTerminal(page);
await moveTerminal(app, page, 'right');
await expectTerminalMovedNotRebuilt(liveSurface, 'right');
- await expectStillScrolledBack(page, `SCROLL_${token}_120`);
+ await expectStillScrolledBack(page, newestScrollLine);
await expectTerminalTabOrder(page, [firstTabId, secondTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
- await expectScrollbackRetains(page, sentinel, scrollStart);
+ await expectScrollbackRetains(page, scrollback);
expect(await readShellPid(page, processMarker)).toBe(processId);
const rightOutput = `RIGHT_OUTPUT_${token}`;
await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(rightOutput)}\r`);
await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(rightOutput);
- await expectScrollbackRetains(page, sentinel, scrollStart);
+ await expectScrollbackRetains(page, scrollback);
await moveTerminal(app, page, 'bottom');
await expectTerminalMovedNotRebuilt(liveSurface, 'bottom');
- await expectStillScrolledBack(page, `SCROLL_${token}_120`);
+ await expectStillScrolledBack(page, newestScrollLine);
await expectTerminalTabOrder(page, [firstTabId, secondTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
- await expectScrollbackRetains(page, sentinel, scrollStart);
+ await expectScrollbackRetains(page, scrollback);
expect(await readShellPid(page, processMarker)).toBe(processId);
const bottomOutput = `BOTTOM_OUTPUT_${token}`;
await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(bottomOutput)}\r`);
await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(bottomOutput);
- const rapidSettlement = waitForTerminalHome(page, 'right');
- await clickTerminalPlacementItemRapidly(app, 7, page);
- await rapidSettlement;
+ const rapidToggles = 7;
+ const rapidDeliveries = await tallyMenuActionDeliveries(page, 'move-terminal');
+ await clickTerminalPlacementItemRapidly(app, rapidToggles, page);
+ await expect
+ .poll(() => readBurstOutcome(liveSurface, rapidDeliveries, 'right'), {
+ message: 'the rapid placement burst never settled at its final placement',
+ })
+ .toEqual({ delivered: rapidToggles, connected: true, atHome: true });
+ await rapidDeliveries.evaluate((tally) => tally.stop());
+ await rapidDeliveries.dispose();
await expectTerminalMovedNotRebuilt(liveSurface, 'right');
await expect(page.locator('section[aria-label="Terminal"]')).toHaveCount(2);
await expect(visibleTerminal(page)).toHaveCount(1);
@@ -528,7 +595,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
const rapidOutput = `RAPID_OUTPUT_${token}`;
await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(rapidOutput)}\r`);
await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(rapidOutput);
- await expectScrollbackRetains(page, sentinel, scrollStart);
+ await expectScrollbackRetains(page, scrollback);
});
test('renderer restart restores the right layout and its live active terminal', async ({