perf(capture): a grid tile's full capture reads no more history than it keeps

GET /api/sessions/:id/terminal?full=1 captured the whole tmux history
(capture-pane -S -<history limit>, 100,000 lines by default) and cut it to
`tail` only afterwards, all of it synchronous on the server's event loop.
A grid tile keeps TILE_SCROLLBACK lines plus its screen, so the rest was
captured to be thrown away, once per tile on every grid open, restore and
deploy reconnect. The route now takes an optional `lines=<n>` (an integer
of at least 1, clamped to the configured history limit) and passes it as
the capture's history bound (the existing historyLimitLines, so -S -<n>);
absent or malformed, the limit itself, so every existing caller gets the
same capture as before. Only full captures read it: the visible-frame path
(a shell tile's `tail=` load) reads no history and is untouched. The
capture still ends with its RELATIVE cursor move back to the caret, still
counts as a full capture (isFullCapture: the line-deleting transforms stay
off) and still reports captureCols/captureRows.

Grid tiles (boundedLoad) send lines=<scrollback + rows> on every full
capture of theirs: a TUI load and a shell history pull. The split's Pane B
asks for everything, as before.

Measured:
- A real haiku Claude pane on tileperf (about 3k lines of history):
  bounded captures (lines=50, 500, 2000, 100000) against the unbounded
  one, 4 PASS 0 FAIL: each a line-aligned suffix of it, ending in the
  same relative cursor move (ESC[4A CR ESC[2C), same source
  (mux-full-history) and capture geometry. Capture time there 72 ms both
  ways, that history being shorter than the tile's bound. As a grid tile
  (it sent lines=10047) its screen matched the pane row for row, 47 of
  47 at the pane's own 77x47, caret on the composer.
- Six tiles restoring with Claude-style loads (full=1&tail=1MiB forced
  on shells with about 19k lines of tmux history each, above the tile's
  bound; n=3+3 interleaved, load 4.2 to 7.2): capture per tile med
  219 ms [194 to 294] -> 155 ms [127 to 211]; server event-loop delay in
  the capture window, max med 262 -> 201 ms; all painted 4.5 -> 3.6 s.
  At checkpoint 1 a 30k-line history cost 713 ms per capture (event loop
  blocked up to 765 ms each); the bound caps that at the tile's size.

Tests: the route passes lines= through, clamps it, ignores every malformed
form and leaves the visible-frame capture exactly as it was; a bounded
capture keeps its rows and ends in the cursor restore; grid tiles send it
on full captures and the split's Pane B does not. Mutation-checked six ways
(lines ignored, no clamp, a lenient parse, lines on the visible path, the
tile sending none, Pane B sending it). Documented in docs/api-reference.md
(/api/v1 is public).

Scope: PR 2 (the grid's loads; server route plus terminal-tile.js).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-10-07 07:44:56 +02:00
parent 50e0d22def
commit 6d72b38db4
5 changed files with 114 additions and 10 deletions
+56
View File
@@ -1037,6 +1037,62 @@ describe('session-routes', () => {
expect(body.data.terminalBuffer.endsWith(`${newestMarker}${cursorRestore}`)).toBe(true);
});
it('`lines=` bounds the history a full capture reads, clamped to the configured limit', async () => {
// Grid tiles send it (TerminalTile._historyLinesQuery): without it a full
// capture reads the whole history limit synchronously, and `tail` cuts it
// only afterwards. Absent or malformed, the limit itself, as before.
const limit = (await harness.ctx.getTerminalHistoryConfig()).tmuxHistoryLimit;
harness.ctx._session.mode = 'claude';
const captureSpy = vi.fn((_name: string, _opts?: { historyLimitLines?: number }) => 'captured frame');
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy;
const linesFor = async (query: string) => {
captureSpy.mockClear();
await harness.app.inject({ method: 'GET', url: `/api/sessions/${harness.ctx._sessionId}/terminal?${query}` });
return captureSpy.mock.calls[0]?.[1]?.historyLimitLines;
};
expect(await linesFor(`full=1&tail=${1024 * 1024}&lines=10040`)).toBe(10040);
expect(await linesFor('full=1&lines=1')).toBe(1);
expect(await linesFor('full=1')).toBe(limit);
expect(await linesFor(`full=1&lines=${limit + 5}`)).toBe(limit);
for (const bad of ['0', '-5', 'abc', '1.5', '', '1e4', '9999999999']) {
expect(await linesFor(`full=1&lines=${bad}`), `lines=${bad}`).toBe(limit);
}
});
it('`lines=` leaves a visible-frame capture (no full=1) exactly as it was', async () => {
harness.ctx._session.mode = 'shell';
const captureSpy = vi.fn(() => 'only the visible frame');
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy;
await harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/terminal?tail=${1024 * 1024}&lines=500`,
});
expect(captureSpy).toHaveBeenCalledWith(harness.ctx._session.muxName, {});
});
it('a capture bounded by `lines=` is still a full capture: rows kept, cursor restore last', async () => {
// Only how much history tmux reads changes. The row-preserving skips key
// on isFullCapture, and the relative cursor move must still end it.
const cursorRestore = '\x1b[3A\r\x1b[2C';
const capture = `\r\n${['first row', 'second row', 'last row'].join('\r\n')}${cursorRestore}`;
harness.ctx._session.mode = 'claude';
harness.ctx._session.terminalBuffer = 'byte history that must not be prepended';
const captureSpy = vi.fn((_name: string, opts?: { fullHistory?: boolean }) =>
opts?.fullHistory ? capture : 'only the visible frame'
);
(harness.ctx.mux as { captureActivePaneBuffer?: unknown }).captureActivePaneBuffer = captureSpy;
const res = await harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/terminal?full=1&tail=${1024 * 1024}&lines=40`,
});
const body = JSON.parse(res.body);
expect(body.data.source).toBe('mux-full-history');
expect(body.data.terminalBuffer.startsWith('\r\nfirst row')).toBe(true);
expect(body.data.terminalBuffer.endsWith(`last row${cursorRestore}`)).toBe(true);
expect(body.data.terminalBuffer).not.toContain('byte history');
});
it('full reload (?full=1) returns the tmux capture ALONE — byte history is not duplicated', async () => {
// The full-history capture is the rendered form of everything already in
// the byte buffer; prepending the byte history would replay the whole
+7 -4
View File
@@ -165,6 +165,9 @@ vm.runInContext(
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const TileGrid = windowStub.CodemanTileGrid as { TILE_SCROLLBACK: number };
const TAIL = 1024 * 1024;
// A grid tile's full captures read no more tmux history than its xterm keeps:
// TILE_SCROLLBACK plus the screen (the fake terminal has 24 rows).
const LINES = `&lines=${TileGrid.TILE_SCROLLBACK + 24}`;
type Tile = {
sessionId: string;
@@ -292,7 +295,7 @@ describe('initial loads', () => {
await drain();
await Promise.all(connecting);
expect(captures.map((c) => c.url)).toEqual([
`/api/sessions/tui/terminal?full=1&tail=${TAIL}`,
`/api/sessions/tui/terminal?full=1&tail=${TAIL}${LINES}`,
`/api/sessions/sh/terminal?tail=${TAIL}`,
]);
});
@@ -361,9 +364,9 @@ describe('refreshes', () => {
expect(inFlight()).toBe(1);
await drain();
expect(captures.map((c) => c.url)).toEqual([
`/api/sessions/a/terminal?full=1&tail=${TAIL}`,
`/api/sessions/sh/terminal?full=1&tail=${TAIL}`,
`/api/sessions/b/terminal?full=1&tail=${TAIL}`,
`/api/sessions/a/terminal?full=1&tail=${TAIL}${LINES}`,
`/api/sessions/sh/terminal?full=1&tail=${TAIL}${LINES}`,
`/api/sessions/b/terminal?full=1&tail=${TAIL}${LINES}`,
]);
});