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
tighten the mode tracker after review: narrower carry, cheaper hot path
[._.]/ Adam Eivyb3a75e8f5a63
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.jsindex 04537dda87..4fdfaa32be 100644--- a/client/src/hooks/useShellSession.js+++ b/client/src/hooks/useShellSession.js@@ -728,12 +728,10 @@ export function useShellSession({ isFullscreen } = {}) {// before repainting this one's buffer, so a previously-viewed full-screen// TUI's lingering mouse/focus tracking can't inject garbage here. The// freshly-painted bufferedOutput re-establishes whatever modes THIS- // session legitimately uses — the server leads it with a mode preamble- // precisely so that holds for a run whose startup announcements have long- // since scrolled out of the replay window (server/lib/terminalReplay.js).- // Without it a watched OpenCode run repaints as a normal-buffer terminal- // and lib/terminalScroll.js can't route a scroll to the app at all.- // See startSession for the full rationale.+ // session legitimately uses — the server leads it with a mode preamble so+ // that holds even once the session's own declaration has scrolled out of+ // the replay window (server/lib/terminalReplay.js). See startSession for+ // the full rationale.resetTerminalWheelScroll(termInstanceRef.current);termInstanceRef.current.reset();if (bufferedOutput) {diff --git a/client/src/lib/terminalScroll.js b/client/src/lib/terminalScroll.jsindex a99289f85f..b05e41cbd8 100644--- a/client/src/lib/terminalScroll.js+++ b/client/src/lib/terminalScroll.js@@ -17,11 +17,9 @@// keybinding — PageUp/PageDown, which is what OpenCode binds its message-page// commands to.//-// Both branches read the terminal's mode state, so both depend on that state being-// correct for a session the client did not watch from the start: the server leads a-// re-attach replay with a preamble re-announcing the modes the 50KB ring buffer-// evicted (`server/lib/terminalReplay.js`). Without it every long-running TUI looks-// like a plain scrollback shell here and nothing below can reach the app.+// Everything below branches on the terminal's mode state, which for a session the+// client did not watch from the start is only correct because the server re-asserts+// it ahead of the replay — see `server/lib/terminalReplay.js`.//// Normal-buffer scroll stays inside xterm through `scrollLines()`. In an alternate// buffer, wheel events are captured before xterm's mouse protocol listener anddiff --git a/server/lib/README.md b/server/lib/README.mdindex 8b9cc0d30e..dc00d2ff00 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()` — follow the same PTY stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and emit a `preamble()` re-announcing the ones still in force. A TUI declares those ONCE, in its first few hundred bytes, so any run long enough to overflow the 50KB window — every watched TUI-agent run — replays as a normal-buffer, mouse-less terminal: the client scrolls its own scrollback instead of the app, and a watched OpenCode run cannot be scrolled at all. Prepended to the replay by `attachSession`. |+| `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. |## Story & narrativediff --git a/server/lib/terminalReplay.js b/server/lib/terminalReplay.jsindex 78348e39f2..bfa0ef642c 100644--- a/server/lib/terminalReplay.js+++ b/server/lib/terminalReplay.js@@ -1,8 +1,9 @@/**- * Sanitize the re-attach replay buffer a PTY session hands a newly attached- * client (`attachSession` in `services/shell.js`).+ * Replay correctness for the buffer a PTY session hands a newly attached client+ * (`attachSession` in `services/shell.js`): what must be STRIPPED out of the+ * recorded bytes, and what must be RE-ASSERTED because it was never in them.*- * ── The bug this fixes ─────────────────────────────────────────────────────────+ * ── The bug the stripping 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@@ -80,47 +81,49 @@ export const stripTerminalQueries = (text) => {};/**- * ── The second replay bug: modes that scrolled out of the ring buffer ──────────+ * ── The other replay bug: modes that scrolled out of the ring buffer ───────────*- * A full-screen TUI announces its terminal state ONCE, in its first few hundred- * bytes: alternate screen (`ESC[?1049h`), mouse tracking (`ESC[?1000;1002;1003h`- * plus an encoding like `ESC[?1006h`), bracketed paste, cursor visibility. The- * replay buffer keeps only the LAST 50KB, so on any run long enough to overflow- * it — which is every watched TUI-agent run — those announcements are gone by the- * time someone attaches. The attaching xterm is `reset()` first, so it repaints a- * long-running OpenCode session as a NORMAL-buffer, mouse-less terminal.+ * A full-screen TUI declares its terminal state ONCE, in its first few hundred+ * bytes — alternate screen, mouse tracking and its encoding, bracketed paste,+ * cursor visibility — and never repeats it. The ring buffer keeps only the LAST+ * 50KB, and the attaching client `reset()`s its terminal before painting the+ * replay, so on any session that has emitted more than that the declaration is+ * gone and the viewer comes up in the DEFAULT state: normal buffer, no mouse.*- * Everything that reads the terminal's mode state then reads the wrong answer:+ * Every consumer that branches on terminal mode then branches wrongly — most+ * visibly `client/src/lib/terminalScroll.js`, which routes a scroll gesture by+ * buffer type and mouse-tracking mode, so a watched TUI-agent run cannot be+ * scrolled at all. (Observed with OpenCode, whose TUI passes 120KB inside a+ * minute; nothing here is specific to it.)*- * - `lib/terminalScroll.js` (client) decides how to scroll from- * `buffer.active.type` and `modes.mouseTrackingMode`. Believing it is in the- * normal buffer, it scrolls local scrollback — frames of a redrawing TUI —- * instead of routing the gesture to the app, and xterm never forwards a wheel- * as a mouse report because no app asked for mouse events. OpenCode's message- * viewport therefore cannot be scrolled at all from the Shell page.- * - `useShellSession`'s arrow-key buttons pick CSI vs SS3 from- * `applicationCursorKeysMode`, and send the wrong one.+ * Growing the buffer only moves the threshold, and pinning its head would replay+ * a declaration the app may since have taken back. So track the modes over the+ * WHOLE stream and have `preamble()` re-declare whatever is still in force,+ * prepended to the replay: attach becomes "state first, then history".*- * Fixed here rather than by growing the ring buffer, which only moves the- * threshold: the tracker watches the WHOLE stream and `preamble()` re-announces- * the modes still in force, prepended to the replay so the attaching terminal- * starts in the state the live PTY is actually in.+ * ── Ceiling ────────────────────────────────────────────────────────────────────+ * This covers `CSI ? … h/l` and nothing else. Other sticky state a mid-stream cut+ * destroys — keypad mode (`ESC =` / `ESC >`), scroll region, charset designation,+ * the SGR pen at the cut point — is out of scope. If that starts to matter, the+ * next step is not a third ad-hoc tracker: it is serializing real terminal state+ * from a server-side headless emulator, the way tmux and asciinema do.*/-// The DEC private modes a re-attaching terminal has to inherit, mapped to the-// value a freshly-`reset()` terminal already holds — only a departure from that-// default is worth re-announcing. Alternate-screen modes lead the list so the-// replayed frames paint into the buffer they were drawn for.-//-// Deliberately NOT tracked: transient modes that are a begin/end pair rather than-// a state (`?2026` synchronized update — replaying a dangling "begin" would freeze-// the view) and modes no PortOS code reads.+// The DEC private modes a re-attaching terminal has to inherit, each mapped to+// the value a freshly-`reset()` terminal already holds — only a departure from+// that default is worth re-declaring. The test for inclusion is STICKY STATE+// THAT CHANGES HOW THE TERMINAL INTERPRETS INPUT OR PAINTS OUTPUT, which is why+// this deliberately excludes begin/end pairs (`?2026` synchronized update —+// re-declaring a dangling "begin" would freeze the view) and feature negotiation+// (`?2027`, `?2031`). Alternate-screen modes lead so the replayed frames paint+// into the buffer they were drawn for.const REPLAYED_PRIVATE_MODES = [[1049, 'l'], // alternate screen + save cursor (xterm)[1047, 'l'], // alternate screen (xterm, no cursor save)[47, 'l'], // alternate screen (DEC)[1, 'l'], // DECCKM — application cursor keys[25, 'h'], // DECTCEM — cursor visible+ [9, 'l'], // X10 mouse — press only, no wheel (terminalScroll.js branches on it)[1000, 'l'], // X11 mouse — button press/release[1002, 'l'], // X11 mouse — button + drag motion[1003, 'l'], // X11 mouse — any motion@@ -132,21 +135,29 @@ const REPLAYED_PRIVATE_MODES = [[2004, 'l'], // bracketed paste];-const MODE_DEFAULTS = new Map(REPLAYED_PRIVATE_MODES);+const TRACKED_MODES = new Set(REPLAYED_PRIVATE_MODES.map(([mode]) => mode));// `ESC[?1000;1002;1003h` sets three modes in one sequence, so the parameter list// is split rather than matched as a single number.const PRIVATE_MODE_SEQUENCE = /\x1b\[\?([\d;]*)([hl])/g;-// A mode sequence can straddle two PTY chunks. Carry only a trailing fragment that-// could still become one — `ESC`, `ESC[`, `ESC[?`, `ESC[?1000;1002` — and cap it so-// a lone `ESC` in a data stream can't grow an unbounded carry.-const PARTIAL_SEQUENCE = /\x1b(?:\[\??[\d;]*)?$/;+// A mode sequence can straddle two PTY chunks, so a trailing fragment that could+// still become one — `ESC`, `ESC[`, `ESC[?`, `ESC[?1000;1002` — is carried into+// the next. Deliberately TIGHTER than the incomplete-CSI grammars in+// `ansiStrip.js` and `tuiHandshake.js`, which carry any CSI prefix: only+// `ESC[?<digits>` can become a private-mode set, so an `ESC[38;5` split out of a+// truecolor run is not worth carrying. The cap bounds the carry so a lone `ESC`+// in a data stream can't grow one without end.+const PARTIAL_SEQUENCE = /\x1b(?:\[(?:\?[\d;]*)?)?$/;const MAX_PARTIAL_LENGTH = 64;const trailingPartialSequence = (text) => {- const tail = text.slice(-MAX_PARTIAL_LENGTH);- return tail.match(PARTIAL_SEQUENCE)?.[0] ?? '';+ const windowStart = Math.max(0, text.length - MAX_PARTIAL_LENGTH);+ // Bounded scan before the slice: plain output has no ESC near its end, and this+ // is per-chunk code on every PTY in the install. Skipping the slice+match there+ // is most of the cost and all of the allocation.+ if (text.indexOf('\x1b', windowStart) === -1) return '';+ return text.slice(windowStart).match(PARTIAL_SEQUENCE)?.[0] ?? '';};/**@@ -162,16 +173,14 @@ export const createTerminalModeTracker = () => {return {/** Feed one chunk of raw PTY output, in stream order. */observe(chunk) {- if (typeof chunk !== 'string' || !chunk) return;+ if (!chunk) return;const text = partial + chunk;partial = trailingPartialSequence(text);if (!text.includes('\x1b[?')) return;- PRIVATE_MODE_SEQUENCE.lastIndex = 0;- let match;- while ((match = PRIVATE_MODE_SEQUENCE.exec(text)) !== null) {- for (const param of match[1].split(';')) {+ for (const [, params, value] of text.matchAll(PRIVATE_MODE_SEQUENCE)) {+ for (const param of params.split(';')) {const mode = Number(param);- if (MODE_DEFAULTS.has(mode)) observed.set(mode, match[2]);+ if (TRACKED_MODES.has(mode)) observed.set(mode, value);}}},diff --git a/server/lib/terminalReplay.test.js b/server/lib/terminalReplay.test.jsindex 8cb7ed59fe..eb93512ac3 100644--- a/server/lib/terminalReplay.test.js+++ b/server/lib/terminalReplay.test.js@@ -75,7 +75,7 @@ describe('createTerminalModeTracker', () => {const tracker = createTerminalModeTracker();tracker.observe(OPENCODE_STARTUP);// Whatever else streams past, the announcement is not repeated.- tracker.observe('rendered output '.repeat(10_000));+ tracker.observe('rendered output');expect(tracker.preamble()).toBe('\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?2004h');@@ -134,11 +134,13 @@ describe('createTerminalModeTracker', () => {expect(tracker.preamble()).toBe('');});- it('shrugs off non-string and empty chunks', () => {+ it('carries only a fragment that could still become a private-mode set', () => {+ // A truecolor SGR run split at the same place looks like an incomplete CSI,+ // but it can never become `ESC[?…h` — carrying it would be pure overhead on+ // the busiest kind of output there is.const tracker = createTerminalModeTracker();- tracker.observe(null);- tracker.observe('');- tracker.observe(undefined);+ tracker.observe('\x1b[38;5');+ tracker.observe(';120mstill colored');expect(tracker.preamble()).toBe('');});});diff --git a/server/services/shell.js b/server/services/shell.jsindex deb001bbc6..834d0cfa03 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -193,10 +193,9 @@ function adoptPtySession(sessionId, ptyProcess, options = {}) {const outputBuffer = [];let bufferSize = 0;const MAX_BUFFER = 50 * 1024;- // A full-screen TUI announces alternate screen and mouse tracking once, in its- // first few hundred bytes — which the ring buffer drops on any run long enough- // to overflow it. Following the WHOLE stream lets attachSession re-announce the- // modes still in force. See lib/terminalReplay.js.+ // 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();// Store session info@@ -227,7 +226,6 @@ function adoptPtySession(sessionId, ptyProcess, options = {}) {// Handle pty outputptyProcess.onData((data) => {- // Before the ring buffer can evict it: mode state is stream-wide, not recent.modeTracker.observe(data);// Buffer output for re-attachoutputBuffer.push(data);@@ -644,16 +642,9 @@ export function attachSession(sessionId, socket, { claim = false } = {}) {broadcastSessionList();return {sessionId,- // Two corrections to the raw ring buffer, both in lib/terminalReplay.js:- //- // - the mode preamble LEADS, because a long-running TUI's `ESC[?1049h` /- // `ESC[?1003h` announcements scrolled out of the 50KB window hours ago, and- // the attaching terminal is reset() before this is painted — without it the- // client thinks a watched OpenCode run is a plain scrollback shell and- // cannot scroll it at all;- // - 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.+ // 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(''))};