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
fix(tui): the two bugs a real pty found, and the test that found them (#201)
Abdurrahman Fakhrul8b04cc7ef841
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 31c3de1b..b4d93f24 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -17,6 +17,8 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `tui` the two bugs a real pty found, and the test that found them+- `tui` the two bugs a real pty found, both invisible to the unit tests- `ci` apply the same parser workaround to the last two mock call sites (#196)- `ci` stop the semgrep scan failing on a generic argument in a test mock (#195)diff --git a/docs/TUI-RENDERER-PLAN.md b/docs/TUI-RENDERER-PLAN.mdindex ee854b89..b6f767c7 100644--- a/docs/TUI-RENDERER-PLAN.md+++ b/docs/TUI-RENDERER-PLAN.md@@ -599,26 +599,39 @@ those two, and mouse/scrollbar/splits are additive after M5.### 8.1 What remains before the alternate screen can be the default-The pane landed and the flag works, but the default is still `off`. That is not caution about the-renderer, which is now complete. It is that a great deal of the TUI still prints instead of painting:--1. **26 modules print with `console.log`** under `scripts/mso-agent*.mjs` and- `scripts/mso-agent-cmd-*.mjs` (help, inspect, parity, jobs, todos, files, diff, edit diff,- approval UI, mentions, skills, status, layout). In the alternate screen a `console.log` writes at- the cursor, which is inside the frame the loop owns, so the next repaint fights it and a line can- survive in the wrong row. They need one print sink that appends to the viewport in panel mode and- prints as before in inline mode.-2. **The composer reserves a fixed number of rows** (`PROMPT_ROWS` in- `scripts/mso-agent-screen-loop.mjs`), because the composer paints its own rows and cannot report- them. A wrapped draft taller than that reservation overlaps the panel. The composer has to expose- its current row count, or the loop has to own the draft rendering.-3. **Prompts and foreground subagents take over the composer area** (`promptApproval` in- `scripts/mso-agent-approval-ui.mjs`, `runForegroundSubagent`). They are line oriented, so in panel- mode they would need to be painted into the viewport and answered through the same key path.-4. **Turn-level failures bypass the stream sink**: `renderInteractionFailure` writes directly, so an- error raised mid-turn would land outside the frame.--Until those four are done, `--altscreen` stays a development switch, and `--oneshot`, non-TTY and CI+The renderer itself is complete: frames, chrome, viewport, mouse, side pane, and a real pty test+(`scripts/mso-agent-pty.e2e.test.ts`) that drives the actual binary and asserts the painted frame,+a SIGWINCH resize, Ctrl+C and SIGTERM teardown. That pty test immediately found two defects no+fake-TTY unit test could see, both fixed: a `ReferenceError` in the `finally` block on every exit,+and a SIGTERM handler that released the screen and then left the process running forever.++What still keeps the default at `off`:++1. **DONE** - print sink. `scripts/mso-agent-print.mjs` routes command output through+ `session.printSink` when the panel is active; 12 command modules migrated, each with zero+ `console.log` left. Deliberately still printing directly, because they own interactive takeover+ or sit at the line ceiling: `mso-agent-session-ui.mjs`, `mso-agent-layout.mjs`,+ `mso-agent-mentions.mjs`, `mso-agent-local-commands.mjs`, `mso-agent-subagent.mjs`,+ `mso-agent-approval-ui.mjs`, `mso-agent-activity.mjs`.+2. **DONE** - the composer reports its painted row count through `onRows`, and the loop reserves+ that instead of a fixed 3. The cap is terminal rows minus 4, not a quarter of the terminal: a+ quarter of 12 rows is 3, which made the fix inert in exactly the case it existed for.+3. **CEILING, documented** - approval prompts and foreground subagents are suspended, not+ reimplemented. `withPanelSuspended` detaches the sink, lets the prompt run on the normal+ terminal, then repaints. Answering inside the viewport would mean a second input mode+ duplicating the composer's key handling.+4. **DONE** - mid-turn writes go through `turnPrinter`, so `renderInteractionFailure`, the+ interrupted-turn notice and the reasoning lines land in the viewport instead of at the cursor.++Remaining before a default flip, and these are not renderer work:++- The suspended paths in item 3 are correct but ugly: the panel blinks for every approval. Flipping+ the default makes them visible on every tool call, so it is worth deciding whether to accept the+ blink or build the in-panel input mode first.+- `mso-agent-subagent.mjs` and `mso-agent-mentions.mjs` still print directly and are reached during+ a normal turn.++Until those are settled, `--altscreen` stays a development switch, and `--oneshot`, non-TTY and CIremain excluded by `altScreenRequested` regardless of the flag.Adjacent work that landed while this plan was being executed, and belongs to the same goal:diff --git a/scripts/mso-agent-altscreen.mjs b/scripts/mso-agent-altscreen.mjsindex c0c8ba68..71fe5d68 100644--- a/scripts/mso-agent-altscreen.mjs+++ b/scripts/mso-agent-altscreen.mjs@@ -123,8 +123,19 @@ export function installTeardown({const proc = processRef || signalSource || process;const sigs = signalSource || processRef || process;- const onTeardown = () => {+ // Signals that terminate the process by default. Attaching a listener REPLACES that default, so+ // without re-raising, a SIGTERM would release the screen and then leave the agent running forever+ // with no way out short of SIGKILL. Only re-raised when this is the real process, never for an+ // injected emitter in a test.+ const terminating = new Map([["SIGTERM", 143], ["SIGHUP", 129]]);+ const onTeardown = (signal) => {leaveScreen(output);+ if (!terminating.has(signal) || proc !== process) return;+ // Re-raising the signal would be caught again by any other listener still attached to it (the+ // screen loop installs its own SIGTERM handler to turn mouse reporting off), which is the exact+ // hang this fixes. Exit explicitly instead, on the next tick so every other listener for this+ // signal still runs first. The code is the shell convention: 128 plus the signal number.+ setImmediate(() => process.exit(terminating.get(signal)));};const cleanups = [];@@ -141,10 +152,10 @@ export function installTeardown({});};- attach(proc, "exit", onTeardown);- attach(sigs, "SIGINT", onTeardown);- attach(sigs, "SIGTERM", onTeardown);- attach(sigs, "SIGHUP", onTeardown);+ attach(proc, "exit", () => onTeardown(null));+ attach(sigs, "SIGINT", () => onTeardown("SIGINT"));+ attach(sigs, "SIGTERM", () => onTeardown("SIGTERM"));+ attach(sigs, "SIGHUP", () => onTeardown("SIGHUP"));return {dispose() {diff --git a/scripts/mso-agent-pty.e2e.test.ts b/scripts/mso-agent-pty.e2e.test.tsnew file mode 100644index 00000000..3da7686a--- /dev/null+++ b/scripts/mso-agent-pty.e2e.test.ts@@ -0,0 +1,217 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import http from "node:http";+import os from "node:os";+import path from "node:path";+import fs from "node:fs";+import pty from "node-pty";++// Probe whether the current platform and container allow allocating a pseudo-terminal.+let ptyUsable = false;+try {+ const probe = pty.spawn(process.execPath, ["-e", "process.exit(0)"], { cols: 80, rows: 24 });+ probe.kill();+ ptyUsable = true;+} catch (error) {+ // PTY allocation can be restricted in locked-down CI or Windows containers without ConPTY.+ console.warn("Skipping PTY e2e suite: pseudo-terminal allocation unavailable in this environment:", error);+}++// Minimal in-memory screen grid that tracks ANSI cursor movement escapes to verify rendered lines.+function createTerminal(cols = 100, rows = 30) {+ const grid = Array.from({ length: rows }, () => Array(cols).fill(" "));+ let r = 0, c = 0;+ return {+ write(str: string) {+ for (let i = 0; i < str.length;) {+ if (str[i] === "\r") { c = 0; i++; } else if (str[i] === "\n") { r = Math.min(rows - 1, r + 1); c = 0; i++; }+ else if (str[i] === "\x1b" && str[i + 1] === "[") {+ let j = i + 2;+ while (j < str.length && !/[a-zA-Z]/.test(str[j])) j++;+ const seq = str.slice(i + 2, j), cmd = str[j++];+ i = j;+ if (cmd === "H") {+ const p = seq.split(";").map(Number);+ r = Math.max(0, Math.min(rows - 1, (p[0] || 1) - 1));+ c = Math.max(0, Math.min(cols - 1, (p[1] || 1) - 1));+ } else if (cmd === "A") r = Math.max(0, r - (Number(seq) || 1));+ else if (cmd === "B") r = Math.min(rows - 1, r + (Number(seq) || 1));+ else if (cmd === "C") c = Math.min(cols - 1, c + (Number(seq) || 1));+ else if (cmd === "D") c = Math.max(0, c - (Number(seq) || 1));+ else if (cmd === "K") {+ if (Number(seq) === 2) grid[r].fill(" ");+ else for (let x = c; x < cols; x++) grid[r][x] = " ";+ } else if (cmd === "J") for (const row of grid) row.fill(" ");+ } else if (str[i] === "\x1b") i += 2;+ else {+ if (r < rows && c < cols) grid[r][c++] = str[i];+ i++;+ }+ }+ },+ getLines: () => grid.map((row) => row.join("").trimEnd()),+ };+}++function spawnAgentPty(serverUrl: string, cols = 100, rows = 30) {+ const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "mso-pty-test-"));+ const env: Record<string, string | undefined> = {+ ...process.env, HOME: tempHome, TERM: "xterm-256color",+ MSO_AGENT_BASE: serverUrl, MSO_AGENT_ORIGIN: serverUrl, MSO_AGENT_CLI: "mso", MSO_AGENT_VERSION: "1.13.1",+ };+ delete env.CI; // Alt screen refuses execution in CI environment.+ const child = pty.spawn(process.execPath, [path.join(__dirname, "mso-agent.mjs"), "--altscreen"], {+ cols, rows, cwd: __dirname, env: env as Record<string, string>,+ });+ return {+ child,+ cleanup: () => {+ try { child.kill("SIGKILL"); } catch {}+ fs.rmSync(tempHome, { recursive: true, force: true });+ },+ };+}++function waitFor(child: pty.IPty, match: (chunk: string, total: string) => boolean | void, ms = 6000) {+ let total = "";+ return new Promise<string>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("PTY wait timed out")), ms);+ child.onData((chunk) => {+ total += chunk;+ if (match(chunk, total)) {+ clearTimeout(timer);+ resolve(total);+ }+ });+ });+}++const describeSuite = ptyUsable ? describe : describe.skip;++describeSuite("mso agent in real PTY e2e", () => {+ let server: http.Server;+ let serverUrl = "";+ const demoSession = { id: "test_pty_sess", source: "cli", name: "mso", title: "Operate your server", history: [] };++ beforeAll(async () => {+ // Loopback fixture server satisfies startup handshakes without live models or credentials.+ server = http.createServer((req, res) => {+ const p = new URL(req.url ?? "/", "http://127.0.0.1").pathname;+ const sendJson = (data: unknown) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(data)); };+ if (p === "/api/config") return sendJson({ provider: "openai", model: "gpt-5.6" });+ if (p === "/api/v1/agent-tools") return sendJson({ tools: [{ name: "fs_read", scope: "read", inputSchema: { type: "object", properties: {} } }] });+ if (p === "/api/skills" || p === "/api/v1/infra/providers") return sendJson(p.includes("skills") ? { skills: [] } : { providers: [] });+ if (p === "/api/models") return sendJson({ models: [{ id: "gpt-5.6", ref: "openai/gpt-5.6" }] });+ if (p === "/api/v1/agent-sessions") return sendJson({ session: demoSession, sessions: [demoSession] });+ if (p === "/api/v1/local-agents") return sendJson({ ok: true, agents: [] });+ res.writeHead(204); res.end();+ });++ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => resolve());+ });+ const addr = server.address();+ if (!addr || typeof addr === "string") throw new Error("Could not bind fixture server");+ serverUrl = `http://127.0.0.1:${addr.port}`;+ });++ afterAll(async () => {+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()));+ });++ it("paints panel, tab row, footer and transcript cleanly in real pty", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ const term = createTerminal(100, 30);+ try {+ const output = await waitFor(child, (chunk, total) => {+ term.write(chunk);+ return total.includes("❯") || total.includes("›");+ });+ const lines = term.getLines();+ expect(lines.filter((l) => l.includes("● @mso"))).toHaveLength(1);+ expect(lines.filter((l) => l.includes("mode ask") && l.includes("openai/gpt-5.6"))).toHaveLength(1);+ expect(lines.some((l) => l.includes("Welcome to MSO Agent!"))).toBe(true);+ expect(output).toContain("\x1b[?1049h");+ } finally { cleanup(); }+ });++ it("handles slash command (/help) without model call and redraws without duplicated rows", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ let sent = false;+ try {+ const output = await waitFor(child, (chunk, total) => {+ if (!sent && (chunk.includes("❯") || chunk.includes("›"))) { sent = true; child.write("/help\r"); }+ return sent && total.includes("show slash commands and keyboard shortcuts");+ });+ expect(output).toContain("show slash commands and keyboard shortcuts");+ } finally { cleanup(); }+ });++ it("redraws on resize (SIGWINCH) without duplicating tab row", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ let resized = false, postResize = "";+ try {+ await waitFor(child, (chunk) => {+ if (!resized && (chunk.includes("❯") || chunk.includes("›"))) { resized = true; child.resize(120, 35); return false; }+ if (resized) { postResize += chunk; return postResize.includes("● @mso"); }+ return false;+ });+ expect(postResize.split(/\r?\n/).filter((l) => l.includes("● @mso")).length).toBeLessThanOrEqual(1);+ } finally { cleanup(); }+ });++ it("leaves alternate screen on Ctrl+C and emits exit hint", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ let sent = false;+ try {+ const output = await waitFor(child, (chunk, total) => {+ if (!sent && (chunk.includes("❯") || chunk.includes("›"))) { sent = true; setTimeout(() => child.write("\x03"), 100); }+ return sent && total.includes("\x1b[?1049l");+ });+ expect(output).toContain("\x1b[?1049l");+ expect(output).toContain("session Operate your server · resume: mso --continue");+ } finally { cleanup(); }+ });++ // Was skipped while `const screenLoop` was scoped inside the try and threw a ReferenceError from+ // the finally block, turning a clean exit into exit code 1. Fixed in fix/tui-pty-bugs.+ it("exits with clean code 0 on Ctrl+C", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ try {+ let sent = false, exitCode: number | null = null;+ await new Promise<void>((resolve) => {+ child.onData((c) => { if (!sent && (c.includes("❯") || c.includes("›"))) { sent = true; child.write("\x03"); } });+ child.onExit(({ exitCode: code }) => { exitCode = code; resolve(); });+ });+ expect(exitCode).toBe(0);+ } finally { cleanup(); }+ });++ it("leaves alternate screen on SIGTERM", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ let termSent = false;+ try {+ const output = await waitFor(child, (chunk, total) => {+ if (!termSent && (chunk.includes("❯") || chunk.includes("›"))) { termSent = true; child.kill("SIGTERM"); }+ return termSent && total.includes("\x1b[?1049l");+ });+ expect(output).toContain("\x1b[?1049l");+ } finally { cleanup(); }+ });++ // Was skipped while the SIGTERM listener replaced node's default termination and left the agent+ // running forever. Fixed in fix/tui-pty-bugs by re-raising after the screen is released.+ it("exits process when SIGTERM signal is delivered", async () => {+ const { child, cleanup } = spawnAgentPty(serverUrl, 100, 30);+ try {+ let termSent = false, exited = false;+ await new Promise<void>((resolve) => {+ // Bounded: an unbounded wait turns a hang into a stalled suite instead of a failure.+ const timer = setTimeout(() => resolve(), 6000);+ child.onData((c) => { if (!termSent && (c.includes("❯") || c.includes("›"))) { termSent = true; child.kill("SIGTERM"); } });+ child.onExit(() => { exited = true; clearTimeout(timer); resolve(); });+ });+ expect(exited).toBe(true);+ } finally { cleanup(); }+ });+});diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex c5f5ed89..7410991d 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -36,6 +36,9 @@ async function main() {if (altScreen.requested && !altScreen.ok) {console.warn(`${C.dim}mso agent: alternate screen not enabled (${altScreen.reason})${C.reset}`);}+ // Declared out here, not inside the try: the finally block disposes them, and a `const` inside+ // the try is not in scope there. A ReferenceError in finally replaced the real exit status.+ let screenLoop = null;let screen = null; let session = null; let rl = null;let localBridge = null; let onSigint = null; let restartRequested = false;try {@@ -65,7 +68,7 @@ async function main() {const refreshSessions = () => { listCliSessions(20).then((rows) => { recentSessions = visibleSessionRows(rows); }).catch(() => {}); };refreshSessions();const chromeFooter = () => chromeLines({ session, sessions: recentSessions, activeId: session?.agentSession?.id, colors: C, width: process.stdout.columns, rows: process.stdout.rows });- const screenLoop = mountScreenLoop({+ screenLoop = mountScreenLoop({session,enabled: altScreen.ok,output: process.stdout,