mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-04 22:49:41 +02:00
fix(terminal): preserve scroll intent across keyboard resize, surface history truncation
Closes #259, closes #258. Both bottom out in the same gap: nothing tracked whether the user was following live output or reading history. #259 — the keyboard path forced the terminal to the bottom unconditionally (onKeyboardShow/onKeyboardHide passed scrollToBottom:true, applied with no check), so opening the keyboard while scrolled up yanked the user down. The settle cycle now captures intent on its FIRST event, before any fit() has reflowed the buffer, and returns to that anchor when the user was reading. A later capture would read an already-moved viewportY, which is why the capture point matters. The param is renamed restoreScroll to match. Separately, flushPendingWrites gated viewport preservation on _hasRecentUserScrollUp(), a 1500ms decay window, so a user who scrolled up and then actually READ for longer lost protection mid-read. Being scrolled up IS the intent however long ago it was expressed, so it now keys off position. The recency window stays as a race guard on the sticky scroll-to-bottom. The full-history repull already held the user's place and is unchanged. #258 — truncation was reported by a grey line written INTO the terminal ("earlier output truncated"), which scrolls away with the output it describes, cannot be acted on, and said the same thing whether the rest was one click away or gone forever. The server set one `truncated` boolean at two sites meaning opposite things, and the client discarded fullSize and source entirely. The route now reports truncationReason ('tail' = intentional partial replay, the rest is retained; 'capped' = the byte ceiling dropped it) plus retainedBytes, and 'capped' is not downgraded by a later tail cut. The client renders a dismissible banner outside terminal output with three honest states: recoverable (offers Load full history), at-ceiling, and exhausted. The Load button forces past the scroll cooldown but NOT past _replayWouldShrinkBuffer, which still refuses a downgrade for repaint-mode panes. The banner is an overlay, not a flex child: FitAddon derives rows/cols from the terminal parent's computed height, so occupying real layout space would SIGWINCH the CLI on every truncation-state change. Verified in a real browser on the 7 skins: banner text and button clear 4.5:1 contrast on all of them, and terminal height is byte-identical with the banner shown. The first cut used --bg-elevated and --accent-muted, which do not exist, so light skins rendered a hardcoded dark bar under dark text; it now uses only tokens every skin redefines. test/terminal-scroll-intent.test.ts lives outside test/mobile/ deliberately — that suite is excluded from test:ci, so a guard placed there is invisible to CI. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
// Port: none (pure helpers from constants.js in a vm context).
|
||||
//
|
||||
// Issue #258: terminal history is split across browser scrollback, the server
|
||||
// byte buffer and tmux, and the only signal the user got was a grey line written
|
||||
// INTO the terminal saying "earlier output truncated for performance". That line
|
||||
// scrolls away with the output it describes, cannot be acted on, and says the
|
||||
// same thing whether the rest is one click away or gone forever.
|
||||
//
|
||||
// computeHistoryTruncationNotice() is the pure core of the replacement banner.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
|
||||
function loadHelpers() {
|
||||
const context = vm.createContext({ console, window: {}, document: {}, navigator: { userAgent: 'test' } });
|
||||
vm.runInContext(
|
||||
`${readFileSync(resolve(PUBLIC, 'constants.js'), 'utf8')}
|
||||
;globalThis.__helpers = { formatHistoryBytes, computeHistoryTruncationNotice };`,
|
||||
context,
|
||||
{ filename: 'constants.js' }
|
||||
);
|
||||
return (context as any).__helpers as {
|
||||
formatHistoryBytes: (n: number) => string;
|
||||
computeHistoryTruncationNotice: (s: Record<string, unknown>) => {
|
||||
visible: boolean;
|
||||
message: string;
|
||||
canLoadMore: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe('formatHistoryBytes', () => {
|
||||
const { formatHistoryBytes } = loadHelpers();
|
||||
|
||||
it('reports sub-KB amounts as a range, not a byte count', () => {
|
||||
expect(formatHistoryBytes(400)).toBe('less than 1 KB');
|
||||
expect(formatHistoryBytes(0)).toBe('less than 1 KB');
|
||||
});
|
||||
|
||||
it('scales to KB and MB', () => {
|
||||
expect(formatHistoryBytes(2048)).toBe('2 KB');
|
||||
expect(formatHistoryBytes(3 * 1024 * 1024)).toBe('3.0 MB');
|
||||
});
|
||||
|
||||
it('survives junk input rather than printing NaN into the UI', () => {
|
||||
expect(formatHistoryBytes(-5)).toBe('less than 1 KB');
|
||||
expect(formatHistoryBytes(NaN as unknown as number)).toBe('less than 1 KB');
|
||||
expect(formatHistoryBytes(undefined as unknown as number)).toBe('less than 1 KB');
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeHistoryTruncationNotice (issue #258)', () => {
|
||||
const { computeHistoryTruncationNotice } = loadHelpers();
|
||||
|
||||
it('stays hidden when the replay was complete', () => {
|
||||
const notice = computeHistoryTruncationNotice({ truncated: false, fullSize: 100, retainedBytes: 100 });
|
||||
expect(notice.visible).toBe(false);
|
||||
expect(notice.canLoadMore).toBe(false);
|
||||
});
|
||||
|
||||
it('offers to load more after an intentional tail replay', () => {
|
||||
const notice = computeHistoryTruncationNotice({
|
||||
truncated: true,
|
||||
reason: 'tail',
|
||||
source: 'history',
|
||||
fullSize: 5 * 1024 * 1024,
|
||||
retainedBytes: 1024 * 1024,
|
||||
});
|
||||
expect(notice.visible).toBe(true);
|
||||
expect(notice.canLoadMore).toBe(true);
|
||||
expect(notice.message).toContain('1.0 MB');
|
||||
expect(notice.message).toContain('more may still be retained');
|
||||
});
|
||||
|
||||
it('promises nothing more once the FULL capture itself hit the ceiling', () => {
|
||||
// This is the case the old boolean could not express: a full-history pull
|
||||
// that was still capped means tmux has already given everything it has.
|
||||
const notice = computeHistoryTruncationNotice({
|
||||
truncated: true,
|
||||
reason: 'capped',
|
||||
source: 'mux-full-history',
|
||||
fullSize: 40 * 1024 * 1024,
|
||||
retainedBytes: 2 * 1024 * 1024,
|
||||
});
|
||||
expect(notice.visible).toBe(true);
|
||||
expect(notice.canLoadMore).toBe(false);
|
||||
expect(notice.message).toContain('cannot be recovered');
|
||||
});
|
||||
|
||||
it('reports exhaustion when a full pull was refused as a downgrade', () => {
|
||||
// _replayWouldShrinkBuffer refused: the browser holds MORE than tmux can
|
||||
// return (a repaint-mode pane keeps no history), so offering "load more"
|
||||
// would be offering to destroy history.
|
||||
const notice = computeHistoryTruncationNotice({
|
||||
truncated: true,
|
||||
reason: 'tail',
|
||||
source: 'history',
|
||||
fullSize: 900000,
|
||||
retainedBytes: 500000,
|
||||
exhausted: true,
|
||||
});
|
||||
expect(notice.visible).toBe(true);
|
||||
expect(notice.canLoadMore).toBe(false);
|
||||
expect(notice.message).toContain('no longer kept');
|
||||
});
|
||||
|
||||
it('lets exhaustion outrank a would-be recoverable state', () => {
|
||||
const recoverable = { truncated: true, reason: 'tail', source: 'history', fullSize: 900, retainedBytes: 100 };
|
||||
expect(computeHistoryTruncationNotice(recoverable).canLoadMore).toBe(true);
|
||||
expect(computeHistoryTruncationNotice({ ...recoverable, exhausted: true }).canLoadMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the in-terminal truncation line is gone (static guard)', () => {
|
||||
it('no longer writes the notice into terminal output', () => {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
// The whole point of #258 is that this notice is no longer part of the
|
||||
// scrollback it describes.
|
||||
expect(app).not.toContain('earlier output truncated for performance');
|
||||
});
|
||||
|
||||
it('renders the banner through textContent, never innerHTML', () => {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
const start = app.indexOf('_renderHistoryTruncationBanner() {');
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const body = app.slice(start, app.indexOf('\n _shouldFocusTerminalForTabSwitch', start));
|
||||
expect(body).not.toContain('innerHTML');
|
||||
});
|
||||
});
|
||||
@@ -351,7 +351,7 @@ describe('Virtual Keyboard', () => {
|
||||
bottomRestores++;
|
||||
};
|
||||
|
||||
KeyboardHandler._scheduleViewportSettle({ scrollToBottom: true });
|
||||
KeyboardHandler._scheduleViewportSettle({ restoreScroll: true });
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
KeyboardHandler._scheduleViewportSettle();
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
@@ -446,7 +446,7 @@ describe('Virtual Keyboard', () => {
|
||||
|
||||
// A real transition arms the work; a following wiggle defers it but the
|
||||
// settle still fires exactly once.
|
||||
KeyboardHandler._scheduleViewportSettle({ scrollToBottom: true });
|
||||
KeyboardHandler._scheduleViewportSettle({ restoreScroll: true });
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
KeyboardHandler._deferViewportSettle();
|
||||
await new Promise((resolve) => setTimeout(resolve, KeyboardHandler.VIEWPORT_SETTLE_MS + 80));
|
||||
|
||||
@@ -55,6 +55,7 @@ vi.mock('../../src/remote-hosts.js', async (orig) => {
|
||||
});
|
||||
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { resolveTerminalHistoryConfig } from '../../src/config/terminal-history.js';
|
||||
|
||||
interface LocalHarness {
|
||||
app: FastifyInstance;
|
||||
@@ -632,6 +633,77 @@ describe('session-routes', () => {
|
||||
expect(body.data.terminalBuffer).toBeDefined();
|
||||
});
|
||||
|
||||
// ── #258: a single `truncated` boolean could not distinguish "we tailed for
|
||||
// speed, the rest is still there" from "the oldest bytes are gone". The UI
|
||||
// needs that difference to know whether offering "Load full history" is a
|
||||
// promise it can keep.
|
||||
describe('truncation reason (#258)', () => {
|
||||
const lines = (n: number) => Array.from({ length: n }, (_, i) => `history line ${i}`).join('\n');
|
||||
|
||||
beforeEach(() => {
|
||||
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = vi.fn(() => null);
|
||||
harness.ctx._session.mode = 'shell';
|
||||
});
|
||||
|
||||
it('reports no reason when nothing was cut', async () => {
|
||||
harness.ctx._session.terminalBuffer = 'short buffer';
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal`,
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.truncated).toBe(false);
|
||||
expect(body.data.truncationReason).toBeNull();
|
||||
expect(body.data.retainedBytes).toBe(body.data.terminalBuffer.length);
|
||||
});
|
||||
|
||||
it("reports 'tail' for an intentional partial replay", async () => {
|
||||
harness.ctx._session.terminalBuffer = lines(4000);
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?tail=500`,
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.truncated).toBe(true);
|
||||
expect(body.data.truncationReason).toBe('tail');
|
||||
// fullSize describes what existed, retainedBytes what was sent.
|
||||
expect(body.data.retainedBytes).toBeLessThan(body.data.fullSize);
|
||||
});
|
||||
|
||||
it("reports 'capped' when the byte ceiling dropped the oldest output", async () => {
|
||||
harness.ctx.getTerminalHistoryConfig = vi.fn(async () => ({
|
||||
...resolveTerminalHistoryConfig({}),
|
||||
terminalBufferMaxBytes: 2000,
|
||||
}));
|
||||
harness.ctx._session.terminalBuffer = lines(4000);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal`,
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.truncated).toBe(true);
|
||||
expect(body.data.truncationReason).toBe('capped');
|
||||
});
|
||||
|
||||
it("keeps 'capped' when a tail cut lands on top of it", async () => {
|
||||
// Both sites fire. 'capped' is the stronger statement (bytes are gone),
|
||||
// so a subsequent tail must not downgrade it to the recoverable reason.
|
||||
harness.ctx.getTerminalHistoryConfig = vi.fn(async () => ({
|
||||
...resolveTerminalHistoryConfig({}),
|
||||
terminalBufferMaxBytes: 2000,
|
||||
}));
|
||||
harness.ctx._session.terminalBuffer = lines(4000);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/terminal?tail=500`,
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.truncationReason).toBe('capped');
|
||||
});
|
||||
});
|
||||
|
||||
it('does not strip VPA-like shell scrollback as Ink redraw bloat', async () => {
|
||||
const shellHistory = Array.from(
|
||||
{ length: 3000 },
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// Port: none (pure logic in a vm context — no browser, no server).
|
||||
//
|
||||
// Issue #259: opening or closing the mobile keyboard forced the terminal to the
|
||||
// bottom, so a user reading scrollback was yanked down to the live output. The
|
||||
// settle cycle now captures scroll intent BEFORE the keyboard reflow and returns
|
||||
// to that anchor instead.
|
||||
//
|
||||
// This lives outside test/mobile/ deliberately. That suite is Playwright-driven
|
||||
// and EXCLUDED from `npm run test:ci` (config/vitest.ci.config.ts), so a
|
||||
// regression guarded only there is invisible to CI — the exact blind spot that
|
||||
// let the #279/#280 merge land a red mobile suite behind two green checks.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const SOURCE = readFileSync(resolve(PUBLIC, 'mobile-handlers.js'), 'utf8');
|
||||
|
||||
interface FakeTerminal {
|
||||
buffer: { active: { viewportY: number; baseY: number } };
|
||||
scrollToBottom: () => void;
|
||||
scrollToLine: (line: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load mobile-handlers.js and hand back its KeyboardHandler.
|
||||
*
|
||||
* The module declares `const KeyboardHandler = {...}` at top level, and a
|
||||
* lexical binding does not survive to the next vm.runInContext call, so the
|
||||
* export is appended to the SAME script rather than read back afterwards.
|
||||
*/
|
||||
function loadKeyboardHandler(opts: { viewportY: number; baseY: number }) {
|
||||
const calls: string[] = [];
|
||||
const terminal: FakeTerminal = {
|
||||
buffer: { active: { viewportY: opts.viewportY, baseY: opts.baseY } },
|
||||
scrollToBottom: () => calls.push('scrollToBottom'),
|
||||
scrollToLine: (line: number) => calls.push(`scrollToLine:${line}`),
|
||||
};
|
||||
const app: any = {
|
||||
terminal,
|
||||
fitAddon: { fit: () => calls.push('fit') },
|
||||
// The real predicate (terminal-ui.js isTerminalAtBottom), reproduced so the
|
||||
// test exercises the same tolerance the runtime uses.
|
||||
isTerminalAtBottom: () => terminal.buffer.active.viewportY >= terminal.buffer.active.baseY - 2,
|
||||
relayoutMobileSubagentWindows: () => {},
|
||||
};
|
||||
let pendingTimer: (() => void) | null = null;
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
window: { scrollTo: () => {}, matchMedia: () => ({ matches: false }), addEventListener: () => {} },
|
||||
document: { body: { classList: { add: () => {}, remove: () => {} } }, addEventListener: () => {} },
|
||||
navigator: { userAgent: 'test', maxTouchPoints: 0 },
|
||||
app,
|
||||
setTimeout: (fn: () => void) => {
|
||||
pendingTimer = fn;
|
||||
return 1;
|
||||
},
|
||||
clearTimeout: () => {
|
||||
pendingTimer = null;
|
||||
},
|
||||
});
|
||||
vm.runInContext(`${SOURCE}\n;globalThis.__KeyboardHandler = KeyboardHandler;`, context, {
|
||||
filename: 'mobile-handlers.js',
|
||||
});
|
||||
const kh = (context as any).__KeyboardHandler;
|
||||
// Stub the layout side effects the settle timer fires alongside the scroll.
|
||||
kh._shrinkPaddingToFit = () => {};
|
||||
kh._sendTerminalResize = () => {};
|
||||
return {
|
||||
kh,
|
||||
terminal,
|
||||
calls,
|
||||
/** Run the coalesced settle timer the way the OS animation eventually would. */
|
||||
settle: () => {
|
||||
const fn = pendingTimer;
|
||||
pendingTimer = null;
|
||||
fn?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('keyboard settle preserves scroll intent (issue #259)', () => {
|
||||
it('scrolls to bottom when the user is following live output', () => {
|
||||
const { kh, calls, settle } = loadKeyboardHandler({ viewportY: 500, baseY: 500 });
|
||||
|
||||
kh._scheduleViewportSettle({ restoreScroll: true });
|
||||
settle();
|
||||
|
||||
expect(calls).toContain('scrollToBottom');
|
||||
expect(calls.some((c) => c.startsWith('scrollToLine'))).toBe(false);
|
||||
});
|
||||
|
||||
it('returns to the anchor instead of the bottom when the user is reading history', () => {
|
||||
const { kh, calls, settle } = loadKeyboardHandler({ viewportY: 120, baseY: 500 });
|
||||
|
||||
kh._scheduleViewportSettle({ restoreScroll: true });
|
||||
settle();
|
||||
|
||||
expect(calls).toContain('scrollToLine:120');
|
||||
expect(calls).not.toContain('scrollToBottom');
|
||||
});
|
||||
|
||||
it('captures the anchor BEFORE the reflow, not after', () => {
|
||||
// The OS emits several viewport heights per animation, so the settle is
|
||||
// re-scheduled repeatedly. Only the first capture predates fit(); a later
|
||||
// one would read a viewportY the reflow had already moved.
|
||||
const { kh, terminal, calls, settle } = loadKeyboardHandler({ viewportY: 120, baseY: 500 });
|
||||
|
||||
kh._scheduleViewportSettle({ restoreScroll: true });
|
||||
terminal.buffer.active.viewportY = 480; // reflow drags the viewport down
|
||||
kh._scheduleViewportSettle({ restoreScroll: true });
|
||||
settle();
|
||||
|
||||
expect(calls).toContain('scrollToLine:120');
|
||||
});
|
||||
|
||||
it('clamps an anchor that outlives the buffer it was captured from', () => {
|
||||
const { kh, terminal, calls, settle } = loadKeyboardHandler({ viewportY: 400, baseY: 500 });
|
||||
|
||||
kh._scheduleViewportSettle({ restoreScroll: true });
|
||||
terminal.buffer.active.baseY = 90; // buffer shrank under us
|
||||
settle();
|
||||
|
||||
expect(calls).toContain('scrollToLine:90');
|
||||
});
|
||||
|
||||
it('leaves the terminal alone when the settle was not a keyboard transition', () => {
|
||||
const { kh, calls, settle } = loadKeyboardHandler({ viewportY: 120, baseY: 500 });
|
||||
|
||||
kh._scheduleViewportSettle({});
|
||||
settle();
|
||||
|
||||
expect(calls).toContain('fit');
|
||||
expect(calls).not.toContain('scrollToBottom');
|
||||
expect(calls.some((c) => c.startsWith('scrollToLine'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keyboard show/hide route through the intent-preserving path (static guard)', () => {
|
||||
it('both transitions ask to restore scroll, never to force the bottom', () => {
|
||||
// Slice from the METHOD DEFINITIONS ("\n name() {"), not the first
|
||||
// occurrence of the name — both are called from _checkKeyboard() further up.
|
||||
const bodyOf = (name: string) => {
|
||||
const start = SOURCE.indexOf(`\n ${name}() {`);
|
||||
expect(start, `${name} definition not found`).toBeGreaterThan(-1);
|
||||
return SOURCE.slice(start, SOURCE.indexOf('\n },', start));
|
||||
};
|
||||
const show = bodyOf('onKeyboardShow');
|
||||
const hide = bodyOf('onKeyboardHide');
|
||||
|
||||
expect(show).toContain('_scheduleViewportSettle({ restoreScroll: true })');
|
||||
expect(hide).toContain('_scheduleViewportSettle({ restoreScroll: true })');
|
||||
// The old unconditional call must not come back.
|
||||
expect(SOURCE).not.toContain('scrollToBottom: true');
|
||||
});
|
||||
});
|
||||
@@ -108,7 +108,9 @@ describe('full-history re-pull downgrade guard (issue #205 round 2)', () => {
|
||||
|
||||
it('is wired into _maybeRefetchFullHistory BEFORE the destructive reset', () => {
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
|
||||
const start = source.indexOf('async _maybeRefetchFullHistory()');
|
||||
// Anchor on the open paren, not the full empty signature: the method takes
|
||||
// options since #258 ({ force }) and this guard is about ORDER, not arity.
|
||||
const start = source.indexOf('async _maybeRefetchFullHistory(');
|
||||
const guard = source.indexOf('this._replayWouldShrinkBuffer(buffer)', start);
|
||||
const reset = source.indexOf('this._resetTerminalForReplay()', start);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user