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

restore a TUI's terminal modes when the replay buffer has dropped them

[._.]/ Adam Eivyc41060dc3932
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index 61eefd3c21..04537dda87 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -293,8 +293,8 @@ export function useShellSession({ isFullscreen } = {}) {
// xterm binds no touch handlers of its own, so without this a swipe over the
// terminal does nothing. Alternate-screen TUIs need the matching wheel capture so
- // OpenCode's supported PageUp/PageDown bindings receive scroll gestures instead
- // of unsupported mouse reports. See lib/terminalScroll.js. Attached here rather
+ // one that never asked for mouse tracking gets its supported PageUp/PageDown
+ // bindings instead of a cursor key. See lib/terminalScroll.js. Attached here rather
// than in its own effect: neither handler has reactive deps, so both lifetimes are
// exactly the terminal instance's (unlike the dictation bridge, which needs
// emitShellInput).
@@ -728,7 +728,12 @@ 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. See startSession for the full rationale.
+ // 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.
resetTerminalWheelScroll(termInstanceRef.current);
termInstanceRef.current.reset();
if (bufferedOutput) {
diff --git a/client/src/lib/terminalScroll.js b/client/src/lib/terminalScroll.js
index 9bece907a6..a99289f85f 100644
--- a/client/src/lib/terminalScroll.js
+++ b/client/src/lib/terminalScroll.js
@@ -12,9 +12,16 @@
//
// • The ALTERNATE screen buffer that a TUI takes (a watched `claude`/`codex` run,
// `vim`, `less`, `htop`) has no scrollback by construction: `ybase` stays 0, so
-// `scrollLines()` and friends clamp to a no-op there. OpenCode's TUI also does
-// not use terminal mouse-wheel reports for its message viewport; its supported
-// path is the terminal's PageUp/PageDown key bindings.
+// `scrollLines()` and friends clamp to a no-op there. A TUI that never asked for
+// mouse tracking gets no wheel reports either, so its only scroll input is a
+// 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.
//
// Normal-buffer scroll stays inside xterm through `scrollLines()`. In an alternate
// buffer, wheel events are captured before xterm's mouse protocol listener and
diff --git a/server/lib/README.md b/server/lib/README.md
index 8b03bbf349..8b9cc0d30e 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. |
+| `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`. |
## Story & narrative
diff --git a/server/lib/terminalReplay.js b/server/lib/terminalReplay.js
index 5f367edc1d..78348e39f2 100644
--- a/server/lib/terminalReplay.js
+++ b/server/lib/terminalReplay.js
@@ -78,3 +78,115 @@ export const stripTerminalQueries = (text) => {
if (!text.includes('\x1b')) return text;
return QUERY_PATTERNS.reduce((out, pattern) => out.replace(pattern, ''), text);
};
+
+/**
+ * ── The second 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.
+ *
+ * Everything that reads the terminal's mode state then reads the wrong answer:
+ *
+ * - `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.
+ *
+ * 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.
+ */
+
+// 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.
+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
+ [1000, 'l'], // X11 mouse — button press/release
+ [1002, 'l'], // X11 mouse — button + drag motion
+ [1003, 'l'], // X11 mouse — any motion
+ [1004, 'l'], // focus in/out reporting
+ [1005, 'l'], // UTF-8 mouse encoding
+ [1006, 'l'], // SGR mouse encoding
+ [1015, 'l'], // urxvt mouse encoding
+ [1016, 'l'], // SGR pixel mouse encoding
+ [2004, 'l'], // bracketed paste
+];
+
+const MODE_DEFAULTS = new Map(REPLAYED_PRIVATE_MODES);
+
+// `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;]*)?$/;
+const MAX_PARTIAL_LENGTH = 64;
+
+const trailingPartialSequence = (text) => {
+ const tail = text.slice(-MAX_PARTIAL_LENGTH);
+ return tail.match(PARTIAL_SEQUENCE)?.[0] ?? '';
+};
+
+/**
+ * Follow the private-mode state of a PTY stream so a later attach can be handed
+ * the modes still in force, whatever the ring buffer has since dropped.
+ *
+ * @returns {{ observe: (chunk: string) => void, preamble: () => string }}
+ */
+export const createTerminalModeTracker = () => {
+ const observed = new Map();
+ let partial = '';
+
+ return {
+ /** Feed one chunk of raw PTY output, in stream order. */
+ observe(chunk) {
+ if (typeof chunk !== 'string' || !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(';')) {
+ const mode = Number(param);
+ if (MODE_DEFAULTS.has(mode)) observed.set(mode, match[2]);
+ }
+ }
+ },
+
+ /**
+ * The sequences that put a freshly-reset terminal into the session's current
+ * mode state — empty when every tracked mode is still at its default.
+ */
+ preamble() {
+ let out = '';
+ for (const [mode, fallback] of REPLAYED_PRIVATE_MODES) {
+ const value = observed.get(mode);
+ if (value && value !== fallback) out += `\x1b[?${mode}${value}`;
+ }
+ return out;
+ }
+ };
+};
diff --git a/server/lib/terminalReplay.test.js b/server/lib/terminalReplay.test.js
index 2206d4e411..8cb7ed59fe 100644
--- a/server/lib/terminalReplay.test.js
+++ b/server/lib/terminalReplay.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { stripTerminalQueries } from './terminalReplay.js';
+import { 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.
@@ -64,3 +64,81 @@ describe('stripTerminalQueries', () => {
expect(stripTerminalQueries(text)).toBe(text);
});
});
+
+// Captured from a real `opencode` PTY at startup: it takes the alternate screen,
+// asks for every X11 mouse tracking level plus SGR encoding, and turns on
+// bracketed paste. All of it in the first few hundred bytes, never repeated.
+const OPENCODE_STARTUP = '\x1b[?2031h\x1b[?25l\x1b[?1049h\x1b[?2027h\x1b[?2004h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h';
+
+describe('createTerminalModeTracker', () => {
+ it('re-announces the modes a TUI set before the ring buffer evicted them', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe(OPENCODE_STARTUP);
+ // Whatever else streams past, the announcement is not repeated.
+ tracker.observe('rendered output '.repeat(10_000));
+ expect(tracker.preamble()).toBe(
+ '\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h\x1b[?2004h'
+ );
+ });
+
+ it('puts the alternate screen first, so replayed frames paint where they were drawn', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe('\x1b[?1006h\x1b[?2004h\x1b[?1049h');
+ expect(tracker.preamble().indexOf('\x1b[?1049h')).toBe(0);
+ });
+
+ it('splits a multi-parameter set into its individual modes', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe('\x1b[?1000;1002;1003;1006h');
+ expect(tracker.preamble()).toBe('\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h');
+ });
+
+ it('follows a mode that was turned back off', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe(OPENCODE_STARTUP);
+ // The TUI exited: alternate screen released, mouse and paste handed back.
+ tracker.observe('\x1b[?1000;1002;1003l\x1b[?2004l\x1b[?1049l\x1b[?25h');
+ expect(tracker.preamble()).toBe('\x1b[?1006h');
+ });
+
+ it('says nothing about a terminal that is still at its defaults', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe('$ ls\r\nfile-a file-b\r\n\x1b[32m$\x1b[0m ');
+ expect(tracker.preamble()).toBe('');
+ });
+
+ it('matches a sequence split across two PTY chunks', () => {
+ // node-pty hands over whatever the read returned; a 9-byte escape sequence
+ // straddling that boundary is ordinary, not pathological.
+ const seq = '\x1b[?1049h';
+ for (let split = 1; split < seq.length; split++) {
+ const tracker = createTerminalModeTracker();
+ tracker.observe(`tail${seq.slice(0, split)}`);
+ tracker.observe(`${seq.slice(split)}head`);
+ expect(tracker.preamble(), `split at ${split}`).toBe(seq);
+ }
+ });
+
+ it('does not carry a partial across unrelated bytes that end the fragment', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe('\x1b[?1049');
+ tracker.observe(' not a terminator');
+ expect(tracker.preamble()).toBe('');
+ });
+
+ it('ignores transient and untracked private modes', () => {
+ const tracker = createTerminalModeTracker();
+ // ?2026 is a synchronized-update BEGIN; re-announcing a dangling one would
+ // freeze the attaching terminal's rendering. ?2031/?2027 are negotiation.
+ tracker.observe('\x1b[?2026h\x1b[?2031h\x1b[?2027h\x1b[?7h');
+ expect(tracker.preamble()).toBe('');
+ });
+
+ it('shrugs off non-string and empty chunks', () => {
+ const tracker = createTerminalModeTracker();
+ tracker.observe(null);
+ tracker.observe('');
+ tracker.observe(undefined);
+ expect(tracker.preamble()).toBe('');
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index b4bdd97958..deb001bbc6 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 { stripTerminalQueries } from '../lib/terminalReplay.js';
+import { createTerminalModeTracker, stripTerminalQueries } from '../lib/terminalReplay.js';
import { findCommandOnPath } from '../lib/processEnv.js';
// Store active shell sessions (persist across socket reconnects)
@@ -193,6 +193,11 @@ 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.
+ const modeTracker = createTerminalModeTracker();
// Store session info
shellSessions.set(sessionId, {
@@ -216,11 +221,14 @@ function adoptPtySession(sessionId, ptyProcess, options = {}) {
// auto-attach — you opt into watching a run by clicking its tab.
...(options.external ? { external: true } : {}),
outputBuffer,
+ modeTracker,
bufferSize: () => bufferSize
});
// Handle pty output
ptyProcess.onData((data) => {
+ // Before the ring buffer can evict it: mode state is stream-wide, not recent.
+ modeTracker.observe(data);
// Buffer output for re-attach
outputBuffer.push(data);
bufferSize += data.length;
@@ -636,10 +644,18 @@ export function attachSession(sessionId, socket, { claim = false } = {}) {
broadcastSessionList();
return {
sessionId,
- // 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(''))
+ // 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.
+ bufferedOutput: session.modeTracker.preamble()
+ + stripTerminalQueries(session.outputBuffer.join(''))
};
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index c841374968..908f5b740c 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -884,6 +884,25 @@ 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, {});