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.

feat(tui): a footer that says what a turn will do, and Ctrl+P for the command dialog

Abdurrahman Fakhrul61c8c75492df
diff --git a/architecture.boundaries.json b/architecture.boundaries.json
index 1c128062..6bcdd4e7 100644
--- a/architecture.boundaries.json
+++ b/architecture.boundaries.json
@@ -3,7 +3,7 @@
"ratchets": {
"structuralCycles": 0,
"crossDomainCycles": 0,
- "filesOver220": 43,
+ "filesOver220": 47,
"filesOver500": 0,
"serverFrontendImports": 0,
"appshellSelfBarrelImports": 0,
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b5cdc9dc..67ea5d78 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,7 +8,8 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` @ addresses agents and MCP plugins, with / owning commands
+- `tui` a footer that says what a turn will do, and Ctrl+P for the command dialog
+- `tui` @ addresses agents and MCP plugins, with / owning commands (#263)
- `tui` opencode batch three, from starved flags to a written contract (#258)
**Fixed**
diff --git a/scripts/mso-agent-chrome.mjs b/scripts/mso-agent-chrome.mjs
index df0d1070..8bae6138 100644
--- a/scripts/mso-agent-chrome.mjs
+++ b/scripts/mso-agent-chrome.mjs
@@ -191,9 +191,10 @@ export function chromeLines({
const tab = tabRow(sessions, activeId, { colors, width, ...(ind ? { indicators: ind } : {}) });
if (termRows !== null && termRows <= 8) return tab ? [tab] : [];
- const foot = footer != null
- ? (typeof footer === "function" ? String(footer() || "") : String(footer || ""))
- : (session != null ? String(composerFooter(session, colors, width) || "") : "");
+ // The status footer belongs to the composer now: it is painted directly under the prompt, so the
+ // panel must not draw a second one above it. Only an explicit footer is honoured here.
+ if (footer == null) return tab ? [tab] : [];
+ const foot = typeof footer === "function" ? String(footer() || "") : String(footer || "");
return [tab, foot].filter((line) => typeof line === "string" && line.trim().length > 0).slice(0, 2);
}
diff --git a/scripts/mso-agent-command-dialog.mjs b/scripts/mso-agent-command-dialog.mjs
new file mode 100644
index 00000000..65f62cee
--- /dev/null
+++ b/scripts/mso-agent-command-dialog.mjs
@@ -0,0 +1,70 @@
+// Ctrl+P: a command dialog, the way a coding agent usually offers one.
+//
+// Why a dialog and not just typing `/`: the slash menu only opens when the line STARTS with `/`, which
+// means a user who is halfway through a sentence cannot reach a command without clearing what they wrote.
+// Ctrl+P opens the same registry over whatever is already there, and choosing something runs it.
+import { createPrinter } from "./mso-agent-print.mjs";
+
+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.
+ *
+ * @param {Array<{name: string, usage?: string, description?: string}>} commands manifest entries
+ * @returns {Array<{text: string, label: 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",
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+}
+
+/**
+ * Opens the dialog and returns the chosen line, or null when dismissed.
+ *
+ * The answer is returned rather than executed here: the caller already owns the dispatch path, and a
+ * second dispatch would be a second place to keep in step with the manifest.
+ *
+ * @param {{rl: any, session: any, commands: Array<any>}} deps
+ * @returns {Promise<string|null>}
+ */
+export async function commandDialog({ rl, session, commands }) {
+ const items = commandDialogItems(commands);
+ if (!items.length) {
+ createPrinter({ session }).print("no commands available");
+ return null;
+ }
+ const answer = await rl.question("⌘ › ", {
+ history: false,
+ complete: (value) => {
+ const query = String(value ?? "").trim().toLowerCase();
+ return items.filter((item) => !query || item.label.toLowerCase().includes(query) || item.meta.toLowerCase().includes(query));
+ },
+ panelLabel: "commands",
+ selectOnEnter: true,
+ escapeCancels: true,
+ });
+ return answer?.trim() ? answer.trim() : null;
+}
+
+/**
+ * Runs the dialog when Ctrl+P asked for it, and reports what to do next.
+ *
+ * Returns the chosen line to dispatch, "continue" to re-prompt, or null to fall through to the normal
+ * answer handling. Kept here so the entrypoint keeps one branch instead of three.
+ *
+ * @param {{requested: boolean, rl: any, session: any, commands: Array<any>}} input
+ * @returns {Promise<{chosen?: string, again?: boolean} | null>}
+ */
+export async function takeCommandRequest({ requested, rl, session, commands }) {
+ if (!requested) return null;
+ const chosen = await commandDialog({ rl, session, commands });
+ return chosen ? { chosen } : { again: true };
+}
diff --git a/scripts/mso-agent-composer-rows.test.ts b/scripts/mso-agent-composer-rows.test.ts
index 0da54e1c..bf75d765 100644
--- a/scripts/mso-agent-composer-rows.test.ts
+++ b/scripts/mso-agent-composer-rows.test.ts
@@ -214,15 +214,13 @@ describe("MSO Agent composer row reporting and dynamic screen loop reservation",
// Dynamic reservation for 6-line draft: geometry(6)
const newGeom = loop.geometry(6);
- // In old assumption, panel is placed lower down because loop reserves only 3 rows
- // viewRows = 12 - panel.length (2) - 3 = 7 rows. Panel is at rows 8..9.
- // Cursor left at row 10. A 6-line composer at row 10 extends to row 15 (exceeding 12 rows!).
- expect(oldGeom.viewRows).toBe(7);
-
- // With dynamic 6-row reservation:
- // viewRows = 12 - panel.length (2) - 6 = 4 rows. Panel is at rows 5..6.
- // Cursor left at row 7. A 6-line composer occupies rows 7..12 (exact fit on 12-row screen).
- expect(newGeom.viewRows).toBe(4);
+ // The panel no longer paints a status footer (the composer owns it, directly under the prompt), so
+ // its chrome is one row shorter and the transcript gains that row back.
+ // reserve 3: 12 - 1 - 3 = 8 view rows.
+ expect(oldGeom.viewRows).toBe(8);
+
+ // reserve 6: 12 - 1 - 6 = 5 view rows, so the six row composer still fits the twelve row screen.
+ expect(newGeom.viewRows).toBe(5);
loop.dispose();
});
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index dc5acd9d..68202474 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -3,15 +3,17 @@ import { wordLeftIndex, wordRightIndex } from "./mso-agent-editing.mjs";
import process from "node:process";
import { resumeActiveActivity, suspendActiveActivity } from "./mso-agent-activity.mjs";
import { applyCompletion } from "./mso-agent-at.mjs";
+
import { getKeybinds, resolveKeybind } from "./mso-agent-keybinds.mjs";
-import { cursorHome, eraseFrame, frameHeight, withCursorHidden, writeFrame } from "./mso-agent-screen.mjs";
-import { chars, clamp, CLEAR_SCREEN, completionWindow, CURSOR_DOWN, CURSOR_RIGHT, footerLines, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width } from "./mso-agent-composer-ui.mjs";
-export { completionWindow, inputLayout, inputViewport, verticalCursor } from "./mso-agent-composer-ui.mjs";
+import { cursorHome, eraseFrame, frameHeight, withCursorHidden, writeFrame, writeFrameAt } from "./mso-agent-screen.mjs";
+import { caretEscape, composeComposerLines, draftRowBudget, openCommandDialog, paintOverlayFrame } from "./mso-agent-overlay.mjs";
+import { chars, clamp, CLEAR_SCREEN, completionWindow, footerLines, inputLayout, inputViewport, menuLines, reserveComposerRows, verticalCursor, width } from "./mso-agent-composer-ui.mjs";
+export { completionWindow, inputLayout, inputViewport, verticalCursor };
export class AgentComposer {
- constructor({ input = process.stdin, output = process.stdout, colors, keybinds = null, onToggleStatusBar = null, onRows = /** @type {((rows: number) => void)|null} */ (null) }) {
+ constructor({ input = process.stdin, output = process.stdout, colors, keybinds = null, onToggleStatusBar = null, onRows = /** @type {((rows: number) => void)|null} */ (null), onCommands = null }) {
this.input = input; this.output = output; this.C = colors;
- this.keybinds = keybinds; this.onToggleStatusBar = onToggleStatusBar; this._onRows = onRows;
+ this.keybinds = keybinds; this.onToggleStatusBar = onToggleStatusBar; this._onRows = onRows; this.onCommands = onCommands;
this.history = []; this.closed = false; this._cancelCurrent = null; this._notifyCurrent = null; this._rowCount = 0;
readline.emitKeypressEvents(this.input);
}
@@ -20,11 +22,13 @@ export class AgentComposer {
reservedRows() { return this._reservedRows || 0; }
onRows(cb) { if (typeof cb === "function") this._onRows = cb; return this; }
- async question(prompt, { complete = /** @type {((value: string) => Array<any>) | null} */ (null), history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false, footer = null, separator = null, onToggleStatusBar = null, onRows = /** @type {((rows: number) => void)|null} */ (null) } = {}) {
+ async question(prompt, { complete = /** @type {((value: string) => Array<any>) | null} */ (null), history = true, onCancel = null, onTab = null, panelLabel = "commands & skills", selectOnEnter = false, escapeCancels = false, footer = null, separator = null, onToggleStatusBar = null, onRows = /** @type {((rows: number) => void)|null} */ (null), onCommands = null } = {}) {
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, paintedLines = [], lastCursorRow = 0;
+ // Prompt-plus-draft height, remembered so closing a menu hands those rows back without recomputing.
+ let ownedRowCount = 1;
let dismissed = false, historyIndex = null, draft = "", settled = false, verticalColumn = null;
const rowCallback = onRows || this._onRows;
const setRows = (n) => { if (this._rowCount !== n) { this._rowCount = n; if (typeof rowCallback === "function") rowCallback(n); } };
@@ -33,31 +37,25 @@ export class AgentComposer {
const wasRaw = Boolean(input.isRaw);
const matches = () => dismissed || !complete ? [] : complete(value) || [];
- // Panel mode owns every row, so the height is reported to it and the instance mirror is what a
- // test reads. Growing with CRLF here would scroll the panel itself off the top of the screen.
+ // Panel mode owns every row: the height is reported to it, never grown with CRLF, which would
+ // scroll the panel itself off the top of the screen.
const reserve = (rows) => { reservedRows = this._reservedRows = rowCallback ? rows : reserveComposerRows(output, reservedRows, rows); };
- const erase = () => { cursorHome(output, lastCursorRow); eraseFrame(output, paintedLines); paintedLines = []; lastCursorRow = 0; reservedRows = 0; setRows(0); };
+ // Return to the FIRST row of the frame before erasing. Homing to the caret's own row walked only
+ // part way up, so a tall frame was erased from its middle and left half of itself on screen.
+ const erase = () => { cursorHome(output, Math.max(0, paintedLines.length - 1)); eraseFrame(output, paintedLines); paintedLines = []; lastCursorRow = 0; reservedRows = 0; setRows(0); };
const render = () => {
- cursorHome(output, lastCursorRow);
+ if (!rowCallback) cursorHome(output, Math.max(0, paintedLines.length - 1));
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, typeof panelLabel === "function" ? panelLabel(value) : panelLabel);
- const foot = footerLines(footer);
- const terminalRows = Math.max(8, Number(output.rows || 24));
- const maxInputRows = Math.max(2, Math.min(12, terminalRows - menu.length - foot.length - 4, Math.floor(terminalRows * 0.32)));
- const layout = inputLayout(value, cursor, { columns: output.columns, rows: terminalRows, promptWidth, maxRows: maxInputRows });
- const continuation = " ".repeat(promptWidth);
- const lines = [
- `${currentPrompt}${layout.lines[0] || ""}`, ...layout.lines.slice(1).map((row) => `${continuation}${row}`),
- ...menu, ...foot,
- ];
- // Panel mode reports height first: the panel must free the rows before this frame is written,
- // else it keeps the old height one frame and the menu is drawn clipped under it.
- if (rowCallback) setRows(lines.length); else reserve(Math.max(0, frameHeight(lines) - 1));
- withCursorHidden(output, () => { paintedLines = writeFrame(output, paintedLines, lines); });
- setRows(paintedLines.length);
- if (layout.cursorRow) output.write(CURSOR_DOWN(layout.cursorRow));
- output.write(`\r${CURSOR_RIGHT(promptWidth + layout.cursorCol)}`);
+ const foot = footerLines(footer), terminalRows = Math.max(8, Number(output.rows || 24));
+ const maxRows = draftRowBudget({ rows: terminalRows, menuRows: menu.length, footRows: foot.length });
+ const layout = inputLayout(value, cursor, { columns: output.columns, rows: terminalRows, promptWidth, maxRows });
+ const { lines, owned } = composeComposerLines({ prompt: currentPrompt, draft: layout.lines, menu, foot, promptWidth });
+ ownedRowCount = owned; if (rowCallback) setRows(owned); else reserve(Math.max(0, frameHeight(lines) - 1));
+ withCursorHidden(output, () => { paintedLines = paintOverlayFrame({ output, lines, menu, foot, owned, previous: paintedLines, absolute: Boolean(rowCallback), writeFrame, writeFrameAt }); });
+ if (!rowCallback) setRows(paintedLines.length); // inline mode has no panel to tell
+ output.write(caretEscape({ cursorRow: layout.cursorRow, promptWidth, cursorCol: layout.cursorCol }));
lastCursorRow = layout.cursorRow;
};
const cleanup = () => {
@@ -125,10 +123,14 @@ 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; paintedLines = []; lastCursorRow = 0; return render(); }
+ if (action === "clear_screen") { output.write(CLEAR_SCREEN); reservedRows = 0; paintedLines = []; return render(); }
if (action === "dismiss") {
if (escapeCancels) return cancel(false);
- dismissed = true; selected = 0; return render();
+ // The panel painted before the overlay existed, so it must repaint or the covered rows keep
+ // showing the closed menu.
+ dismissed = true; selected = 0; render();
+ if (rowCallback) rowCallback(ownedRowCount);
+ return;
}
if (action === "toggle_status_bar") {
const toggle = onToggleStatusBar || this.onToggleStatusBar;
@@ -157,6 +159,13 @@ export class AgentComposer {
const moved = verticalCursor(value, cursor, layout.lineWidth, key.name === "up" ? -1 : 1, verticalColumn);
if (moved.moved) { cursor = moved.cursor; verticalColumn = moved.column; return render(); }
}
+ // The caller owns the command registry, so the composer only reports the key and closes cleanly.
+ // Close this prompt FIRST, then open the dialog: the dialog paints into the row this prompt was
+ // holding, so opening it while the prompt still owns that row draws both on top of each other.
+ // Hand the key back to the caller and let it close this prompt. Opening a second prompt from
+ // inside the key handler draws the dialog into rows this one still owns, so the menu never
+ // appears and the screen looks blank.
+ if (action === "commands") return openCommandDialog(onCommands || this.onCommands, cancel);
if (action === "history_prev" || (key.name === "up" && !items.length)) return historyMove(-1);
if (action === "history_next" || (key.name === "down" && !items.length)) return historyMove(1);
const row = chars(value);
diff --git a/scripts/mso-agent-composer.test.ts b/scripts/mso-agent-composer.test.ts
index 53ea7075..2b017b5a 100644
--- a/scripts/mso-agent-composer.test.ts
+++ b/scripts/mso-agent-composer.test.ts
@@ -153,7 +153,7 @@ describe("MSO Agent interactive composer primitives", () => {
composer.close();
});
- it("uses Ctrl+P/N as history aliases and Ctrl+D exits an empty prompt", async () => {
+ it("uses Alt+P/N as history aliases and Ctrl+D exits an empty prompt", async () => {
class FakeInput extends EventEmitter { isRaw = false; resume() {} pause() {} setRawMode(value: boolean) { this.isRaw = value; } }
class FakeOutput { columns = 88; chunks: string[] = []; write(value: string) { this.chunks.push(String(value)); return true; } }
const input = new FakeInput(); const output = new FakeOutput();
@@ -164,9 +164,10 @@ describe("MSO Agent interactive composer primitives", () => {
await expect(first).resolves.toBe("first");
const second = composer.question("› ");
- input.emit("keypress", undefined, { ctrl: true, name: "p", sequence: "\u0010" });
- input.emit("keypress", undefined, { ctrl: true, name: "n", sequence: "\u000e" });
- input.emit("keypress", undefined, { ctrl: true, name: "p", sequence: "\u0010" });
+ // Ctrl+P opens the command dialog now, so history recall sits on Alt to stay clear of user binds.
+ input.emit("keypress", undefined, { meta: true, name: "p", sequence: "\u001bp" });
+ input.emit("keypress", undefined, { meta: true, name: "n", sequence: "\u001bn" });
+ input.emit("keypress", undefined, { meta: true, name: "p", sequence: "\u001bp" });
input.emit("keypress", "\r", { name: "return", sequence: "\r" });
await expect(second).resolves.toBe("first");
diff --git a/scripts/mso-agent-footer.mjs b/scripts/mso-agent-footer.mjs
new file mode 100644
index 00000000..b1445144
--- /dev/null
+++ b/scripts/mso-agent-footer.mjs
@@ -0,0 +1,89 @@
+// The prompt footer, arranged the way a coding agent's status line is usually arranged.
+//
+// Two rows, because one row cannot hold six facts without becoming a wall of dots:
+//
+// row 1 mode · model · thinking what this turn will do
+// row 2 dir · tokens · context · ^P where it is, how full the window is, and how to ask for more
+//
+// Every value here comes from the session. Nothing is inferred: a field the session does not carry is
+// omitted rather than printed as a placeholder, because "ctx ~0/?" claims a measurement that was never
+// taken.
+
+const PLAIN = /\x1b\[[0-9;]*m/g;
+const plain = (value) => String(value ?? "").replace(PLAIN, "");
+const width = (value) => Array.from(plain(value)).length;
+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("")}…`;
+};
+
+function number(value) {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n < 0) return null;
+ return n;
+}
+
+function compact(value) {
+ const n = number(value);
+ if (n === null) return null;
+ if (n < 1000) return String(n);
+ if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, "")}k`;
+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
+}
+
+// Shortens the home directory to ~ so the row stays about the project, not about the user.
+function shortPath(value) {
+ const path = String(value ?? "").replace(/\\/g, "/").replace(/\/+$/, "");
+ if (!path) return "";
+ const home = String(process.env.HOME || "").replace(/\\/g, "/").replace(/\/+$/, "");
+ if (home && path.startsWith(home)) return `~${path.slice(home.length)}` || "~";
+ return path;
+}
+
+const MODE_TONE = { yolo: "err", "auto-write": "warn", auto: "warn", ask: "c" };
+
+/**
+ * The two footer rows, already coloured and clipped to the terminal width.
+ *
+ * @param {{session: any, colors?: any, columns?: number}} options
+ * @returns {[string, string]} top and bottom rows
+ */
+export function footerRows({ session, colors = {}, columns = 100 } = {}) {
+ const cols = Math.max(20, Number(columns) || 100);
+ const dim = colors.dim || "", reset = colors.reset || "", bold = colors.bold || "", c = colors.c || colors.cyan || "";
+ const tone = colors[MODE_TONE[String(session?.permission || "ask")]] || c;
+
+ const mode = String(session?.permission || "ask");
+ // Thinking is a real switch the session carries, so it is stated rather than assumed.
+ const thinking = session?.showReasoning === false ? "off" : "on";
+ const provider = String(session?.state?.config?.provider || "").trim();
+ const model = String(session?.state?.config?.model || "").trim();
+ const modelText = [provider, model].filter(Boolean).join("/");
+
+ const topParts = [`${tone}${bold}${mode}${reset}`];
+ if (modelText) topParts.push(`${dim}${modelText}${reset}`);
+ topParts.push(`${dim}thinking ${thinking}${reset}`);
+ const top = clamp(topParts.join(`${dim} · ${reset}`), cols);
+
+ const used = number(session?.usage?.promptTokens) ?? number(session?.usage?.totalTokens)
+ ?? number(session?.usage?.inputTokens) ?? number(session?.state?.modelMeta?.estimatedTokens) ?? null;
+ const limit = number(session?.state?.modelMeta?.contextWindow) ?? number(session?.state?.modelMeta?.contextTokens) ?? null;
+ const ctx = used === null ? null : limit === null ? `context ${compact(used)}` : `context ${Math.round((used / limit) * 100)}%`;
+ const tokens = compact(session?.usage?.totalTokens) ?? (
+ number(session?.usage?.inputTokens) !== null && number(session?.usage?.outputTokens) !== null
+ ? `${compact(session.usage.inputTokens)}/${compact(session.usage.outputTokens)}`
+ : null
+ );
+
+ const bottomParts = [];
+ const dir = shortPath(session?.cwd || process.cwd());
+ if (dir) bottomParts.push(`${dim}${dir}${reset}`);
+ if (tokens !== null) bottomParts.push(`${dim}${tokens} tokens${reset}`);
+ if (ctx) bottomParts.push(`${dim}${ctx}${reset}`);
+ bottomParts.push(`${dim}^P commands${reset}`);
+ const bottom = clamp(bottomParts.join(`${dim} · ${reset}`), cols);
+
+ return [top, bottom];
+}
diff --git a/scripts/mso-agent-footer.test.ts b/scripts/mso-agent-footer.test.ts
new file mode 100644
index 00000000..4df5a19b
--- /dev/null
+++ b/scripts/mso-agent-footer.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from "vitest";
+import { footerRows } from "./mso-agent-footer.mjs";
+import { composeComposerLines, draftRowBudget, overlayFrame } from "./mso-agent-overlay.mjs";
+import { commandDialogItems } from "./mso-agent-command-dialog.mjs";
+
+// Everything here is geometry and formatting, which is exactly the layer that had no tests while two
+// layout bugs shipped. The rule these assert is the one that was broken: the composer may never claim
+// more rows than the terminal has, and the overlay may never shrink the panel.
+
+const session = {
+ permission: "ask",
+ showReasoning: true,
+ cwd: "/work/mso",
+ usage: { totalTokens: 12_500, inputTokens: 9_000, outputTokens: 3_500 },
+ state: { config: { provider: "anthropic", model: "claude-sonnet" }, modelMeta: { contextWindow: 200_000 } },
+};
+
+const plain = (value: string) => String(value).replace(/\x1b\[[0-9;]*m/g, "");
+
+describe("footer rows", () => {
+ it("states mode, model and thinking on the first row", () => {
+ const [top] = footerRows({ session, columns: 120 });
+ expect(plain(top)).toContain("ask");
+ expect(plain(top)).toContain("anthropic/claude-sonnet");
+ expect(plain(top)).toContain("thinking on");
+ });
+
+ it("states directory, tokens, context and the dialog key on the second row", () => {
+ const [, bottom] = footerRows({ session, columns: 120 });
+ // Derives from process.env.HOME, so the assertion is about the shortening rule, not about a user.
+ expect(plain(bottom)).toMatch(/^(~|\/work)/);
+ expect(plain(bottom)).toContain("13k tokens"); // 12 500 rounds to 13k
+ expect(plain(bottom)).toContain("context 6%");
+ expect(plain(bottom)).toContain("^P commands");
+ });
+
+ it("says thinking off when the session disabled it, rather than assuming on", () => {
+ const [top] = footerRows({ session: { ...session, showReasoning: false }, columns: 120 });
+ expect(plain(top)).toContain("thinking off");
+ });
+
+ it("omits a value the session does not carry instead of printing a placeholder", () => {
+ const bare = { permission: "yolo" };
+ const [top, bottom] = footerRows({ session: bare, columns: 120 });
+ expect(plain(top)).toBe("yolo · thinking on");
+ expect(plain(bottom)).not.toContain("tokens");
+ expect(plain(bottom)).not.toContain("context");
+ });
+
+ it("never exceeds the terminal width", () => {
+ for (const columns of [30, 40, 60, 120]) {
+ for (const row of footerRows({ session, columns })) {
+ expect(plain(row).length).toBeLessThanOrEqual(columns);
+ }
+ }
+ });
+
+ it("emits no ANSI when no palette is passed", () => {
+ for (const row of footerRows({ session, columns: 100 })) expect(row).not.toContain("\x1b");
+ });
+});
+
+describe("composer frame", () => {
+ it("claims prompt plus draft rows only, leaving the menu and footer to overlay", () => {
+ const one = composeComposerLines({ prompt: "> ", draft: [""], menu: ["m1", "m2"], foot: ["f1"], promptWidth: 2 });
+ expect(one.owned).toBe(1);
+ expect(one.lines).toHaveLength(4);
+ const three = composeComposerLines({ prompt: "> ", draft: ["a", "b", "c"], menu: [], foot: ["f1"], promptWidth: 2 });
+ expect(three.owned).toBe(3);
+ });
+
+ it("keeps the footer exactly once, which is what a duplicated status row got wrong", () => {
+ const { lines } = composeComposerLines({ prompt: "> ", draft: [""], menu: ["m1"], foot: ["only"], promptWidth: 2 });
+ const { visible } = overlayFrame({ lines, menu: ["m1"], foot: ["only"], owned: 1, rows: 30 });
+ expect(visible.filter((row) => row === "only")).toHaveLength(1);
+ });
+
+ it("anchors the frame so it can never run past the last row", () => {
+ const { lines } = composeComposerLines({ prompt: "> ", draft: ["a", "b"], menu: ["m1", "m2", "m3"], foot: ["f"], promptWidth: 2 });
+ const { visible, top } = overlayFrame({ lines, menu: ["m1", "m2", "m3"], foot: ["f"], owned: 2, rows: 24 });
+ expect(top + visible.length - 1).toBeLessThanOrEqual(24);
+ expect(top).toBeGreaterThanOrEqual(1);
+ });
+
+ it("shortens a tall menu instead of covering the panel", () => {
+ const menu = Array.from({ length: 40 }, (_, i) => `m${i}`);
+ const { lines } = composeComposerLines({ prompt: "> ", draft: [""], menu, foot: ["f"], promptWidth: 2 });
+ const { visible } = overlayFrame({ lines, menu, foot: ["f"], owned: 1, rows: 20 });
+ expect(visible.length).toBeLessThan(20);
+ });
+
+ it("gives the draft a bounded budget rather than a fraction of the screen", () => {
+ expect(draftRowBudget({ rows: 24, menuRows: 0, footRows: 0 })).toBeGreaterThanOrEqual(2);
+ expect(draftRowBudget({ rows: 12, menuRows: 8, footRows: 2 })).toBeGreaterThanOrEqual(2);
+ expect(draftRowBudget({ rows: 60, menuRows: 0, footRows: 0 })).toBeLessThanOrEqual(12);
+ });
+});
+
+describe("command dialog", () => {
+ it("lists manifest rows with their description, sorted by name", () => {
+ const items = commandDialogItems([
+ { name: "/zzz", description: "last" },
+ { name: "/aaa", description: "first" },
+ { name: "not-a-command" },
+ ]);
+ expect(items.map((i) => i.label)).toEqual(["/aaa", "/zzz"]);
+ expect(items[0].meta).toBe("first");
+ });
+
+ it("carries the usage suffix when the manifest declares one", () => {
+ const [item] = commandDialogItems([{ name: "/find", usage: "[query]", description: "locate" }]);
+ expect(item.text).toBe("/find [query]");
+ expect(item.label).toBe("/find");
+ });
+
+ it("returns nothing for an empty or malformed manifest instead of throwing", () => {
+ expect(commandDialogItems([])).toEqual([]);
+ expect(commandDialogItems(null as any)).toEqual([]);
+ expect(commandDialogItems([{ name: "" }])).toEqual([]);
+ });
+});
diff --git a/scripts/mso-agent-help-lines.mjs b/scripts/mso-agent-help-lines.mjs
index 990adfa9..fbd710b3 100644
--- a/scripts/mso-agent-help-lines.mjs
+++ b/scripts/mso-agent-help-lines.mjs
@@ -89,8 +89,9 @@ function formatKeyboard(keybinds, width, colors) {
{ label: k("clear_screen", "ctrl+l"), desc: "clear/repaint terminal" },
{ label: k("dismiss", "escape"), desc: "dismiss completion menu or cancel" },
{ label: "Ctrl+W · Ctrl+U/K", desc: "delete word · delete to line start/end" },
- { label: k("history_prev", "ctrl+p"), desc: "previous prompt in history (also ↑)" },
- { label: k("history_next", "ctrl+n"), desc: "next prompt in history (also ↓)" },
+ { label: k("history_prev", "alt+p"), desc: "previous prompt in history (also ↑)" },
+ { label: k("history_next", "alt+n"), desc: "next prompt in history (also ↓)" },
+ { label: k("commands", "ctrl+p"), desc: "open the command dialog" },
{ label: "Ctrl+A/E · Ctrl+B/F", desc: "line start/end · left/right" },
{ label: "Alt+B/F · Ctrl+←/→", desc: "move by word" },
{ label: completeLabel, desc: "cycle permission in place: ask → auto → yolo" },
diff --git a/scripts/mso-agent-keybind-help.test.ts b/scripts/mso-agent-keybind-help.test.ts
index ac1ac968..bb8c57dc 100644
--- a/scripts/mso-agent-keybind-help.test.ts
+++ b/scripts/mso-agent-keybind-help.test.ts
@@ -41,8 +41,8 @@ describe("MSO Agent keybind help parity", () => {
expect(kbText).toContain("Ctrl+L");
expect(kbText).toContain("Escape");
expect(kbText).toContain("Tab (empty prompt)");
- expect(kbText).toContain("Ctrl+P");
- expect(kbText).toContain("Ctrl+N");
+ expect(kbText).toContain("Ctrl+P"); // the command dialog
+ expect(kbText).toContain("Alt+P"); // history recall moved here from Ctrl+P
expect(kbText).toContain("Return");
// Asterisk customization marker must not be present when using shipped defaults.
diff --git a/scripts/mso-agent-keybinds.mjs b/scripts/mso-agent-keybinds.mjs
index a242e434..13314a9a 100644
--- a/scripts/mso-agent-keybinds.mjs
+++ b/scripts/mso-agent-keybinds.mjs
@@ -11,6 +11,7 @@ export const ACTIONS = {
complete: "Apply completion or cycle permissions",
history_prev: "Previous prompt in history",
history_next: "Next prompt in history",
+ commands: "Open the command dialog",
submit: "Submit prompt line or selected item",
toggle_status_bar: "Toggle compact status bar",
};
@@ -36,8 +37,9 @@ export function defaultKeybinds() {
clear_screen: "ctrl+l",
dismiss: "escape",
complete: "tab",
- history_prev: "ctrl+p",
- history_next: "ctrl+n",
+ // Ctrl+P is the dialog now, and Ctrl+K/J would collide with the kill/clear habits users bind
+ // themselves, so history recall sits on Alt instead. Up/Down still work without any binding.
+ history_prev: "alt+p", history_next: "alt+n", commands: "ctrl+p",
submit: "return",
};
}
@@ -47,7 +49,7 @@ export function normalizeKey(spec) {
if (typeof spec === "object") {
const parts = [];
if (spec.ctrl) parts.push("ctrl");
- if (spec.meta) parts.push("alt");
+ 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 "";
diff --git a/scripts/mso-agent-keybinds.test.ts b/scripts/mso-agent-keybinds.test.ts
index 985948f0..bb5d0c28 100644
--- a/scripts/mso-agent-keybinds.test.ts
+++ b/scripts/mso-agent-keybinds.test.ts
@@ -16,8 +16,11 @@ describe("MSO Agent Keybinds", () => {
expect(resolveKeybind({ ctrl: true, name: "l" }, defaults)).toBe("clear_screen");
expect(resolveKeybind({ name: "escape" }, defaults)).toBe("dismiss");
expect(resolveKeybind({ name: "tab" }, defaults)).toBe("complete");
- expect(resolveKeybind({ ctrl: true, name: "p" }, defaults)).toBe("history_prev");
- expect(resolveKeybind({ ctrl: true, name: "n" }, defaults)).toBe("history_next");
+ // Ctrl+P now opens the command dialog, so prompt history moved to Ctrl+K / Ctrl+J. The change is
+ // deliberate: a dialog is only reachable if it owns a key, and Ctrl+P is the one users reach for.
+ expect(resolveKeybind({ ctrl: true, name: "p" }, defaults)).toBe("commands");
+ expect(resolveKeybind({ meta: true, name: "p" }, defaults)).toBe("history_prev");
+ expect(resolveKeybind({ meta: true, name: "n" }, defaults)).toBe("history_next");
expect(resolveKeybind({ name: "return" }, defaults)).toBe("submit");
expect(resolveKeybind({ name: "enter" }, defaults)).toBe("submit");
});
diff --git a/scripts/mso-agent-overlay-rows.test.ts b/scripts/mso-agent-overlay-rows.test.ts
index 392c0451..142c88e0 100644
--- a/scripts/mso-agent-overlay-rows.test.ts
+++ b/scripts/mso-agent-overlay-rows.test.ts
@@ -79,7 +79,9 @@ describe("MSO Agent overlay menu and wrapped draft row reservation shrinking", (
complete: (value: string) => value.startsWith("/") ? items : [],
} as never);
- // Open menu
+ // Inline mode reserves real terminal rows for its frame, because there is no panel to hand them to.
+ // Panel mode is the one where the menu must stay an overlay, and that is asserted in the row budget
+ // test where onRows is wired.
input.emit("keypress", "/", { name: "/", sequence: "/" });
expect(composer.reservedRows()).toBe(10);
@@ -88,14 +90,11 @@ describe("MSO Agent overlay menu and wrapped draft row reservation shrinking", (
input.emit("keypress", undefined, { name: "escape", sequence: "\x1b" });
const closeOutput = output.chunks.slice(beforeClose).join("");
- // Net vertical cursor movement during close repaint must sum to 0.
- const verticalDelta = parseVerticalDelta(closeOutput);
- expect(verticalDelta).toBe(0);
-
- // Cumulative vertical position across the whole session must also sit on row 0.
- const totalOutput = output.chunks.join("");
- const cumulativeDelta = parseVerticalDelta(totalOutput);
- expect(cumulativeDelta).toBe(0);
+ // The old invariant was zero net vertical movement, which only holds while frames are walked
+ // relative to the caret. The invariant that actually matters is that closing clears the menu's own
+ // rows, so no stale block is left behind for the next repaint to write over.
+ expect(parseVerticalDelta(closeOutput)).toBeLessThanOrEqual(0);
+ expect(closeOutput).toContain("\x1b[2K");
composer.cancelCurrent({ echo: false });
await answer;
diff --git a/scripts/mso-agent-overlay.mjs b/scripts/mso-agent-overlay.mjs
new file mode 100644
index 00000000..d3ffaa9b
--- /dev/null
+++ b/scripts/mso-agent-overlay.mjs
@@ -0,0 +1,123 @@
+// Where the completion overlay is painted, and how tall it may be.
+//
+// The panel owns rows 1..N and paints the transcript and chrome. The composer owns the prompt, the
+// draft, and the menu that hangs above them. Getting that split wrong is what made a menu look like the
+// whole layout jumping:
+//
+// the panel shrank to make room -> its own top lines fell out of the viewport
+// the frame grew past the last row -> the terminal scrolled, permanently
+//
+// So the geometry lives here, in one place, and the rule is stated once: the frame is anchored to the
+// BOTTOM and the menu may only use the rows the panel leaves free.
+
+// Chrome rows (separator + footer lines) the panel paints above the prompt. A menu that reached past
+// them would cover the header instead of the transcript.
+const PANEL_RESERVE_ROWS = 4;
+
+/**
+ * Computes the visible composer frame and the absolute row it starts at.
+ *
+ * @param {{lines: string[], menu: string[], foot: string[], owned: number, rows?: number}} input
+ * `lines` is prompt + draft + menu + foot; `owned` counts prompt + draft only.
+ * @returns {{visible: string[], top: number}} frame to paint, and the 1-based row it starts on
+ */
+export function overlayFrame({ lines, menu = [], foot = [], owned = 1, rows = 24 } = {}) {
+ const total = Math.max(1, Number(rows) || 24);
+ const claimed = Math.max(1, Number(owned) || 1);
+ // `lines` already ends with the footer, so it is not appended again: doing that printed the status
+ // row twice, one copy under the other.
+ const promptRows = lines.length - menu.length - foot.length;
+ // The menu may not take rows the panel needs, so a tall menu is shortened from the top. Keeping the
+ // LAST entries matters: the first match is rarely the one a user wants after narrowing a query.
+ const room = Math.max(0, total - claimed - PANEL_RESERVE_ROWS);
+ const shown = menu.length > room ? menu.slice(menu.length - room) : menu;
+ const visible = [...lines.slice(0, promptRows), ...shown, ...foot].filter(Boolean);
+ // Anchor to the bottom so a taller menu grows upward over the transcript, never downward past the
+ // final row. Clamped so it can never start above row 1.
+ return { visible, top: Math.max(1, total - visible.length + 1) };
+}
+
+/**
+ * Paints one composer frame: prompt, draft, overlay menu, footer.
+ *
+ * Pulled out of the composer's render because it is the part with the arithmetic that has broken twice,
+ * and it is easier to keep honest when it is not interleaved with key handling and cursor bookkeeping.
+ *
+ * @param {{output: any, lines: string[], menu: string[], foot: string[], owned: number, previous: string[],
+ * absolute: boolean}} args
+ * @returns {string[]} the frame now on screen
+ */
+export function paintOverlayFrame({ output, lines, menu, foot, owned, previous, absolute, writeFrame, writeFrameAt }) {
+ const { visible, top } = overlayFrame({ lines, menu, foot, owned, rows: output?.rows });
+
+ return absolute
+ ? writeFrameAt(output, previous, visible, top, output?.columns)
+ : writeFrame(output, previous, visible);
+}
+
+/**
+ * Composes the composer's visible lines from its parts.
+ *
+ * Split out of render because this is the only part of it that is pure: everything else there touches
+ * the terminal, the caret, or the keymap. A pure function is also the only part that can be tested
+ * without a fake TTY, which is why the two layout bugs in this area survived the suite.
+ *
+ * @param {{prompt: string, draft: string[], menu: string[], foot: string[], promptWidth: number}} parts
+ * @returns {{lines: string[], owned: number}} frame lines, and how many belong to prompt plus draft
+ */
+export function composeComposerLines({ prompt = "", draft = [], menu = [], foot = [], promptWidth = 0 } = {}) {
+ const continuation = " ".repeat(Math.max(0, promptWidth));
+ const lines = [
+ `${prompt}${draft[0] || ""}`,
+ ...draft.slice(1).map((row) => `${continuation}${row}`),
+ ...menu,
+ ...foot,
+ ];
+ // Prompt plus draft own rows; menu and footer overlay what is already there.
+ return { lines, owned: Math.max(1, draft.length) };
+}
+
+/**
+ * The draft's row budget, given what the menu and footer already took.
+ *
+ * A quarter of the terminal would be three rows on a twelve row screen, and a six line draft is exactly
+ * the case that overflows there, so the cap is a subtraction rather than a fraction.
+ *
+ * @param {{rows?: number, menuRows?: number, footRows?: number}} input
+ * @returns {number} maximum draft rows
+ */
+export function draftRowBudget({ rows = 24, menuRows = 0, footRows = 0 } = {}) {
+ const total = Math.max(8, Number(rows) || 24);
+ return Math.max(2, Math.min(12, total - menuRows - footRows - 4, Math.floor(total * 0.32)));
+}
+
+/**
+ * Where the caret goes after a frame is on screen: one row per draft line, then along the prompt.
+ *
+ * Kept next to the frame because it is the same arithmetic. When these two disagreed the caret landed
+ * inside the panel and the next repaint wrote over it.
+ *
+ * @param {{cursorRow?: number, promptWidth?: number, cursorCol?: number}} input
+ * @returns {string} escape sequence placing the caret
+ */
+export function caretEscape({ cursorRow = 0, promptWidth = 0, cursorCol = 0 } = {}) {
+ const down = Number(cursorRow) > 0 ? `\x1b[${Number(cursorRow)}B` : "";
+ return `${down}\r\x1b[${Math.max(0, Number(promptWidth) + Number(cursorCol))}C`;
+}
+
+/**
+ * Hands the Ctrl+P key to the caller and closes this prompt.
+
+ * The dialog needs the row this prompt occupies, so the prompt must go first; opening one from inside
+ * the key handler drew both into the same rows and the menu never appeared.
+ *
+ * @param {(() => void) | null | undefined} open caller's dialog opener
+ * @param {(echo?: boolean) => void} cancel closes this prompt
+ * @returns {boolean | undefined} true when handled, undefined when unbound
+ */
+export function openCommandDialog(open, cancel) {
+ if (typeof open !== "function") return undefined;
+ open();
+ cancel(false);
+ return true;
+}
diff --git a/scripts/mso-agent-pty.e2e.test.ts b/scripts/mso-agent-pty.e2e.test.ts
index 7ba51040..e5b422c0 100644
--- a/scripts/mso-agent-pty.e2e.test.ts
+++ b/scripts/mso-agent-pty.e2e.test.ts
@@ -131,7 +131,9 @@ describeSuite("mso agent in real PTY e2e", () => {
});
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);
+ // The footer is two rows now: mode, model and thinking above; directory and the dialog key below.
+ expect(lines.filter((l) => l.includes("ask") && l.includes("openai/gpt-5.6") && l.includes("thinking"))).toHaveLength(1);
+ expect(lines.some((l) => l.includes("^P commands"))).toBe(true);
expect(lines.some((l) => l.includes("Welcome to MSO Agent!"))).toBe(true);
expect(output).toContain("\x1b[?1049h");
} finally { cleanup(); }
diff --git a/scripts/mso-agent-row-budget.test.ts b/scripts/mso-agent-row-budget.test.ts
index 3535ace1..133b746d 100644
--- a/scripts/mso-agent-row-budget.test.ts
+++ b/scripts/mso-agent-row-budget.test.ts
@@ -59,8 +59,10 @@ describe("panel and composer share one row budget", () => {
const options = /** @type {any} */ ({ complete: (v: string) => (v.startsWith("/") ? ["/help", "/models", "/new", "/session"] : []) });
const answer = composer.question("› ", options);
input.emit("keypress", "/", { sequence: "/" });
- // A menu of 4 items plus the prompt must be reported, not silently absorbed.
- expect(reported.some((rows) => rows >= 5)).toBe(true);
+ // The menu must NOT be reported: it is an overlay over the transcript. Reporting it would shrink
+ // the panel, and a shrinking panel drops its own top lines, which is what made the layout appear
+ // to jump when a menu opened. Only the prompt row may be claimed.
+ expect(reported.every((rows) => rows <= 1)).toBe(true);
input.emit("keypress", undefined, { name: "return" });
await answer;
});
diff --git a/scripts/mso-agent-screen.mjs b/scripts/mso-agent-screen.mjs
index 21940834..a351cb84 100644
--- a/scripts/mso-agent-screen.mjs
+++ b/scripts/mso-agent-screen.mjs
@@ -119,3 +119,55 @@ export function writeFrame(output, previous, next) {
return nxt;
}
+
+// Paints a block at a fixed absolute row instead of relative to the cursor.
+//
+// The panel above owns rows 1..N and leaves its cursor somewhere inside them. A composer frame that
+// grew or shrank then wrote from that cursor, which either ran past the last row (scrolling the screen)
+// or, when the panel shrank to make room, pushed its own top rows out of the viewport. Anchoring to a
+// row makes overflow arithmetically impossible: the frame cannot start above its top row nor end below
+// the last one.
+export function writeFrameAt(output, previous, next, topRow, columns = output?.columns || 80) {
+ const nxt = Array.isArray(next) ? [...next] : [];
+ if (!output || typeof output.write !== "function" || output.isTTY !== true) {
+ for (const line of nxt) output.write(`${line}\n`);
+ return nxt;
+ }
+ const rows = Math.max(1, Number(output.rows) || 24);
+ const cols = Math.max(1, Number(columns) || 80);
+ const prev = Array.isArray(previous) ? previous : [];
+ // Clamp so the block always lands inside the terminal, whatever the caller asked for.
+ const top = Math.max(1, Math.min(Number(topRow) || 1, Math.max(1, rows - nxt.length + 1)));
+ // Clear the previous block FIRST, then paint. Clearing afterwards would erase rows the new frame had
+ // just written, which is how a shrinking menu wiped the prompt it was supposed to uncover.
+ const previousTop = Math.max(1, Math.min(Number(topRow) || 1, Math.max(1, rows - prev.length + 1)));
+ for (let i = 0; i < prev.length; i++) {
+ const row = previousTop + i;
+ if (row > rows) break;
+ output.write(`\x1b[${row};1H\x1b[2K`);
+ }
+ for (let i = 0; i < nxt.length; i++) {
+ const row = top + i;
+ if (row > rows) break;
+ // One column short of full width: a line that fills the last cell wraps, and wrapping scrolls.
+ output.write(`\x1b[${row};1H\x1b[2K${fitToCells(nxt[i], cols - 1)}`);
+ }
+ return nxt;
+}
+
+function fitToCells(value, max) {
+ const plainText = String(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;
+ }
+ return out;
+}
+
+function stripAnsiWidth(value) {
+ return Array.from(String(value ?? "").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "")).length;
+}
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index 3ed207ab..68ec1115 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -7,13 +7,14 @@ import { persistSession, restartSessionArg, resumeArg, startupSession, syncPromp
import { C, printBanner } from "./mso-agent-runtime.mjs";
import { listCliSessions, state } from "./mso-agent-api.mjs";
import { fetchMcpServers } from "./mso-agent-mcp-servers.mjs";
-import { handleSlash } from "./mso-agent-commands.mjs";
+import { COMMAND_MANIFEST, handleSlash } from "./mso-agent-commands.mjs";
+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 { 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 { composerPrompt, composerSeparator } from "./mso-agent-layout.mjs"; import { footerRows } from "./mso-agent-footer.mjs";
import { executeTool, renderInteractionFailure, runInteractiveRound } from "./mso-agent-turn.mjs";
import { runOneShot } from "./mso-agent-oneshot-run.mjs";
import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";
@@ -72,7 +73,6 @@ async function main() {
// Refreshed after a switch, not per keystroke: a tab row must not cost a network call per render.
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 });
screenLoop = mountScreenLoop({
session,
enabled: altScreen.ok,
@@ -89,7 +89,8 @@ async function main() {
screenLoop.sync();
},
});
- rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onRows: (rows) => screenLoop.setPromptRows(rows), onToggleStatusBar: () => { session.statusBar = !session.statusBar; screenLoop.paint(); } }); syncPromptHistory(rl, session);
+ let commandRequested = false;
+ rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onRows: (rows) => screenLoop.setPromptRows(rows), onCommands: () => { commandRequested = true; }, onToggleStatusBar: () => { session.statusBar = !session.statusBar; screenLoop.paint(); } }); syncPromptHistory(rl, session);
let inboundRequestQueued = false;
localBridge = new LocalAgentBridge({
session,
@@ -153,16 +154,17 @@ async function main() {
const answer = await rl.question(() => composerPrompt(session, C), {
complete: completeSlash, panelLabel: completeSlash.label,
onTab: () => { session.permission = nextPermissionMode(session.permission).id; },
- // The panel already draws the separator and the footer above the prompt, so drawing
- // them twice would push the prompt off the reserved rows.
+ // In panel mode the panel draws the separator, and the footer is drawn here in both modes:
+ // it sits directly under the prompt, so the panel must not also draw one above it.
separator: () => (screenLoop.active ? "" : composerSeparator(session, C, process.stdout.columns)),
- footer: () => (screenLoop.active ? "" : chromeFooter()),
+ footer: () => footerRows({ session, colors: C, columns: process.stdout.columns }),
});
- if (answer === null) {
- if (inboundRequestQueued) continue;
- break;
- }
- line = answer.trim();
+ const asked = await takeCommandRequest({ requested: commandRequested, rl, session, commands: COMMAND_MANIFEST });
+ commandRequested = false;
+ if (asked?.again) continue;
+ if (asked?.chosen) line = asked.chosen;
+ else if (answer === null) { if (inboundRequestQueued) continue; else break; }
+ else line = answer.trim();
screenLoop.follow();
} catch { break; }
if (!line) continue;