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): let the composer reservation shrink, so Esc really closes the menu (#223)

Abdurrahman Fakhrulda623e1a96f4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 9b0e0871..2c4998cf 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -14,6 +14,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `tui` let the composer reservation shrink, so Esc really closes the menu
- `tui` stop the panel erasing the slash menu, and keep the banner ASCII art (#221)
- `security` validate the model half of a provider/model ref
- `security` read only .message from a caught error, never stringify it
diff --git a/scripts/mso-agent-composer-ui.mjs b/scripts/mso-agent-composer-ui.mjs
index 662cbcc2..3f5167fc 100644
--- a/scripts/mso-agent-composer-ui.mjs
+++ b/scripts/mso-agent-composer-ui.mjs
@@ -25,11 +25,23 @@ export const width = (value) => chars(plain(value)).length;
export const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
export function reserveComposerRows(output, reservedRows, rows) {
- if (rows <= reservedRows) return reservedRows;
- if (reservedRows) output.write(CURSOR_DOWN(reservedRows));
- for (let i = reservedRows; i < rows; i++) output.write("\r\n");
- output.write(`${CURSOR_UP(rows)}\r`);
- return rows;
+ const current = Math.max(0, Number(reservedRows) || 0);
+ const target = Math.max(0, Number(rows) || 0);
+ if (target === current) return current;
+ if (!output || typeof output.write !== "function") return target;
+ if (target > current) {
+ if (current) output.write(CURSOR_DOWN(current));
+ for (let i = current; i < target; i++) output.write("\r\n");
+ output.write(`${CURSOR_UP(target)}\r`);
+ return target;
+ }
+ // Shrink symmetrically. Moving down to the OLD extent and clearing upward releases the rows the
+ // frame no longer uses. Without this a closed completion menu left its rows reserved forever, so
+ // the prompt never moved back up and a gap sat above it.
+ if (current) output.write(CURSOR_DOWN(current));
+ for (let i = current; i > target; i--) output.write(`\r${CLEAR_LINE}${CURSOR_UP(1)}`);
+ output.write(`${CURSOR_UP(target)}\r`);
+ return target;
}
export function eraseComposerRows(output, reservedRows) {
diff --git a/scripts/mso-agent-composer.mjs b/scripts/mso-agent-composer.mjs
index 3f300a0d..6f18f4c4 100644
--- a/scripts/mso-agent-composer.mjs
+++ b/scripts/mso-agent-composer.mjs
@@ -16,6 +16,7 @@ export class AgentComposer {
}
rowCount() { return this._rowCount; }
+ reservedRows() { return this._reservedRows || 0; }
onRows(cb) { if (typeof cb === "function") this._onRows = cb; return this; }
async question(prompt, { complete = 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) } = {}) {
@@ -33,7 +34,9 @@ export class AgentComposer {
const matches = () => dismissed || !complete ? [] : complete(value) || [];
// Reserve physical rows only when the frame grows. Redraws diff row-by-row in place
// without emitting LF/CRLF, keeping terminal scrollback clean.
- const reserve = (rows) => { reservedRows = reserveComposerRows(output, reservedRows, rows); };
+ // Mirrored on the instance so a test can assert the reservation came back down after an overlay
+ // closes; otherwise the shrink is only visible as terminal side effects.
+ const reserve = (rows) => { reservedRows = this._reservedRows = reserveComposerRows(output, reservedRows, rows); };
const erase = () => { cursorHome(output, lastCursorRow); eraseFrame(output, paintedLines); paintedLines = []; lastCursorRow = 0; reservedRows = 0; setRows(0); };
const render = () => {
cursorHome(output, lastCursorRow);
diff --git a/scripts/mso-agent-overlay-rows.test.ts b/scripts/mso-agent-overlay-rows.test.ts
new file mode 100644
index 00000000..392c0451
--- /dev/null
+++ b/scripts/mso-agent-overlay-rows.test.ts
@@ -0,0 +1,171 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vitest";
+import { AgentComposer } from "./mso-agent-composer.mjs";
+import { reserveComposerRows } from "./mso-agent-composer-ui.mjs";
+
+class FakeInput extends EventEmitter {
+ isRaw = false;
+ resume() {}
+ pause() {}
+ setRawMode(value: boolean) { this.isRaw = value; }
+}
+
+class FakeOutput extends EventEmitter {
+ isTTY = true;
+ columns = 80;
+ rows = 24;
+ chunks: string[] = [];
+ write(value: string) {
+ this.chunks.push(String(value));
+ return true;
+ }
+}
+
+// Parses ANSI cursor movement sequences to determine net vertical row delta.
+function parseVerticalDelta(outputStream: string): number {
+ let delta = 0;
+ const regex = /\x1b\[(\d+)([AB])|\r?\n/g;
+ let match: RegExpExecArray | null;
+ while ((match = regex.exec(outputStream)) !== null) {
+ if (match[2] === "A") delta -= Number(match[1]);
+ else if (match[2] === "B") delta += Number(match[1]);
+ else delta += 1;
+ }
+ return delta;
+}
+
+describe("MSO Agent overlay menu and wrapped draft row reservation shrinking", () => {
+ it("open the menu (12 items), render, close it, render: the reserved row count returns to the original value", async () => {
+ const input = new FakeInput();
+ const output = new FakeOutput();
+ const colors = { blue: "", bold: "", reset: "", dim: "", warn: "", c: "", cyan: "", err: "" };
+ const items = Array.from({ length: 12 }, (_, i) => ({ text: `/cmd${i}`, meta: `help ${i}` }));
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });
+
+ const answer = composer.question("› ", {
+ complete: (value: string) => value.startsWith("/") ? items : [],
+ } as never);
+
+ // Initial state before opening completion menu
+ expect(composer.reservedRows()).toBe(0);
+
+ // Typing slash triggers complete() with 12 items. completionWindow caps visible items to 8,
+ // plus top and bottom borders, producing 10 menu lines below the 1-line draft (total 11 lines).
+ input.emit("keypress", "/", { name: "/", sequence: "/" });
+ expect(composer.reservedRows()).toBe(10);
+
+ // Esc dismisses the completion overlay. Reserved rows must shrink back to 0 instead of ratcheting.
+ input.emit("keypress", undefined, { name: "escape", sequence: "\x1b" });
+ expect(composer.reservedRows()).toBe(0);
+
+ // Direct reserveComposerRows check confirms symmetric return value contract.
+ const directOutput = new FakeOutput();
+ expect(reserveComposerRows(directOutput, 0, 10)).toBe(10);
+ expect(reserveComposerRows(directOutput, 10, 0)).toBe(0);
+
+ composer.cancelCurrent({ echo: false });
+ await answer;
+ composer.close();
+ });
+
+ it("after closing, the total emitted cursor movement leaves the cursor on the same row it started on", async () => {
+ const input = new FakeInput();
+ const output = new FakeOutput();
+ const colors = { blue: "", bold: "", reset: "", dim: "", warn: "", c: "", cyan: "", err: "" };
+ const items = Array.from({ length: 12 }, (_, i) => ({ text: `/cmd${i}`, meta: `help ${i}` }));
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });
+
+ const answer = composer.question("› ", {
+ complete: (value: string) => value.startsWith("/") ? items : [],
+ } as never);
+
+ // Open menu
+ input.emit("keypress", "/", { name: "/", sequence: "/" });
+ expect(composer.reservedRows()).toBe(10);
+
+ // Capture output specifically during the close action
+ const beforeClose = output.chunks.length;
+ 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);
+
+ composer.cancelCurrent({ echo: false });
+ await answer;
+ composer.close();
+ });
+
+ it("typing a wrapped draft that grows the frame, then backspacing to one line, also shrinks the reservation back", async () => {
+ const input = new FakeInput();
+ const output = new FakeOutput();
+ output.columns = 20; // lineWidth is 16 with prompt "› "
+ const colors = { blue: "", bold: "", reset: "", dim: "", warn: "", c: "", cyan: "", err: "" };
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });
+
+ const answer = composer.question("› ");
+ expect(composer.reservedRows()).toBe(0);
+
+ // Type 35 chars to wrap across 3 lines: row 0 (16 chars), row 1 (16 chars), row 2 (3 chars).
+ for (const ch of "a".repeat(35)) input.emit("keypress", ch, { name: ch, sequence: ch });
+ expect(composer.reservedRows()).toBe(2);
+
+ // Backspace 30 characters to return to 5 characters on a single visual row.
+ for (let i = 0; i < 30; i++) {
+ input.emit("keypress", undefined, { name: "backspace", sequence: "\x7f" });
+ }
+ expect(composer.reservedRows()).toBe(0);
+
+ composer.cancelCurrent({ echo: false });
+ await answer;
+ composer.close();
+ });
+
+ it("no newline is emitted during any of the above repaints", async () => {
+ const input = new FakeInput();
+ const output = new FakeOutput();
+ output.columns = 20;
+ const colors = { blue: "", bold: "", reset: "", dim: "", warn: "", c: "", cyan: "", err: "" };
+ const items = Array.from({ length: 12 }, (_, i) => ({ text: `/cmd${i}`, meta: `help ${i}` }));
+ const composer = new AgentComposer({ input: input as never, output: output as never, colors });
+
+ const answer = composer.question("› ", {
+ complete: (value: string) => value.startsWith("/") ? items : [],
+ } as never);
+
+ // Initial render is done. Now open menu.
+ input.emit("keypress", "/", { name: "/", sequence: "/" });
+
+ // Close menu: repaint must NOT emit any newline characters.
+ const beforeClose = output.chunks.length;
+ input.emit("keypress", undefined, { name: "escape", sequence: "\x1b" });
+ const closeWrites = output.chunks.slice(beforeClose).join("");
+ expect(closeWrites).not.toContain("\n");
+
+ // Grow draft by typing wrapped text.
+ for (const ch of "z".repeat(35)) input.emit("keypress", ch, { name: ch, sequence: ch });
+
+ // Shrink draft by backspacing: in-place repaint must NOT emit any newline characters.
+ const beforeBackspace = output.chunks.length;
+ for (let i = 0; i < 30; i++) {
+ input.emit("keypress", undefined, { name: "backspace", sequence: "\x7f" });
+ }
+ const backspaceWrites = output.chunks.slice(beforeBackspace).join("");
+ expect(backspaceWrites).not.toContain("\n");
+
+ // Direct shrink reservation call must also never emit newlines.
+ const directOutput = new FakeOutput();
+ reserveComposerRows(directOutput, 12, 0);
+ expect(directOutput.chunks.join("")).not.toContain("\n");
+
+ composer.cancelCurrent({ echo: false });
+ await answer;
+ composer.close();
+ });
+});