mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(web): repair the history gap while reading, queue download-time output, add a phone reload control (#814)
Review follow-up on #815, and the phone case from #814: the gap opens below a reader who stays scrolled up while output arrives, and the bottom-only trigger never fired there. - Open the buffer load before the capture fetch so output arriving during the download is queued and replayed, not wiped by the reset. Every non-replay exit flushes the queue. A drop at the 128 KiB cap during an open load is deferred and resumed when the load ends instead of spending its retries against it. - Clear the live-output mark only when the response is source 'mux-full-history', on the scroll and tab-switch paths. - Repair on any upward scroll in a marked non-shell session, not only from the bottom. A content anchor (3-row signature, searched at most 2000 rows either side) keeps the row being read in place; no match falls back to distance from the bottom. - Tie replay travel to its session so a tab switch does not swallow moves on the new tab. - Reveal the partial-history notice when the initiating gesture reached the top, even if the anchor moved the viewport off row 0. - Touch-only Reload history button (#historyReloadBtn), styled in styles.css so wide touch viewports get it too. Non-touch pages skip its work entirely. - Docs, JSDoc and a changeset. Unit tests, and a Playwright browser test with trusted touch events and real xterm. Fixes #814
This commit is contained in:
1 parent
fd31315582
commit
b890ef3302
10 files changed
+1050
-84
No files matched your search
@@ -0,0 +1,451 @@
|
||||
/** Real xterm + trusted phone gestures recover tmux repaint gaps while reading (#814). */
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
|
||||
import type { Terminal } from '@xterm/xterm';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
|
||||
type Anchor = { signature: string[]; offset: number; viewportY: number; rowsFromBottom: number };
|
||||
type HistoryApp = {
|
||||
terminal: Terminal & {
|
||||
_core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } };
|
||||
};
|
||||
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
|
||||
sessions: Map<string, object>;
|
||||
activeSessionId: string;
|
||||
hideWelcome(): void;
|
||||
_onSessionTerminal(event: { id: string; data: string }): void;
|
||||
_liveOutputSinceFullPull: Set<string>;
|
||||
_fullHistoryRepullInFlight: boolean;
|
||||
_isLoadingBuffer: boolean;
|
||||
pendingWrites: string[];
|
||||
_terminalWriteInFlight: boolean;
|
||||
_bufferLoadOwner: unknown;
|
||||
_loadBufferQueue: { data: string; at: number }[] | null;
|
||||
_selectGeneration: number;
|
||||
_initGeneration: number;
|
||||
terminalLoadStates: Map<string, unknown>;
|
||||
_terminalFontReady: Promise<void>;
|
||||
_resizeTimeout: number | null;
|
||||
_lastResizeDims: { cols: number; rows: number } | null;
|
||||
_syncStickyScrollBaseline(): void;
|
||||
_captureViewportAnchor(): Anchor;
|
||||
_syncHistoryReloadButton(): void;
|
||||
};
|
||||
type RepairWindow = Window & {
|
||||
app: HistoryApp;
|
||||
repairTest: { pulls: number; anchor: Anchor | null; inject: boolean };
|
||||
repairReadiness?: { cols: number; rows: number; frames: number };
|
||||
};
|
||||
|
||||
const SESSION = 'history-repair-browser';
|
||||
const MARKER = 'AFTER-CAPTURE-DURING-DOWNLOAD';
|
||||
let server: WebServer;
|
||||
let browser: Browser;
|
||||
let baseUrl: string;
|
||||
const pageEvents = new WeakMap<Page, string[]>();
|
||||
|
||||
async function setupState(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app?.terminal?.buffer.active;
|
||||
return {
|
||||
appLoaded: document.body.classList.contains('app-loaded'),
|
||||
baseY: buffer?.baseY,
|
||||
length: buffer?.length,
|
||||
viewportY: buffer?.viewportY,
|
||||
cols: app?.terminal?.cols,
|
||||
rows: app?.terminal?.rows,
|
||||
resizePending: Boolean(app?._resizeTimeout),
|
||||
lastResizeDims: app?._lastResizeDims,
|
||||
proposedDims: app?.fitAddon?.proposeDimensions(),
|
||||
cellHeight: app?.terminal?._core?._renderService?.dimensions?.css?.cell?.height,
|
||||
pendingWrites: app?.pendingWrites?.length,
|
||||
terminalWriteInFlight: app?._terminalWriteInFlight,
|
||||
isLoadingBuffer: app?._isLoadingBuffer,
|
||||
bufferLoadOwner: app?._bufferLoadOwner,
|
||||
loadBufferQueue: app?._loadBufferQueue?.length ?? 0,
|
||||
activeSessionId: app?.activeSessionId,
|
||||
selectGeneration: app?._selectGeneration,
|
||||
sessions: app?.sessions ? [...app.sessions.keys()] : [],
|
||||
initGeneration: app?._initGeneration,
|
||||
terminalLoadStates: app?.terminalLoadStates ? [...app.terminalLoadStates] : [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function failureDetails(page: Page, error: unknown): Promise<Error> {
|
||||
const setup = await setupState(page).catch(String);
|
||||
const buffer = await bufferState(page).catch(String);
|
||||
return new Error(JSON.stringify({ setup, buffer, events: pageEvents.get(page) }), { cause: error });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new WebServer(0, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${server.boundPort}`;
|
||||
browser = await chromium.launch({ headless: true });
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
await server?.stop();
|
||||
}, 30_000);
|
||||
|
||||
async function openTerminal(
|
||||
touch: boolean,
|
||||
viewport = touch ? { width: 390, height: 640 } : { width: 1280, height: 800 }
|
||||
): Promise<{ context: BrowserContext; page: Page }> {
|
||||
const context = await browser.newContext({
|
||||
hasTouch: touch,
|
||||
isMobile: touch,
|
||||
viewport,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const events: string[] = [];
|
||||
pageEvents.set(page, events);
|
||||
page.on('console', (message) => {
|
||||
events.push(`console.${message.type()}: ${message.text()}`);
|
||||
if (events.length > 100) events.shift();
|
||||
});
|
||||
page.on('pageerror', (error) => events.push(`pageerror: ${error.stack || error.message}`));
|
||||
try {
|
||||
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => document.body.classList.contains('app-loaded'));
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app?.terminal && app._initGeneration > 0 && !app._isLoadingBuffer && app.terminalLoadStates.size === 0;
|
||||
});
|
||||
await page.evaluate(async (session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// A client-only OMP session isolates the rendering path from real CLI/PTYS.
|
||||
// Opening it changes layout, so finish the real resize path BEFORE seeding.
|
||||
app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'History repair' });
|
||||
app.activeSessionId = session;
|
||||
app.hideWelcome();
|
||||
await app._terminalFontReady;
|
||||
await document.fonts.ready;
|
||||
// Empty xterm can still carry fallback render metrics. Paint a glyph
|
||||
// before fitting, then clear it before the fixture's numbered output.
|
||||
const rendered = Promise.withResolvers<void>();
|
||||
const listener = app.terminal.onRender(() => {
|
||||
listener.dispose();
|
||||
rendered.resolve();
|
||||
});
|
||||
app.terminal.write('W');
|
||||
await rendered.promise;
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
app.terminal.write('\x1bc', resolve);
|
||||
await promise;
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
}, SESSION);
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
const { cols, rows } = app.terminal;
|
||||
const proposed = app.fitAddon.proposeDimensions();
|
||||
const cellHeight = app.terminal._core?._renderService?.dimensions?.css?.cell?.height || 0;
|
||||
if (
|
||||
cellHeight <= 0 ||
|
||||
proposed?.cols !== cols ||
|
||||
proposed?.rows !== rows ||
|
||||
app._resizeTimeout ||
|
||||
app._isLoadingBuffer ||
|
||||
app.terminalLoadStates.size ||
|
||||
app.pendingWrites.length ||
|
||||
app._terminalWriteInFlight ||
|
||||
app._lastResizeDims?.cols !== cols ||
|
||||
app._lastResizeDims?.rows !== rows
|
||||
) {
|
||||
w.repairReadiness = undefined;
|
||||
return false;
|
||||
}
|
||||
// Synchronous rAF polling: require the initial match plus two more frames.
|
||||
// An async predicate returns a truthy Promise, which Playwright won't retry.
|
||||
const previous = w.repairReadiness;
|
||||
const frames = previous?.cols === cols && previous.rows === rows ? previous.frames + 1 : 1;
|
||||
w.repairReadiness = { cols, rows, frames };
|
||||
return frames >= 3;
|
||||
});
|
||||
await page.evaluate(
|
||||
async ({ session, marker }) => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
// Startup resets and resize clears have already parsed at fitted geometry.
|
||||
w.repairTest = { pulls: 0, anchor: null, inject: false };
|
||||
const captureAnchor = app._captureViewportAnchor.bind(app);
|
||||
app._captureViewportAnchor = () => {
|
||||
const anchor = captureAnchor();
|
||||
w.repairTest.anchor = anchor;
|
||||
return anchor;
|
||||
};
|
||||
const realFetch = window.fetch.bind(window);
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
|
||||
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
|
||||
if (!url.includes('full=1')) throw new Error(`Unexpected history request: ${url}`);
|
||||
w.repairTest.pulls++;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(),
|
||||
json: async () => {
|
||||
// This is after headers and before replay, inside the real load window.
|
||||
if (w.repairTest.inject) app._onSessionTerminal({ id: session, data: `\r\n${marker}\r\n` });
|
||||
const terminalBuffer =
|
||||
Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`).join('\r\n') + '\r\n';
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
terminalBuffer,
|
||||
source: 'mux-full-history',
|
||||
paneHistoryLines: 121,
|
||||
truncated: false,
|
||||
fullSize: terminalBuffer.length,
|
||||
retainedBytes: terminalBuffer.length,
|
||||
},
|
||||
};
|
||||
},
|
||||
}) as unknown as Promise<Response>;
|
||||
}) as typeof window.fetch;
|
||||
// All output still enters through the production terminal event path.
|
||||
app._onSessionTerminal({
|
||||
id: session,
|
||||
data: Array.from({ length: 60 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}\r\n`).join(''),
|
||||
});
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
},
|
||||
{ session: SESSION, marker: MARKER }
|
||||
);
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app.terminal.buffer.active;
|
||||
return (
|
||||
buffer.length === 61 &&
|
||||
buffer.baseY === 61 - app.terminal.rows &&
|
||||
!app.pendingWrites.length &&
|
||||
!app._terminalWriteInFlight &&
|
||||
Array.from({ length: 60 }, (_, i) => buffer.getLine(i)?.translateToString(true)).every(
|
||||
(row, i) => row === `NUMBER-${String(i).padStart(3, '0')}`
|
||||
)
|
||||
);
|
||||
});
|
||||
// The initial 60 lines stand in for the last successful full-history replay.
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
app.terminal.scrollToBottom();
|
||||
app._syncStickyScrollBaseline();
|
||||
app._liveOutputSinceFullPull.delete(session);
|
||||
}, SESSION);
|
||||
} catch (error) {
|
||||
const state = await setupState(page).catch(String);
|
||||
await context.close();
|
||||
throw new Error(`Terminal setup failed: ${JSON.stringify({ state, events })}`, { cause: error });
|
||||
}
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
/** Finger down scrolls history up; cancel at the endpoint to avoid momentum. */
|
||||
async function scrollHistoryByTouch(page: Page, distance: number): Promise<void> {
|
||||
const box = await page.locator('#terminalContainer').boundingBox();
|
||||
if (!box) throw new Error('Terminal container is not visible');
|
||||
const x = box.x + box.width / 2;
|
||||
const y = box.y + Math.min(80, box.height / 4);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const before = await page.evaluate(() => (window as RepairWindow).app.terminal.buffer.active.viewportY);
|
||||
try {
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + distance }] });
|
||||
await page.waitForFunction((previous) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app.terminal.buffer.active.viewportY !== previous || app._fullHistoryRepullInFlight;
|
||||
}, before);
|
||||
// A trusted cancellation ends the drag without xterm/app momentum changing
|
||||
// the reading position after the gesture or starting another top pull.
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] });
|
||||
} finally {
|
||||
await cdp.detach();
|
||||
}
|
||||
}
|
||||
|
||||
async function burst(page: Page): Promise<void> {
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// tmux scrolls a whole screen and repaints the last 24 rows. The numbered
|
||||
// rows 60..119 exist only in tmux and are deliberately absent from this stream.
|
||||
const repaint = Array.from({ length: 24 }, (_, row) => `\x1b[${row + 1};1H\x1b[2KNUMBER-${120 + row}`).join('');
|
||||
app._onSessionTerminal({ id: session, data: `\x1b[24S${repaint}` });
|
||||
}, SESSION);
|
||||
await page.waitForFunction((session) => (window as RepairWindow).app._liveOutputSinceFullPull.has(session), SESSION);
|
||||
}
|
||||
|
||||
async function bufferState(page: Page) {
|
||||
return page.evaluate((marker) => {
|
||||
const w = window as RepairWindow;
|
||||
const buffer = w.app.terminal.buffer.active;
|
||||
const rows = Array.from(
|
||||
{ length: buffer.length },
|
||||
(_, i) => buffer.getLine(i)?.translateToString(true).trim() || ''
|
||||
);
|
||||
const anchor = w.repairTest.anchor;
|
||||
return {
|
||||
numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)),
|
||||
markerHits: rows.filter((row) => row.includes(marker)).length,
|
||||
anchorOffset: anchor ? rows.indexOf(anchor.signature[0]) - buffer.viewportY : null,
|
||||
expectedOffset: anchor?.offset,
|
||||
pulls: w.repairTest.pulls,
|
||||
viewportY: buffer.viewportY,
|
||||
baseY: buffer.baseY,
|
||||
session: w.app.activeSessionId,
|
||||
length: buffer.length,
|
||||
pendingWrites: w.app.pendingWrites.length,
|
||||
terminalWriteInFlight: w.app._terminalWriteInFlight,
|
||||
bufferLoadOwner: w.app._bufferLoadOwner,
|
||||
loadBufferQueue: w.app._loadBufferQueue,
|
||||
selectGeneration: w.app._selectGeneration,
|
||||
initGeneration: w.app._initGeneration,
|
||||
sessions: [...w.app.sessions.keys()],
|
||||
marked: w.app._liveOutputSinceFullPull.has(w.app.activeSessionId),
|
||||
loading: w.app._isLoadingBuffer,
|
||||
inFlight: w.app._fullHistoryRepullInFlight,
|
||||
};
|
||||
}, MARKER);
|
||||
}
|
||||
|
||||
async function waitForRepair(page: Page): Promise<void> {
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
return (
|
||||
w.repairTest.pulls === 1 &&
|
||||
!w.app._fullHistoryRepullInFlight &&
|
||||
!w.app._isLoadingBuffer &&
|
||||
!w.app.pendingWrites.length &&
|
||||
!w.app._terminalWriteInFlight
|
||||
);
|
||||
});
|
||||
// xterm's parse marker is the completion signal for the production flush.
|
||||
await page.evaluate(async () => {
|
||||
const app = (window as RepairWindow).app;
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
});
|
||||
}
|
||||
|
||||
const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`);
|
||||
|
||||
describe('history gap repair on phones', () => {
|
||||
it('repairs from mid-history after a real upward scroll and holds the content anchor', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
const position = await page.evaluate(() => {
|
||||
const b = (window as RepairWindow).app.terminal.buffer.active;
|
||||
return { viewportY: b.viewportY, baseY: b.baseY };
|
||||
});
|
||||
expect(position.viewportY).toBeGreaterThan(0);
|
||||
expect(position.baseY - position.viewportY).toBeGreaterThan(5);
|
||||
await burst(page);
|
||||
expect((await bufferState(page)).numbers).not.toContain('NUMBER-090');
|
||||
await scrollHistoryByTouch(page, 40);
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
expect(state.numbers).toEqual(allNumbers);
|
||||
expect(state.anchorOffset).toBe(state.expectedOffset);
|
||||
expect(state.pulls).toBe(1);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('keeps output arriving during the capture download exactly once', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
await burst(page);
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).repairTest.inject = true;
|
||||
});
|
||||
await scrollHistoryByTouch(page, 40);
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
const detail = JSON.stringify({ state, events: pageEvents.get(page) });
|
||||
expect(state.markerHits, detail).toBe(1);
|
||||
expect(state.numbers, detail).toEqual(allNumbers);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('offers a touch reload while reading and tapping it recovers the missing rows', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
await burst(page);
|
||||
const button = page.getByRole('button', { name: 'Reload history' });
|
||||
await button.waitFor({ state: 'visible' });
|
||||
const box = await button.boundingBox();
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.width).toBeGreaterThanOrEqual(44);
|
||||
await button.tap();
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
expect(state.numbers).toEqual(allNumbers);
|
||||
expect(state.anchorOffset).toBe(state.expectedOffset);
|
||||
expect(await button.isVisible()).toBe(false);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('floats a 44px reload control on wide touch viewports without resizing the terminal', async () => {
|
||||
const { context, page } = await openTerminal(true, { width: 1280, height: 800 });
|
||||
try {
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app.terminal.scrollToLine(10);
|
||||
});
|
||||
const dimensions = () =>
|
||||
page.evaluate(() => {
|
||||
const terminal = (window as RepairWindow).app.terminal;
|
||||
const box = document.getElementById('terminalContainer')!.getBoundingClientRect();
|
||||
return { width: box.width, height: box.height, cols: terminal.cols, rows: terminal.rows };
|
||||
});
|
||||
const before = await dimensions();
|
||||
expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false);
|
||||
await burst(page);
|
||||
const button = page.getByRole('button', { name: 'Reload history' });
|
||||
await button.waitFor({ state: 'visible' });
|
||||
expect(await button.evaluate((element) => getComputedStyle(element).position)).toBe('absolute');
|
||||
const box = await button.boundingBox();
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.width).toBeGreaterThanOrEqual(44);
|
||||
expect(await dimensions()).toEqual(before);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('never shows the reload control in a non-touch context', async () => {
|
||||
const { context, page } = await openTerminal(false);
|
||||
try {
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app.terminal.scrollToLine(10);
|
||||
});
|
||||
await burst(page);
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app._syncHistoryReloadButton();
|
||||
});
|
||||
expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false);
|
||||
expect((await bufferState(page)).pulls).toBe(0);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -121,6 +121,8 @@ function makeApp() {
|
||||
let resolvePull: (() => void) | null = null;
|
||||
const app = {
|
||||
activeSessionId: 's1' as string | null,
|
||||
sessions: new Map([['s1', { mode: 'omp' }]]),
|
||||
_liveOutputSinceFullPull: new Set<string>(),
|
||||
terminal: { buffer: { active: buffer } },
|
||||
// Each gesture's pull is held open until the test settles it.
|
||||
_maybeRefetchFullHistory: vi.fn(
|
||||
@@ -184,6 +186,29 @@ describe('partial-history notice: lazy reveal', () => {
|
||||
expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ viewportY: 0, revealed: true },
|
||||
{ viewportY: 200, revealed: false },
|
||||
])(
|
||||
'retains the initiating top state through a marked repair from row $viewportY',
|
||||
async ({ viewportY, revealed }) => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._liveOutputSinceFullPull.add('s1');
|
||||
app._maybeRefetchFullHistory.mockImplementation(async () => {
|
||||
app._setHistoryTruncation('s1', { ...TAIL, source: 'mux-full-history' });
|
||||
buffer.viewportY = 100; // The content anchor restored the old top below recovered rows.
|
||||
});
|
||||
buffer.viewportY = viewportY;
|
||||
app._maybeLoadMoreHistoryOnScroll(-5);
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' });
|
||||
expect(bar.hidden).toBe(!revealed);
|
||||
if (revealed) expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
}
|
||||
);
|
||||
|
||||
it('a later frame of the same gesture does not flash the pre-pull state while the pull runs', async () => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
|
||||
@@ -49,7 +49,7 @@ function methodSource(source: string, method: string): string {
|
||||
}
|
||||
|
||||
/** Real terminal-ui.js mixin, for `_estimateReplayRows` / `_replayWouldShrinkBuffer`. */
|
||||
function loadTerminalMixin(): Record<string, unknown> {
|
||||
function loadTerminalMixin(globals: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8');
|
||||
const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, unknown> };
|
||||
const context = vm.createContext({
|
||||
@@ -63,6 +63,7 @@ function loadTerminalMixin(): Record<string, unknown> {
|
||||
CodemanApp: FakeCodemanApp,
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
document: { addEventListener: vi.fn() },
|
||||
...globals,
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
return FakeCodemanApp.prototype;
|
||||
@@ -75,6 +76,20 @@ function loadRefetch(): (this: unknown, opts?: { force?: boolean; anchor?: strin
|
||||
return vm.runInContext(`({ ${body} })._maybeRefetchFullHistory`, context);
|
||||
}
|
||||
|
||||
function loadAppMethod(name: string, globals: Record<string, unknown> = {}): Function {
|
||||
const source = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
return vm.runInContext(
|
||||
`({ ${methodSource(source, name)} }).${name}`,
|
||||
vm.createContext({
|
||||
performance,
|
||||
TERMINAL_TAIL_SIZE,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
_crashDiag: { log: vi.fn() },
|
||||
...globals,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** The REAL `_setHistoryTruncation`, so the banner state a pull leaves behind is what production would hold. */
|
||||
function loadSetHistoryTruncation(): (this: unknown, sessionId: string, payload?: Record<string, unknown>) => void {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
@@ -125,6 +140,7 @@ function makeApp(
|
||||
_selectGeneration: 7,
|
||||
_fullHistoryRepullInFlight: false,
|
||||
_isLoadingBuffer: false,
|
||||
_loadBufferQueue: null as { at: number; data: string }[] | null,
|
||||
_fullHistoryRepullAt: new Map<string, number>(),
|
||||
_fullHistoryRepullUseless: new Set<string>(),
|
||||
_paneHistoryLines: new Map<string, number>(),
|
||||
@@ -134,12 +150,25 @@ function makeApp(
|
||||
rows: 30,
|
||||
// xterm's scrollback option; 0 leaves the browser-cap check out of a test.
|
||||
options: { scrollback },
|
||||
buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0 } },
|
||||
scrollToLine: vi.fn(),
|
||||
buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0, getLine: (_row: number) => undefined } },
|
||||
scrollToTop: vi.fn(),
|
||||
},
|
||||
_estimateReplayRows: mixin._estimateReplayRows,
|
||||
_replayWouldShrinkBuffer: mixin._replayWouldShrinkBuffer,
|
||||
_beginBufferLoad: mixin._beginBufferLoad,
|
||||
_finishBufferLoad: vi.fn(function (this: unknown, owner: string, opts?: object) {
|
||||
return (mixin._finishBufferLoad as Function).call(this, owner, opts);
|
||||
}),
|
||||
batchTerminalWrite: vi.fn(function (this: unknown, data: string) {
|
||||
return (mixin.batchTerminalWrite as Function).call(this, data);
|
||||
}),
|
||||
_captureViewportAnchor: mixin._captureViewportAnchor,
|
||||
_restoreViewportAnchor: mixin._restoreViewportAnchor,
|
||||
pendingWrites: [] as string[],
|
||||
_scheduleTerminalWriteFlush: vi.fn(),
|
||||
isTerminalAtBottom: () => true,
|
||||
_scheduleDroppedOutputRecovery: vi.fn(),
|
||||
_fetchTerminalCapture: vi.fn(async (url: string) => {
|
||||
urls.push(url);
|
||||
return {
|
||||
@@ -159,8 +188,11 @@ function makeApp(
|
||||
setHistoryTruncation.call(app, sessionId, p);
|
||||
}),
|
||||
_resetTerminalForReplay: vi.fn(),
|
||||
_bufferLoadFinishOpts: vi.fn(() => ({})),
|
||||
chunkedTerminalWrite: vi.fn(async () => ({ parsedAt: performance.now(), bufferLength: 400, completed: true })),
|
||||
_bufferLoadFinishOpts: loadAppMethod('_bufferLoadFinishOpts'),
|
||||
chunkedTerminalWrite: vi.fn(async (_buffer?: string, _size?: number, owner?: string, opts?: object) => {
|
||||
(mixin._finishBufferLoad as Function).call(app, owner, opts);
|
||||
return { parsedAt: performance.now(), bufferLength: 400, completed: true };
|
||||
}),
|
||||
_syncStickyScrollBaseline: vi.fn(),
|
||||
};
|
||||
return { app, urls };
|
||||
@@ -262,8 +294,7 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
const app = Object.assign(base, {
|
||||
_liveOutputSinceFullPull: new Set<string>(),
|
||||
_liveOutputGen: new Map<string, number>(),
|
||||
_earlyReplayTravel: null as number[] | null,
|
||||
pendingWrites: [] as string[],
|
||||
_earlyReplayTravel: null as { sessionId: string; moves: number[] } | null,
|
||||
_wasAtBottomBeforeWrite: false,
|
||||
_scheduleTerminalWriteFlush: vi.fn(),
|
||||
_restoreTerminalViewport: vi.fn(),
|
||||
@@ -285,10 +316,11 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
app.terminal.scrollToLine.mockImplementation((row: number) => {
|
||||
active.viewportY = row;
|
||||
});
|
||||
app.chunkedTerminalWrite.mockImplementation(async () => {
|
||||
app.chunkedTerminalWrite.mockImplementation(async (_buffer, _size, owner, opts) => {
|
||||
active.baseY = 370;
|
||||
active.viewportY = 370;
|
||||
active.length = 400;
|
||||
(mixin._finishBufferLoad as Function).call(app, owner, opts);
|
||||
return { parsedAt: performance.now(), bufferLength: 400, completed: true };
|
||||
});
|
||||
const liveOutput = () => {
|
||||
@@ -305,14 +337,12 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
const replay = app.chunkedTerminalWrite.getMockImplementation()!;
|
||||
const { promise: gate, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: ready, resolve: started } = Promise.withResolvers<void>();
|
||||
app.chunkedTerminalWrite.mockImplementationOnce(async () => {
|
||||
app._isLoadingBuffer = true;
|
||||
app.chunkedTerminalWrite.mockImplementationOnce(async (...args) => {
|
||||
active.baseY = 0;
|
||||
active.viewportY = 0;
|
||||
started();
|
||||
await gate;
|
||||
const result = await replay();
|
||||
app._isLoadingBuffer = false;
|
||||
const result = await replay(...args);
|
||||
beforeComplete();
|
||||
return result;
|
||||
});
|
||||
@@ -326,6 +356,12 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
liveOutput();
|
||||
await scroll(-5);
|
||||
expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']);
|
||||
expect(app.chunkedTerminalWrite).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
32 * 1024,
|
||||
expect.stringMatching(/^buffer-/),
|
||||
expect.objectContaining({ flushQueued: true })
|
||||
);
|
||||
expect(active.viewportY).toBe(365);
|
||||
expect(active.baseY - active.viewportY).toBe(5);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(false);
|
||||
@@ -359,20 +395,31 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._earlyReplayTravel).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a session dirty when live output lands while the capture is still downloading', async () => {
|
||||
it('queues download-time output and replays it through batchTerminalWrite after the capture', async () => {
|
||||
const { app, urls, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url: string) => {
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
const capture = await fetchCapture(url);
|
||||
// tmux has captured; this output is newer than the capture the replay writes.
|
||||
liveOutput();
|
||||
await promise;
|
||||
return capture;
|
||||
});
|
||||
await scroll(-5);
|
||||
const pull = scroll(-5);
|
||||
loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'download-time output' });
|
||||
expect(app._loadBufferQueue).toEqual([expect.objectContaining({ data: 'download-time output' })]);
|
||||
release();
|
||||
await pull;
|
||||
expect(urls).toHaveLength(1);
|
||||
expect(app.batchTerminalWrite).toHaveBeenCalledWith('download-time output');
|
||||
expect(app.pendingWrites).toContain('download-time output');
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
// Flushing the replayed queue marks the session again.
|
||||
(mixin.flushPendingWrites as Function).call(app);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps live output flushed before the final restore dirty for the next early pull', async () => {
|
||||
const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp();
|
||||
liveOutput();
|
||||
@@ -417,14 +464,17 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._liveOutputSinceFullPull.size).toBe(0);
|
||||
});
|
||||
|
||||
it('does not pull early for downward travel or while already reading older rows', async () => {
|
||||
const { active, urls, liveOutput, scroll } = makeScrollApp();
|
||||
it('repairs while already reading mid-history, but never on downward travel', async () => {
|
||||
const { app, active, urls, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
active.viewportY = 50;
|
||||
await scroll(-5);
|
||||
active.viewportY = 95;
|
||||
expect(urls).toHaveLength(1);
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' });
|
||||
app._fullHistoryRepullAt.clear();
|
||||
liveOutput();
|
||||
await scroll(3);
|
||||
expect(urls).toEqual([]);
|
||||
expect(urls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => {
|
||||
@@ -450,6 +500,144 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
expect(app._fullHistoryRepullUseless.has('s1')).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])(
|
||||
'flushes download-time output on the %s non-replay path',
|
||||
async (exit) => {
|
||||
const { app } = makeApp(exit === 'bounded-shell' ? 'shell' : 'omp', {
|
||||
bufferRows: 200,
|
||||
capture: lines(400),
|
||||
});
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async () => {
|
||||
await promise;
|
||||
if (exit === 'rejection') throw new Error('offline');
|
||||
if (exit === 'tab-switch') app._selectGeneration++;
|
||||
return {
|
||||
headersAt: performance.now(),
|
||||
headers: { get: () => '' },
|
||||
json: { data: { terminalBuffer: exit === 'empty' ? '' : lines(10), source: 'mux-full-history' } },
|
||||
};
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'queued while fetching' });
|
||||
release();
|
||||
await pull;
|
||||
expect(app.chunkedTerminalWrite).not.toHaveBeenCalled();
|
||||
expect(app._finishBufferLoad).toHaveBeenCalledOnce();
|
||||
expect(app._finishBufferLoad).toHaveBeenCalledWith(expect.any(String), { flushQueued: true, since: 0 });
|
||||
expect(app.pendingWrites).toContain('queued while fetching');
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('counts download-time output toward the 128 KiB dropped-output recovery cap', async () => {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async () => {
|
||||
await promise;
|
||||
return {
|
||||
headersAt: performance.now(),
|
||||
headers: { get: () => '' },
|
||||
json: { data: { terminalBuffer: '', source: 'history' } },
|
||||
};
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
const onTerminal = loadAppMethod('_onSessionTerminal');
|
||||
onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) });
|
||||
onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) });
|
||||
expect(app._scheduleDroppedOutputRecovery).toHaveBeenCalledWith('s1', 0, 70_000);
|
||||
expect(app._loadBufferQueue).toHaveLength(1);
|
||||
release();
|
||||
await pull;
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'defers real dropped-output recovery through a slow pull (timer already armed: %s)',
|
||||
async (armed) => {
|
||||
vi.useFakeTimers();
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
try {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const retry = vi.fn(({ repainted, stillActive, attempt }) => !repainted && stillActive && attempt < 4);
|
||||
const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', {
|
||||
setTimeout,
|
||||
window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } },
|
||||
});
|
||||
const refresh = vi.fn(async () => true);
|
||||
Object.assign(app, {
|
||||
_scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args),
|
||||
_onSessionNeedsRefresh: refresh,
|
||||
});
|
||||
if (armed) schedule.call(app, 's1');
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url) => {
|
||||
await promise;
|
||||
return fetchCapture(url);
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
const onTerminal = loadAppMethod('_onSessionTerminal');
|
||||
onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) });
|
||||
onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) });
|
||||
await vi.advanceTimersByTimeAsync(20_000); // Longer than all five normal retry intervals.
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
release();
|
||||
await pull;
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
expect(refresh).toHaveBeenCalledWith({ id: 's1' });
|
||||
expect(retry).toHaveBeenCalledWith(expect.objectContaining({ attempt: 0, repainted: true }));
|
||||
} finally {
|
||||
release();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('does not resume a deferred recovery for a tab that is no longer active', () => {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const owner = (app._beginBufferLoad as Function).call(app);
|
||||
Object.assign(app, { _pendingDroppedOutputRecovery: 's1', activeSessionId: 's2' });
|
||||
app._finishBufferLoad(owner);
|
||||
expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled();
|
||||
expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => {
|
||||
const { app, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url) => {
|
||||
const capture = await fetchCapture(url);
|
||||
capture.json.data.source = source;
|
||||
return capture;
|
||||
});
|
||||
await scroll(-5);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history');
|
||||
});
|
||||
|
||||
it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => {
|
||||
const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp();
|
||||
liveOutput();
|
||||
const paused = pauseReplay();
|
||||
const pull = scroll(-5);
|
||||
await paused.ready;
|
||||
app.activeSessionId = 's2';
|
||||
app._selectGeneration++;
|
||||
active.baseY = 100;
|
||||
active.viewportY = 100;
|
||||
(mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, 3);
|
||||
expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith(null);
|
||||
expect(app._earlyReplayTravel?.moves).toEqual([]);
|
||||
paused.release();
|
||||
await pull;
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
expect(app._earlyReplayTravel).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a skipped bounded window never damages the Load full history banner', () => {
|
||||
@@ -635,3 +823,190 @@ describe('an unloaded buffer is not held to an older downgrade refusal', () => {
|
||||
expect(app._fullHistoryRepullInFlight).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('content anchors hold the reader through a history repair', () => {
|
||||
function fixture(rows: string[], viewportY = 5) {
|
||||
let content = rows;
|
||||
const active = {
|
||||
viewportY,
|
||||
baseY: rows.length - 3,
|
||||
length: rows.length,
|
||||
getLine: vi.fn((row: number) =>
|
||||
content[row] === undefined
|
||||
? undefined
|
||||
: {
|
||||
translateToString: () => content[row],
|
||||
}
|
||||
),
|
||||
};
|
||||
const app = { terminal: { buffer: { active }, scrollToLine: vi.fn() } };
|
||||
const capture = () => (mixin._captureViewportAnchor as Function).call(app);
|
||||
const restore = (anchor: unknown, next: string[]) => {
|
||||
content = next;
|
||||
active.baseY = next.length - 3;
|
||||
active.length = next.length;
|
||||
return (mixin._restoreViewportAnchor as Function).call(app, anchor);
|
||||
};
|
||||
return { app, active, capture, restore };
|
||||
}
|
||||
|
||||
it('keeps a three-row signature at its viewport offset when rows are inserted below the reader', () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
|
||||
rows[5] = '';
|
||||
const { app, capture, restore } = fixture(rows);
|
||||
const anchor = capture();
|
||||
const target = restore(anchor, [...rows.slice(0, 12), ...Array(20).fill('recovered'), ...rows.slice(12)]);
|
||||
expect(target).toBe(5);
|
||||
expect(app.terminal.scrollToLine).toHaveBeenCalledWith(5);
|
||||
expect(anchor.viewportY).toBe(5);
|
||||
expect(anchor.offset).toBe(1);
|
||||
});
|
||||
|
||||
it('chooses the nearest exact signature over a nearer first-row-only match', () => {
|
||||
const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1);
|
||||
const anchor = capture();
|
||||
const next = Array(34).fill('other');
|
||||
next.splice(3, 3, 'A', 'B', 'C');
|
||||
next.splice(10, 3, 'A', 'wrong', 'wrong');
|
||||
next.splice(17, 3, 'A', 'B', 'C');
|
||||
expect(restore(anchor, next)).toBe(17);
|
||||
});
|
||||
|
||||
it('falls back to the nearest first row, then distance from the bottom when nothing matches', () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
|
||||
const { capture, restore } = fixture(rows);
|
||||
const anchor = capture();
|
||||
const next = Array(40).fill('other');
|
||||
next[8] = 'row 5';
|
||||
next[17] = 'row 5';
|
||||
expect(restore(anchor, next)).toBe(17);
|
||||
expect(restore(anchor, Array(40).fill('no match'))).toBe(15);
|
||||
});
|
||||
|
||||
it('keeps bottom distance within the bottom tolerance even if matching text exists', () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
|
||||
const { capture, restore } = fixture(rows, 26);
|
||||
expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36);
|
||||
});
|
||||
|
||||
it.each(['first-row-only', 'absent'])('bounds a 50k-row search with an %s signature', (kind) => {
|
||||
const rows = Array.from({ length: 50_000 }, (_, i) => `original ${i}`);
|
||||
const { active, capture, restore } = fixture(rows, 25_000);
|
||||
const anchor = capture();
|
||||
const next = Array(50_000).fill('other');
|
||||
if (kind === 'first-row-only') {
|
||||
next[25_100] = anchor.signature[0];
|
||||
next[24_800] = anchor.signature[0];
|
||||
}
|
||||
// An exact match outside the budget must not make the scan traverse 50k rows.
|
||||
next.splice(30_000, 3, ...anchor.signature);
|
||||
active.getLine.mockClear();
|
||||
expect(restore(anchor, next)).toBe(kind === 'first-row-only' ? 25_100 : 25_000);
|
||||
expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4005);
|
||||
});
|
||||
});
|
||||
|
||||
describe('touch history reload control', () => {
|
||||
function fixture({
|
||||
touch = true,
|
||||
mode = 'omp',
|
||||
bottom = false,
|
||||
marked = true,
|
||||
inFlight = false,
|
||||
tiles = false,
|
||||
active = true,
|
||||
} = {}) {
|
||||
const button = { hidden: true, disabled: false, textContent: '', onclick: null as (() => void) | null };
|
||||
const ui = loadTerminalMixin({
|
||||
MobileDetection: { isTouchDevice: () => touch },
|
||||
document: { addEventListener: vi.fn(), getElementById: () => button },
|
||||
});
|
||||
const app = {
|
||||
activeSessionId: active ? 's1' : null,
|
||||
sessions: new Map([['s1', { mode }]]),
|
||||
isTerminalAtBottom: () => bottom,
|
||||
_liveOutputSinceFullPull: new Set(marked ? ['s1'] : []),
|
||||
_fullHistoryRepullInFlight: inFlight,
|
||||
_tilesOwnTerminal: () => tiles,
|
||||
_maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}),
|
||||
_syncHistoryReloadButton: () => (ui._syncHistoryReloadButton as Function).call(app),
|
||||
};
|
||||
return { app, button };
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ opts: {}, visible: true },
|
||||
{ opts: { touch: false }, visible: false },
|
||||
{ opts: { mode: 'shell' }, visible: false },
|
||||
{ opts: { bottom: true }, visible: false },
|
||||
{ opts: { marked: false }, visible: false },
|
||||
{ opts: { inFlight: true }, visible: false },
|
||||
{ opts: { tiles: true }, visible: false },
|
||||
{ opts: { active: false }, visible: false },
|
||||
])('visibility is $visible for $opts', ({ opts, visible }) => {
|
||||
const { app, button } = fixture(opts);
|
||||
app._syncHistoryReloadButton();
|
||||
expect(button.hidden).toBe(!visible);
|
||||
});
|
||||
|
||||
it('forces a content-anchored pull on tap and resets the loading state on settle', async () => {
|
||||
const { app, button } = fixture();
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._maybeRefetchFullHistory.mockReturnValueOnce(promise);
|
||||
app._syncHistoryReloadButton();
|
||||
const tapped = button.onclick!();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ force: true, anchor: 'content' });
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(button.textContent).toBe('Loading…');
|
||||
release();
|
||||
await tapped;
|
||||
expect(button.disabled).toBe(false);
|
||||
expect(button.textContent).toBe('↻ Reload history');
|
||||
});
|
||||
});
|
||||
|
||||
describe('selectSession only clears live-output marks for actual full mux captures', () => {
|
||||
it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => {
|
||||
const errors = vi.fn();
|
||||
const select = loadAppMethod('selectSession', {
|
||||
console: { log: vi.fn(), error: errors },
|
||||
document: { querySelector: () => null },
|
||||
localStorage: { setItem: vi.fn(), getItem: () => null },
|
||||
requestIdleCallback: vi.fn(),
|
||||
});
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } });
|
||||
const methods = Object.fromEntries(
|
||||
[
|
||||
'_setTerminalLoadState',
|
||||
'_clearTerminalLoadState',
|
||||
'_cleanupPreviousSession',
|
||||
'_renderHistoryTruncationBanner',
|
||||
'_updateSseSubscription',
|
||||
'hideWelcome',
|
||||
'markIdleAlertSeen',
|
||||
'_updateActiveTabImmediate',
|
||||
'closeSessionSidebarOnHandheld',
|
||||
'renderSessionTabs',
|
||||
'_updateLocalEchoState',
|
||||
'syncTerminalGeometry',
|
||||
'_markTerminalBufferReconciled',
|
||||
'_connectWs',
|
||||
'scrollToLastNonEmptyLine',
|
||||
].map((name) => [name, vi.fn()])
|
||||
);
|
||||
Object.assign(app, methods, {
|
||||
activeSessionId: 's2',
|
||||
_fullHistoryLoaded: new Set(),
|
||||
_liveOutputSinceFullPull: new Set(['s1']),
|
||||
_liveOutputGen: new Map(),
|
||||
_shouldFocusTerminalForTabSwitch: () => false,
|
||||
_isStaleSelect: () => false,
|
||||
sendResize: async () => false,
|
||||
});
|
||||
Object.assign(app.terminal, { scrollToBottom: vi.fn() });
|
||||
await select.call(app, 's1');
|
||||
expect(errors).not.toHaveBeenCalled();
|
||||
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
|
||||
expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user