Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph

**Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph--pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit)

**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection and drop recovery use a bounded 1 MiB `?tail=`, and Shell loads the rest only via **Load full history**, never on ordinary scroll. ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)
**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection and drop recovery use a bounded 1 MiB `?tail=`, and a Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay)

**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only, per-device): a second live session ("Pane B") beside the active one, in its own `SplitTerminalPane` (terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Deliberately plainer than the primary pane — no local-echo overlay, CJK IME, or touch handlers — and NOT persisted across reloads. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions)

Expand Down
2 changes: 1 addition & 1 deletion docs/architecture-invariants.md

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions docs/wiki/The-Dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,9 @@ Worth knowing:

- **Scrollback.** Agent/TUI sessions pull their entire tmux scrollback on first open.
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
switching; press **Load full history** to pull the rest explicitly. Ordinary Shell scrolling
and automatic output recovery stay within the bounded browser buffer.
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
history; press **Load full history** to pull the rest explicitly. Automatic output
recovery stays within the bounded browser buffer.
- **Wheel and touch scrolling** are forwarded into Claude's own transcript on recent Claude
versions, so the wheel scrolls the conversation rather than the terminal. `Shift+Wheel` is
always local scrollback. Other CLIs scroll locally.
Expand Down
48 changes: 42 additions & 6 deletions src/web/public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6320,10 +6320,15 @@ class CodemanApp {
if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
if (this.detachedSessions?.has(sessionId)) return;
const session = this.sessions.get(sessionId);
// A shell's full capture can be many megabytes. Replaying it from an
// ordinary scroll gesture blocks xterm's main thread, so keep that cost
// behind the explicit "Load full history" button.
if (!force && session?.mode === 'shell') return;
// A shell's full capture can be many megabytes, and replaying all of it from
// an ordinary scroll gesture blocks xterm's main thread. So a shell scroll
// pulls a BOUNDED window of tmux's full history (the same 1 MiB a tab switch
// loads, but of the scrollback rather than the visible frame) and the
// unbounded pull stays behind the "Load full history" button. Declining
// outright left a shell pane about one screen of browser scrollback after any
// burst, and the button only renders once a replay was truncated, so a young
// shell tab had no way back to output tmux was still holding.
const boundedShellPull = !force && session?.mode === 'shell';
const now = Date.now();
// Momentum scrolling fires this dozens of times per flick, and a burst of new
// output is the normal reason to want a re-pull, so cooldown rather than latch.
Expand All @@ -6336,7 +6341,12 @@ class CodemanApp {
this._fullHistoryRepullInFlight = true;
try {
const requestStartedAt = performance.now();
const capture = await this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?full=1`, { full: true });
const capture = await this._fetchTerminalCapture(
boundedShellPull
? `/api/sessions/${sessionId}/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}`
: `/api/sessions/${sessionId}/terminal?full=1`,
{ full: true }
);
const headersReceivedAt = capture.headersAt;
const payload = capture.json?.data ?? {};
const bodyParsedAt = performance.now();
Expand All @@ -6357,7 +6367,33 @@ class CodemanApp {
// Bail on a tab switch mid-fetch: writing here would paint another session's
// history into the terminal the user is now looking at.
if (!buffer || this.activeSessionId !== sessionId) return;
if (this._replayWouldShrinkBuffer(buffer)) {
const windowRows = this._estimateReplayRows(buffer, this.terminal.cols);
// A bounded window no longer than the browser's buffer buys nothing, and
// resetting to rewrite it would jump the viewport on every scroll that
// outlasts the cooldown at the top. This runs BEFORE the downgrade guard
// on purpose: that guard reads "smaller than the browser" as "tmux has
// nothing more to give", which is true of an unbounded capture but not of a
// window cut at the tail size, so a bounded window must never reach the
// exhausted path, which would take Load full history off the banner while
// tmux still holds the rest. Nothing was written here, so the banner state
// is left as the load that produced it set it: re-labelling it from this
// payload would call a terminal that holds ALL of a Load full history pull
// "the most recent 1 MiB".
if (boundedShellPull && windowRows <= this.terminal.buffer.active.length) {
// An untruncated window IS all of tmux's history, so nothing is missing,
// and the next burst of output can put more in tmux than the browser has:
// keep the normal 4 s cooldown. A truncated one is the opposite case, since
// the gesture can never reach anything older than what the browser already
// shows, and every ask costs the server a synchronous capture-pane of the
// whole history (`tail` is applied after the capture): back off to 60 s.
// Trade-off: only a successful replay clears that latch, so a tab switch or
// burst that shrinks the browser's buffer below the window can leave a
// scroll-to-top inert for up to a minute. Load full history (`force`)
// bypasses the cooldown, and the latch is bounded, never permanent.
if (payload.truncated) (this._fullHistoryRepullUseless ||= new Set()).add(sessionId);
return;
}
if (this._replayWouldShrinkBuffer(buffer, windowRows)) {
timing.refused = true;
timing.totalMs = performance.now() - requestStartedAt;
this._recordTerminalLoadTiming(timing);
Expand Down
14 changes: 9 additions & 5 deletions src/web/public/terminal-ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -3304,9 +3304,9 @@ Object.assign(CodemanApp.prototype, {
/**
* Post-scroll companion to _noteTerminalUserScroll: hitting the TOP of the
* buffer while scrolling up gives the app a chance to pull the rest of tmux's
* scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions decline
* automatic pulls because their captures can be large; their banner button is
* the explicit path. Must be called AFTER scrollLines(), since the check is on
* scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions pull a
* bounded window because their captures can be large; their banner button is
* the unbounded path. Must be called AFTER scrollLines(), since the check is on
* the resulting position, and it is deliberately not folded into
* _noteTerminalUserScroll for exactly that reason.
*/
Expand Down Expand Up @@ -3354,13 +3354,17 @@ Object.assign(CodemanApp.prototype, {
* below the last line, and _estimateReplayRows can only approximate wrapping.
* Only a capture that is worse by more than a full screen counts as a
* downgrade, which leaves every genuine recovery case untouched.
*
* A caller that already estimated the capture's rows passes them as
* `estimatedRows`, so a megabyte capture is not scanned twice.
*/
_replayWouldShrinkBuffer(capture) {
_replayWouldShrinkBuffer(capture, estimatedRows) {
const term = this.terminal;
const rowsNow = term?.buffer?.active?.length || 0;
if (!rowsNow) return false;
const screen = term?.rows || 24;
return this._estimateReplayRows(capture, term?.cols) + screen < rowsNow;
const rows = estimatedRows ?? this._estimateReplayRows(capture, term?.cols);
return rows + screen < rowsNow;
},

/**
Expand Down
9 changes: 6 additions & 3 deletions test/history-truncation-notice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('the in-terminal truncation line is gone (static guard)', () => {
expect(app).not.toContain('earlier output truncated for performance');
});

it('loads a bounded shell tail first and keeps full history user-triggered', () => {
it('loads a bounded shell tail first and keeps unbounded full history user-triggered', () => {
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
expect(app).toContain("session?.mode !== 'shell' && !this._fullHistoryLoaded.has(sessionId)");
expect(app).toContain("!restoredSnapshot && session?.mode !== 'shell'");
Expand All @@ -131,10 +131,13 @@ describe('the in-terminal truncation line is gone (static guard)', () => {
// an abort deadline (a `?full=1` body can be megabytes and used to hang
// indefinitely on a stalled mobile link). The URL and the full-vs-tail
// decision this guard exists to pin are unchanged.
expect(app).toContain('this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?full=1`, { full: true })');
expect(app).toContain(': `/api/sessions/${sessionId}/terminal?full=1`,\n { full: true }');
expect(app).toContain("if (this.sessions.get(sessionId)?.mode !== 'shell')");
expect(app).toContain("if (session?.mode === 'shell')");
expect(app).toContain("if (!force && session?.mode === 'shell') return;");
// A shell scroll gesture pulls a BOUNDED window of full history; only the
// button pulls all of it (behaviour pinned in shell-scroll-history-pull.test.ts).
expect(app).toContain("const boundedShellPull = !force && session?.mode === 'shell';");
expect(app).toContain('`/api/sessions/${sessionId}/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}`');
expect(app).toContain("trigger: force ? 'full-history-button' : 'full-history-scroll'");
});

Expand Down
Loading
Loading