fix(web): clear the Reload mark after a drop-recovery capture (#814)

- _onSessionNeedsRefresh samples the live-output generation before its
  fetch and, after replaying a mux-full-history capture, clears
  _liveOutputSinceFullPull and _historyReloadDismissed while it still owns
  the active session and the generation is unchanged; the ?tail= fallback
  never clears them.
- test/terminal-viewport-marker.test.ts: gated test driving the real
  flushPendingWrites over @xterm/headless at a full scrollback; the reading
  row holds with the marker and drifts without it.
- Docs: the anchor sentence matches minimumScore, and the refresh rule is
  in the Repair while reading paragraph.
This commit is contained in:
Hadrien Kerlero committed 2026-11-22 02:44:24 +01:00
1 parent 444f375ac7
commit bc00ad4335
4 files changed
+214 -1

No files matched your search

+96
View File
@@ -1354,3 +1354,99 @@ describe('selectSession only clears live-output marks for actual full mux captur
expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history');
});
});
describe('drop-recovery refresh clears the live-output mark only for a mux capture', () => {
function makeRefreshApp(source = 'mux-full-history') {
const errors = vi.fn();
const refresh = loadAppMethod('_onSessionNeedsRefresh', {
console: { error: errors },
computeRewriteScrollLine: () => null,
});
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } });
const recovery = Object.assign(app, {
_tilesOwnTerminal: () => false,
_markTerminalBufferReconciled: vi.fn(),
sendResize: vi.fn(),
_localEchoOverlay: { rerender: vi.fn() },
_liveOutputSinceFullPull: new Set(['s1']),
_liveOutputGen: new Map([['s1', 7]]),
_historyReloadDismissed: new Set(['s1']),
_syncHistoryReloadAction: vi.fn(),
});
Object.assign(app.terminal, { scrollToBottom: vi.fn() });
return { app: recovery, refresh, errors };
}
it('clears the mark and dismissal after replaying a full mux capture', async () => {
const { app, refresh, errors } = makeRefreshApp();
expect(await refresh.call(app)).toBe(true);
expect(errors).not.toHaveBeenCalled();
expect(app._fetchTerminalCapture).toHaveBeenCalledWith('/api/sessions/s1/terminal?full=1', { full: true });
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(false);
expect(app._historyReloadDismissed.has('s1')).toBe(false);
// The clear syncs once, and the real truncation-banner update syncs again.
expect(app._syncHistoryReloadAction).toHaveBeenCalledTimes(2);
});
it('keeps the mark and dismissal for a history answer', async () => {
const { app, refresh, errors } = makeRefreshApp('history');
expect(await refresh.call(app)).toBe(true);
expect(errors).not.toHaveBeenCalled();
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce();
});
it('keeps the mark and dismissal when live output arrives during the fetch', async () => {
const { app, refresh, errors } = makeRefreshApp();
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
app._fetchTerminalCapture.mockImplementation(async (url) => {
app._liveOutputGen.set('s1', 8);
return fetchCapture(url);
});
expect(await refresh.call(app)).toBe(true);
expect(errors).not.toHaveBeenCalled();
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce();
});
it('keeps the mark and dismissal when a full mux capture falls back to a history tail', async () => {
const { app, refresh, errors } = makeRefreshApp();
app._replayWouldShrinkBuffer = vi.fn(() => true);
app._fetchTerminalCapture.mockResolvedValueOnce({
headersAt: performance.now(),
headers: { get: () => '' },
json: { data: { terminalBuffer: lines(10), source: 'mux-full-history' } },
});
app._fetchTerminalCapture.mockResolvedValueOnce({
headersAt: performance.now(),
headers: { get: () => '' },
json: { data: { terminalBuffer: lines(60), source: 'history' } },
});
expect(await refresh.call(app)).toBe(true);
expect(errors).not.toHaveBeenCalled();
expect(app._fetchTerminalCapture).toHaveBeenLastCalledWith(`/api/sessions/s1/terminal?tail=${TERMINAL_TAIL_SIZE}`);
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce();
});
it.each(['session', 'owner'])('keeps the mark when the refresh loses its %s during replay', async (changed) => {
const { app, refresh, errors } = makeRefreshApp();
app.chunkedTerminalWrite.mockImplementationOnce(async () => {
if (changed === 'session') app.activeSessionId = 's2';
else Reflect.set(app, '_terminalRefreshOwner', { sessionId: 's1' });
return { parsedAt: performance.now(), bufferLength: 400, completed: true };
});
expect(await refresh.call(app)).toBe(true);
expect(errors).not.toHaveBeenCalled();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(app._syncHistoryReloadAction).not.toHaveBeenCalled();
});
});
+105
View File
@@ -0,0 +1,105 @@
/**
* Live flushes at the scrollback cap must preserve the row being read, not its
* absolute buffer index. Use real asynchronous xterm parsing so markers track
* circular-buffer trimming before the mixin restores the viewport (#814).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless';
const { Terminal } = xtermHeadless as unknown as {
Terminal: new (opts: Record<string, unknown>) => HeadlessTerminal;
};
const read = (rel: string) => readFileSync(resolve(import.meta.dirname, '..', rel), 'utf8');
const write = (terminal: HeadlessTerminal, data: string) => new Promise<void>((done) => terminal.write(data, done));
const topRow = (terminal: HeadlessTerminal) => {
const buffer = terminal.buffer.active;
return buffer.getLine(buffer.viewportY)?.translateToString(true);
};
function loadHarness(terminal: HeadlessTerminal) {
const CodemanApp = function CodemanApp(this: unknown) {};
const context = vm.createContext({
CodemanApp,
window: {},
globalThis: {},
document: { getElementById: () => null, querySelector: () => null },
console,
MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' },
Object,
performance,
setTimeout,
clearTimeout,
});
vm.runInContext(read('src/web/public/constants.js'), context, { filename: 'constants.js' });
vm.runInContext(read('src/web/public/terminal-ui.js'), context, { filename: 'terminal-ui.js' });
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
Object.assign(app, {
terminal,
pendingWrites: [],
sessions: new Map([['reading', { mode: 'claude' }]]),
activeSessionId: 'reading',
_isLoadingBuffer: false,
_wasAtBottomBeforeWrite: false,
_localEchoOverlay: null,
isTerminalAtBottom: () => terminal.buffer.active.viewportY === terminal.buffer.active.baseY,
_scheduleTerminalWriteFlush: () => {},
_noteMobileImeAuthoritativeOutput: () => {},
_hasRecentUserScrollUp: () => false,
_syncHistoryReloadAction: () => {},
});
return app;
}
async function flushAtScrollbackCap(markersEnabled: boolean) {
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 100, allowProposedApi: true });
try {
// Hide only the marker API for the negative control; writes, buffer trims,
// scrolling, and _restoreTerminalViewport remain the real implementations.
if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined });
const app = loadHarness(terminal);
await write(terminal, Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join(''));
expect(terminal.buffer.active.baseY).toBe(100);
const buffer = terminal.buffer.active;
let readingRow = -1;
for (let row = 0; row < buffer.length; row++) {
if (buffer.getLine(row)?.translateToString(true) === 'line 140') {
readingRow = row;
break;
}
}
expect(readingRow).toBeGreaterThanOrEqual(0);
terminal.scrollToLine(readingRow);
expect(topRow(terminal)).toBe('line 140');
expect(app.isTerminalAtBottom()).toBe(false);
for (let flush = 0; flush < 5; flush++) {
app.pendingWrites.push(Array.from({ length: 4 }, (_, i) => `line ${200 + flush * 4 + i}\r\n`).join(''));
app.flushPendingWrites();
// This barrier runs after the flush's write callback, including its
// viewport restoration. No wall-clock delay stands in for parsing.
await write(terminal, '');
expect(app._terminalWriteInFlight).toBe(false);
}
return topRow(terminal);
} finally {
terminal.dispose();
}
}
describe('live terminal viewport at the scrollback cap', () => {
it('keeps line 140 visible across five flushes using xterm markers', async () => {
expect(await flushAtScrollbackCap(true)).toBe('line 140');
});
it('discriminates against absolute-index restoration without markers', async () => {
const row = await flushAtScrollbackCap(false);
expect(row).not.toBe('line 140');
expect(row).toBe('line 160');
});
});