fix(terminal): load tmux history instead of paging Claude after a hollow tab switch

After a server restart the byte recording a tab switch replays (`?tail=`) holds only the tmux client's attach repaint, so an inline Claude session came back with an empty local buffer while tmux still held its scrollback. The hollow-buffer fallback then sent PageUp/PageDown to Claude, which moved the composer cursor instead of the transcript, until a page reload. Pre-existing on an unmodified build; every restart of the server showed it.

The paging fallback now stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0), dropping the gesture debt and any page keys already queued, so the gesture falls through to the local path, whose scroll-to-top pull fetches `full=1` and the gesture scrolls on from there. Zero and unknown counts keep paging (fullscreen Claude, codex, opencode, remote and Docker panes). The pull no longer inherits a downgrade refusal's 60 s latch for such a buffer, drops a completion that outlived a tab switch back to the same session (select generation, not only the session id), records no count from an error envelope (a JSON 5xx would otherwise forget it and hand the next gesture back to paging), and re-positions the local-echo overlay after its rewrite. The refresh path records its count only once it still owns the terminal, for the same reason. The `[scroll]` line prints `paneHistoryLines` so an unloaded buffer reads apart from a hollow one, and the invariant docs record the exception.

Measured with phone emulation after a restart: before, the second visit landed at baseY 0 and every swipe sent PageUp; after, the first swipe fetched the history once with nothing sent to Claude and the gesture scrolled 21 rows, with an unsent draft intact on the overlay.
This commit is contained in:
JD committed 2026-10-22 15:13:01 -04:00
1 parent 002de32a08
commit 84adb701d7
9 files changed
+301 -16

No files matched your search

+82 -1
View File
@@ -24,6 +24,10 @@
* the real `_setHistoryTruncation` and the real `computeHistoryTruncationNotice`
* to pin what the user is actually told.
*
* The last block pins the pull's own tab-switch guard: a capture that lands
* after A -> B -> A is dropped by the select generation, since the session id
* alone matches again while the switch back is still replaying.
*
* The method is extracted from app.js and run in a `vm` against stubs (no jsdom
* on this box; see connection-indicator.test.ts), with the REAL row estimators
* from terminal-ui.js, which decide both the downgrade and the no-gain skip.
@@ -118,17 +122,19 @@ function makeApp(
activeSessionId: 's1',
sessions: new Map([['s1', { mode }]]),
detachedSessions: new Set<string>(),
_selectGeneration: 7,
_fullHistoryRepullInFlight: false,
_isLoadingBuffer: false,
_fullHistoryRepullAt: new Map<string, number>(),
_fullHistoryRepullUseless: new Set<string>(),
_paneHistoryLines: new Map<string, number>(),
terminalBufferCache: new Map<string, string>(),
terminal: {
cols: 80,
rows: 30,
// xterm's scrollback option; 0 leaves the browser-cap check out of a test.
options: { scrollback },
buffer: { active: { length: bufferRows } },
buffer: { active: { length: bufferRows, baseY: 0 } },
scrollToLine: vi.fn(),
scrollToTop: vi.fn(),
},
@@ -144,6 +150,7 @@ function makeApp(
}),
_recordTerminalLoadTiming: vi.fn(),
_logScrollRouting: vi.fn(),
_notePaneHistory: vi.fn(),
// The real method behind a spy, so a test sees both what it was called with
// and the banner state (`_historyTruncation`) it leaves behind.
_historyTruncation: new Map<string, unknown>(),
@@ -358,3 +365,77 @@ describe('_replayWouldShrinkBuffer takes rows the caller already estimated', ()
expect(ctx._estimateReplayRows).toHaveBeenCalledTimes(1);
});
});
describe('a pull that outlives a tab switch never rewrites the terminal', () => {
it('drops the capture when the select generation moved during the fetch, even back to the same session', async () => {
// A -> B -> A while the request was out: the active id matches again, but
// selectSession is replaying its own capture, and a reset here would land
// in the middle of that write.
const { app } = makeApp('claude', { bufferRows: 40, capture: lines(300) });
app._fetchTerminalCapture.mockImplementationOnce(async () => {
app._selectGeneration = 9;
return {
headersAt: performance.now(),
headers: { get: () => '' },
json: { data: { terminalBuffer: lines(300), source: 'mux-full-history' } },
};
});
await refetch.call(app);
expect(app._resetTerminalForReplay).not.toHaveBeenCalled();
expect(app.chunkedTerminalWrite).not.toHaveBeenCalled();
expect(app._fullHistoryRepullInFlight).toBe(false);
// Nor does the stale response overwrite what the switch back recorded about the pane.
expect(app._notePaneHistory).not.toHaveBeenCalled();
});
it('replays when no switch happened, and records the pane', async () => {
const { app } = makeApp('claude', { bufferRows: 40, capture: lines(300) });
await refetch.call(app);
expect(app._resetTerminalForReplay).toHaveBeenCalledTimes(1);
expect(app.chunkedTerminalWrite).toHaveBeenCalledTimes(1);
expect(app._notePaneHistory).toHaveBeenCalledWith('s1', expect.objectContaining({ source: 'mux-full-history' }));
});
});
describe('an unloaded buffer is not held to an older downgrade refusal', () => {
it('pulls on the normal cooldown when the buffer is one screen and the pane holds scrollback', async () => {
// A refused pull latches a 60 s cooldown because the browser then held MORE
// than tmux. A tab switch that replays a hollow tail voids that premise, and
// with paging suppressed for such a buffer the latch would leave the gesture
// dead for up to a minute.
const { app, urls } = makeApp('claude', { bufferRows: 30, capture: lines(300) });
app._fullHistoryRepullUseless.add('s1');
app._fullHistoryRepullAt.set('s1', Date.now() - 10_000);
app.terminal.buffer.active.baseY = 0;
app._paneHistoryLines.set('s1', 11_344);
await refetch.call(app);
expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']);
expect(app._resetTerminalForReplay).toHaveBeenCalledTimes(1);
});
it('keeps the latch while the buffer still holds the history the refusal was about', async () => {
const { app, urls } = makeApp('claude', { bufferRows: 300, capture: lines(300) });
app._fullHistoryRepullUseless.add('s1');
app._fullHistoryRepullAt.set('s1', Date.now() - 10_000);
app.terminal.buffer.active.baseY = 270;
app._paneHistoryLines.set('s1', 11_344);
await refetch.call(app);
expect(urls).toEqual([]);
});
it('records nothing from an error envelope, so the remembered count survives for the retry', async () => {
// A JSON 5xx parses like any response. Recording its empty data would
// forget the count and hand the next gesture back to the paging fallback.
const { app } = makeApp('claude', { bufferRows: 30, capture: lines(300) });
app._paneHistoryLines.set('s1', 11_344);
app._fetchTerminalCapture.mockImplementationOnce(async () => ({
headersAt: performance.now(),
headers: { get: () => '' },
json: { success: false, error: 'tmux capture failed' },
}));
await refetch.call(app);
expect(app._notePaneHistory).not.toHaveBeenCalled();
expect(app._resetTerminalForReplay).not.toHaveBeenCalled();
expect(app._fullHistoryRepullInFlight).toBe(false);
});
});