Merge pull request #609: fix(remote): close the row gaps at the join in a remote history load

Conflict resolved in tmux-manager.ts: #609's screen-aware
joinScrollbackAndFrame keeps #602's merge-time SGR reset before the frame,
and #609's join tests expect it. The #601/#602 route test now mocks the
remote read in #609's { scrollback, screen } shape.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-10-13 18:04:05 +02:00
commit 239f15437b
7 files changed
+555 -107

No files matched your search

+8
View File
@@ -196,6 +196,14 @@ export interface PaneCaptureOptions {
* session's real history lives in the REMOTE tmux (`remote-pane-history.ts`).
*/
scrollbackOverride?: string;
/**
* With `scrollbackOverride`: the screen rows of the pane that history came
* from, read right after it. The frame this pane captures later can have
* scrolled past some of them, or show only part of a taller screen, so the
* rows above where the frame's top overlaps them are kept between the
* scrollback and the frame (`joinScrollbackAndFrame`).
*/
scrollbackOverrideScreen?: string;
/**
* Byte cap the consumer will keep from the capture. Sizes the child-process
* stdout buffer (with slack) so multi-MB scrollback dumps aren't killed by
+136 -45
View File
@@ -11,9 +11,25 @@
* the local pane is what the live stream keeps drawing into, so its frame and caret
* position are the ones the browser must end up with.
*
* ONE ssh round trip prints the remote pane's `#{history_size}` and its scrollback
* rows (`capture-pane -S -<N> -E -1`). The size is load-bearing: with no history at
* all, tmux clamps `-E -1` to the first VISIBLE row and would return it as history.
* ONE ssh round trip reads the remote pane's scrollback rows (`capture-pane -S -<N>
* -E -1`), its `#{history_size}` and its screen. The size is load-bearing: with no
* history at all, tmux clamps `-E -1` to the first VISIBLE row and would return it
* as history. The screen closes the seam between the remote read and the local
* frame, which is read only after the round trip: rows that scrolled in between,
* and the top of a remote screen taller than the local pane, are on that screen
* alone, and the caller keeps the screen rows above where the local frame overlaps
* it (`joinScrollbackAndFrame`).
*
* ⚠️ The three reads are ONE tmux command list (`a \; b \; c`), not three tmux
* runs. tmux runs a client's command list back to back without reading pane output
* in between, so the history ends exactly where the screen begins. As separate runs
* the shell kept writing between them, and the rows that scrolled in those
* milliseconds were in neither capture (measured on a busy pane: every read lost
* rows). This rests on how tmux's command queue behaves, not on a documented
* guarantee. tmux output cannot carry the NUL markers, so a random marker line
* printed by `display-message` separates the history from the size and screen.
* tmux before 3.2 prints no newline after `capture-pane -p`, so the marker can be
* glued onto an unterminated last history row; the parser accepts it there too.
*
* Bounded and fail-soft. Any failure (unreachable host, auth, missing session, odd
* output) returns null and the caller keeps the local capture, so a remote load is
@@ -29,6 +45,7 @@
*/
import { exec } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { promisify } from 'node:util';
import type { SessionRemote } from './types/session.js';
import { buildSshConnectionArgs, classifyRemoteAliveExit, remoteSshTarget, shellescape } from './remote-hosts.js';
@@ -53,9 +70,26 @@ const REMOTE_HISTORY_SLOT_WAIT_MS = 1_500;
/** After a failed read, skip that host for this long and use the local capture. */
const REMOTE_HISTORY_BACKOFF_MS = 30_000;
/** Headroom over the remote `tail -c` bound for the size line and markers. */
/**
* Headroom over the remote `tail -c` bound for what it does not cover: the two NUL
* markers and anything a login banner or rc file prints before the script.
*/
const REMOTE_HISTORY_SLACK_BYTES = 64 * 1024;
/**
* Added to the configured byte cap for the remote `tail -c` bound. That bound
* covers the whole tmux output, and the marker, the size and the screen come last
* (a wide, tall screen of colored rows runs to a few hundred KB); without this, a
* small cap would cut into the screen and lose the read. The route trims what it
* returns to the configured cap anyway, keeping the newest bytes.
*/
const REMOTE_SCREEN_ALLOWANCE_BYTES = 1024 * 1024;
/** The remote `tail -c` bound for a configured byte cap; 0 (unbounded) stays 0. */
export function remoteTailBytes(maxBytes: number): number {
return maxBytes > 0 ? Math.trunc(maxBytes) + REMOTE_SCREEN_ALLOWANCE_BYTES : 0;
}
/** Read ceiling when the configured byte cap is 0 (unbounded) and no `tail -c` runs. */
const UNBOUNDED_READ_MAX_BYTES = 64 * 1024 * 1024;
@@ -66,17 +100,28 @@ const UNBOUNDED_READ_MAX_BYTES = 64 * 1024 * 1024;
const backoffUntil = new Map<string, number>();
/**
* The remote shell script. Its first byte is a NUL so a login banner or an rc-file
* `echo` printed before it runs is separated without guessing (the same marker
* `buildRemoteProbeCommand` uses); a second NUL ends the history size.
* A fresh marker line for one read. Random, so no row the pane really holds can be
* taken for it.
*/
export function newScrollbackMarker(): string {
return `codeman-history-${randomBytes(8).toString('hex')}`;
}
/**
* The remote shell script. It prints a NUL, the tmux output, then a second NUL:
* the first separates a login banner or an rc-file `echo` printed before the
* script runs without guessing (the same marker `buildRemoteProbeCommand` uses),
* and both are printed whether or not tmux succeeds, so their presence says the
* script ran on the host. The tmux output is the history rows, `marker`, the
* history size, then the screen rows.
*/
export function buildRemoteScrollbackScript(
socket: string,
sessionName: string,
historyLines: number,
maxBytes: number
tailBytes: number,
marker: string
): string {
const tmux = `tmux -L ${shellescape(socket)}`;
// `=name:` is an EXACT session match, then its active pane. A bare name is
// read as a pane index or window name first, so a discovered session named
// `0` would capture some other session's pane.
@@ -84,11 +129,18 @@ export function buildRemoteScrollbackScript(
const lines = Math.max(1, Math.trunc(historyLines));
// The newest rows are the ones worth keeping, so the byte bound is applied on
// the remote side (`tail -c`) rather than by killing the read at maxBuffer.
// A cap of 0 means unbounded, as in the route.
const bound = maxBytes > 0 ? ` | tail -c ${Math.trunc(maxBytes)}` : '';
// It covers the whole tmux output, history first, so with the screen
// allowance in `remoteTailBytes()` a cut lands in the history. 0 means
// unbounded, as in the route.
const bound = tailBytes > 0 ? ` | tail -c ${Math.trunc(tailBytes)}` : '';
// ONE tmux command list, so no pane output is read between the history and
// the screen (see the @fileoverview). `\;` reaches tmux as a lone `;`.
return (
`printf '\\0' && ${tmux} display-message -p -t ${target} '#{history_size}' && printf '\\0' && ` +
`${tmux} capture-pane -p -e -J -S -${lines} -E -1 -t ${target}${bound}`
`printf '\\0'; tmux -L ${shellescape(socket)} ` +
`capture-pane -p -e -J -S -${lines} -E -1 -t ${target} \\; ` +
`display-message -p -t ${target} ${shellescape(marker)} \\; ` +
`display-message -p -t ${target} '#{history_size}' \\; ` +
`capture-pane -p -e -J -t ${target}${bound}; printf '\\0'`
);
}
@@ -97,37 +149,66 @@ export function buildRemoteScrollbackCommand(
remote: SessionRemote,
sessionId: string,
historyLines: number,
maxBytes: number
tailBytes: number,
marker: string
): string {
const { socket, sessionName } = remoteTmuxLocation(remote, sessionId);
const script = buildRemoteScrollbackScript(socket, sessionName, historyLines, maxBytes);
const script = buildRemoteScrollbackScript(socket, sessionName, historyLines, tailBytes, marker);
// `exec` so a timeout kill reaches ssh itself, not only the local `sh -c`.
return ['exec', ...buildSshConnectionArgs(remote), remoteSshTarget(remote), shellescape(script)].join(' ');
}
/**
* A `tail -c` cut lands mid-row (possibly mid-escape) whenever it bit, so the
* first, partial row is dropped. Under the bound, the rows are whole.
*/
export function dropPartialFirstRow(scrollback: string, maxBytes: number): string {
if (maxBytes <= 0 || Buffer.byteLength(scrollback, 'utf-8') < maxBytes) return scrollback;
const newline = scrollback.indexOf('\n');
return newline === -1 ? '' : scrollback.slice(newline + 1);
/** What one round trip read from the remote pane: its scrollback rows, then its screen. */
export interface RemoteScrollback {
/** History rows above the screen, oldest first; '' when the pane has none. */
scrollback: string;
/** The screen's rows, read in the same tmux command list, so they begin where the scrollback ends. */
screen: string;
}
/**
* The scrollback rows from the script's stdout, '' when the pane has no history,
* or null when the output is not the script's.
* The scrollback and screen rows from the script's stdout, or null when the
* output is not the script's or tmux printed nothing usable (no such session,
* or a byte cap so small it cut into the screen). The marker may end an
* unterminated history row (tmux before 3.2); when the output reached
* `tailBytes`, the history's partial first row is dropped.
*/
export function parseRemoteScrollbackOutput(stdout: string): string | null {
export function parseRemoteScrollbackOutput(
stdout: string,
marker: string,
tailBytes: number
): RemoteScrollback | null {
const start = stdout.indexOf('\0');
if (start === -1) return null;
const sizeEnd = stdout.indexOf('\0', start + 1);
const end = stdout.indexOf('\0', start + 1);
if (end === -1) return null;
// The marker ends a row, after the history's last row. Usually it is a row of
// its own, but tmux before 3.2 prints no newline after `capture-pane -p`, so
// when the history ends inside a wrapped line (`-J` leaves it unterminated)
// the marker is glued onto that row. It is random per read, so no row the
// pane really holds ends with it.
const markerRow = `${marker}\n`;
const raw = stdout.slice(start + 1, end);
const at = raw.indexOf(markerRow);
if (at === -1) return null;
const sizeStart = at + markerRow.length;
const sizeEnd = raw.indexOf('\n', sizeStart);
if (sizeEnd === -1) return null;
const sizeText = stdout.slice(start + 1, sizeEnd).trim();
const sizeText = raw.slice(sizeStart, sizeEnd).trim();
if (!/^\d+$/.test(sizeText)) return null;
if (Number(sizeText) === 0) return '';
return stdout.slice(sizeEnd + 1);
const screen = raw.slice(sizeEnd + 1);
// With no history at all, tmux clamps `-E -1` to the first visible row.
if (Number(sizeText) === 0) return { scrollback: '', screen };
// A tail -c cut lands in the history (the bound leaves room for the rest),
// mid-row and possibly mid-escape, so the first, partial row is dropped. A
// cut exactly on the marker row leaves no history at all.
let scrollback = raw.slice(0, at);
if (tailBytes > 0 && Buffer.byteLength(raw, 'utf-8') >= tailBytes) {
const newline = scrollback.indexOf('\n');
scrollback = newline === -1 ? '' : scrollback.slice(newline + 1);
}
if (scrollback !== '' && !scrollback.endsWith('\n')) scrollback += '\n';
return { scrollback, screen };
}
/** Runs the ssh command line and resolves its stdout; rejects like `exec` does. */
@@ -143,8 +224,8 @@ const execRunner: RemoteScrollbackRunner = async (command, opts) =>
* Only a TRANSPORT failure backs the host off (ssh's own exit 255, a timeout, a
* spawn error, output that is not the script's): those say the host is
* unreachable for every session on it. A remote command failing (a session
* that is gone: tmux exits 1, or answers nothing between the markers when the
* `| tail -c` pipe hides its status) is about this session only, so it returns
* that is gone: tmux answers nothing between the NULs, and the closing `printf`
* hides its exit status) is about this session only, so it returns
* null and the next session on that host still tries. Same split as
* `classifyRemoteAliveExit()`.
*
@@ -157,7 +238,7 @@ export async function fetchRemoteScrollback(
historyLines: number,
maxBytes: number,
run?: RemoteScrollbackRunner
): Promise<string | null> {
): Promise<RemoteScrollback | null> {
if (!run && process.env.VITEST) return null;
const runner = run ?? execRunner;
const until = backoffUntil.get(remote.hostId);
@@ -165,32 +246,42 @@ export async function fetchRemoteScrollback(
if (Date.now() < until) return null;
backoffUntil.delete(remote.hostId);
}
const command = buildRemoteScrollbackCommand(remote, sessionId, historyLines, maxBytes);
const marker = newScrollbackMarker();
const tailBytes = remoteTailBytes(maxBytes);
const command = buildRemoteScrollbackCommand(remote, sessionId, historyLines, tailBytes, marker);
try {
const stdout = await runWithRemoteSshLimit(
() =>
runner(command, {
timeout: REMOTE_HISTORY_TIMEOUT_MS,
maxBuffer: (maxBytes > 0 ? maxBytes : UNBOUNDED_READ_MAX_BYTES) + REMOTE_HISTORY_SLACK_BYTES,
maxBuffer: (tailBytes > 0 ? tailBytes : UNBOUNDED_READ_MAX_BYTES) + REMOTE_HISTORY_SLACK_BYTES,
}),
// The pool is shared with 20 s file probes; past this the local capture
// is the better answer than waiting behind them.
{ maxWaitMs: REMOTE_HISTORY_SLOT_WAIT_MS }
);
const scrollback = parseRemoteScrollbackOutput(stdout);
if (scrollback === null) {
// Both markers arrived, so the script ran on the host and only tmux had
// nothing to say: no such session. The `| tail -c` pipe hides tmux's
// exit status, so this comes back as exit 0 rather than exit 1, and it
// is about this session alone. Output without the markers is not the
// script's at all, which says the host is not answering as expected.
const ranOnHost = stdout.split('\0').length >= 3;
const parsed = parseRemoteScrollbackOutput(stdout, marker, tailBytes);
if (parsed === null) {
// Both NULs arrived, so the script ran on the host and only tmux had
// nothing to say: no such session. The script's last command is the
// closing `printf`, so this comes back as exit 0 rather than tmux's
// exit 1, and it is about this session alone. Output without the NULs
// is not the script's at all, which says the host is not answering as
// expected.
const parts = stdout.split('\0');
const ranOnHost = parts.length >= 3;
if (!ranOnHost) backoffUntil.set(remote.hostId, Date.now() + REMOTE_HISTORY_BACKOFF_MS);
const what = ranOnHost ? 'no such remote tmux session' : 'unexpected output';
// tmux printed something, but not the marker, size and screen in order.
const unreadable = ranOnHost && parts[1] !== '';
const what = !ranOnHost
? 'unexpected output'
: unreadable
? 'unreadable remote tmux output'
: 'no such remote tmux session';
console.warn(`[remote-history] ${remote.label}: ${what}; using the local capture`);
return null;
}
return dropPartialFirstRow(scrollback, maxBytes);
return parsed;
} catch (err) {
// A busy pool says nothing about the host.
if (err instanceof RemoteSshSlotTimeoutError) return null;
+84 -6
View File
@@ -694,16 +694,93 @@ export function normalizeScrollbackEol(buffer: string): string {
return buffer.replace(/\r?\n/g, '\r\n');
}
/** `capture-pane -p` text as rows: tmux ends it with one `\n`, and '' has none. */
function captureRows(text: string): string[] {
return text === '' ? [] : text.replace(/\n$/, '').split('\n');
}
/**
* Least overlap that places a frame in a screen: rows compared, and how many
* of them hold text. A placement too LOW repeats the rows between the true one
* and it, so a short overlap (one `$` or `❯` row, a rule line) is not trusted:
* past this, the plain join, which can only lose rows, is the safer answer.
*/
const FRAME_MATCH_MIN_ROWS = 3;
const FRAME_MATCH_MIN_CONTENT_ROWS = 2;
/**
* A captured row as plain text: escape sequences (SGR, OSC 8 links) and
* trailing blanks dropped. Two tmuxes render the same cell content, but need
* not encode its attributes the same way.
*/
function capturedRowText(row: string): string {
// eslint-disable-next-line no-control-regex
return row.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '').trimEnd();
}
/**
* Where a later frame of the same pane begins among the rows of an earlier
* screen capture, or -1 when that cannot be told.
*
* The frame's top rows must equal the screen's rows from that index on, as
* text. Two rows are left out of the comparison: the screen's trailing blank
* rows (output after the screen read fills them in the frame) and its last
* content row (output in flight may have finished it since). Every compared
* row must match, the overlap must reach FRAME_MATCH_MIN_ROWS rows with
* FRAME_MATCH_MIN_CONTENT_ROWS of them non-blank, and the SMALLEST index wins,
* so a block that merely repeats further down is only chosen when nothing
* above it matches. A row that changed between the two reads (a spinner, a
* clock) fails the true placement; the minimum keeps a lower one from being
* taken on a row or two that happen to be equal.
*
* An agent TUI mid-turn (Claude Code, codex, opencode) is not placed: it keeps
* a live region (spinner, composer, footer) pinned to the bottom and inserts new
* rows above it, so the frame is not a shifted copy of the screen and the
* comparison down to the screen's last content row fails. The caller then falls
* back to the plain join. A plain shell places.
*/
export function findFrameInScreen(screenRows: string[], frameRows: string[]): number {
const screen = screenRows.map(capturedRowText);
const frame = frameRows.map(capturedRowText);
let lastContent = screen.length - 1;
while (lastContent >= 0 && screen[lastContent] === '') lastContent--;
for (let start = 0; start < lastContent; start++) {
const overlap = Math.min(lastContent - start, frame.length);
if (overlap < FRAME_MATCH_MIN_ROWS) break; // only shrinks from here on
let matches = true;
let contentRows = 0;
for (let k = 0; k < overlap && matches; k++) {
if (screen[start + k] !== frame[k]) matches = false;
else if (frame[k] !== '') contentRows++;
}
if (matches && contentRows >= FRAME_MATCH_MIN_CONTENT_ROWS) return start;
}
return -1;
}
/**
* Put scrollback rows read elsewhere (`PaneCaptureOptions.scrollbackOverride`)
* above a visible-frame capture, as one capture in tmux's own shape: rows joined
* by a bare `\n`. Undefined or empty scrollback leaves the frame as it is.
*
* `screen` is that other pane's screen, read right after its scrollback. The
* frame is captured later, so rows can have scrolled out of it in between, and
* a frame showing part of a taller screen starts below that screen's top.
* Either way the screen rows above the frame's first row are in neither the
* scrollback nor the frame, so they go between the two. When the frame cannot
* be placed in the screen ({@link findFrameInScreen}), the join is the plain
* scrollback-over-frame one.
*/
export function joinScrollbackAndFrame(scrollback: string | undefined, frame: string): string {
if (!scrollback) return frame;
// Two separate captures: tmux encodes the frame relative to the DEFAULT
// state, so the scrollback's last row must not leave its attributes active.
return `${scrollback.replace(/\n$/, '')}\x1b[0m\n${frame}`;
export function joinScrollbackAndFrame(scrollback: string | undefined, frame: string, screen?: string): string {
let above = scrollback ? captureRows(scrollback) : [];
if (screen) {
const screenRows = captureRows(screen);
const frameStart = findFrameInScreen(screenRows, captureRows(frame));
if (frameStart > 0) above = above.concat(screenRows.slice(0, frameStart));
}
// Separate captures: tmux encodes the frame relative to the DEFAULT state, so
// the rows above it must not leave their attributes active.
return above.length > 0 ? `${above.join('\n')}\x1b[0m\n${frame}` : frame;
}
/** Pane geometry and caret position, as `display-message` reports them. */
@@ -3933,7 +4010,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
const rawCapture = joinScrollbackAndFrame(
scrollbackOverride,
execSync(`${this.tmux()} ${captureFlags} -t ${shellescape(target)}`, execOpts)
execSync(`${this.tmux()} ${captureFlags} -t ${shellescape(target)}`, execOpts),
scrollbackOverride !== undefined ? opts?.scrollbackOverrideScreen : undefined
);
// Query the cursor BEFORE deciding anything else. On the full-history path
// it settles both how the capture is trimmed and whether a cursor move is
+4 -1
View File
@@ -3138,7 +3138,10 @@ export function registerSessionRoutes(
captureOpts.historyLimitLines,
terminalBufferMaxBytes
);
if (remoteScrollback !== null) captureOpts.scrollbackOverride = remoteScrollback;
if (remoteScrollback !== null) {
captureOpts.scrollbackOverride = remoteScrollback.scrollback;
captureOpts.scrollbackOverrideScreen = remoteScrollback.screen;
}
}
const capture = (opts: PaneCaptureOptions): string | null =>
muxName && typeof ctx.mux.captureActivePaneBuffer === 'function'