Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
refactor(tui): paint the composer through a frame writer instead of appending (#189)
Abdurrahman Fakhrul15c7e903b56c
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 9baf3558..bf4d9517 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,17 +4,27 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → Account → About shows as “What's new”.+## 2026-10-31++**Added**++- `tui` a transcript model, because scrollback is the only transcript that exists (#187)++**Docs**++- `tui` record milestone status in the renderer plan+## 2026-10-30**Added**-- `tui` a transcript model, because scrollback is the only transcript that exists- `agent` /jobs, so background subagents are visible instead of fire and forget (#183)- `tui` configurable keybinds, with the defaults kept byte-identical (#182)- `agent` show the todo checklist in the TUI and in the status row (#179)**Changed**+- `tui` paint the composer through a frame writer instead of appending- `tui` share the cell and pane primitives instead of growing a second copy (#186)**Tests**@@ -1505,25 +1515,3 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh- `deps-dev` bump the development-minor-patch group with 4 updates- `deps` bump the production-minor-patch group with 4 updates- `security` update Codex Security to 0.1.21--## 2026-08-26--**Added**--- `mcp` add reverse-engineering implementation playbook--**Fixed**--- `security` split documentation scan scope-- `security` bound Codex component scope-- `security` use complete Codex component scans-- `security` size Codex budget for full scan--**Docs**--- refresh changelog--**Chores**--- `security` add ultimate assurance suite-- `security` add Codex Security scanningdiff --git a/docs/TUI-RENDERER-PLAN.md b/docs/TUI-RENDERER-PLAN.mdindex 12e0722e..39342db2 100644--- a/docs/TUI-RENDERER-PLAN.md+++ b/docs/TUI-RENDERER-PLAN.md@@ -583,6 +583,24 @@ those two, and mouse/scrollbar/splits are additive after M5.## 8. Migration order, gates green after every step+### Status, updated as milestones land++| Milestone | Work | State | Evidence |+|---|---|---|---|+| M0 | This plan, classified in docs/README.md | DONE | PR #185, `2dfcda8` |+| M1 | Shared cell primitives, `scripts/tui/cells.mjs` | DONE | PR #186, `5b45314`; layout.mjs 67 to 20 lines |+| M2 | Transcript model, `scripts/mso-agent-transcript.mjs` | DONE | PR #187; reuses formatEditDiff, formatTodoBlock, formatDiffBody |+| M3 | Frame writer, `scripts/mso-agent-screen.mjs`, inline mode | DONE | PR #189; composer 221 to 217 lines, ratchet 43 to 42 |+| M4 | Chrome and tabs as a bottom block | IN PROGRESS | no alt screen yet, scrollback intact |+| M5 | Alternate screen behind a flag, with teardown | NOT STARTED | irreversible step; waits for M4 |+| M6 | Transcript viewport and scrollbar | NOT STARTED | needs M5 |+| M7 | Mouse | NOT STARTED | needs the owner's selection policy |+| M8 | Split panes, then flip the alt screen default | NOT STARTED | needs M6 and M7 |++Adjacent work that landed while this plan was being executed, and belongs to the same goal:+`feat/agent-jobs-view` (#183, `/jobs` for background subagents) and `feat/tui-keybinds` (#182,+`~/.mso/keybinds.json`), which closed P2-3.+M0. Documentation. This file, one classification row in `docs/README.md` (required by`scripts/check-docs.mjs:56-63`), a pointer from[TUI-PARITY-PLAN.md](./TUI-PARITY-PLAN.md):56-62, anddiff --git a/scripts/mso-agent-composer-session.test.ts b/scripts/mso-agent-composer-session.test.tsindex b82308e0..0b6096b8 100644--- a/scripts/mso-agent-composer-session.test.ts+++ b/scripts/mso-agent-composer-session.test.ts@@ -10,6 +10,7 @@ class FakeInput extends EventEmitter {setRawMode(value: boolean) { this.isRaw = value; }}class FakeOutput {+ isTTY = true;columns = 96;chunks: string[] = [];write(value: string) { this.chunks.push(String(value)); return true; }diff --git a/scripts/mso-agent-composer-wrap.test.ts b/scripts/mso-agent-composer-wrap.test.tsindex bca9ff0b..33ae25c7 100644--- a/scripts/mso-agent-composer-wrap.test.ts+++ b/scripts/mso-agent-composer-wrap.test.ts@@ -26,6 +26,7 @@ describe("MSO Agent responsive wrapped composer", () => {it("repaints a wrapped draft on terminal resize without losing the submitted value", async () => {class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }class FakeOutput extends EventEmitter {+ isTTY = true;columns = 24; rows = 16; chunks: string[] = [];write(value: string) { this.chunks.push(String(value)); return true; }}diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjsindex 29d8fbf0..5ef846c8 100644--- a/scripts/mso-agent-composer.mjs+++ b/scripts/mso-agent-composer.mjs@@ -3,10 +3,8 @@ import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";import process from "node:process";import { resumeActiveActivity, suspendActiveActivity } from "./mso-agent-activity.mjs";import { getKeybinds, resolveKeybind } from "./mso-agent-keybinds.mjs";--import {- chars, clamp, CLEAR_LINE, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, eraseComposerRows, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width,-} from "./mso-agent-composer-ui.mjs";+import { cursorHome, eraseFrame, frameHeight, withCursorHidden, writeFrame } from "./mso-agent-screen.mjs";+import { chars, clamp, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width } from "./mso-agent-composer-ui.mjs";export { completionWindow, inputLayout, inputViewport, verticalCursor } from "./mso-agent-composer-ui.mjs";export class AgentComposer {@@ -21,7 +19,7 @@ export class AgentComposer {if (this.closed) return null;const input = this.input, output = this.output, C = this.C;return new Promise((resolve) => {- let value = "", cursor = 0, selected = 0, reservedRows = 0;+ let value = "", cursor = 0, selected = 0, reservedRows = 0, paintedLines = [], lastCursorRow = 0;let dismissed = false, historyIndex = null, draft = "", settled = false, verticalColumn = null;const promptText = () => String(typeof prompt === "function" ? prompt() : prompt);const footerText = () => String(typeof footer === "function" ? footer() : (footer || ""));@@ -29,33 +27,31 @@ export class AgentComposer {const wasRaw = Boolean(input.isRaw);const matches = () => dismissed || !complete ? [] : complete(value) || [];- // Reserve physical rows only when the dropdown first grows. Selection changes then- // redraw with cursor movement only -- no LF/CRLF -- so ↑/↓ never create scrollback rows.+ // Reserve physical rows only when the frame grows. Redraws diff row-by-row in place+ // without emitting LF/CRLF, keeping terminal scrollback clean.const reserve = (rows) => { reservedRows = reserveComposerRows(output, reservedRows, rows); };- const erase = () => eraseComposerRows(output, reservedRows);+ const erase = () => { cursorHome(output, lastCursorRow); eraseFrame(output, paintedLines); paintedLines = []; lastCursorRow = 0; reservedRows = 0; };const render = () => {- const currentPrompt = promptText();- const promptWidth = width(currentPrompt);- const items = matches();+ cursorHome(output, lastCursorRow);+ const currentPrompt = promptText(), promptWidth = width(currentPrompt), items = matches();selected = items.length ? clamp(selected, 0, items.length - 1) : 0;const menu = menuLines(items, selected, output.columns, C, panelLabel);- const footerRow = footerText();- const footerRows = footerRow ? 1 : 0;+ const footerRow = footerText(), footerRows = footerRow ? 1 : 0;const terminalRows = Math.max(8, Number(output.rows || 24));const maxInputRows = Math.max(2, Math.min(12, terminalRows - menu.length - footerRows - 4, Math.floor(terminalRows * 0.32)));const layout = inputLayout(value, cursor, { columns: output.columns, rows: terminalRows, promptWidth, maxRows: maxInputRows });- const inputExtraRows = Math.max(0, layout.lines.length - 1);- const below = inputExtraRows + menu.length + footerRows;- reserve(below);- erase();const continuation = " ".repeat(promptWidth);- output.write(`${currentPrompt}${layout.lines[0] || ""}`);- for (const row of layout.lines.slice(1)) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${continuation}${row}`);- for (const row of menu) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${row}`);- if (footerRow) output.write(`${CURSOR_DOWN(1)}\r${CLEAR_LINE}${footerRow}`);- const backUp = menu.length + footerRows + (layout.lines.length - 1 - layout.cursorRow);- if (backUp) output.write(CURSOR_UP(backUp));+ const lines = [+ `${currentPrompt}${layout.lines[0] || ""}`,+ ...layout.lines.slice(1).map((row) => `${continuation}${row}`),+ ...menu,+ ...(footerRow ? [footerRow] : []),+ ];+ reserve(Math.max(0, frameHeight(lines) - 1));+ withCursorHidden(output, () => { paintedLines = writeFrame(output, paintedLines, lines); });+ if (layout.cursorRow) output.write(CURSOR_DOWN(layout.cursorRow));output.write(`\r${CURSOR_RIGHT(promptWidth + layout.cursorCol)}`);+ lastCursorRow = layout.cursorRow;};const cleanup = () => {input.off("keypress", onKey);@@ -126,7 +122,7 @@ export class AgentComposer {const items = matches();const action = resolveKeybind(key, this.keybinds || getKeybinds());if (action === "interrupt") return value ? edit("", 0) : cancel(true);- if (action === "clear_screen") { output.write(CLEAR_SCREEN); reservedRows = 0; return render(); }+ if (action === "clear_screen") { output.write(CLEAR_SCREEN); reservedRows = 0; paintedLines = []; lastCursorRow = 0; return render(); }if (action === "dismiss") {if (escapeCancels) return cancel(false);dismissed = true; selected = 0; return render();diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.tsindex 17c91947..53ea7075 100644--- a/scripts/mso-agent-composer.test.ts+++ b/scripts/mso-agent-composer.test.ts@@ -31,6 +31,7 @@ describe("MSO Agent interactive composer primitives", () => {setRawMode(value: boolean) { this.isRaw = value; }}class FakeOutput {+ isTTY = true;columns = 88;chunks: string[] = [];write(value: string) { this.chunks.push(String(value)); return true; }diff --git a/scripts/mso-agent-screen.mjs b/scripts/mso-agent-screen.mjsnew file mode 100644index 00000000..21940834--- /dev/null+++ b/scripts/mso-agent-screen.mjs@@ -0,0 +1,121 @@+import process from "node:process";+import { cellWidth } from "./tui/cells.mjs";++// Measures physical terminal rows occupied by painted lines, taking terminal column wrapping into account.+export function frameHeight(painted, columns = process.stdout?.columns || 80) {+ const lines = Array.isArray(painted) ? painted : typeof painted === "string" ? [painted] : [];+ if (lines.length === 0) return 0;+ const cols = Math.max(1, Number(columns) || 80);+ let total = 0;+ for (const line of lines) {+ const w = cellWidth(line);+ // An empty line still occupies one physical row in the terminal.+ total += w === 0 ? 1 : Math.max(1, Math.ceil(w / cols));+ }+ return total;+}++// Moves cursor to the start of the block (row 0, col 0) from an offset row.+// Guarded against non-TTY streams so piped or redirect environments do not receive escape noise.+export function cursorHome(output, rows = 0) {+ if (output?.isTTY !== true || !output || typeof output.write !== "function") return;+ const count = Math.max(0, Number(rows) || 0);+ if (count > 0) output.write(`\x1b[${count}A\r`);+ else output.write("\r");+}++// Wraps a block repaint in cursor hide/show escapes to eliminate visual cursor flicker.+// Restores cursor visibility even if the callback throws, and no-ops on non-TTY streams.+export function withCursorHidden(output, fn) {+ if (output?.isTTY !== true || !output || typeof output.write !== "function") {+ return fn();+ }+ output.write("\x1b[?25l");+ try {+ return fn();+ } finally {+ output.write("\x1b[?25h");+ }+}++// Erases a previously painted frame and restores the cursor to the initial top-left origin.+// Uses cursor down and line clear sequences rather than newlines to keep terminal scrollback untouched.+export function eraseFrame(output, painted) {+ if (output?.isTTY !== true || !output || typeof output.write !== "function") return;+ const count = Array.isArray(painted) ? painted.length : Math.max(0, Number(painted) || 0);+ if (count <= 0) return;+ output.write("\r\x1b[2K");+ for (let i = 1; i < count; i++) {+ output.write("\x1b[1B\r\x1b[2K");+ }+ if (count > 1) {+ output.write(`\x1b[${count - 1}A\r`);+ }+}++// Writes a retained frame by diffing row by row against the previous frame.+// Emits only the minimal escape sequences to update changed rows and clear removed rows.+// Never emits a newline inside the frame block so scrollback is never created.+export function writeFrame(output, previous, next) {+ const nxt = Array.isArray(next) ? [...next] : [];+ if (!output || typeof output.write !== "function") return nxt;++ // Non-TTY mode (pipes, file redirects, CI) falls back to sequential lines without escape codes.+ if (output.isTTY !== true) {+ for (const line of nxt) {+ output.write(`${line}\n`);+ }+ return nxt;+ }++ const prev = Array.isArray(previous) ? previous : [];++ // Idempotent redraw: identical frames produce zero output to prevent unnecessary terminal updates.+ if (prev.length === nxt.length && prev.every((line, i) => line === nxt[i])) {+ return nxt;+ }++ // If next frame is empty, clear any existing rows and return early.+ if (nxt.length === 0) {+ if (prev.length > 0) eraseFrame(output, prev);+ return [];+ }++ const maxRows = Math.max(prev.length, nxt.length);+ let currentRow = 0;+ let paintedAny = false;++ for (let i = 0; i < maxRows; i++) {+ const prevLine = prev[i];+ const nextLine = nxt[i];++ if (i < nxt.length) {+ // Skip row if content is unchanged to minimize terminal escape overhead.+ if (prevLine === nextLine) continue;++ if (i > currentRow) {+ output.write(`\x1b[${i - currentRow}B`);+ currentRow = i;+ }+ output.write(`\r\x1b[2K${nextLine}`);+ paintedAny = true;+ } else {+ // Row existed previously but is truncated in the new frame; clear the residual line.+ if (i > currentRow) {+ output.write(`\x1b[${i - currentRow}B`);+ currentRow = i;+ }+ output.write("\r\x1b[2K");+ paintedAny = true;+ }+ }++ // Return cursor to the top origin (row 0, col 0) so callers retain a predictable reference frame.+ if (currentRow > 0) {+ output.write(`\x1b[${currentRow}A\r`);+ } else if (paintedAny) {+ output.write("\r");+ }++ return nxt;+}diff --git a/scripts/mso-agent-screen.test.ts b/scripts/mso-agent-screen.test.tsnew file mode 100644index 00000000..1037cee8--- /dev/null+++ b/scripts/mso-agent-screen.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from "vitest";+import { cursorHome, eraseFrame, frameHeight, withCursorHidden, writeFrame } from "./mso-agent-screen.mjs";++// A terminal by default, because that is the path being tested. The non-TTY cases below+// construct the same class and set isTTY = false explicitly.+class FakeOutput {+ columns = 80;+ chunks: string[] = [];+ isTTY?: boolean = true;+ write(value: string) {+ this.chunks.push(String(value));+ return true;+ }+}++describe("MSO Agent retained screen and frame writer", () => {+ it("treats an undefined isTTY as a pipe, because node leaves it undefined outside a terminal", () => {+ const output = new FakeOutput();+ output.isTTY = undefined;+ writeFrame(output, [], ["alpha"]);+ const combined = output.chunks.join("");+ expect(combined).toContain("alpha");+ expect(combined).not.toContain("\x1b[");+ });++ it("first paint of two rows emits them once, in order", () => {+ const output = new FakeOutput();+ const painted = writeFrame(output, [], ["alpha", "beta"]);+ expect(painted).toEqual(["alpha", "beta"]);+ const combined = output.chunks.join("");+ expect(combined).toContain("alpha");+ expect(combined).toContain("beta");+ expect(combined.indexOf("alpha")).toBeLessThan(combined.indexOf("beta"));+ // Ensure rows are written once, not duplicated during initial paint.+ expect(combined.split("alpha").length).toBe(2);+ expect(combined.split("beta").length).toBe(2);+ });++ it("repainting the same two rows emits nothing", () => {+ const output = new FakeOutput();+ const initial = writeFrame(output, [], ["alpha", "beta"]);+ const writeCountBefore = output.chunks.length;+ const next = writeFrame(output, initial, ["alpha", "beta"]);+ expect(next).toEqual(["alpha", "beta"]);+ expect(output.chunks.length).toBe(writeCountBefore);+ });++ it("changing one row rewrites only that row", () => {+ const output = new FakeOutput();+ const initial = writeFrame(output, [], ["header", "row1", "footer"]);+ const writeCountBefore = output.chunks.length;+ const next = writeFrame(output, initial, ["header", "row1 updated", "footer"]);+ expect(next).toEqual(["header", "row1 updated", "footer"]);+ const diff = output.chunks.slice(writeCountBefore).join("");+ expect(diff).toContain("row1 updated");+ expect(diff).not.toContain("header");+ expect(diff).not.toContain("footer");+ });++ it("shrinking from three rows to two clears the third", () => {+ const output = new FakeOutput();+ const initial = writeFrame(output, [], ["row1", "row2", "row3"]);+ const writeCountBefore = output.chunks.length;+ const next = writeFrame(output, initial, ["row1", "row2"]);+ expect(next).toEqual(["row1", "row2"]);+ const diff = output.chunks.slice(writeCountBefore).join("");+ // Erase sequence must be emitted for the third row, without touching row1 or row2.+ expect(diff).toContain("\x1b[2K");+ expect(diff).not.toContain("row1");+ expect(diff).not.toContain("row2");+ expect(diff).not.toContain("row3");+ });++ it("no \\n appears in any write produced while painting a frame", () => {+ const output = new FakeOutput();+ const frame1 = writeFrame(output, [], ["line 1", "line 2", "line 3"]);+ const frame2 = writeFrame(output, frame1, ["line 1 updated", "line 2", "line 3"]);+ const frame3 = writeFrame(output, frame2, ["line 1 updated", "line 2"]);+ expect(frame3).toEqual(["line 1 updated", "line 2"]);+ for (const chunk of output.chunks) {+ expect(chunk).not.toContain("\n");+ }+ });++ it("a non-TTY output receives plain lines and no escape sequences", () => {+ const output = new FakeOutput();+ output.isTTY = false;+ const painted = writeFrame(output, [], ["plain first", "plain second"]);+ expect(painted).toEqual(["plain first", "plain second"]);+ const combined = output.chunks.join("");+ expect(combined).toBe("plain first\nplain second\n");+ expect(combined).not.toContain("\x1b");+ });++ it("withCursorHidden restores the cursor when the callback throws", () => {+ const output = new FakeOutput();+ expect(() => {+ withCursorHidden(output, () => {+ throw new Error("simulated failure during repaint");+ });+ }).toThrow("simulated failure during repaint");+ // Ensure hide sequence was sent first and show sequence was sent in finally block.+ expect(output.chunks[0]).toBe("\x1b[?25l");+ expect(output.chunks[output.chunks.length - 1]).toBe("\x1b[?25h");++ // Guard check: non-TTY stream receives no cursor escape sequences.+ const nonTty = new FakeOutput();+ nonTty.isTTY = false;+ const value = withCursorHidden(nonTty, () => "safe-result");+ expect(value).toBe("safe-result");+ expect(nonTty.chunks.length).toBe(0);+ });++ it("frameHeight matches the number of painted rows, including a row that had to wrap", () => {+ expect(frameHeight([])).toBe(0);+ expect(frameHeight(["single line"], 80)).toBe(1);+ expect(frameHeight(["first", "second"], 80)).toBe(2);+ // A 100-cell row on an 80-column terminal wraps into 2 physical rows.+ const longLine = "x".repeat(100);+ expect(frameHeight(["short", longLine], 80)).toBe(3);+ // ANSI codes should be stripped and not inflate cell width calculations.+ const ansiLine = `\x1b[31m${"y".repeat(100)}\x1b[0m`;+ expect(frameHeight(["short", ansiLine], 80)).toBe(3);+ });++ it("cursorHome and eraseFrame operate without emitting newlines", () => {+ const output = new FakeOutput();+ cursorHome(output, 2);+ expect(output.chunks.join("")).toBe("\x1b[2A\r");++ const nonTty = new FakeOutput();+ nonTty.isTTY = false;+ cursorHome(nonTty, 2);+ expect(nonTty.chunks.length).toBe(0);++ const eraseOutput = new FakeOutput();+ eraseFrame(eraseOutput, ["line 1", "line 2", "line 3"]);+ const erased = eraseOutput.chunks.join("");+ expect(erased).not.toContain("\n");+ expect(erased).toContain("\x1b[2K");+ });+});