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: keep replay semantics in one test file and drop the test-only size()

[._.]/ Adam Eivy646557df2642
diff --git a/server/lib/README.md b/server/lib/README.md
index ce7656e532..0a7111b7af 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 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. |
+| `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: 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 })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
## Story & narrative
diff --git a/server/lib/terminalReplay.js b/server/lib/terminalReplay.js
index 7af6bcec4f..aaa7b28667 100644
--- a/server/lib/terminalReplay.js
+++ b/server/lib/terminalReplay.js
@@ -202,23 +202,17 @@ 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.
+ * above, behind one object. They are properties of the replay rather than of
+ * any caller, so they belong to whatever owns the bytes — `render()` is what
+ * guarantees the preamble leads, instead of an attach site having to remember
+ * it.
*
* 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 }}
+ * @returns {{ push: (data: string) => void, render: () => string }}
*/
export const createReplayBuffer = ({ maxBytes = 50 * 1024 } = {}) => {
const chunks = [];
@@ -228,8 +222,7 @@ export const createReplayBuffer = ({ maxBytes = 50 * 1024 } = {}) => {
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.
+ // Observed before eviction can drop the startup chunk that declared them.
modes.observe(data);
chunks.push(data);
bytes += data.length;
@@ -238,15 +231,9 @@ export const createReplayBuffer = ({ maxBytes = 50 * 1024 } = {}) => {
}
},
- /**
- * 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.
- */
+ /** What a newly attached client is handed. */
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 3ef3b7418e..1edb7c5dee 100644
--- a/server/lib/terminalReplay.test.js
+++ b/server/lib/terminalReplay.test.js
@@ -145,26 +145,16 @@ describe('createTerminalModeTracker', () => {
});
});
-// 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.
+// The whole re-attach contract, with no shell service and no PTY. These are the
+// only home for replay semantics: `services/shell.test.js` asserts the wiring
+// (attachSession hands back render()), not what render() decides.
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));
+ expect(replay.render()).toBe('B'.repeat(20) + 'C'.repeat(20));
});
it('keeps a single chunk that alone exceeds the cap — it is the live screen', () => {
@@ -172,7 +162,6 @@ describe('createReplayBuffer', () => {
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', () => {
@@ -182,14 +171,16 @@ describe('createReplayBuffer', () => {
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)
- );
+ const preamble = '\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?2004h';
+ expect(replay.render()).toBe(preamble + 'g'.repeat(20));
+ // The preamble is the ONLY place those modes still appear — the declaration
+ // itself was evicted, which is why it has to be re-asserted at all.
+ expect(replay.render().slice(preamble.length)).not.toContain('\x1b[?');
});
it('strips a query split across two recorded chunks', () => {
+ // node-pty hands over whatever the read returned; stripping runs over the
+ // JOINED buffer so a sequence straddling two chunks still matches.
const replay = createReplayBuffer();
replay.push('before\x1b[');
replay.push('6nafter');
@@ -197,8 +188,6 @@ describe('createReplayBuffer', () => {
});
it('starts empty', () => {
- const replay = createReplayBuffer();
- expect(replay.size()).toBe(0);
- expect(replay.render()).toBe('');
+ expect(createReplayBuffer().render()).toBe('');
});
});
diff --git a/server/services/shell.js b/server/services/shell.js
index 153459bb4c..b3f7957856 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -189,8 +189,8 @@ function ptyTerminalOptions({ cwd, cols, rows }) {
* spawned them, which ends the session through `unregisterExternalSession`.
*/
function adoptPtySession(sessionId, ptyProcess, options = {}) {
- // The last 50KB of output, replayed to a client that attaches later. The
- // buffer owns its own eviction, query-stripping and mode tracking — see
+ // Recent output, replayed to a client that attaches later. The buffer owns
+ // its own window, eviction, query-stripping and mode tracking — see
// lib/terminalReplay.js.
const replay = createReplayBuffer();
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index 1bc0fdce75..ae3e1f5b73 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -145,23 +145,6 @@ describe('createShellSession', () => {
expect(onData).toHaveBeenCalledWith('hello');
});
- it('buffers output and trims oldest chunks past 50KB', () => {
- const id = shell.createShellSession(makeSocket());
- const oldest = 'A'.repeat(20 * 1024);
- const middle = 'B'.repeat(20 * 1024);
- const newest = 'C'.repeat(20 * 1024);
- ptyInstances[0].emitData(oldest);
- ptyInstances[0].emitData(middle);
- ptyInstances[0].emitData(newest);
-
- const session = shell.getSession(id);
- 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);
- expect(result.bufferedOutput).toContain(newest);
- });
-
it('catches synchronous errors from the onData hook without crashing', async () => {
const onData = vi.fn(() => { throw new Error('hook explodes'); });
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -348,6 +331,9 @@ describe('attachSession', () => {
expect(shell.attachSession('does-not-exist', makeSocket())).toBeNull();
});
+ // The WIRING only: that attach hands back what the session buffer rendered.
+ // What that render DECIDES — eviction, query stripping, the mode preamble and
+ // its ordering — is pinned in lib/terminalReplay.test.js, with no PTY.
it('swaps socket and returns buffered output', () => {
const sock1 = makeSocket('sock-A');
const id = shell.createShellSession(sock1);
@@ -358,31 +344,6 @@ describe('attachSession', () => {
expect(shell.getSession(id).socket).toBe(sock2);
});
- // A full-screen TUI (Claude Code / Ink, vim) emits `ESC[6n` on nearly every
- // render, and the ring buffer stores raw PTY output verbatim. Replaying those
- // queries makes the attaching xterm answer EVERY one of them as input — and the
- // TUI that asked is gone, so the cursor-position reports land on the shell
- // prompt as literal `56;3R56;3R…` garbage. Queries must not survive the replay.
- it('strips terminal queries from the replay buffer so the client cannot answer them', () => {
- const sock1 = makeSocket('sock-A');
- const id = shell.createShellSession(sock1);
- ptyInstances[0].emitData('\x1b[32mprompt\x1b[0m' + '\x1b[6n'.repeat(50));
- const result = shell.attachSession(id, makeSocket('sock-B'));
- expect(result.bufferedOutput).not.toContain('\x1b[6n');
- // Colour/rendering state still has to repaint correctly.
- expect(result.bufferedOutput).toBe('\x1b[32mprompt\x1b[0m');
- });
-
- it('strips a query split across two PTY chunks', () => {
- const sock1 = makeSocket('sock-A');
- const id = shell.createShellSession(sock1);
- // node-pty hands over whatever arrived; an escape sequence can straddle reads.
- ptyInstances[0].emitData('done\x1b[');
- ptyInstances[0].emitData('6n');
- const result = shell.attachSession(id, makeSocket('sock-B'));
- expect(result.bufferedOutput).toBe('done');
- });
-
it('emits shell:detached on the previous socket when displaced', () => {
const sock1 = makeSocket('sock-A');
const id = shell.createShellSession(sock1);
@@ -884,25 +845,6 @@ describe('registerExternalSession / unregisterExternalSession', () => {
expect(viewer.emit).toHaveBeenCalledWith('shell:output', { sessionId: id, data: 'live' });
});
- it('re-announces the TUI modes the ring buffer evicted, so the viewer can scroll it', () => {
- const pty = makeFakePty();
- const id = shell.registerExternalSession('run-long', pty, { label: 'OpenCode TUI' });
- // What a full-screen TUI announces once, at startup, and never repeats.
- pty.emitData('\x1b[?1049h\x1b[?2004h\x1b[?1000;1002;1003h\x1b[?1006h');
- // A watched agent run then streams far more than the 50KB the buffer keeps.
- pty.emitData('rendered frame '.repeat(8 * 1024));
-
- const preamble = '\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?2004h';
- const { bufferedOutput } = shell.attachSession(id, makeSocket('viewer'));
- // The preamble leads, so the attaching terminal lands in the alternate buffer
- // with mouse tracking on — which is what the client's scroll path
- // (client/src/lib/terminalScroll.js) branches on.
- expect(bufferedOutput.startsWith(preamble)).toBe(true);
- // And it is the ONLY place those modes still appear: the ring buffer dropped
- // the startup chunk, which is why the preamble has to exist at all.
- expect(bufferedOutput.slice(preamble.length)).not.toContain('\x1b[?');
- });
-
it('is fully interactive — input writes through and resize works', () => {
const pty = makeFakePty();
const id = shell.registerExternalSession('run-rw', pty, {});