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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop the Shell replaying a dead TUI's cursor queries into the prompt
Adam Eivy23007d315514
diff --git a/server/lib/README.md b/server/lib/README.mdindex 85e6feb2c9..a832a6a841 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -115,6 +115,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. |## Story & narrativediff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 5163731edc..8c53177ff4 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -582,7 +582,14 @@ describe('deferred imports stay deferred (#6156)', () => {// dependency-free module account for the rest. The publisher itself reaches// git.js and appQualityFederation.js through `await import()`, and the audit// hook reaches the publisher the same way, so neither is in any closure.-const MAX_STATIC_INSTANTIATIONS = 104590;+// `lib/terminalReplay.js` raises this by a further 37 — one instantiation per+// test file whose closure reaches the `lib/index.js` barrel, and nothing more.+// It cannot be narrowed away: the catalog rule (root AGENTS.md) requires every+// new `server/lib/` module to be re-exported from the barrel, and+// `lib/index.test.js` fails without it. The module is deliberately+// dependency-free (a few regexes over a string), so it adds no edge into any+// subtree — its only consumer, `services/shell.js`, deep-imports it directly.+const MAX_STATIC_INSTANTIATIONS = 104627;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex a8048157c3..cb3e2cea5b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -67,6 +67,7 @@ export * from './socketEventInventory.js';export * as spriteValidation from './spriteValidation.js';export * as storyBuilderValidation from './storyBuilderValidation.js';export * as telegramValidation from './telegramValidation.js';+export * from './terminalReplay.js';export * from './validation.js';// Cross-domain Zod fragments both `validation.js` and the per-domain files// import (leaf module, no cycle). Flat because `validation.js` re-exports thediff --git a/server/lib/terminalReplay.js b/server/lib/terminalReplay.jsnew file mode 100644index 0000000000..5f367edc1d--- /dev/null+++ b/server/lib/terminalReplay.js@@ -0,0 +1,80 @@+/**+ * Sanitize the re-attach replay buffer a PTY session hands a newly attached+ * client (`attachSession` in `services/shell.js`).+ *+ * ── The bug this fixes ─────────────────────────────────────────────────────────+ * The 50KB ring buffer stores raw PTY output verbatim, and full-screen TUIs+ * (Claude Code / Ink, vim, htop) pepper that output with terminal QUERIES —+ * `ESC[6n` "where is the cursor?" most of all, emitted on essentially every+ * render. A query is not history: it is a question whose answer the terminal+ * emulator sends back as INPUT.+ *+ * So when a second tab attaches (deep link, reload, session switch, socket+ * reconnect) and the client writes the replay buffer into xterm, xterm cannot+ * tell a replayed historical query from a live one. It dutifully answers every+ * one of them — hundreds, for a buffer that caught a TUI mid-render — and each+ * reply is emitted through `onData` → `shell:input` → straight into the PTY.+ *+ * The TUI that asked is long gone by then, so those replies land on the SHELL+ * PROMPT. zsh's line editor eats the `ESC[` as an unmatched key-binding prefix+ * and self-inserts the remainder as literal text, so the user watches+ * `56;3R56;3R56;3R…` (a cursor-position report for row 56, column 3) pour into+ * their command line. Worse, that echoed garbage is itself PTY output, so it is+ * appended to the same ring buffer — which still holds the queries — and every+ * later attach re-fires the burst and adds more.+ *+ * ── The fix ────────────────────────────────────────────────────────────────────+ * Strip the response-soliciting sequences on the way OUT, at attach time, over+ * the joined (contiguous) buffer — so a sequence split across two stored chunks+ * is still matched, and no state has to be carried between chunks. LIVE output+ * is deliberately untouched: a TUI that is actually running must still get its+ * answers.+ *+ * Removing them is visually lossless. Every sequence below renders nothing; it+ * only asks a question. Stateful sequences that the replay legitimately needs to+ * re-establish (mouse tracking, bracketed paste, alternate screen, SGR) are NOT+ * touched.+ *+ * Not `ansiStrip.js`: that one removes ALL escape sequences to recover plain text+ * for log/summary extraction. The replay buffer is fed back to a real terminal, so+ * it must keep everything that paints — this removes only the questions.+ *+ * The set is exactly what @xterm/xterm actually replies to, verified by feeding+ * each sequence to a real terminal and watching `onData`. Sequences other+ * emulators answer but xterm does not (XTVERSION `ESC[>q`, XTWINOPS `ESC[18t`,+ * XTGETTCAP, kitty `ESC[?u`) are left alone — they cannot produce this bug here,+ * and stripping more than necessary risks eating real output.+ */++// The final byte is the only thing that disambiguates these from the cursor-move+// and SGR sequences they sit among in real output, so each pattern is anchored on+// it rather than on the parameters.+const QUERY_PATTERNS = [+ // DSR — Device Status Report. `ESC[6n` (cursor position) is the one TUIs spam;+ // `ESC[5n` (operating status) is answered too. `CSI > Ps n` is XTMODKEYS, which+ // sets state and solicits nothing, so the `>` form is deliberately excluded.+ /\x1b\[\??\d*(?:;\d+)*n/g,+ // DA — Device Attributes. `ESC[c` (DA1) and `ESC[>c` (DA2) both get answered.+ /\x1b\[[<>=?]?\d*(?:;\d+)*c/g,+ // DECRQM — request mode state, answered with a DECRPM report.+ /\x1b\[\??\d+(?:;\d+)*\$p/g,+ // DECRQSS — request a setting's current value, answered with a DECRPSS string.+ // Lazy to the first ST so an unterminated query can't swallow the rest of the+ // buffer.+ /\x1bP\$q[\s\S]*?\x1b\\/g,+ // OSC color queries — `OSC 10/11/12;?` (fg/bg/cursor) and `OSC 4;<n>;?` /+ // `OSC 5;<n>;?` (palette). Terminated by BEL or ST.+ /\x1b\](?:1[0-2]|[45];\d+);\?(?:\x07|\x1b\\)/g,+];++/**+ * Remove every sequence that would make a terminal emulator send input back.+ *+ * @param {string} text - raw PTY output (the joined re-attach ring buffer)+ * @returns {string} the same output with response-soliciting queries removed+ */+export const stripTerminalQueries = (text) => {+ if (typeof text !== 'string') return '';+ if (!text.includes('\x1b')) return text;+ return QUERY_PATTERNS.reduce((out, pattern) => out.replace(pattern, ''), text);+};diff --git a/server/lib/terminalReplay.test.js b/server/lib/terminalReplay.test.jsnew file mode 100644index 0000000000..2206d4e411--- /dev/null+++ b/server/lib/terminalReplay.test.js@@ -0,0 +1,66 @@+import { describe, it, expect } from 'vitest';+import { 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.+describe('stripTerminalQueries', () => {+ it('removes the cursor-position query a TUI emits on every render', () => {+ expect(stripTerminalQueries('before\x1b[6nafter')).toBe('beforeafter');+ });++ it('removes every query xterm answers', () => {+ const queries = [+ '\x1b[6n', // DSR cursor position → ESC[row;colR+ '\x1b[5n', // DSR operating status → ESC[0n+ '\x1b[?6n', // DECXCPR+ '\x1b[c', // DA1 → ESC[?1;2c+ '\x1b[0c', // DA1 with explicit param+ '\x1b[>c', // DA2 → ESC[>0;276;0c+ '\x1b[?2004$p', // DECRQM → ESC[?2004;1$y+ '\x1bP$qm\x1b\\', // DECRQSS → ESCP1$r0m ST+ '\x1b]11;?\x07', // OSC 11 bg colour, BEL-terminated+ '\x1b]10;?\x1b\\', // OSC 10 fg colour, ST-terminated+ '\x1b]4;1;?\x07', // OSC 4 palette entry+ ];+ for (const q of queries) {+ expect(stripTerminalQueries(`a${q}b`), `should strip ${JSON.stringify(q)}`).toBe('ab');+ }+ });++ it('strips a whole burst, which is how the flood actually arrives', () => {+ const burst = '\x1b[6n'.repeat(200);+ expect(stripTerminalQueries(`prompt${burst}`)).toBe('prompt');+ });++ // The replay buffer's whole job is to repaint the screen and re-establish the+ // modes the session is actually using. Eating any of that would be a worse bug+ // than the one being fixed.+ it('preserves rendering and stateful sequences', () => {+ const keep = [+ '\x1b[0m', '\x1b[1;32m', '\x1b[38;5;254m', // SGR+ '\x1b[2J', '\x1b[K', '\x1b[114D', '\x1b[10A', // erase / cursor motion+ '\x1b[?1049h', '\x1b[?1049l', // alternate screen+ '\x1b[?2004h', '\x1b[?2004l', // bracketed paste+ '\x1b[?1000h', '\x1b[?1006h', // mouse tracking+ '\x1b]133;A\x07', '\x1b]133;B\x07', // shell integration marks+ '\x1b]0;window title\x07', // window title+ '\x1b=', '\x1b[?1h', // keypad / cursor key modes+ ];+ for (const seq of keep) {+ expect(stripTerminalQueries(`a${seq}b`), `should keep ${JSON.stringify(seq)}`).toBe(`a${seq}b`);+ }+ });++ it('leaves plain text and empty input alone', () => {+ expect(stripTerminalQueries('no escapes here')).toBe('no escapes here');+ expect(stripTerminalQueries('')).toBe('');+ expect(stripTerminalQueries(null)).toBe('');+ expect(stripTerminalQueries(undefined)).toBe('');+ });++ it('does not let an unterminated DECRQSS swallow the rest of the buffer', () => {+ // No ST, so the pattern must not match and eat everything after it.+ const text = 'head\x1bP$qm tail that must survive';+ expect(stripTerminalQueries(text)).toBe(text);+ });+});diff --git a/server/services/shell.js b/server/services/shell.jsindex 9bdeb7bc59..b4bdd97958 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -9,6 +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 { stripTerminalQueries } from '../lib/terminalReplay.js';import { findCommandOnPath } from '../lib/processEnv.js';// Store active shell sessions (persist across socket reconnects)@@ -635,7 +636,10 @@ export function attachSession(sessionId, socket, { claim = false } = {}) {broadcastSessionList();return {sessionId,- bufferedOutput: session.outputBuffer.join('')+ // Queries stripped, not raw: a replayed `ESC[6n` is a question the attaching+ // terminal answers as INPUT, and the TUI that asked it is long gone — the+ // reply lands on the shell prompt. See lib/terminalReplay.js.+ bufferedOutput: stripTerminalQueries(session.outputBuffer.join(''))};}diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex 4c50ba0b2f..c841374968 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -358,6 +358,31 @@ 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);