Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: give the PTY re-attach buffer one owner in terminalReplay.js (#7546)

[._.]/ Adam Eivy07892e09dc96
diff --git a/server/lib/README.md b/server/lib/README.md
index dc00d2ff00..ce7656e532 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -122,7 +122,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spriteValidation.js` | Sprite Manager Zod schemas — record import/create/update, reference generate/lock/unlock + fork, walk-cycle generate/approve/reopen/trim, per-track generate/approve schemas built from the animation-track registry, publish binding + runtime contract, atlas publish/compile, and user-defined animation-track create/update. Split out of `validation.js` (#3873), which re-exports it. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
-| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay by `attachSession`: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. |
+| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay by the buffer itself: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. `createReplayBuffer({ maxBytes })` — the ring buffer that owns both corrections and the bytes they apply to: `push(chunk)` appends, observes modes and evicts past the cap (keeping the newest chunk whole, since a chunk larger than the cap is the live screen), `render()` returns the mode preamble followed by the stripped buffer in that load-bearing order, `size()` reports the bytes retained. `services/shell.js` holds one per PTY session. |
## Story & narrative
diff --git a/server/lib/terminalReplay.js b/server/lib/terminalReplay.js
index bfa0ef642c..7af6bcec4f 100644
--- a/server/lib/terminalReplay.js
+++ b/server/lib/terminalReplay.js
@@ -199,3 +199,54 @@ export const createTerminalModeTracker = () => {
}
};
};
+
+/**
+ * The re-attach ring buffer itself: the recorded bytes plus BOTH corrections
+ * this module exists for, behind one object.
+ *
+ * Both corrections above are properties of the replay, not of the caller, so
+ * they belong to whatever owns the bytes. Held apart — as a chunk array, a byte
+ * count, a mode tracker and an expression that composes them at attach time —
+ * each new correction had to be threaded through two functions hundreds of
+ * lines apart in `services/shell.js`, and "the preamble leads" was an ordering
+ * an unrelated caller had to remember rather than something the buffer
+ * guarantees. Here `render()` guarantees it, and the whole replay contract is
+ * testable with no PTY.
+ *
+ * Eviction keeps the NEWEST chunk unconditionally: a single chunk larger than
+ * the cap is the live screen, and dropping it would hand an attaching client an
+ * empty terminal.
+ *
+ * @param {{ maxBytes?: number }} [options]
+ * @returns {{ push: (data: string) => void, render: () => string, size: () => number }}
+ */
+export const createReplayBuffer = ({ maxBytes = 50 * 1024 } = {}) => {
+ const chunks = [];
+ const modes = createTerminalModeTracker();
+ let bytes = 0;
+
+ return {
+ /** Record one chunk of raw PTY output, in stream order. */
+ push(data) {
+ // Modes are observed over the WHOLE stream, before eviction can drop the
+ // startup chunk that declared them — that is the point of the tracker.
+ modes.observe(data);
+ chunks.push(data);
+ bytes += data.length;
+ while (bytes > maxBytes && chunks.length > 1) {
+ bytes -= chunks.shift().length;
+ }
+ },
+
+ /**
+ * What a newly attached client should be handed. The modes in force lead:
+ * they have to be set before the frames drawn under them are painted.
+ */
+ render() {
+ return modes.preamble() + stripTerminalQueries(chunks.join(''));
+ },
+
+ /** Bytes currently retained — at most `maxBytes`, unless one chunk exceeds it. */
+ size: () => bytes
+ };
+};
diff --git a/server/lib/terminalReplay.test.js b/server/lib/terminalReplay.test.js
index eb93512ac3..3ef3b7418e 100644
--- a/server/lib/terminalReplay.test.js
+++ b/server/lib/terminalReplay.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { createTerminalModeTracker, stripTerminalQueries } from './terminalReplay.js';
+import { createReplayBuffer, createTerminalModeTracker, stripTerminalQueries } from './terminalReplay.js';
// The exact replies @xterm/xterm sends for each query, captured from a real
// terminal. These are what used to reach the PTY — and land on the shell prompt.
@@ -144,3 +144,61 @@ describe('createTerminalModeTracker', () => {
expect(tracker.preamble()).toBe('');
});
});
+
+// The whole re-attach contract, with no shell service and no PTY: what a client
+// that attaches late is handed, and what the ring buffer had to drop to stay
+// bounded.
+describe('createReplayBuffer', () => {
+ it('replays what was recorded', () => {
+ const replay = createReplayBuffer();
+ replay.push('first ');
+ replay.push('second');
+ expect(replay.render()).toBe('first second');
+ });
+
+ it('evicts oldest chunks past the cap, keeping the newest whole', () => {
+ const replay = createReplayBuffer({ maxBytes: 50 });
+ replay.push('A'.repeat(20));
+ replay.push('B'.repeat(20));
+ replay.push('C'.repeat(20));
+ expect(replay.size()).toBeLessThanOrEqual(50);
+ const rendered = replay.render();
+ expect(rendered).not.toContain('A');
+ expect(rendered).toBe('B'.repeat(20) + 'C'.repeat(20));
+ });
+
+ it('keeps a single chunk that alone exceeds the cap — it is the live screen', () => {
+ const replay = createReplayBuffer({ maxBytes: 10 });
+ const screen = 'X'.repeat(50);
+ replay.push(screen);
+ expect(replay.render()).toBe(screen);
+ expect(replay.size()).toBe(50);
+ });
+
+ it('leads with the modes still in force, then the frames drawn under them', () => {
+ const replay = createReplayBuffer({ maxBytes: 20 });
+ // The TUI declares its modes once at startup, then renders until the ring
+ // buffer has evicted that declaration entirely.
+ replay.push(OPENCODE_STARTUP);
+ replay.push('f'.repeat(20));
+ replay.push('g'.repeat(20));
+ const rendered = replay.render();
+ expect(rendered).toBe(
+ '\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?2004h'
+ + 'g'.repeat(20)
+ );
+ });
+
+ it('strips a query split across two recorded chunks', () => {
+ const replay = createReplayBuffer();
+ replay.push('before\x1b[');
+ replay.push('6nafter');
+ expect(replay.render()).toBe('beforeafter');
+ });
+
+ it('starts empty', () => {
+ const replay = createReplayBuffer();
+ expect(replay.size()).toBe(0);
+ expect(replay.render()).toBe('');
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index 834d0cfa03..153459bb4c 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -9,7 +9,7 @@ import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
import { buildRunThenExitCommand } from '../lib/shellExit.js';
import { buildReadinessProbe } from '../lib/shellReadinessProbe.js';
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
-import { createTerminalModeTracker, stripTerminalQueries } from '../lib/terminalReplay.js';
+import { createReplayBuffer } from '../lib/terminalReplay.js';
import { findCommandOnPath } from '../lib/processEnv.js';
// Store active shell sessions (persist across socket reconnects)
@@ -189,14 +189,10 @@ function ptyTerminalOptions({ cwd, cols, rows }) {
* spawned them, which ends the session through `unregisterExternalSession`.
*/
function adoptPtySession(sessionId, ptyProcess, options = {}) {
- // Buffer recent output for re-attach (last 50KB)
- const outputBuffer = [];
- let bufferSize = 0;
- const MAX_BUFFER = 50 * 1024;
- // Terminal modes are declared once, at TUI startup, so the ring buffer drops
- // them on any run long enough to overflow it. This follows the WHOLE stream so
- // attachSession can re-declare them. See lib/terminalReplay.js.
- const modeTracker = createTerminalModeTracker();
+ // The last 50KB of output, replayed to a client that attaches later. The
+ // buffer owns its own eviction, query-stripping and mode tracking — see
+ // lib/terminalReplay.js.
+ const replay = createReplayBuffer();
// Store session info
shellSessions.set(sessionId, {
@@ -219,20 +215,12 @@ function adoptPtySession(sessionId, ptyProcess, options = {}) {
// Keeps the session out of the interactive cap count and out of Shell's
// auto-attach — you opt into watching a run by clicking its tab.
...(options.external ? { external: true } : {}),
- outputBuffer,
- modeTracker,
- bufferSize: () => bufferSize
+ replay
});
// Handle pty output
ptyProcess.onData((data) => {
- modeTracker.observe(data);
- // Buffer output for re-attach
- outputBuffer.push(data);
- bufferSize += data.length;
- while (bufferSize > MAX_BUFFER && outputBuffer.length > 1) {
- bufferSize -= outputBuffer.shift().length;
- }
+ replay.push(data);
const session = shellSessions.get(sessionId);
session?.socket?.emit('shell:output', { sessionId, data });
if (session) runHook('onData', session, session.onData, data);
@@ -642,11 +630,7 @@ export function attachSession(sessionId, socket, { claim = false } = {}) {
broadcastSessionList();
return {
sessionId,
- // Mode preamble, then the stripped buffer — both explained in
- // lib/terminalReplay.js. The order is load-bearing: the modes have to be in
- // force before the frames that were drawn under them are painted.
- bufferedOutput: session.modeTracker.preamble()
- + stripTerminalQueries(session.outputBuffer.join(''))
+ bufferedOutput: session.replay.render()
};
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index 908f5b740c..1bc0fdce75 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -155,7 +155,7 @@ describe('createShellSession', () => {
ptyInstances[0].emitData(newest);
const session = shell.getSession(id);
- expect(session.bufferSize()).toBeLessThanOrEqual(50 * 1024);
+ expect(session.replay.size()).toBeLessThanOrEqual(50 * 1024);
const result = shell.attachSession(id, makeSocket('sock-B'));
expect(result.bufferedOutput).not.toContain('A');
expect(result.bufferedOutput).toContain(middle);