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): mid-turn writes go into the panel, and prompts suspend it instead of fighting it (#204)

Abdurrahman Fakhrulac5ef88a2e30
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b02cbcbd..f467e187 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` the composer reports its height, so the panel stops guessing how much to reserve
+- `tui` mid-turn writes go into the panel, and prompts suspend it instead of fighting it
+- `tui` the composer reports its height, so the panel stops guessing how much to reserve (#203)
- `tui` one print sink, so command output lands in the panel instead of on top of it (#202)
- `tui` a right-hand side pane for todos, the last diff and changed files (#198)
- `tui` mouse wheel scrolling and tab clicks, only inside the alternate screen (#197)
diff --git a/scripts/mso-agent-approval-ui.mjs b/scripts/mso-agent-approval-ui.mjs
index d7137897..6ee806d0 100644
--- a/scripts/mso-agent-approval-ui.mjs
+++ b/scripts/mso-agent-approval-ui.mjs
@@ -1,3 +1,5 @@
+import { withPanelSuspended } from "./mso-agent-turn-print.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;
@@ -53,19 +55,22 @@ export function approvalDetailLines(tool, input, approval) {
];
}
-export async function requestExactToolApproval(rl, { tool, input = {}, approval, onCancel = null, signal = null, colors = {}, print = console.log }) {
- let focused = false;
- const dim = colors.dim || "", reset = colors.reset || "", blue = colors.blue || "", bold = colors.bold || "";
- const status = () => `${blue}${bold}${approvalStatusLine(tool, input, focused)}${reset}${dim} · Tab focus · Enter details${reset} `;
- const opened = await rl.question(status, {
- history: false,
- onCancel,
- onTab: () => { focused = true; },
+export async function requestExactToolApproval(rl, { tool, input = {}, approval, onCancel = null, signal = null, colors = {}, print = console.log, screenLoop = null }) {
+ const loop = screenLoop || rl?.screenLoop;
+ return withPanelSuspended(loop, async () => {
+ let focused = false;
+ const dim = colors.dim || "", reset = colors.reset || "", blue = colors.blue || "", bold = colors.bold || "";
+ const status = () => `${blue}${bold}${approvalStatusLine(tool, input, focused)}${reset}${dim} · Tab focus · Enter details${reset} `;
+ const opened = await rl.question(status, {
+ history: false,
+ onCancel,
+ onTab: () => { focused = true; },
+ });
+ if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
+ if (opened === null) return false;
+ for (const line of approvalDetailLines(tool, input, approval)) print(line);
+ const decision = String(await rl.question(" decision [allow/deny] › ", { history: false, onCancel }) ?? "").trim().toLowerCase();
+ if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
+ return decision === "allow";
});
- if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
- if (opened === null) return false;
- for (const line of approvalDetailLines(tool, input, approval)) print(line);
- const decision = String(await rl.question(" decision [allow/deny] › ", { history: false, onCancel }) ?? "").trim().toLowerCase();
- if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");
- return decision === "allow";
}
diff --git a/scripts/mso-agent-input-hook.mjs b/scripts/mso-agent-input-hook.mjs
new file mode 100644
index 00000000..881346f3
--- /dev/null
+++ b/scripts/mso-agent-input-hook.mjs
@@ -0,0 +1,44 @@
+import { parseMouseChunk } from "./mso-agent-mouse.mjs";
+
+// readline emits keypress on stdin and the composer is one of its listeners, so consuming a scroll
+// key or a mouse sequence before the composer acts on it needs interception, and adding an option
+// 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;
+ if (typeof originalEmit !== "function") return { dispose() {} };
+
+ const consumeMouse = (payload) => {
+ const events = parseMouseChunk(payload);
+ if (!events.length) return false;
+ for (const event of events) onMouse(event);
+ return true;
+ };
+
+ input.emit = function patchedEmit(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");
+ }
+ }
+ }
+ if (event === "keypress") {
+ const sequence = args[1]?.sequence || (typeof args[0] === "string" ? args[0] : "");
+ if (typeof sequence === "string" && sequence.startsWith("\x1b[<") && consumeMouse(sequence)) return true;
+ if (args[1] && onKey(args[1])) return true;
+ }
+ return Reflect.apply(originalEmit, this, [event, ...args]);
+ };
+
+ return {
+ dispose() {
+ input.emit = originalEmit;
+ },
+ };
+}
diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjs
index d3415274..2f32b715 100644
--- a/scripts/mso-agent-screen-loop.mjs
+++ b/scripts/mso-agent-screen-loop.mjs
@@ -1,7 +1,8 @@
import process from "node:process";
import { chromeLines, tabAtPoint } from "./mso-agent-chrome.mjs";
import { composerSeparator } from "./mso-agent-layout.mjs";
-import { disableMouse, enableMouse, handleMouse, parseMouseChunk } from "./mso-agent-mouse.mjs";
+import { disableMouse, enableMouse, handleMouse } from "./mso-agent-mouse.mjs";
+import { installInputHook } from "./mso-agent-input-hook.mjs";
import { writeFrame } from "./mso-agent-screen.mjs";
import { transcriptLines } from "./mso-agent-transcript.mjs";
import { appendStream, commitStream, createViewport, handleViewportKey, resetFollow, setLines } from "./mso-agent-viewport.mjs";
@@ -38,8 +39,11 @@ export function mountScreenLoop({
if (!enabled || !session) {
return {
active: false,
+ session: null,
paint() {},
sync() {},
+ suspend() {},
+ resume() {},
follow() {},
geometry() { return { cols: 80, rows: 24, panel: [], viewRows: 0, tabRowY: 0, pWidth: 0, transWidth: 80, kind: null, promptRows: PROMPT_ROWS }; },
setPromptRows() {},
@@ -58,13 +62,12 @@ export function mountScreenLoop({
const viewport = createViewport({ rows: output.rows || 24 });
let painted = [];
- let keysPatched = false;
- let originalEmit = null;
let promptReservation = PROMPT_ROWS;
+ let savedSink = null;
const setPromptRows = (rows) => {
- // When the composer reports its painted row count, clamp it so the panel
- // never jumps on erase (0) and never gets pushed off screen by tall drafts.
+ // When the composer reports its painted row count, clamp it so the panel never jumps on erase
+ // and never gets pushed off screen by a tall draft.
const termRows = Math.max(6, Number(output.rows) || 24);
const clamped = clampPromptRows(rows, termRows);
if (clamped !== promptReservation) {
@@ -77,9 +80,7 @@ export function mountScreenLoop({
if (typeof composer.onRows === "function") composer.onRows(setPromptRows);
else composer.onRows = setPromptRows;
}
- if (session) {
- session.onComposerRows = setPromptRows;
- }
+ session.onComposerRows = setPromptRows;
const geometry = (reservation = promptReservation) => {
const cols = Math.max(20, Number(output.columns) || 80);
@@ -152,63 +153,63 @@ export function mountScreenLoop({
return false;
};
- // readline emits keypress on stdin, and the composer is one of its listeners. Intercepting emit
- // is the only way to consume keys and mouse sequences before the composer acts on them without
- // growing the composer, which sits at its line ceiling.
- originalEmit = input.emit;
- if (typeof originalEmit === "function") {
- keysPatched = true;
- input.emit = function patchedEmit(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 > 0) {
- for (const ev of events) dispatchMouse(ev);
- 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");
- }
- }
- }
- if (event === "keypress") {
- const seq = args[1]?.sequence || (typeof args[0] === "string" ? args[0] : "");
- if (typeof seq === "string" && seq.startsWith("\x1b[<")) {
- const events = parseMouseChunk(seq);
- if (events.length > 0) {
- for (const ev of events) dispatchMouse(ev);
- return true;
- }
- }
- if (args[1] && handleViewportKey(viewport, args[1], { rows: geometry().viewRows })) {
- paint();
- return true;
- }
- }
- return Reflect.apply(originalEmit, this, [event, ...args]);
- };
- }
+ // A line oriented prompt needs the terminal to itself, so the sink is detached for the duration
+ // and the panel repaints afterwards. Building an in-panel input mode would mean a second
+ // implementation of the composer's key handling.
+ const suspend = () => {
+ if (!session.streamSink) return;
+ savedSink = session.streamSink;
+ delete session.streamSink;
+ };
+ const resume = () => {
+ if (savedSink) {
+ session.streamSink = savedSink;
+ savedSink = null;
+ }
+ paint();
+ };
+
+ const hook = installInputHook({
+ input,
+ onKey: (key) => {
+ if (!handleViewportKey(viewport, key, { rows: geometry().viewRows })) return false;
+ paint();
+ return true;
+ },
+ onMouse: (event) => dispatchMouse(event),
+ });
setLines(viewport, transcriptLines(session, { colors, width: geometry().transWidth }));
paint();
- return {
+ const loop = {
active: true,
+ session,
paint,
sync,
+ suspend,
+ resume,
follow: () => resetFollow(viewport),
geometry,
setPromptRows,
dispose() {
["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => detach(process, sig, onTeardown));
output.off?.("resize", onResize);
- if (keysPatched) input.emit = originalEmit;
+ hook.dispose();
disableMouse(output);
if (session.streamSink) delete session.streamSink;
if (session.onComposerRows) delete session.onComposerRows;
+ if (session.screenLoop) delete session.screenLoop;
// The panel owns the whole screen, so the inline transcript is repainted once on the way out
// instead of leaving the alternate buffer's last frame on screen.
painted = [];
},
};
+ // An approval raised deep inside a tool call has to find the panel without a new parameter
+ // threaded through every layer, so the loop announces itself on the session. dispose clears it.
+ session.screenLoop = loop;
+ return loop;
}
+
+export function suspendScreenLoop(loop) { loop?.suspend?.(); }
+export function resumeScreenLoop(loop) { loop?.resume?.(); }
diff --git a/scripts/mso-agent-turn-print.mjs b/scripts/mso-agent-turn-print.mjs
new file mode 100644
index 00000000..6adb0e1f
--- /dev/null
+++ b/scripts/mso-agent-turn-print.mjs
@@ -0,0 +1,50 @@
+// Routes terminal output during interactive turns. When the retained panel
+// is active, writes must go through the stream sink into the viewport buffer
+// instead of escaping to the cursor. Line-oriented prompts and subagents that
+// require full-terminal ownership suspend the panel temporarily.
+
+export function turnPrinter(session, fallback = console.log) {
+ return (...args) => {
+ const sink = session?.streamSink;
+ if (sink && typeof sink.write === "function") {
+ const text = args.map((arg) => (typeof arg === "string" ? arg : String(arg ?? ""))).join(" ");
+ sink.write(`${text}\n`);
+ } else {
+ fallback(...args);
+ }
+ };
+}
+
+export const getTurnPrinter = turnPrinter;
+
+export async function withPanelSuspended(loop, fn) {
+ if (!loop || !loop.active) {
+ return fn();
+ }
+ const session = loop.session;
+ const savedSink = session?.streamSink;
+ let suspendedViaMethod = false;
+
+ if (typeof loop.suspend === "function") {
+ loop.suspend();
+ suspendedViaMethod = true;
+ } else if (session && savedSink) {
+ // Fallback when a plain fake loop object without methods is supplied in tests.
+ delete session.streamSink;
+ }
+
+ try {
+ return await fn();
+ } finally {
+ if (suspendedViaMethod && typeof loop.resume === "function") {
+ loop.resume();
+ } else {
+ if (!suspendedViaMethod && session && savedSink) {
+ session.streamSink = savedSink;
+ }
+ if (typeof loop.paint === "function") {
+ loop.paint();
+ }
+ }
+ }
+}
diff --git a/scripts/mso-agent-turn-print.test.ts b/scripts/mso-agent-turn-print.test.ts
new file mode 100644
index 00000000..d8fcb6df
--- /dev/null
+++ b/scripts/mso-agent-turn-print.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from "vitest";
+import { turnPrinter, withPanelSuspended } from "./mso-agent-turn-print.mjs";
+import { renderInteractionFailure } from "./mso-agent-turn.mjs";
+import { C } from "./mso-agent-runtime.mjs";
+
+describe("mid-turn write routing and panel suspension", () => {
+ it("routes writes to the fallback when no sink is installed", () => {
+ // When the panel is off or not active, output must be byte-identical to normal terminal writes.
+ const session = {};
+ const fallback = vi.fn();
+ const print = turnPrinter(session, fallback);
+
+ print("plain message");
+ print("message", "with", "multiple", "parts");
+
+ expect(fallback).toHaveBeenCalledTimes(2);
+ expect(fallback).toHaveBeenNthCalledWith(1, "plain message");
+ expect(fallback).toHaveBeenNthCalledWith(2, "message", "with", "multiple", "parts");
+ });
+
+ it("routes lines to the stream sink and leaves the fallback untouched when sink is installed", () => {
+ // When the panel is active, streamSink catches turn writes so they land in the viewport.
+ const sink = { write: vi.fn() };
+ const session = { streamSink: sink };
+ const fallback = vi.fn();
+ const print = turnPrinter(session, fallback);
+
+ print("buffered error or turn notice");
+
+ expect(sink.write).toHaveBeenCalledTimes(1);
+ expect(sink.write).toHaveBeenCalledWith("buffered error or turn notice\n");
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it("sends section divider and each error line to the sink during renderInteractionFailure", () => {
+ // Failures mid-turn must land in the viewport buffer instead of breaking frame rows.
+ const sink = { write: vi.fn() };
+ const session = { streamSink: sink, agentSession: { name: "test-agent" } };
+ const print = turnPrinter(session);
+ const error = new Error("simulated failure mid-turn");
+
+ renderInteractionFailure(error, session, {}, C, print);
+
+ expect(sink.write).toHaveBeenCalled();
+ const combined = sink.write.mock.calls.map((call) => call[0]).join("");
+ expect(combined).toContain("Error");
+ expect(combined).toContain("simulated failure mid-turn");
+ });
+
+ it("suspends active panel so prompt output reaches fallback, sink receives nothing, and repaints after", async () => {
+ // Answering approval prompts needs full terminal interaction; panel closes and repaints after.
+ const sink = { write: vi.fn() };
+ const session = { streamSink: sink };
+ const fallback = vi.fn();
+ const loop = {
+ active: true,
+ session,
+ paint: vi.fn(),
+ };
+ const print = turnPrinter(session, fallback);
+
+ await withPanelSuspended(loop, async () => {
+ // During suspended execution, turnPrinter falls back to stdout instead of corrupting the sink.
+ print("approval prompt: allow or deny?");
+ });
+
+ expect(fallback).toHaveBeenCalledWith("approval prompt: allow or deny?");
+ expect(sink.write).not.toHaveBeenCalled();
+ expect(loop.paint).toHaveBeenCalledTimes(1);
+ expect(session.streamSink).toBe(sink);
+ });
+
+ it("repaints and restores the sink even when the suspended function throws, propagating the error", async () => {
+ // Panel must not remain disabled if an interrupt or error terminates prompt input early.
+ const sink = { write: vi.fn() };
+ const session = { streamSink: sink };
+ const loop = {
+ active: true,
+ session,
+ paint: vi.fn(),
+ };
+
+ await expect(
+ withPanelSuspended(loop, async () => {
+ throw new Error("turn interrupted during approval");
+ }),
+ ).rejects.toThrow("turn interrupted during approval");
+
+ expect(loop.paint).toHaveBeenCalledTimes(1);
+ expect(session.streamSink).toBe(sink);
+ });
+
+ it("calls the function and repaints nothing when the panel is inactive", async () => {
+ // When the panel is inactive, withPanelSuspended is a transparent passthrough.
+ const loop = {
+ active: false,
+ paint: vi.fn(),
+ };
+ const fallback = vi.fn();
+
+ const result = await withPanelSuspended(loop, () => {
+ fallback("un-panelled call");
+ return 42;
+ });
+
+ expect(result).toBe(42);
+ expect(fallback).toHaveBeenCalledWith("un-panelled call");
+ expect(loop.paint).not.toHaveBeenCalled();
+ });
+});
diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjs
index 84e76261..b193e3bf 100644
--- a/scripts/mso-agent-turn.mjs
+++ b/scripts/mso-agent-turn.mjs
@@ -16,6 +16,7 @@ import { oneShotApproves } from "./mso-agent-oneshot.mjs";
import { reasoningLine } from "./mso-agent-reasoning.mjs";
import { parseEditResult, printEditDiff } from "./mso-agent-edit-diff.mjs";
import { parseTodoCall, printTodoBlock, rememberTodos } from "./mso-agent-todos.mjs";
+import { turnPrinter } from "./mso-agent-turn-print.mjs";
function lazyAssistantOutput(session, options = {}) {
if (options.quiet) return null;
@@ -39,9 +40,7 @@ function lazyAssistantOutput(session, options = {}) {
* hard-coded 10; now `OS_AGENT_MAX_ROUNDS` (default 1000 = no practical cap). */
export function agentRoundLimit() {
const configured = Number(process.env.OS_AGENT_MAX_ROUNDS);
- return Number.isFinite(configured) && configured > 0
- ? Math.trunc(configured)
- : 1000;
+ return Number.isFinite(configured) && configured > 0 ? Math.trunc(configured) : 1000;
}
export async function executeTool(rl, tool, call, agentSession, permission = "ask", signal = undefined, onInterrupt = null, options = {}) {
@@ -58,12 +57,11 @@ export async function executeTool(rl, tool, call, agentSession, permission = "as
if (!approved) {
if (options.approvalScope) return { ok: false, result: "denied by user" };
const approvalState = options.approvalState || null;
- if (approvalState) approvalState.pendingApproval = {
- tool: tool.name, scope: tool.scope, digest: approval?.digest || null, createdAt: new Date().toISOString(),
- };
+ if (approvalState) approvalState.pendingApproval = { tool: tool.name, scope: tool.scope, digest: approval?.digest || null, createdAt: new Date().toISOString() };
try {
+ const screenLoop = options.screenLoop || approvalState?.screenLoop;
approved = await requestExactToolApproval(rl, {
- tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C,
+ tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C, screenLoop,
});
if (approvalState) approvalState.pendingApproval = null;
} catch (error) {
@@ -72,7 +70,7 @@ export async function executeTool(rl, tool, call, agentSession, permission = "as
}
} else if (needsApprovalDigest && !options.quiet && !options.approvalScope) {
if (options.activity) options.activity.label(tool);
- else console.log(`${C.c}${C.bold}[${tool.scope}]${C.reset} ${tool.name}`);
+ else (options.print || console.log)(`${C.c}${C.bold}[${tool.scope}]${C.reset} ${tool.name}`);
}
if (!approved) return { ok: false, result: "denied by user" };
if (!options.quiet) {
@@ -127,9 +125,10 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
})).begin();
const roundLimit = agentRoundLimit();
beginSkillInvocation(session, skillContext, C);
+ const print = options.print || turnPrinter(session);
const turnStream = options.streamTurn || streamTurn;
const toolExecutor = options.executeTool || executeTool;
- const toolOptions = { ...options, activity };
+ const toolOptions = { ...options, activity, print, screenLoop: options.screenLoop || session?.screenLoop };
let workSectionPrinted = false;
try {
for (let turn = 0; turn < roundLimit; turn++) {
@@ -151,7 +150,7 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
session.lastElapsedMs = Date.now() - startedAt;
if (!options.quiet && session.showReasoning !== false) {
const line = reasoningLine(result.usage);
- if (line) console.log(`${C.dim}${line}${C.reset}`);
+ if (line) print(`${C.dim}${line}${C.reset}`);
}
session.history.push({ role: "assistant", text: result.text, toolUses: result.toolUses });
if (!result.toolUses.length) {
@@ -177,7 +176,7 @@ export async function agentRound(rl, session, skillContext = null, signal = unde
session.history.push({ role: "tool", results });
}
activity?.finish(completedReceipt(calls, session.lastElapsedMs));
- if (!options.quiet) console.log(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);
+ if (!options.quiet) print(`${C.warn}turn limit reached; ask to continue if needed.${C.reset}`);
return { text: finalText, calls, rounds, usage: session.usage, elapsedMs: session.lastElapsedMs, turnLimitReached: true };
} catch (error) {
if (signal?.aborted || isAbortError(error)) session.history.splice(historyCheckpoint);
@@ -200,15 +199,16 @@ export async function runInteractiveRound(rl, session, skillContext, interrupts,
const signal = interrupts.beginTurn();
await localBridge?.setState("busy");
let roundResult = null;
+ const print = turnPrinter(session);
try {
- roundResult = await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent());
+ roundResult = await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent(), { print });
await persistSession(session);
} catch (error) {
if (signal.aborted || isAbortError(error)) {
- console.log(`${C.dim}turn interrupted.${C.reset}`);
+ print(`${C.dim}turn interrupted.${C.reset}`);
} else {
const journal = error?.turnJournal || { calls: roundResult?.calls || [] };
- const state = renderInteractionFailure(error, session, journal, C);
+ const state = renderInteractionFailure(error, session, journal, C, print);
if (isRecoverableInteractionError(error)) session.history.push(recoverableHistoryRow(state));
}
await persistSession(session).catch(() => undefined);