Skip to content

armgit / mso

Public Imported from GitHub
0

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.

fix(tui): fifteen audits, and the defects that made the panel lie about safety (#273)

Abdurrahman Fakhrulf8ff8b4d15d6
diff --git a/.env.example b/.env.example
index 47e442e7..8323b029 100644
--- a/.env.example
+++ b/.env.example
@@ -254,6 +254,7 @@ OS_SESSION_SECRET=
# OS_AGENT_PROFILES_DIR=~/.mso/agent-profiles # private Owner-device saved profiles and revisions
# MSO_AGENT_WORKTREE_ROOT=~/.cache/mso-worktrees # task-owned Git worktrees for source-changing agent workflows
# MSO_AGENT_THEME=dark # TUI palette: dark (default) | light | mono; NO_COLOR or a non-TTY forces mono
+# MSO_AGENT_TIMEOUT_MS=120000 # upper bound for one local API request, so a dead server cannot freeze the TUI
# Session artifacts use this same root: temp/<client-hash>/<session-id> (owner-only).
# OS_AGENT_ARTIFACT_RETENTION_DAYS=7 # dormant artifacts only; clamped 1-30; active leases preserved
# OS_PROJECT_AGENT_TASKS_DIR=~/.mso/project-agent-tasks # private project-agent message/status records
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d869612e..b5d74935 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `tui` fifteen audits, and the defects that made the panel lie about safety
- keep credentials out of Composio cache keys
- preserve window drafts and modal focus
- bind Composio sessions to selected connections
@@ -26,13 +27,21 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Tests**
+- `tui` derive the wide-character fixture path from HOME
- retain Camoufox abort callback contract
**Docs**
+- `env` document MSO_AGENT_TIMEOUT_MS
- reconcile all frontend audit findings
- record rendered surfaces verification
+**Chores**
+
+- changelog pass
+- regenerate changelog after merging main
+- changelog
+
## 2026-11-03
**Added**
diff --git a/scripts/mso-agent-api.mjs b/scripts/mso-agent-api.mjs
index 532f7467..629f6aa9 100644
--- a/scripts/mso-agent-api.mjs
+++ b/scripts/mso-agent-api.mjs
@@ -7,6 +7,9 @@ const ORIGIN = String(process.env.MSO_AGENT_ORIGIN || BASE);
const JAR = String(process.env.MSO_AGENT_JAR || "");
export const CLI = String(process.env.MSO_AGENT_CLI || "mso");
export const VERSION = String(process.env.MSO_AGENT_VERSION || "");
+// Upper bound for one request. Long enough for a slow local tool call, short enough that a dead server
+// cannot freeze the UI forever.
+const REQUEST_TIMEOUT_MS = Math.max(1000, Number(process.env.MSO_AGENT_TIMEOUT_MS) || 120_000);
function cookieHeader() {
if (!JAR) return "";
@@ -35,7 +38,12 @@ export async function apiResponse(path, init = {}) {
const method = String(init.method || "GET").toUpperCase();
let res;
try {
- res = await fetch(`${BASE}${path}`, { ...init, headers: requestHeaders(Boolean(init.body), init.headers) });
+ // A request with no deadline can hang forever, and Ctrl+C cannot break a pending await, so the TUI
+ // froze with no way out. A caller-supplied signal still wins; the timeout only bounds the unbounded.
+ const signal = init.signal
+ ? AbortSignal.any([init.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)])
+ : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
+ res = await fetch(`${BASE}${path}`, { ...init, signal, headers: requestHeaders(Boolean(init.body), init.headers) });
} catch (error) {
if (["AbortError", "TimeoutError"].includes(String(error?.name || ""))) throw error;
throw new AgentApiError(error instanceof Error ? error.message : "transport failure", {
@@ -43,11 +51,18 @@ export async function apiResponse(path, init = {}) {
});
}
if (!res.ok) {
- const text = await res.text();
+ // The server's own sentence beats "HTTP 500". Only an `{error}` object was read, so an HTML or plain
+ // text error page — which is exactly what a proxy or a crashed handler returns — was replaced by the
+ // status code, hiding the reason from the user.
+ let text = "";
+ try { text = await res.text(); } catch { text = ""; }
let body = null;
try { body = text ? JSON.parse(text) : null; } catch { body = text; }
+ const serverMessage = typeof body === "object" && body
+ ? String(body.error ?? body.message ?? "")
+ : String(body ?? "").trim().slice(0, 300);
throw new AgentApiError(
- typeof body === "object" && body?.error ? String(body.error) : `HTTP ${res.status}`,
+ serverMessage ? `${serverMessage} · HTTP ${res.status}` : `HTTP ${res.status}`,
{ status: res.status, path, method, requestDispatched: true },
);
}
@@ -56,7 +71,16 @@ export async function apiResponse(path, init = {}) {
export async function api(path, init = {}) {
const res = await apiResponse(path, init);
- const text = await res.text();
+ let text = "";
+ try {
+ text = await res.text();
+ } catch (error) {
+ // A body that dies mid-read happens AFTER the request was dispatched. Reporting it as a plain failure
+ // let a write-scope caller think nothing happened and retry, which is how a double write occurs.
+ throw new AgentApiError(`response body dropped after dispatch${error?.message ? `: ${error.message}` : ""}`, {
+ path, method: String(init?.method || "GET").toUpperCase(), requestDispatched: true, cause: error,
+ });
+ }
try { return text ? JSON.parse(text) : null; } catch { return text; }
}
diff --git a/scripts/mso-agent-approval-summary.mjs b/scripts/mso-agent-approval-summary.mjs
index 0134e2af..2e459be8 100644
--- a/scripts/mso-agent-approval-summary.mjs
+++ b/scripts/mso-agent-approval-summary.mjs
@@ -17,8 +17,12 @@ function cleanTarget(value, max = 80) {
// Extracts the primary actionable target from tool input without guessing missing fields.
export function extractApprovalTarget(input = {}, tool = {}) {
- // Prefer explicit execution commands because they carry the highest risk profile.
+ // Prefer explicit execution commands because they carry the highest risk profile. A multi-line command
+ // is reported line-count-first: collapsing it hides what actually runs, and a leading "#" would make the
+ // rest of the script read as a comment.
if (typeof input?.command === "string" && input.command.trim()) {
+ const lines = input.command.split(/\r?\n/).filter((line) => line.trim());
+ if (lines.length > 1) return `${cleanTarget(lines[0], 56)} (+${lines.length - 1} more lines)`;
return cleanTarget(input.command);
}
// File operations identify targets by path or source-destination pairs.
diff --git a/scripts/mso-agent-approval-ui.mjs b/scripts/mso-agent-approval-ui.mjs
index 87046e7f..cc6917be 100644
--- a/scripts/mso-agent-approval-ui.mjs
+++ b/scripts/mso-agent-approval-ui.mjs
@@ -4,10 +4,30 @@ import { ApprovalSummaryFormatter } from "./mso-agent-approval-summary.mjs";
const SECRET_KEY = /(api[_-]?key|token|secret|password|passwd|credential|cookie|authorization|private[_-]?key)/i;
const SECRET_TEXT = /((?:api[_-]?key|token|secret|password|passwd|credential|authorization)\s*[=:]\s*)[^\s,;]+|\bBearer\s+[^\s,;]+/gi;
+function redact(value) {
+ return String(value ?? "").replace(SECRET_TEXT, (match, prefix) => prefix ? `${prefix}[redacted]` : "Bearer [redacted]");
+}
+
function oneLine(value, max = 100) {
- const clean = String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();
- const safe = clean.replace(SECRET_TEXT, (match, prefix) => prefix ? `${prefix}[redacted]` : "Bearer [redacted]");
- return Array.from(safe).length <= max ? safe : `${Array.from(safe).slice(0, Math.max(1, max - 1)).join("")}…`;
+ const clean = redact(value).replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();
+ return Array.from(clean).length <= max ? clean : `${Array.from(clean).slice(0, Math.max(1, max - 1)).join("")}…`;
+}
+
+// A shell command is a SEQUENCE of lines, and flattening it is a lie with consequences: "a # note\nrm -f x"
+// renders as one line where everything after "#" reads as a comment, so the approver approves something
+// that looks harmless while the executor runs the second line. Each line is kept and numbered.
+function commandLines(value, max = 120) {
+ const lines = redact(value).split(/\r?\n/).map((line) => line.replace(/\t/g, " ").replace(/\s+$/, ""));
+ while (lines.length > 1 && !lines[lines.length - 1]) lines.pop();
+ const shown = lines.slice(0, 12);
+ const out = shown.map((line, i) => (shown.length > 1 ? `${i + 1}│ ${clip(line, max)}` : clip(line, max)));
+ if (lines.length > shown.length) out.push(`… +${lines.length - shown.length} more lines (run denied until shown in full)`);
+ return out;
+}
+
+function clip(value, max) {
+ const chars = Array.from(String(value ?? ""));
+ return chars.length <= max ? chars.join("") : `${chars.slice(0, Math.max(1, max - 1)).join("")}…`;
}
function safeValue(value, key = "", depth = 0) {
@@ -15,10 +35,16 @@ function safeValue(value, key = "", depth = 0) {
if (depth > 3) return "[…]";
if (value === null || typeof value === "boolean" || typeof value === "number") return value;
if (typeof value === "string") return oneLine(value, 180);
- if (Array.isArray(value)) return value.slice(0, 8).map((item) => safeValue(item, "", depth + 1));
+ if (Array.isArray(value)) {
+ const shown = value.slice(0, 8).map((item) => safeValue(item, "", depth + 1));
+ // Saying how many were withheld matters: an approver who sees 8 of 40 files is approving 8 files.
+ return value.length > shown.length ? [...shown, `… +${value.length - shown.length} more`] : shown;
+ }
if (value && typeof value === "object") {
+ const entries = Object.entries(value);
const out = {};
- for (const [childKey, child] of Object.entries(value).slice(0, 16)) out[childKey] = safeValue(child, childKey, depth + 1);
+ for (const [childKey, child] of entries.slice(0, 16)) out[childKey] = safeValue(child, childKey, depth + 1);
+ if (entries.length > 16) out["…"] = `+${entries.length - 16} more fields`;
return out;
}
return String(value ?? "");
@@ -26,7 +52,11 @@ function safeValue(value, key = "", depth = 0) {
export function approvalActionSummary(tool, input = {}) {
const name = String(tool?.name || "tool");
- if (name === "exec_run" || name === "exec_job_start") return `run ${oneLine(input.command || "command", 72)}`;
+ if (name === "exec_run" || name === "exec_job_start") {
+ const lines = commandLines(input.command ?? "command", 72);
+ // A multi-line command says how many lines there are, so the one-line status cannot understate it.
+ return lines.length > 1 ? `run ${lines[0]} (+${lines.length - 1} more lines)` : `run ${lines[0]}`;
+ }
if (name === "fs_write") return `write ${oneLine(input.path || "file", 72)}`;
if (name === "fs_delete") return `delete ${oneLine(input.path || "path", 72)}`;
if (name === "fs_move") return `move ${oneLine(input.from || "source", 32)} → ${oneLine(input.to || "target", 32)}`;
@@ -46,14 +76,21 @@ export function approvalStatusLine(tool, input, focused = false) {
}
export function approvalDetailLines(tool, input, approval) {
- return [
+ const lines = [
"Approval details",
` tool ${String(tool?.name || "tool")}`,
` scope ${String(tool?.scope || "write")}`,
- ` args ${approvalArgsSummary(input)}`,
- ` digest sha256 ${approval.digest}`,
- " choose allow or deny",
];
+ // A command gets one numbered row per line. The flattened JSON form comes after it, because that is
+ // the shape the executor actually runs and the approver must see it in that shape.
+ if (typeof input?.command === "string" && input.command.includes("\n")) {
+ lines.push(" command");
+ for (const row of commandLines(input.command, 100)) lines.push(` ${row}`);
+ }
+ lines.push(` args ${approvalArgsSummary(input)}`);
+ lines.push(` digest sha256 ${approval.digest}`);
+ lines.push(" choose allow or deny");
+ return lines;
}
// Session-scoped approval formatter tracking confirmed tool calls in memory.
diff --git a/scripts/mso-agent-command-dialog.mjs b/scripts/mso-agent-command-dialog.mjs
index 65f62cee..94c43478 100644
--- a/scripts/mso-agent-command-dialog.mjs
+++ b/scripts/mso-agent-command-dialog.mjs
@@ -11,18 +11,29 @@ const PLAIN = /\x1b\[[0-9;]*m/g;
* Builds the rows the dialog lists. One source, so the dialog can never offer a command the handler
* does not know.
*
+ * `value` is the command name alone, because that is what gets dispatched. `text` carries the usage
+ * hint and is only for display: selecting a row used to send the whole hint as arguments, so picking
+ * `/terminal [cmd]` ran `sh -c "[cmd]"` and picking `/queue [drop|clear|prompt]` enqueued the literal
+ * placeholder as a prompt. 32 of 46 rows were wrong that way.
+ *
* @param {Array<{name: string, usage?: string, description?: string}>} commands manifest entries
- * @returns {Array<{text: string, label: string, meta: string, kind: string}>}
+ * @returns {Array<{text: string, label: string, value: string, meta: string, kind: string}>}
*/
export function commandDialogItems(commands = []) {
return (Array.isArray(commands) ? commands : [])
.filter((row) => row && typeof row.name === "string" && row.name.startsWith("/"))
- .map((row) => ({
- text: row.usage ? `${row.name} ${row.usage}` : row.name,
- label: row.name,
- meta: String(row.description || "").replace(PLAIN, ""),
- kind: "command",
- }))
+ .flatMap((row) => {
+ // A row may declare several names ("/exit, /quit"). Each is its own command, and dispatching the
+ // joined string made the whole row unusable: the first token became "/exit," which matched nothing.
+ return String(row.name).split(",").map((raw) => raw.trim()).filter((name) => name.startsWith("/"))
+ .map((name) => ({
+ text: row.usage ? `${name} ${row.usage}` : name,
+ label: name,
+ value: name,
+ meta: String(row.description || "").replace(PLAIN, ""),
+ kind: "command",
+ }));
+ })
.sort((a, b) => a.label.localeCompare(b.label));
}
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 1dac6ebe..6572f6f6 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -54,7 +54,7 @@ import { spawnSync } from "node:child_process";
import process from "node:process";
import { C } from "./mso-agent-runtime.mjs";
import { BASE, CLI, api, state } from "./mso-agent-api.mjs";
-import { leaveScreen } from "./mso-agent-altscreen.mjs";
+import { withPanelSuspended } from "./mso-agent-turn-print.mjs";
import {
loadSlashSkill,
printSkillChoices,
@@ -77,15 +77,28 @@ import { createPrinter } from "./mso-agent-print.mjs";
export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
+// Set once by handleSlash, so runCli can suspend the panel around a child process without every caller
+// threading the loop through. Module-level because runCli is passed around as a bare function.
+let runCliLoop = null;
+
function runCli(args) {
- // Releases the alternate screen buffer before handing the terminal to an interactive child process.
- leaveScreen();
- const result = spawnSync(CLI, args, {
- stdio: "inherit",
- env: { ...process.env, MSO_BASE: BASE },
+ // Hands the terminal to a child process and takes it back. The previous version called leaveScreen()
+ // and never re-entered: only a panel suspend/resume pair restores the alternate screen, and suspend()
+ // was never called here, so `screenLoop.active` stayed true and every later frame painted onto the
+ // user's normal screen, overwriting their scrollback for the rest of the session. `withPanelSuspended`
+ // is the pair: suspend re-enables line input and disables the panel, resume restores both.
+ let status = 1;
+ // The loop is reached through the session, which every command context already carries; runCli is
+ // handed around as a bare function, so it cannot close over the loop at module scope.
+ withPanelSuspended(runCliLoop || null, () => {
+ const result = spawnSync(CLI, args, {
+ stdio: "inherit",
+ env: { ...process.env, MSO_BASE: BASE },
+ });
+ if (result.error) console.error(`${C.err}${result.error.message}${C.reset}`);
+ status = result.status ?? 1;
});
- if (result.error) console.error(`${C.err}${result.error.message}${C.reset}`);
- return result.status ?? 1;
+ return status;
}
async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
@@ -115,8 +128,9 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
return "handled";
}
session.history.push({ role: "user", text: prompt.trim() });
- if (session.history.length > 48)
- session.history.splice(0, session.history.length - 48);
+ // No splice here. The old line dropped everything past 48 rows from the in-memory history, and the next
+ // persistSession wrote that shortened array back: one /skill call permanently deleted the conversation.
+ // The server already bounds history (MAX_HISTORY), and the plain prompt path never trims in memory.
await runTurn(loaded);
return "handled";
}
@@ -132,6 +146,7 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
const [cmd, ...args] = line.trim().split(/\s+/);
+ runCliLoop = session?.screenLoop || null;
const local = await handleLocalCommand(cmd, args, session, { runCli, runSubagent });
if (local) return local;
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 68202474..80e1a253 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -69,7 +69,10 @@ export class AgentComposer {
if (settled) return;
settled = true;
erase();
- if (echo) output.write(`${promptText()}${displayValue}\r\n`);
+ // In panel mode the panel owns the screen: a raw CRLF writes a row OUTSIDE the retained frame,
+ // and the frame never clears it, so the prompt text stays on screen under the dialog. The caller
+ // repaints and records the line through the print sink instead.
+ if (echo && !rowCallback) output.write(`${promptText()}${displayValue}\r\n`);
cleanup();
if (history && result?.trim()) { this.history.unshift(result); if (this.history.length > 100) this.history.length = 100; }
resolve(result);
@@ -79,7 +82,7 @@ export class AgentComposer {
if (typeof onCancel === "function") onCancel();
settled = true;
erase();
- if (echo) output.write("^C\r\n");
+ if (echo && !rowCallback) output.write("^C\r\n");
cleanup();
resolve(null);
return true;
diff --git a/scripts/mso-agent-exit.mjs b/scripts/mso-agent-exit.mjs
new file mode 100644
index 00000000..e4706018
--- /dev/null
+++ b/scripts/mso-agent-exit.mjs
@@ -0,0 +1,58 @@
+// The exit path for the interactive TUI.
+//
+// Split out of the entrypoint because it is the one place where ORDER is the whole point, and it is easy to
+// reintroduce: the farewell line has to be written AFTER the alternate screen is left, or it lands in the
+// buffer that is about to be discarded and the user never sees it.
+
+/**
+ * Writes JSON on stdout for a `--json` caller, then reports the failure on stderr and exits non-zero.
+ *
+ * A caller that asked for JSON asked for a machine-readable contract. Printing only a sentence to stderr
+ * broke that contract on exactly the paths where it matters most: failures.
+ *
+ * @param {unknown} error
+ * @param {{colors?: any, argv?: string[], exit?: (code: number) => void, stdout?: any, stderr?: any}} [deps]
+ */
+export function failRun(error, deps = {}) {
+ const {
+ colors = {}, argv = process.argv, exit = (code) => process.exit(code),
+ stdout = process.stdout, stderr = process.stderr,
+ } = deps;
+ const message = error instanceof Error ? error.message : String(error);
+ if (argv.includes("--json")) stdout.write(`${JSON.stringify({ ok: false, error: message, kind: "runtime" })}\n`);
+ stderr.write(`${colors.err || ""}mso agent: ${message}${colors.reset || ""}\n`);
+ exit(1);
+}
+
+/**
+ * Runs the teardown sequence in the order the terminal needs it.
+ *
+ * Screen disposal comes BEFORE anything that prints: leaving the alternate screen discards it, so a line
+ * written earlier is erased along with the frame.
+ *
+ * @param {{session?: any, restartRequested?: boolean, resumeHint?: boolean, localBridge?: any,
+ * closeComposer?: () => void, disposePanel?: () => void, disposeScreen?: () => void,
+ * print?: (line: string) => void, colors?: any}} input
+ */
+export async function finishRun({
+ session, restartRequested = false, resumeHint = true, localBridge = null,
+ closeComposer = () => {}, disposePanel = () => {}, disposeScreen = () => {},
+ print = (line) => console.log(line), colors = {},
+}) {
+ const title = String(session?.agentSession?.title || "MSO Agent session")
+ .replace(/[\r\n\t]+/g, " ").trim().slice(0, 80);
+ const dim = colors.dim || "", reset = colors.reset || "";
+
+ if (localBridge) await localBridge.close({ ended: !restartRequested }).catch(() => undefined);
+ closeComposer();
+ disposePanel();
+ disposeScreen();
+
+ // Both of these belong to the normal screen, so they run after the panel has handed it back.
+ if (!restartRequested && session && resumeHint) {
+ print(`${dim}session ${title} · resume: mso --continue · switch: /sessions${reset}`);
+ }
+ if (!restartRequested) return null;
+ print(`${dim}↻ refreshing Agent runtime · keeping ${title || "current session"}${reset}`);
+ return "restart";
+}
diff --git a/scripts/mso-agent-footer.mjs b/scripts/mso-agent-footer.mjs
index 8f6f363a..068a3816 100644
--- a/scripts/mso-agent-footer.mjs
+++ b/scripts/mso-agent-footer.mjs
@@ -11,15 +11,27 @@
import { contextStatus } from "./mso-agent-status.mjs";
import { queueList } from "./mso-agent-queue.mjs";
+import { cellWidth, stripAnsi } from "./tui/cells.mjs";
-const PLAIN = /\x1b\[[0-9;]*m/g;
-const plain = (value) => String(value ?? "").replace(PLAIN, "");
-const width = (value) => Array.from(plain(value)).length;
+const width = (value) => cellWidth(value);
+
+// Clips to `max` cells by measuring the PLAIN text and then applying the colour once.
+//
+// Slicing the styled string cut escape sequences in half: the cut landed inside "\x1b[2m" and the "…" that
+// followed was not a CSI final byte, so the terminal kept buffering and ate the next real characters. It
+// also emitted no reset, which bled dim/yolo colour into the prompt. Measuring in cells (not code points)
+// is the second half of the fix: a CJK path is twice as wide as its character count says.
const clamp = (value, max) => {
- const text = String(value ?? "");
- if (width(text) <= max) return text;
- const chars = Array.from(text);
- return `${chars.slice(0, Math.max(0, max - 1)).join("")}…`;
+ const plainText = stripAnsi(value);
+ if (cellWidth(plainText) <= max) return String(value ?? "");
+ let out = "", used = 0;
+ for (const ch of plainText) {
+ const w = cellWidth(ch);
+ if (used + w > Math.max(0, max - 1)) break;
+ out += ch;
+ used += w;
+ }
+ return `${out}…`;
};
function number(value) {
diff --git a/scripts/mso-agent-footer.test.ts b/scripts/mso-agent-footer.test.ts
index 4a234386..d8f0df71 100644
--- a/scripts/mso-agent-footer.test.ts
+++ b/scripts/mso-agent-footer.test.ts
@@ -70,12 +70,18 @@ describe("footer rows", () => {
});
describe("composer frame", () => {
- it("claims prompt plus draft rows only, leaving the menu and footer to overlay", () => {
+ it("claims prompt, draft AND footer rows; only the menu overlays", () => {
+ // The footer is permanent and sits under the prompt, so the panel must reserve it. Reserving only
+ // prompt+draft left the frame two rows taller than the reservation, which painted the status rows
+ // over the panel's tab row (and its hit test) once the draft wrapped.
const one = composeComposerLines({ prompt: "> ", draft: [""], menu: ["m1", "m2"], foot: ["f1"], promptWidth: 2 });
- expect(one.owned).toBe(1);
+ expect(one.owned).toBe(2);
expect(one.lines).toHaveLength(4);
const three = composeComposerLines({ prompt: "> ", draft: ["a", "b", "c"], menu: [], foot: ["f1"], promptWidth: 2 });
- expect(three.owned).toBe(3);
+ expect(three.owned).toBe(4);
+ // The menu is still excluded: it is transient and grows over the transcript.
+ const menuOnly = composeComposerLines({ prompt: "> ", draft: [""], menu: Array(10).fill("m"), foot: [], promptWidth: 2 });
+ expect(menuOnly.owned).toBe(1);
});
it("keeps the footer exactly once, which is what a duplicated status row got wrong", () => {
diff --git a/scripts/mso-agent-input-hook.mjs b/scripts/mso-agent-input-hook.mjs
index df2a3396..63b52c40 100644
--- a/scripts/mso-agent-input-hook.mjs
+++ b/scripts/mso-agent-input-hook.mjs
@@ -5,9 +5,13 @@ import { parseMouseChunk } from "./mso-agent-mouse.mjs";
// to the composer would mean growing a file that sits at its line ceiling. This owns that patch and
// nothing else, so the screen loop stays under the line ratchet.
export function installInputHook({ input, onKey, onMouse }) {
- const originalEmit = input.emit;
+ const originalEmit = input?.emit;
if (typeof originalEmit !== "function") return { dispose() {}, setEnabled() {} };
let enabled = true;
+ // A mouse report can arrive split across two `data` chunks. Only complete sequences were stripped, so
+ // the tail fell through to readline and was typed into the prompt as text ("64;10;5M"). The dangling
+ // fragment is held here and prepended to the next chunk until it completes.
+ let pendingMouse = "";
const consumeMouse = (payload) => {
const events = parseMouseChunk(payload);
@@ -22,14 +26,18 @@ export function installInputHook({ input, onKey, onMouse }) {
if (!enabled) return Reflect.apply(originalEmit, this, [event, ...args]);
if (event === "data" && args[0]) {
const chunk = typeof args[0] === "string" ? args[0] : (args[0] instanceof Buffer ? args[0].toString("utf8") : "");
- if (chunk.includes("\x1b[<")) {
- const events = parseMouseChunk(chunk);
- if (events.length) {
- for (const item of events) onMouse(item);
- const stripped = chunk.replace(/\x1b\[<\d+;\d+;\d+[Mm]/g, "");
- if (!stripped) return true;
- args[0] = typeof args[0] === "string" ? stripped : Buffer.from(stripped, "utf8");
- }
+ const buffered = pendingMouse + chunk;
+ if (buffered.includes("\x1b[<")) {
+ const events = parseMouseChunk(buffered);
+ if (events.length) for (const item of events) onMouse(item);
+ const stripped = buffered.replace(/\x1b\[<\d+;\d+;\d+[Mm]/g, "");
+ // Everything after an unterminated report marker may still be completing: hold it.
+ const tail = stripped.lastIndexOf("\x1b[<");
+ pendingMouse = tail >= 0 ? stripped.slice(tail) : "";
+ const rest = tail >= 0 ? stripped.slice(0, tail) : stripped;
+ if (!rest) return true;
+ // Preserve the original argument type: a Buffer caller must keep receiving a Buffer.
+ args[0] = args[0] instanceof Buffer ? Buffer.from(rest, "utf8") : rest;
}
}
if (event === "keypress") {
@@ -41,7 +49,7 @@ export function installInputHook({ input, onKey, onMouse }) {
};
return {
- setEnabled(next) { enabled = next; },
+ setEnabled(next) { enabled = next; if (!next) pendingMouse = ""; },
dispose() {
input.emit = originalEmit;
},
diff --git a/scripts/mso-agent-key-normalize.mjs b/scripts/mso-agent-key-normalize.mjs
new file mode 100644
index 00000000..036c3df2
--- /dev/null
+++ b/scripts/mso-agent-key-normalize.mjs
@@ -0,0 +1,73 @@
+// Turning a physical key event (or a binding string) into one canonical spelling.
+//
+// This is its own module because it is pure, it has more edge cases than anything else in the keymap, and
+// two of them silently disabled keys outright:
+//
+// a bare Escape arrives as meta:true -> counting it as Alt made "escape" unmatchable
+// ctrl+i IS tab -> storing "ctrl+i" killed the Tab binding it replaced
+// "shift+ctrl+k" -> a permuted spelling never matched {ctrl,shift,k}
+//
+// Every caller compares normalized strings, so one wrong spelling is a dead binding with no error.
+
+// Control bytes that readline reports under a different name.
+const CONTROL_ALIASES = { i: "tab", m: "return", j: "return", h: "backspace" };
+
+// Names readline can produce. A binding whose key is not one of these can never fire, so it is refused
+// rather than stored: storing it replaced a working default with a no-op.
+const KNOWN_KEYS = new Set([
+ "escape", "return", "tab", "space", "backspace", "delete", "insert",
+ "left", "right", "up", "down", "home", "end", "pageup", "pagedown",
+ "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
+]);
+
+// Canonical modifier order. The object path always emits ctrl,alt,shift, so the string path must too.
+const MODIFIER_ORDER = ["ctrl", "alt", "shift"];
+
+export function isKnownKeyName(name) {
+ return KNOWN_KEYS.has(name);
+}
+
+/**
+ * @param {any} spec a keypress object from readline, or a binding string like "ctrl+shift+k"
+ * @returns {string} canonical spelling, or "" when the spec cannot describe a real key
+ */
+export function normalizeKey(spec) {
+ if (!spec) return "";
+ if (typeof spec === "object") {
+ const parts = [];
+ // The name is lowered FIRST: comparing the raw name meant {name:"Escape"} produced alt+escape while
+ // {name:"escape"} did not, so one spelling of the same physical key was dead.
+ const name = String(spec.name || "").toLowerCase().trim();
+ if (spec.ctrl) parts.push("ctrl");
+ if (spec.meta && name !== "escape") parts.push("alt");
+ if (spec.shift) parts.push("shift");
+ if (!name) return "";
+ parts.push(name === "enter" ? "return" : name);
+ return parts.join("+");
+ }
+
+ const tokens = String(spec).toLowerCase().trim().replace(/\s+/g, "").split("+").filter(Boolean);
+ if (!tokens.length) return "";
+ const mods = new Set();
+ let key = "";
+ let unknown = "";
+ for (const token of tokens) {
+ if (token === "ctrl" || token === "control") mods.add("ctrl");
+ else if (token === "alt" || token === "meta") mods.add("alt");
+ else if (token === "shift") mods.add("shift");
+ // A multi-character token that is not a known key is a typo such as "ctrlp+k". Treating it as the key
+ // produced a single-letter binding that swallowed typing: one keystroke cleared the screen and the
+ // letter could never be typed.
+ else if (token.length > 1 && !KNOWN_KEYS.has(token) && token !== "enter") unknown = token;
+ else key = token === "enter" ? "return" : token;
+ }
+ if (unknown) return "";
+
+ // ctrl+i IS tab: readline reports one key, so ctrl is dropped rather than kept alongside.
+ if (key.length === 1 && mods.has("ctrl") && CONTROL_ALIASES[key]) {
+ mods.delete("ctrl");
+ key = CONTROL_ALIASES[key];
+ }
+ if (!key) return "";
+ return [...MODIFIER_ORDER.filter((mod) => mods.has(mod)), key].join("+");
+}
diff --git a/scripts/mso-agent-keybinds.mjs b/scripts/mso-agent-keybinds.mjs
index 13314a9a..5cac9844 100644
--- a/scripts/mso-agent-keybinds.mjs
+++ b/scripts/mso-agent-keybinds.mjs
@@ -1,4 +1,5 @@
import fs from "node:fs";
+import { isKnownKeyName, normalizeKey } from "./mso-agent-key-normalize.mjs";
import os from "node:os";
import path from "node:path";
import { createPrinter } from "./mso-agent-print.mjs";
@@ -44,30 +45,7 @@ export function defaultKeybinds() {
};
}
-export function normalizeKey(spec) {
- if (!spec) return "";
- if (typeof spec === "object") {
- const parts = [];
- if (spec.ctrl) parts.push("ctrl");
- if (spec.meta && spec.name !== "escape") parts.push("alt"); // bare Escape reports meta:true
- if (spec.shift) parts.push("shift");
- const name = String(spec.name || "").toLowerCase().trim();
- if (!name) return "";
- parts.push(name === "enter" ? "return" : name);
- return parts.join("+");
- }
- const tokens = String(spec).toLowerCase().trim().replace(/\s+/g, "").split("+").filter(Boolean);
- if (!tokens.length) return "";
- const mods = [];
- let key = "";
- for (const token of tokens) {
- if (token === "ctrl" || token === "control") mods.push("ctrl");
- else if (token === "alt" || token === "meta") mods.push("alt");
- else if (token === "shift") mods.push("shift");
- else key = token === "enter" ? "return" : token;
- }
- return key ? [...mods, key].join("+") : "";
-}
+export { normalizeKey } from "./mso-agent-key-normalize.mjs";
/**
* @param {any} key
@@ -152,12 +130,30 @@ export function loadKeybinds({ path: filePath = defaultKeybindsPath(), readFile
warnings.push(`invalid key "${keyValue}" for action "${actionKey}"`);
continue;
}
+ // A key the terminal can never report is a binding that silently does nothing, and it also replaced
+ // the default that worked. Refusing it keeps the working default instead of trading it for a no-op.
+ const keyPart = norm.split("+").pop();
+ if (!(keyPart.length === 1 || isKnownKeyName(keyPart))) {
+ warnings.push(`unknown key "${keyValue}" for action "${actionKey}" (kept previous binding)`);
+ continue;
+ }
+ if (keyPart === "escape" && norm.includes("alt")) {
+ // Alt+Escape is not reported by node at all, and a bare Escape never normalises to alt+escape.
+ warnings.push(`"alt+escape" is unreachable; bind "escape" instead (action "${actionKey}")`);
+ continue;
+ }
if (READLINE_EDITING_KEYS.has(norm)) {
warnings.push(`binding "${norm}" overrides line editing`);
}
resolved[action] = norm;
}
+ // Report action-vs-action collisions at load. detectConflicts existed but nothing called it, so two
+ // actions on one key silently resolved by declaration order while /keybind conflicts reported clean.
+ for (const conflict of detectConflicts(resolved)) {
+ warnings.push(`"${conflict.key}" is bound to ${conflict.actions.join(" and ")}; only ${conflict.actions[0]} wins`);
+ }
+
return settle(resolved, warnings, filePath);
}
diff --git a/scripts/mso-agent-oneshot-run.mjs b/scripts/mso-agent-oneshot-run.mjs
index 948813b5..3046cbf7 100644
--- a/scripts/mso-agent-oneshot-run.mjs
+++ b/scripts/mso-agent-oneshot-run.mjs
@@ -21,12 +21,20 @@ export async function runOneShot(opts) {
// not reasoning text, so nothing here changes the turn. Passing `thinking` into
// agentRound would be dead config, so the flag is consumed in the payload below.
const result = await agentRound(null, session, null, undefined, null, { quiet: true, approvalScope: opts.approvalScope });
- await persistSession(session);
+ // A bookkeeping failure must not discard a completed answer.
+ await persistSession(session).catch(() => undefined);
+ // `ok` is derived, never assumed. It used to be the literal `true`, so a run whose only write was DENIED
+ // or whose tool returned ok:false still reported success and exited 0: an agent driving this saw
+ // "no output, success" and moved on. A turn that hit its limit is also not a success.
+ const calls = Array.isArray(result?.calls) ? result.calls : [];
+ const failedCalls = calls.filter((call) => call && call.ok === false);
+ const ok = failedCalls.length === 0 && !result?.turnLimitReached;
const payload = {
- ok: true, sessionId: session.agentSession.id,
+ ok, sessionId: session.agentSession.id,
model: `${s.config?.provider || ""}/${s.config?.model || ""}`.replace(/^\//, ""),
approvalScope: opts.approvalScope, text: result?.text || "", rounds: result?.rounds || 0,
- toolCalls: result?.calls || [], usage: result?.usage || session.usage, routing: session.lastRouting, elapsedMs: result?.elapsedMs || session.lastElapsedMs,
+ toolCalls: calls, usage: result?.usage || session.usage, routing: session.lastRouting, elapsedMs: result?.elapsedMs || session.lastElapsedMs,
+ ...(failedCalls.length ? { failedCalls: failedCalls.map((call) => call.name || "tool") } : {}),
// Prove what was actually attached instead of leaving --file unverifiable.
...(opts.files?.length ? { files: opts.files } : {}),
// `--thinking` surfaces the reasoning ACCOUNTING the provider really reported.
@@ -37,4 +45,6 @@ export async function runOneShot(opts) {
};
if (opts.json) process.stdout.write(`${JSON.stringify(payload)}\n`);
else process.stdout.write(`${payload.text}${payload.text.endsWith("\n") || !payload.text ? "" : "\n"}`);
+ // Exit code carries the outcome, so a script can branch without parsing stdout.
+ return ok;
}
diff --git a/scripts/mso-agent-overlay.mjs b/scripts/mso-agent-overlay.mjs
index a561a16a..5399a62e 100644
--- a/scripts/mso-agent-overlay.mjs
+++ b/scripts/mso-agent-overlay.mjs
@@ -73,8 +73,12 @@ export function composeComposerLines({ prompt = "", draft = [], menu = [], foot
...menu,
...foot,
];
- // Prompt plus draft own rows; menu and footer overlay what is already there.
- return { lines, owned: Math.max(1, draft.length) };
+ // Prompt, draft AND footer own rows. The menu is the only part that overlays, because a menu is
+ // transient and grows over the transcript. The footer is permanent: it sits below the prompt, so the
+ // panel must reserve it too. Reserving only prompt+draft left the frame two rows taller than the
+ // reservation, which painted the status rows over the panel's own tab row (and the tab hit test with
+ // it) as soon as the draft wrapped to a second line.
+ return { lines, owned: Math.max(1, draft.length) + foot.length };
}
/**
diff --git a/scripts/mso-agent-permissions.mjs b/scripts/mso-agent-permissions.mjs
index ac89e1b7..518b08c8 100644
--- a/scripts/mso-agent-permissions.mjs
+++ b/scripts/mso-agent-permissions.mjs
@@ -12,7 +12,11 @@ export function permissionMode(value) {
}
export function nextPermissionMode(current) {
- const index = Math.max(0, PERMISSION_MODES.findIndex((mode) => mode.id === current));
+ // An unrecognised mode falls back to the SAFEST one, not to the next one. `Math.max(0, findIndex(...))`
+ // made any unknown string resolve to index 0 and then advance to `auto`, so a typo or an old config
+ // escalated write approval instead of staying at ask.
+ const index = PERMISSION_MODES.findIndex((mode) => mode.id === permissionMode(current)?.id);
+ if (index < 0) return PERMISSION_MODES[0];
return PERMISSION_MODES[(index + 1) % PERMISSION_MODES.length];
}
diff --git a/scripts/mso-agent-pty.e2e.test.ts b/scripts/mso-agent-pty.e2e.test.ts
index 391c2b85..15fc2818 100644
--- a/scripts/mso-agent-pty.e2e.test.ts
+++ b/scripts/mso-agent-pty.e2e.test.ts
@@ -172,7 +172,10 @@ describeSuite("mso agent in real PTY e2e", () => {
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");
+ // Wait for the HINT, not just the alt-screen exit. The hint is written after the alternate screen is
+ // left (that order is the fix: writing it earlier put it in the buffer about to be discarded), so
+ // stopping at "\x1b[?1049l" returns before the line that is being asserted.
+ return sent && total.includes("\x1b[?1049l") && total.includes("resume: mso --continue");
});
expect(output).toContain("\x1b[?1049l");
expect(output).toContain("session Operate your server · resume: mso --continue");
diff --git a/scripts/mso-agent-qa-sweep.test.ts b/scripts/mso-agent-qa-sweep.test.ts
new file mode 100644
index 00000000..b957f763
--- /dev/null
+++ b/scripts/mso-agent-qa-sweep.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from "vitest";
+import { approvalActionSummary, approvalArgsSummary, approvalDetailLines } from "./mso-agent-approval-ui.mjs";
+import { nextPermissionMode } from "./mso-agent-permissions.mjs";
+import { contextStatus } from "./mso-agent-status.mjs";
+import { commandDialogItems } from "./mso-agent-command-dialog.mjs";
+import { normalizeKey, loadKeybinds } from "./mso-agent-keybinds.mjs";
+import { composeComposerLines, overlayFrame } from "./mso-agent-overlay.mjs";
+import { footerRows } from "./mso-agent-footer.mjs";
+import { cellWidth } from "./tui/cells.mjs";
+
+// One test file for the QA sweep, so every fix carries the failure that motivated it. Each block names
+// what the bug looked like to a user, because that is what a future refactor would reintroduce.
+
+describe("approval fidelity", () => {
+ const multiLine = "echo done # cleanup\nrm -f /tmp/victim";
+
+ it("never flattens a multi-line command into what reads as a comment", () => {
+ // The old summary printed "run echo done # cleanup rm -f /tmp/victim", where everything after "#"
+ // looks like a shell comment. The executor runs BOTH lines.
+ const summary = approvalActionSummary({ name: "exec_run" }, { command: multiLine });
+ expect(summary).toContain("+1 more lines");
+ expect(summary).not.toContain("rm -f");
+ });
+
+ it("shows every command line, numbered, in the detail view", () => {
+ const lines = approvalDetailLines({ name: "exec_run", scope: "exec" }, { command: multiLine }, { digest: "d" });
+ const body = lines.join("\n");
+ expect(body).toContain("1│ echo done # cleanup");
+ expect(body).toContain("2│ rm -f /tmp/victim");
+ });
+
+ it("reports how many array or object entries were withheld", () => {
+ // Eight of forty files with no marker is an approval for eight files.
+ const shown = approvalArgsSummary({ files: Array.from({ length: 40 }, (_, i) => `f${i}`) });
+ expect(shown).toContain("+32 more");
+ });
+
+ it("keeps a single-line command on one row", () => {
+ expect(approvalActionSummary({ name: "exec_run" }, { command: "ls -la" })).toBe("run ls -la");
+ });
+});
+
+describe("permission mode", () => {
+ it("falls back to the safest mode on unknown input instead of escalating", () => {
+ // findIndex(-1) clamped to 0 and then ADVANCED to auto, so a typo granted write approval.
+ for (const bad of ["bogus", "", undefined, null, "ASKing"]) {
+ expect(nextPermissionMode(bad).id).toBe("ask");
+ }
+ });
+
+ it("still cycles in order for known modes", () => {
+ expect(nextPermissionMode("ask").id).toBe("auto");
+ expect(nextPermissionMode("auto").id).toBe("yolo");
+ expect(nextPermissionMode("yolo").id).toBe("ask");
+ });
+});
+
+describe("context percentage", () => {
+ it("measures against the window, so a full window reads 100%", () => {
+ // The old formula divided by a budget capped at 120k, so a 200k window could never exceed 55%.
+ const rows = Array.from({ length: 800 }, () => ({ role: "user", text: "x".repeat(1000) }));
+ const ctx = contextStatus(rows, { context: 200_000 });
+ expect(ctx.stored).toBeGreaterThan(ctx.limit ?? 0);
+ expect(ctx.percent).toBe(100);
+ });
+
+ it("reports null percent when no window is configured", () => {
+ expect(contextStatus([{ role: "user", text: "hi" }], {}).percent).toBeNull();
+ });
+});
+
+describe("command dialog", () => {
+ it("dispatches the command name, never the usage placeholder", () => {
+ // Selecting "/terminal [cmd]" ran `sh -c "[cmd]"`; 32 of 46 rows carried a placeholder.
+ const items = commandDialogItems([
+ { name: "/terminal", usage: "[cmd]", description: "run" },
+ { name: "/queue", usage: "[drop|clear|prompt]", description: "queue" },
+ ]);
+ expect(items.map((i) => i.value)).toEqual(["/queue", "/terminal"]);
+ expect(items.find((i) => i.value === "/terminal")?.text).toBe("/terminal [cmd]");
+ });
+
+ it("splits a row that declares several names", () => {
+ // "/exit, /quit" dispatched the first token "/exit," which matched nothing, so the dialog could not quit.
+ const items = commandDialogItems([{ name: "/exit, /quit", description: "leave" }]);
+ expect(items.map((i) => i.value)).toEqual(["/exit", "/quit"]);
+ });
+});
+
+describe("keybinds", () => {
+ it("canonicalises modifier order so a permuted binding still fires", () => {
+ expect(normalizeKey("shift+ctrl+k")).toBe(normalizeKey({ ctrl: true, shift: true, name: "k" }));
+ expect(normalizeKey("alt+ctrl+p")).toBe("ctrl+alt+p");
+ });
+
+ it("treats ctrl+i as tab, which is what the terminal reports", () => {
+ expect(normalizeKey("ctrl+i")).toBe("tab");
+ expect(normalizeKey("ctrl+m")).toBe("return");
+ });
+
+ it("refuses an unknown key instead of binding a bare letter that swallows typing", () => {
+ const loaded = loadKeybinds({
+ path: "/tmp/unused-keybinds.json",
+ readFile: () => JSON.stringify({ clear_screen: "ctrlp+p" }),
+ });
+ expect(loaded.bindings.clear_screen).toBe("ctrl+l");
+ expect(loaded.warnings.join(" ")).toContain("invalid key");
+ });
+
+ it("warns when two actions claim one key", () => {
+ const loaded = loadKeybinds({
+ path: "/tmp/unused-keybinds.json",
+ readFile: () => JSON.stringify({ submit: "ctrl+c" }),
+ });
+ expect(loaded.warnings.join(" ")).toMatch(/interrupt and submit/);
+ });
+});
+
+describe("composer frame budget", () => {
+ it("reserves the footer, so the frame never paints over the panel", () => {
+ const foot = ["mode · model", "/repo · ^P commands"];
+ for (const draftRows of [1, 2, 3, 5]) {
+ const { lines, owned } = composeComposerLines({
+ prompt: "> ", draft: Array(draftRows).fill("x"), menu: [], foot, promptWidth: 2,
+ });
+ const { top, visible } = overlayFrame({ lines, menu: [], foot, owned, rows: 24 });
+ expect(owned).toBe(draftRows + foot.length);
+ expect(top + visible.length - 1).toBeLessThanOrEqual(24);
+ }
+ });
+
+ it("keeps only the menu as an overlay, because it is transient", () => {
+ const { owned } = composeComposerLines({
+ prompt: "> ", draft: [""], menu: Array(12).fill("m"), foot: ["f"], promptWidth: 2,
+ });
+ expect(owned).toBe(2);
+ });
+});
+
+describe("terminal width", () => {
+ it("keeps footer rows inside the terminal for wide characters and colours", () => {
+ const colors = { dim: "\x1b[2m", reset: "\x1b[0m", bold: "\x1b[1m", c: "\x1b[36m" };
+ for (const columns of [20, 30, 60, 100]) {
+ const session = {
+ permission: "ask",
+ // Derived from HOME so the fixture is about the shortening rule, not about one machine's paths.
+ cwd: `${process.env.HOME || "/work"}/projects/日本語/クライアント/株式会社サンプル`,
+ usage: { totalTokens: 123_456 },
+ history: [{ role: "user", text: "x".repeat(2000) }],
+ state: { config: { provider: "openai", model: "gpt" }, modelMeta: { context: 200_000 } },
+ };
+ for (const row of footerRows({ session, colors, columns })) {
+ expect(cellWidth(row)).toBeLessThanOrEqual(columns);
+ // A clipped escape sequence would leave a dangling CSI that eats following characters.
+ expect((row.match(/\x1b\[/g) || []).length).toBe((row.match(/\x1b\[[0-9;]*m/g) || []).length);
+ }
+ }
+ });
+});
diff --git a/scripts/mso-agent-runtime.mjs b/scripts/mso-agent-runtime.mjs
index 4fbc70da..a2f904b0 100644
--- a/scripts/mso-agent-runtime.mjs
+++ b/scripts/mso-agent-runtime.mjs
@@ -4,7 +4,7 @@ export { api, apiResponse, state, createCliSession, loadCliSession, resumeCliSes
import { selectToolsForTurn } from "./mso-agent-tool-router.mjs";
import { projectHistoryForModel } from "./mso-agent-context.mjs";
import { C, fit, MSO_TITLE_ART, printAgentBanner } from "./mso-agent-ui.mjs";
-import { AgentApiError } from "./mso-agent-errors.mjs";
+import { AgentApiError, isAgentApiError } from "./mso-agent-errors.mjs";
import { buildMemoryContext } from "../lib/agent/memory-context.mjs";
import { latestIntentText } from "../lib/orchestration/capability-catalog.mjs";
export { C, MSO_TITLE_ART } from "./mso-agent-ui.mjs";
@@ -130,37 +130,67 @@ export async function streamTurn(
stopReason = null,
usage = null;
const toolUses = [];
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buf += dec.decode(value, { stream: true });
- const blocks = buf.split("\n\n");
- buf = blocks.pop() || "";
- for (const block of blocks) {
- let event = "message",
- data = "";
- for (const line of block.split("\n")) {
- if (line.startsWith("event:")) event = line.slice(6).trim();
- else if (line.startsWith("data:")) data += line.slice(5).trim();
- }
- if (!data) continue;
- if (event === "delta") {
- const chunk = JSON.parse(data);
- text += chunk;
- output?.write?.(chunk);
- } else if (event === "tool_use") toolUses.push(JSON.parse(data));
- else if (event === "done") {
- const done = JSON.parse(data);
- stopReason = done?.stopReason ?? null;
- usage = done?.usage ?? null;
- } else if (event === "error") {
- let message = "assistant stream error";
- try { message = String(JSON.parse(data) || message); } catch { message = String(data || message); }
- throw new AgentApiError(message, {
- path: "/api/assistant", method: "POST", requestDispatched: true,
- });
+ // The read loop is wrapped, not just the fetch. A socket that dies mid-stream or a malformed delta used
+ // to escape as a bare TypeError/SyntaxError, which is not an AgentApiError, so no error row was written
+ // and the turn looked like it completed with no output. `reader.cancel` runs in `finally` so an
+ // aborted stream stops billing the provider.
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const blocks = buf.split("\n\n");
+ buf = blocks.pop() || "";
+ for (const block of blocks) {
+ let event = "message",
+ data = "";
+ for (const line of block.split("\n")) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
+ }
+ if (!data) continue;
+ if (event === "delta") {
+ const chunk = JSON.parse(data);
+ // A non-string delta is refused, not coerced: String({}) is "[object Object]" in the transcript.
+ if (typeof chunk !== "string") throw new AgentApiError("assistant sent a non-text delta", {
+ path: "/api/assistant", method: "POST", requestDispatched: true,
+ });
+ text += chunk;
+ output?.write?.(chunk);
+ } else if (event === "tool_use") toolUses.push(JSON.parse(data));
+ else if (event === "done") {
+ const done = JSON.parse(data);
+ stopReason = done?.stopReason ?? null;
+ usage = done?.usage ?? null;
+ } else if (event === "error") {
+ let message = "assistant stream error";
+ try {
+ const payload = JSON.parse(data);
+ message = String(payload?.error ?? payload?.message ?? payload ?? message);
+ } catch { message = String(data || message); }
+ throw new AgentApiError(message, {
+ path: "/api/assistant", method: "POST", requestDispatched: true,
+ });
+ }
}
}
+ } catch (error) {
+ if (isAgentApiError(error)) throw error;
+ // The server's own words beat a bare "terminated": surface the cause when there is one.
+ const detail = error?.cause?.message ? `: ${error.cause.message}` : "";
+ throw new AgentApiError(`assistant stream failed${detail}`, {
+ path: "/api/assistant", method: "POST", requestDispatched: true, cause: error,
+ });
+ } finally {
+ // Releasing the reader is what stops a provider from continuing to generate (and bill) after the
+ // client gave up. Swallow cancel errors: the original failure is the one worth reporting.
+ await reader.cancel?.().catch?.(() => {});
+ }
+ // A closed stream with no `done` event is a truncated answer, not a complete one.
+ if (stopReason === null) {
+ throw new AgentApiError("assistant stream ended before the turn completed", {
+ path: "/api/assistant", method: "POST", requestDispatched: true,
+ });
}
if (text && !text.endsWith("\n")) output?.write?.("\n");
return {
diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjs
index 14b4bffa..65eb71af 100644
--- a/scripts/mso-agent-screen-loop.mjs
+++ b/scripts/mso-agent-screen-loop.mjs
@@ -89,7 +89,14 @@ export function mountScreenLoop({
// because the composer paints relative to the cursor and cannot be told where to begin.
const paint = () => {
if (output?.isTTY !== true) return;
+ // A suspended panel must not paint. Every one of paint's callers is live during a suspension: a
+ // resize, a printed line, and the composer reporting a taller frame all reach here while a child
+ // process or the approval prompt owns the terminal. Painting then wrote the whole frame onto the
+ // NORMAL screen and erased the prompt the user was answering.
+ if (panelSuspend?.isSuspended?.()) return;
const { panel, viewRows, pWidth, transWidth, railWidth, kind } = geometry();
+ // The viewport must clamp against the rows it can actually draw, not the terminal's rows.
+ viewport.viewRows = viewRows;
const body = renderViewport(viewport, { colors, width: transWidth, rows: viewRows });
const side = pWidth > 0 ? paneLines({ kind, session, colors, width: pWidth, rows: viewRows }) : [];
const rail = railWidth > 0 ? tabRailLines(currentSessions(), session?.agentSession?.id, { colors, width: railWidth, rows: viewRows }) : [];
diff --git a/scripts/mso-agent-screen.mjs b/scripts/mso-agent-screen.mjs
index a351cb84..a7e9f6e3 100644
--- a/scripts/mso-agent-screen.mjs
+++ b/scripts/mso-agent-screen.mjs
@@ -155,19 +155,57 @@ export function writeFrameAt(output, previous, next, topRow, columns = output?.c
return nxt;
}
+// Clips a styled line to `max` DISPLAY CELLS, keeping escape sequences.
+//
+// This used to count code points, so a CJK or emoji line reported half its real width and was emitted at
+// up to twice the budget. A line wider than the terminal wraps, and wrapping on the last row scrolls the
+// screen — the one thing the retained frame must never do. The width rule now comes from tui/cells.mjs,
+// the same module the transcript and pane use, so every renderer agrees on what a cell is.
+//
+// Tabs are expanded first: a terminal advances a tab to the next multiple of 8, but every measurement here
+// counted it as one cell, so tab-indented output (code blocks, pasted text) overflowed and scrolled.
+function expandTabs(value) {
+ const text = String(value ?? "");
+ if (!text.includes("\t")) return text;
+ let out = "", col = 0;
+ for (let i = 0; i < text.length;) {
+ const ansi = /^\x1b\[[0-9;?]*[ -/]*[@-~]/.exec(text.slice(i));
+ if (ansi) { out += ansi[0]; i += ansi[0].length; continue; }
+ const ch = text[i];
+ if (ch === "\t") {
+ // Tab stop at the next multiple of 8, which is what the terminal does.
+ const spaces = 8 - (col % 8);
+ out += " ".repeat(spaces);
+ col += spaces;
+ } else {
+ const cp = text.codePointAt(i) ?? 0;
+ const char = String.fromCodePoint(cp);
+ out += char;
+ col += cellWidth(char);
+ i += char.length;
+ continue;
+ }
+ i += 1;
+ }
+ return out;
+}
+
function fitToCells(value, max) {
- const plainText = String(value ?? "");
+ const plainText = expandTabs(value);
if (stripAnsiWidth(plainText) <= max) return plainText;
let out = "", shown = 0;
- for (let i = 0; i < plainText.length;) {
- const ansi = /^\x1b\[[0-9;?]*[ -/]*[@-~]/.exec(plainText.slice(i));
- if (ansi) { out += ansi[0]; i += ansi[0].length; continue; }
- if (shown >= max) { i++; continue; }
- out += plainText[i]; shown += 1; i += 1;
+ // for..of walks CODE POINTS, so a surrogate pair is never split into a lone surrogate.
+ for (const ch of plainText) {
+ const ansi = /^\x1b\[[0-9;?]*[ -/]*[@-~]/.exec(plainText.slice(shown));
+ if (ansi) { out += ansi[0]; continue; }
+ const w = cellWidth(ch);
+ if (shown + w > max) continue;
+ out += ch;
+ shown += w;
}
return out;
}
function stripAnsiWidth(value) {
- return Array.from(String(value ?? "").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "")).length;
+ return cellWidth(value);
}
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index fb3646da..e54c0362 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -28,13 +28,19 @@ function historyContextEstimate(history) {
export function contextStatus(history, modelMeta) {
const limit = Number(modelMeta?.context || 0);
const projected = projectHistoryForModel(history, limit);
+ const stored = historyContextEstimate(history);
+ const hasLimit = Number.isFinite(limit) && limit > 0;
return {
used: projected.estimatedTokens,
- stored: historyContextEstimate(history),
+ stored,
omittedRows: projected.omittedRows,
budget: projected.budgetTokens,
- limit: Number.isFinite(limit) && limit > 0 ? limit : null,
- percent: limit > 0 ? Math.min(999, Math.round((projected.estimatedTokens / limit) * 100)) : null,
+ limit: hasLimit ? limit : null,
+ // Occupancy is measured against the WINDOW, not against the projection budget. The old formula divided
+ // by a budget capped at 120k, so a 200k window could never read above 55%: a session already past the
+ // window was told it was half full. Overflow above 100% is reported as 100%, since "more than full" is
+ // not a percentage. `used` still describes what will actually be sent.
+ percent: hasLimit ? Math.max(0, Math.min(100, Math.round((stored / limit) * 100))) : null,
};
}
diff --git a/scripts/mso-agent-ui.mjs b/scripts/mso-agent-ui.mjs
index 85b03e1f..2616c1f8 100644
--- a/scripts/mso-agent-ui.mjs
+++ b/scripts/mso-agent-ui.mjs
@@ -1,5 +1,6 @@
import process from "node:process";
import { activityText, formatDuration } from "./mso-agent-activity.mjs";
+import { cellWidth, stripAnsi } from "./tui/cells.mjs";
import {
applyTheme,
C,
@@ -70,14 +71,23 @@ export function completedReceipt(calls, elapsedMs) {
]);
}
-function plain(value) { return String(value ?? "").replace(/\x1b\[[0-9;]*m/g, ""); }
-function width(value) { return [...plain(value)].length; }
+function plain(value) { return stripAnsi(value); }
+function width(value) { return cellWidth(value); }
export function fit(value, max) {
const source = plain(value).replace(/[\r\n\t]+/g, " ");
if (max <= 0) return "";
- if ([...source].length <= max) return source;
+ // Measured in CELLS: a CJK character is two columns, so the old code-point count returned a "fitted"
+ // string up to twice the budget and the box row wrapped.
+ if (cellWidth(source) <= max) return source;
if (max <= 1) return "…".slice(0, max);
- return [...source].slice(0, max - 1).join("") + "…";
+ let out = "", used = 0;
+ for (const ch of source) {
+ const w = cellWidth(ch);
+ if (used + w > Math.max(0, max - 1)) break;
+ out += ch;
+ used += w;
+ }
+ return `${out}…`;
}
function pad(value, max) {
const clean = fit(value, max);
@@ -86,7 +96,9 @@ function pad(value, max) {
function rule(char, n) { return char.repeat(Math.max(0, n)); }
function terminalWidth() {
const cols = Number(process.stdout.columns || 104);
- return Math.max(72, Math.min(118, cols - 2));
+ // The old floor of 72 ignored the real width, so on a 60-column terminal every box row was drawn 74
+ // cells wide. The floor exists to keep the banner readable, but readability cannot exceed the screen.
+ return Math.max(24, Math.min(118, cols - 2));
}
function countSkills(data) { return Array.isArray(data?.skills) ? data.skills.length : 0; }
function summarizeInfra(data) {
@@ -125,10 +137,13 @@ function kv(label, value, widthLimit) {
const labelWidth = Math.min(13, Math.max(8, widthLimit > 36 ? 12 : 9));
return `${pad(label, labelWidth)} ${fit(value, Math.max(0, widthLimit - labelWidth - 1))}`;
}
+// Body rows are drawn as "│ " + content + " │", which costs four cells of the two border columns, so the
+// content budget is two cells less than the space between the borders. Padding straight to `inner` made
+// every body row two cells wider than the box above it.
function panelLine(left, right, leftWidth, rightWidth, gap = 3) {
return `│ ${pad(left, leftWidth)}${" ".repeat(gap)}${pad(right, rightWidth)} │`;
}
-function panelSingle(text, inner) { return `│ ${pad(text, inner)} │`; }
+function panelSingle(text, inner) { return `│ ${pad(text, Math.max(0, inner - 2))} │`; }
function panelTitle(title, inner) {
const label = ` ${title} `;
const remaining = Math.max(0, inner - width(label));
@@ -187,7 +202,7 @@ export function printAgentBanner(s, agentSession, { base, version, print = (line
for (const line of lines) print(panelSingle(line, inner));
}
print(`└${rule("─", inner)}┘`);
- print(`${C.dim}${s.tools.length} tools · ${countSkills(s.skills)} skills · /skills · /<skill> · /help${C.reset}`);
+ print(fit(`${C.dim}${s.tools.length} tools · ${countSkills(s.skills)} skills · /skills · /<skill> · /help${C.reset}`, inner));
print();
- print(`${C.bold}Welcome to MSO Agent!${C.reset} Type your message or /help for commands.`);
+ print(fit(`${C.bold}Welcome to MSO Agent!${C.reset} Type your message or /help for commands.`, inner));
}
diff --git a/scripts/mso-agent-viewport.mjs b/scripts/mso-agent-viewport.mjs
index e7dd6710..51c33179 100644
--- a/scripts/mso-agent-viewport.mjs
+++ b/scripts/mso-agent-viewport.mjs
@@ -57,7 +57,10 @@ function enforceCap(viewport) {
} else {
viewport.lines.unshift(dropMarker);
}
- const maxOffset = Math.max(0, getAllLines(viewport).length - viewport.rows);
+ // Clamp against the rows actually RENDERED, which is fewer than the terminal's rows once the panel and
+ // the prompt are subtracted. Using terminal rows here let the offset outrun the window, so a scroll
+ // jumped and /find landed on a line that was not visible.
+ const maxOffset = Math.max(0, getAllLines(viewport).length - (Number(viewport.viewRows) || viewport.rows));
viewport.offset = Math.min(viewport.offset, maxOffset);
}
@@ -70,11 +73,17 @@ export function setLines(viewport, lines) {
for (const item of Array.isArray(lines) ? lines : [lines]) {
for (const part of String(item ?? "").replace(/\r/g, "").split("\n")) flat.push(part);
}
+ // A replaced buffer is a DIFFERENT transcript (a session switch, /clear, or a rebuilt turn), so an old
+ // scroll offset no longer refers to anything. Keeping it opened the next session at its OLDEST lines,
+ // with the newest ones off-screen and no indication why.
+ const previous = viewport.lines;
+ const topBefore = previous.length ? previous[Math.max(0, previous.length - viewport.rows - viewport.offset)] : null;
const wasFollowing = viewport.offset === 0;
+ const overlap = topBefore !== null && flat.includes(topBefore);
viewport.lines = flat;
viewport.droppedCount = 0;
enforceCap(viewport);
- if (wasFollowing) viewport.offset = 0;
+ if (wasFollowing || !overlap) viewport.offset = 0;
}
// Ingests streaming chunks, buffering partial trailing lines without committing them prematurely.
@@ -111,6 +120,9 @@ export function viewportWindow(viewport, rows) {
const maxOffset = total - r;
const clampedOffset = Math.max(0, Math.min(viewport.offset, maxOffset));
+ // Write the clamp back: leaving a stale larger offset let it keep growing on every append, and once the
+ // buffer later fit the window the report said follow:true while the stored offset was still huge.
+ viewport.offset = clampedOffset;
const targetStart = total - r - clampedOffset;
const { start, end } = windowFor(allLines, targetStart + Math.floor(r / 2), r);
return {
@@ -143,15 +155,19 @@ export function handleViewportKey(viewport, key, { rows } = {}) {
viewport.offset = maxOffset;
return true;
}
- if (((key.ctrl && key.shift) && (key.name === "g" || key.name === "G")) || key.name === "end") {
+ if ((key.ctrl && key.shift && (key.name === "g" || key.name === "G")) || key.name === "end") {
viewport.offset = 0;
return true;
}
- if (key.ctrl && key.name === "u") {
+ // Ctrl+U and Ctrl+D are documented EDITING keys (delete to line start, delete right) and the help
+ // screen advertises them. Sharing them with scrolling meant Ctrl+U silently stopped clearing the prompt
+ // as soon as the transcript grew past one screen. Scrolling moved to Alt+U / Alt+D so the two can never
+ // shadow each other again.
+ if (key.alt && (key.name === "u" || key.name === "U")) {
viewport.offset = Math.min(maxOffset, viewport.offset + halfPage);
return true;
}
- if (key.ctrl && key.name === "d") {
+ if (key.alt && (key.name === "d" || key.name === "D")) {
viewport.offset = Math.max(0, viewport.offset - halfPage);
return true;
}
diff --git a/scripts/mso-agent-viewport.test.ts b/scripts/mso-agent-viewport.test.ts
index 1dd383cb..0b9d4e0e 100644
--- a/scripts/mso-agent-viewport.test.ts
+++ b/scripts/mso-agent-viewport.test.ts
@@ -140,11 +140,21 @@ describe("mso-agent-viewport", () => {
expect(handleViewportKey(vp, { ctrl: true, shift: true, name: "g" }, { rows: 10 })).toBe(true);
expect(vp.offset).toBe(0);
- expect(handleViewportKey(vp, { ctrl: true, name: "u" }, { rows: 10 })).toBe(true);
+ // Scrolling moved to Alt+U / Alt+D because Ctrl+U and Ctrl+D are documented line-editing keys: sharing
+ // them meant Ctrl+U stopped clearing the prompt once the transcript filled a screen. The composer owns
+ // Ctrl+U/Ctrl+D now, so the viewport must NOT consume them.
+ expect(handleViewportKey(vp, { ctrl: true, name: "u" }, { rows: 10 })).toBe(false);
+ expect(vp.offset).toBe(0);
+
+ expect(handleViewportKey(vp, { alt: true, name: "u" }, { rows: 10 })).toBe(true);
expect(vp.offset).toBe(5);
- expect(handleViewportKey(vp, { ctrl: true, name: "d" }, { rows: 10 })).toBe(true);
+ expect(handleViewportKey(vp, { alt: true, name: "d" }, { rows: 10 })).toBe(true);
expect(vp.offset).toBe(0);
+
+ expect(handleViewportKey(vp, { ctrl: true, name: "d" }, { rows: 10 })).toBe(false);
+ // And the keys must still not scroll when the buffer is short, which is the other half of the same bug.
+ expect(handleViewportKey(vp, { alt: true, name: "u" }, { rows: 60 })).toBe(true);
});
it("8. a resize from 30 rows to 8 rows keeps the buffer intact and the offset clamped", () => {
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 68ec1115..1031c370 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -12,6 +12,7 @@ import { takeCommandRequest } from "./mso-agent-command-dialog.mjs";
import { createPromptCompletion } from "./mso-agent-prompt-completion.mjs"; import { pluginToolFilter, resolveMentions } from "./mso-agent-at.mjs";
import { nextPermissionMode, permissionMode } from "./mso-agent-permissions.mjs";
import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-lifecycle.mjs";
+import { failRun, finishRun } from "./mso-agent-exit.mjs";
import { oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";
import { LocalAgentBridge, handleLocalAgentMentionInput, runForegroundSubagent } from "./mso-agent-collaboration.mjs";
import { composerPrompt, composerSeparator } from "./mso-agent-layout.mjs"; import { footerRows } from "./mso-agent-footer.mjs";
@@ -32,7 +33,13 @@ async function main() {
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) { process.stdout.write(`${oneShotHelp()}\n`); return; }
const oneShot = parseOneShot(argv);
- if (oneShot) return runOneShot(oneShot);
+ if (oneShot) {
+ // The exit code has to carry the outcome: a caller scripting `mso agent --oneshot` reads the status,
+ // not the prose. A failed run used to exit 0.
+ const ok = await runOneShot(oneShot);
+ if (ok === false) process.exitCode = 3;
+ return;
+ }
if (!process.stdin.isTTY || !process.stdout.isTTY) {
console.error("mso agent needs an interactive terminal. For autonomous one-shot use: mso agent --oneshot \"<prompt>\" [--json]");
process.exit(2);
@@ -205,17 +212,14 @@ async function main() {
} finally {
if (onSigint) process.off("SIGINT", onSigint);
if (session) await persistSession(session).catch(() => undefined);
- const sessionTitle = String(session?.agentSession?.title || "MSO Agent session").replace(/[\r\n\t]+/g, " ").trim().slice(0, 80);
- if (!restartRequested && session) console.log(`${C.dim}session ${sessionTitle} · resume: mso --continue · switch: /sessions${C.reset}`);
- if (localBridge) await localBridge.close({ ended: !restartRequested }).catch(() => undefined);
- rl?.close();
- screenLoop?.dispose();
- screen?.dispose();
- }
- if (restartRequested) {
- console.log(`${C.dim}↻ refreshing Agent runtime · keeping ${session.agentSession.title || "current session"}${C.reset}`);
- relaunchCurrentAgentSession(session);
+ const next = await finishRun({
+ session, restartRequested, localBridge, colors: C,
+ closeComposer: () => rl?.close(),
+ disposePanel: () => screenLoop?.dispose(),
+ disposeScreen: () => screen?.dispose(),
+ });
+ if (next === "restart") relaunchCurrentAgentSession(session);
}
}
-if (Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href) main().catch((error) => { console.error(`${C.err}mso agent: ${error instanceof Error ? error.message : String(error)}${C.reset}`); process.exit(1); });
+if (Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href) main().catch((error) => failRun(error, { colors: C }));