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): an alternate screen behind a flag, with teardown on every exit path (#192)

Abdurrahman Fakhrul49c7393e85e2
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b1985583..8c1f4ac5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,12 +8,13 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `tui` an alternate screen behind a flag, with teardown on every exit path
- `tui` a tab row and a footer that stay put, painted through the frame writer (#191)
- `tui` a transcript model, because scrollback is the only transcript that exists (#187)
**Fixed**
-- `ci` apply the same parser workaround to the last two mock call sites
+- `ci` apply the same parser workaround to the last two mock call sites (#196)
- `ci` stop the semgrep scan failing on a generic argument in a test mock (#195)
**Changed**
diff --git a/docs/TUI-RENDERER-PLAN.md b/docs/TUI-RENDERER-PLAN.md
index 6cf05996..cf2e75b6 100644
--- a/docs/TUI-RENDERER-PLAN.md
+++ b/docs/TUI-RENDERER-PLAN.md
@@ -591,8 +591,8 @@ those two, and mouse/scrollbar/splits are additive after M5.
| M1 | Shared cell primitives, `scripts/tui/cells.mjs` | DONE | PR #186, `5b45314`; layout.mjs 67 to 20 lines |
| M2 | Transcript model, `scripts/mso-agent-transcript.mjs` | DONE | PR #187; reuses formatEditDiff, formatTodoBlock, formatDiffBody |
| M3 | Frame writer, `scripts/mso-agent-screen.mjs`, inline mode | DONE | PR #189; composer 221 to 217 lines, ratchet 43 to 42 |
-| M4 | Chrome and tabs as a bottom block | DONE | PR #190; chromeLines and tabs switch; composer 216 lines |
-| M5 | Alternate screen behind a flag, with teardown | NOT STARTED | irreversible step; waits for M4 |
+| M4 | Chrome and tabs as a bottom block | DONE | PR #191; chromeLines and tabs switch; composer 216 lines |
+| M5 | Alternate screen behind a flag, with teardown | DONE | PR #192; default off; teardown on exit, signals, execve, spawnSync |
| M6 | Transcript viewport and scrollbar | NOT STARTED | needs M5 |
| M7 | Mouse | NOT STARTED | needs the owner's selection policy |
| M8 | Split panes, then flip the alt screen default | NOT STARTED | needs M6 and M7 |
diff --git a/scripts/mso-agent-altscreen.mjs b/scripts/mso-agent-altscreen.mjs
new file mode 100644
index 00000000..c0c8ba68
--- /dev/null
+++ b/scripts/mso-agent-altscreen.mjs
@@ -0,0 +1,157 @@
+import process from "node:process";
+
+export const ENTER_SEQUENCE = "\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H";
+export const LEAVE_SEQUENCE = "\x1b[0m\x1b[?25h\x1b[?1049l";
+
+// Tracks active streams currently displaying alternate screen buffer.
+const activeOutputs = new Set();
+
+export function isScreenActive(output = process.stdout) {
+ return activeOutputs.has(output);
+}
+
+// Determines if alternate screen mode was explicitly requested and conditions permit it.
+// Guarded to prevent accidental activation in CI, non-TTY environments, or one-shot mode.
+/** @param {{ argv?: string[], env?: Record<string, string | undefined>, isTTY?: boolean }} [options] */
+export function altScreenRequested({
+ argv = process.argv.slice(2),
+ env = process.env,
+ isTTY = process.stdout?.isTTY,
+} = {}) {
+ const args = Array.isArray(argv) ? argv : [];
+ const environment = env || {};
+
+ const requested = Boolean(
+ args.includes("--altscreen") ||
+ args.includes("--alt-screen") ||
+ environment.MSO_ALT_SCREEN === "1" ||
+ environment.MSO_ALTSCREEN === "1"
+ );
+
+ if (!requested) {
+ return { ok: false, enabled: false, requested: false, reason: "not_requested" };
+ }
+
+ if (isTTY !== true) {
+ return { ok: false, enabled: false, requested: true, reason: "not_tty" };
+ }
+
+ const ci = environment.CI;
+ if (Boolean(ci && ci !== "0" && ci !== "false")) {
+ return { ok: false, enabled: false, requested: true, reason: "ci_environment" };
+ }
+
+ if (args.includes("--oneshot") || args.includes("-z")) {
+ return { ok: false, enabled: false, requested: true, reason: "oneshot_mode" };
+ }
+
+ return { ok: true, enabled: true, requested: true, reason: null };
+}
+
+// Enters alternate screen mode idempotently.
+// Writes enter sequence only on the first call for a given output stream.
+/** @param {any} [output] */
+export function enterScreen(output = process.stdout) {
+ if (!output || typeof output.write !== "function") return false;
+ if (activeOutputs.has(output)) return false;
+ try {
+ output.write(ENTER_SEQUENCE);
+ activeOutputs.add(output);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Releases alternate screen mode idempotently.
+// Deletes from tracking set before writing so teardown does not repeat on write errors.
+/** @param {any} [output] */
+export function leaveScreen(output) {
+ if (output) {
+ if (!activeOutputs.has(output)) return false;
+ activeOutputs.delete(output);
+ if (typeof output.write !== "function") return false;
+ try {
+ output.write(LEAVE_SEQUENCE);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ if (activeOutputs.size === 0) return false;
+ let released = false;
+ for (const stream of [...activeOutputs]) {
+ activeOutputs.delete(stream);
+ if (typeof stream?.write === "function") {
+ try {
+ stream.write(LEAVE_SEQUENCE);
+ released = true;
+ } catch {
+ // Suppress write errors during exit to allow remaining teardown to continue.
+ }
+ }
+ }
+ return released;
+}
+
+// One call for the entrypoint: register teardown first, then enter, so a signal that arrives
+// during the write is already covered. Dispose releases the screen before removing handlers,
+// because removing first would leave a handled exit with the alternate buffer still active.
+/** @param {{ requested?: any, output?: any, processRef?: any }} [options] */
+export function startAltScreen({ requested, output = process.stdout, processRef } = {}) {
+ if (!requested?.ok) return { entered: false, dispose() {} };
+ const teardown = installTeardown({ output, processRef });
+ const entered = enterScreen(output);
+ return {
+ entered,
+ dispose() {
+ leaveScreen(output);
+ teardown.dispose();
+ },
+ };
+}
+
+// Installs exit, SIGINT, SIGTERM, and SIGHUP listeners that release alternate screen.
+// Returns a dispose function to restore exact original listener count without replacing pre-existing handlers.
+/** @param {{ output?: any, processRef?: any, signalSource?: any }} [options] */
+export function installTeardown({
+ output = process.stdout,
+ processRef,
+ signalSource,
+} = {}) {
+ const proc = processRef || signalSource || process;
+ const sigs = signalSource || processRef || process;
+
+ const onTeardown = () => {
+ leaveScreen(output);
+ };
+
+ const cleanups = [];
+
+ const attach = (target, event, listener) => {
+ if (!target || typeof target.on !== "function") return;
+ target.on(event, listener);
+ cleanups.push(() => {
+ if (typeof target.off === "function") {
+ target.off(event, listener);
+ } else if (typeof target.removeListener === "function") {
+ target.removeListener(event, listener);
+ }
+ });
+ };
+
+ attach(proc, "exit", onTeardown);
+ attach(sigs, "SIGINT", onTeardown);
+ attach(sigs, "SIGTERM", onTeardown);
+ attach(sigs, "SIGHUP", onTeardown);
+
+ return {
+ dispose() {
+ for (const cleanup of cleanups) {
+ cleanup();
+ }
+ cleanups.length = 0;
+ },
+ };
+}
diff --git a/scripts/mso-agent-altscreen.test.ts b/scripts/mso-agent-altscreen.test.ts
new file mode 100644
index 00000000..ae9642ff
--- /dev/null
+++ b/scripts/mso-agent-altscreen.test.ts
@@ -0,0 +1,191 @@
+import { EventEmitter } from "node:events";
+import { describe, expect, it } from "vitest";
+import {
+ ENTER_SEQUENCE,
+ LEAVE_SEQUENCE,
+ altScreenRequested,
+ enterScreen,
+ installTeardown,
+ leaveScreen,
+ startAltScreen,
+} from "./mso-agent-altscreen.mjs";
+
+class FakeOutput {
+ columns = 80;
+ chunks: string[] = [];
+ isTTY?: boolean = true;
+ write(value: string) {
+ this.chunks.push(String(value));
+ return true;
+ }
+}
+
+describe("MSO Agent alternate screen manager", () => {
+ it("no flag, no TTY, CI set, and one-shot mode each return false with a distinct reason", () => {
+ const noFlag = altScreenRequested({ argv: [], env: {}, isTTY: true });
+ expect(noFlag.ok).toBe(false);
+ expect(noFlag.reason).toBe("not_requested");
+
+ const noTty = altScreenRequested({ argv: ["--altscreen"], env: {}, isTTY: false });
+ expect(noTty.ok).toBe(false);
+ expect(noTty.reason).toBe("not_tty");
+
+ const ciSet = altScreenRequested({ argv: ["--altscreen"], env: { CI: "true" }, isTTY: true });
+ expect(ciSet.ok).toBe(false);
+ expect(ciSet.reason).toBe("ci_environment");
+
+ const oneShot = altScreenRequested({ argv: ["--altscreen", "--oneshot", "inspect"], env: {}, isTTY: true });
+ expect(oneShot.ok).toBe(false);
+ expect(oneShot.reason).toBe("oneshot_mode");
+
+ const reasons = [noFlag.reason, noTty.reason, ciSet.reason, oneShot.reason];
+ expect(new Set(reasons).size).toBe(4);
+ });
+
+ it("the flag plus a TTY returns true", () => {
+ const result = altScreenRequested({ argv: ["--altscreen"], env: {}, isTTY: true });
+ expect(result.ok).toBe(true);
+ expect(result.reason).toBe(null);
+ });
+
+ it("default is OFF and behaviour is byte-identical with no writes", () => {
+ const output = new FakeOutput();
+ const result = altScreenRequested({ argv: [], env: {}, isTTY: true });
+ expect(result.ok).toBe(false);
+ if (result.ok) enterScreen(output);
+ expect(output.chunks.length).toBe(0);
+ });
+
+ it("enterScreen writes the enter sequence once and a second call writes nothing", () => {
+ const output = new FakeOutput();
+ const first = enterScreen(output);
+ expect(first).toBe(true);
+ expect(output.chunks).toEqual([ENTER_SEQUENCE]);
+
+ const second = enterScreen(output);
+ expect(second).toBe(false);
+ expect(output.chunks).toEqual([ENTER_SEQUENCE]);
+
+ leaveScreen(output);
+ });
+
+ it("leaveScreen after enter writes the leave sequence once; leaveScreen without enter writes nothing", () => {
+ const unentered = new FakeOutput();
+ const unenteredResult = leaveScreen(unentered);
+ expect(unenteredResult).toBe(false);
+ expect(unentered.chunks.length).toBe(0);
+
+ const entered = new FakeOutput();
+ enterScreen(entered);
+ expect(entered.chunks).toEqual([ENTER_SEQUENCE]);
+
+ const firstLeave = leaveScreen(entered);
+ expect(firstLeave).toBe(true);
+ expect(entered.chunks).toEqual([ENTER_SEQUENCE, LEAVE_SEQUENCE]);
+
+ const secondLeave = leaveScreen(entered);
+ expect(secondLeave).toBe(false);
+ expect(entered.chunks).toEqual([ENTER_SEQUENCE, LEAVE_SEQUENCE]);
+ });
+
+ it("installTeardown then dispose restores the exact listener count for every signal it touched", () => {
+ const fakeSource = new EventEmitter();
+ const output = new FakeOutput();
+ const signals = ["exit", "SIGINT", "SIGTERM", "SIGHUP"] as const;
+
+ const initialCounts = Object.fromEntries(signals.map((sig) => [sig, fakeSource.listenerCount(sig)]));
+
+ const teardown = installTeardown({ output, signalSource: fakeSource });
+
+ for (const sig of signals) {
+ expect(fakeSource.listenerCount(sig)).toBe(initialCounts[sig] + 1);
+ }
+
+ teardown.dispose();
+
+ for (const sig of signals) {
+ expect(fakeSource.listenerCount(sig)).toBe(initialCounts[sig]);
+ }
+ });
+
+ it("emitting SIGTERM on the fake source after install writes the leave sequence", () => {
+ const fakeSource = new EventEmitter();
+ const output = new FakeOutput();
+
+ enterScreen(output);
+ expect(output.chunks).toEqual([ENTER_SEQUENCE]);
+
+ const teardown = installTeardown({ output, signalSource: fakeSource });
+ fakeSource.emit("SIGTERM");
+
+ expect(output.chunks).toEqual([ENTER_SEQUENCE, LEAVE_SEQUENCE]);
+ teardown.dispose();
+ });
+
+ it("a pre-existing SIGINT handler still runs after teardown is installed (the new handler must chain, not replace)", () => {
+ const fakeSource = new EventEmitter();
+ const output = new FakeOutput();
+ let preExistingRan = false;
+
+ fakeSource.on("SIGINT", () => {
+ preExistingRan = true;
+ });
+
+ enterScreen(output);
+ const teardown = installTeardown({ output, signalSource: fakeSource });
+
+ fakeSource.emit("SIGINT");
+
+ expect(preExistingRan).toBe(true);
+ expect(output.chunks).toEqual([ENTER_SEQUENCE, LEAVE_SEQUENCE]);
+ teardown.dispose();
+ });
+
+ it("an SIGINT that arrives before enterScreen writes nothing", () => {
+ const fakeSource = new EventEmitter();
+ const output = new FakeOutput();
+
+ const teardown = installTeardown({ output, signalSource: fakeSource });
+ fakeSource.emit("SIGINT");
+
+ expect(output.chunks.length).toBe(0);
+ teardown.dispose();
+ });
+
+ it("leaveScreen handles partial write errors gracefully", () => {
+ const errorOutput = {
+ isTTY: true,
+ write() {
+ throw new Error("broken pipe");
+ },
+ };
+ enterScreen(errorOutput);
+ // Safe teardown: errors during write do not bubble or prevent deactivating the screen.
+ expect(() => leaveScreen(errorOutput)).not.toThrow();
+ // Subsequent calls are safe no-ops because state was cleared before write.
+ expect(leaveScreen(errorOutput)).toBe(false);
+ });
+
+ it("startAltScreen enters only when allowed and dispose releases before detaching", () => {
+ const denied = new FakeOutput();
+ const notRequested = new EventEmitter();
+ const before = notRequested.listenerCount("SIGTERM");
+ const skip = startAltScreen({ requested: { ok: false }, output: denied, processRef: notRequested });
+ expect(skip.entered).toBe(false);
+ expect(denied.chunks).toEqual([]);
+ expect(notRequested.listenerCount("SIGTERM")).toBe(before);
+ skip.dispose();
+
+ const output = new FakeOutput();
+ const signals = new EventEmitter();
+ const screen = startAltScreen({ requested: { ok: true }, output, processRef: signals });
+ expect(screen.entered).toBe(true);
+ expect(output.chunks).toEqual([ENTER_SEQUENCE]);
+ expect(signals.listenerCount("SIGTERM")).toBe(1);
+
+ screen.dispose();
+ expect(output.chunks).toEqual([ENTER_SEQUENCE, LEAVE_SEQUENCE]);
+ expect(signals.listenerCount("SIGTERM")).toBe(0);
+ expect(signals.listenerCount("exit")).toBe(0);
+ });
+});
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index fe8e3dac..356fb8a9 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -2,6 +2,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 {
loadSlashSkill,
printSkillChoices,
@@ -21,6 +22,8 @@ import { handleJobsCommand } from "./mso-agent-jobs.mjs";
export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
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 },
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 21f05cc2..cfe4e667 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -42,6 +42,7 @@ export const HELP_LINES = [
" /image <path> attach a local image to the next prompt",
" /clear clear this session conversation",
" /exit, /quit quit",
+ " --altscreen dev only: retain full terminal in alternate screen",
"",
"Keyboard",
" Ctrl+C clear input; empty prompt exits; active turn interrupts",
diff --git a/scripts/mso-agent-lifecycle.mjs b/scripts/mso-agent-lifecycle.mjs
index be3a631c..8ddc8a74 100644
--- a/scripts/mso-agent-lifecycle.mjs
+++ b/scripts/mso-agent-lifecycle.mjs
@@ -1,5 +1,6 @@
import process from "node:process";
import { CLI } from "./mso-agent-api.mjs";
+import { leaveScreen } from "./mso-agent-altscreen.mjs";
const RESTART_PERMISSION_ENV = "MSO_AGENT_RESTART_PERMISSION";
const RESTART_STATUSBAR_ENV = "MSO_AGENT_RESTART_STATUSBAR";
@@ -33,6 +34,8 @@ export function relaunchAgentSession(
// execve replaces the current process image instead of spawning a child. Combined
// with the CLI wrapper's `exec node`, repeated /restart keeps a constant process
// depth and reloads both the current wrapper and Agent modules from disk.
+ // Releases the alternate screen buffer before handing the terminal to the replaced process image.
+ leaveScreen();
execve(command, [command, "agent", "--restart-session", id], env);
throw new Error("MSO Agent process replacement unexpectedly returned");
}
diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjs
index a9a060d8..dccb5575 100644
--- a/scripts/mso-agent.mjs
+++ b/scripts/mso-agent.mjs
@@ -16,6 +16,7 @@ import { agentRound, executeTool, renderInteractionFailure, runInteractiveRound
import { pathToFileURL } from "node:url";
import { createQueue, dequeue } from "./mso-agent-queue.mjs";
import { pendingImageBlock } from "./mso-agent-image.mjs";
+import { altScreenRequested, startAltScreen } from "./mso-agent-altscreen.mjs";
import { visibleSessionRows } from "./mso-agent-sessions.mjs";
import { chromeLines } from "./mso-agent-chrome.mjs";
@@ -63,80 +64,88 @@ async function main() {
console.error("mso agent needs an interactive terminal. For autonomous one-shot use: mso agent --oneshot \"<prompt>\" [--json]");
process.exit(2);
}
- const restartSessionId = restartSessionArg(argv);
- const requested = restartSessionId ? null : resumeArg(argv);
- const restartUi = consumeRestartUiState();
- const forcedPermission = argv.some((arg) => ["--yolo", "-yolo", "-y"].includes(arg))
- ? "yolo"
- : (permissionMode(restartUi.permission)?.id || "ask");
- const [s, agentSession] = await Promise.all([state(), startupSession(requested, restartSessionId)]);
- if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");
- printBanner(s, agentSession);
- const session = {
- state: s,
- agentSession,
- history: Array.isArray(agentSession.history) ? agentSession.history : [],
- pendingSkill: null, activeSkill: null, lastInvokedSkill: null,
- titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,
- usage: { apiCalls: 0 }, lastRouting: null, lastElapsedMs: 0,
- statusBar: restartUi.statusBar ?? true, permission: forcedPermission, pendingApproval: null,
- // Ephemeral queue: held only in memory for this TUI process and not persisted to server state.
- queue: createQueue(),
- };
- let recentSessions = session.agentSession ? [session.agentSession] : [];
- const refreshSessions = () => { listCliSessions(20).then((rows) => { recentSessions = visibleSessionRows(rows); }).catch(() => {}); };
- refreshSessions();
- const rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onToggleStatusBar: () => { session.statusBar = !session.statusBar; } }); syncPromptHistory(rl, session);
- let inboundRequestQueued = false;
- const localBridge = new LocalAgentBridge({
- session,
- composer: rl,
- onRequest: () => {
- // A local request otherwise only becomes model context on the next manual
- // turn. Cancel the idle editor and let the main loop run it immediately.
- inboundRequestQueued = true;
- rl.cancelCurrent({ echo: false });
- },
- });
- await localBridge.start();
- const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });
- let lastTurnInterrupted = false;
- const originalBeginTurn = interrupts.beginTurn.bind(interrupts);
- interrupts.beginTurn = () => {
- const signal = originalBeginTurn();
- lastTurnInterrupted = false;
- signal.addEventListener("abort", () => {
- lastTurnInterrupted = true;
- }, { once: true });
- return signal;
- };
- const originalInterruptCurrent = interrupts.interruptCurrent.bind(interrupts);
- interrupts.interruptCurrent = () => {
- lastTurnInterrupted = true;
- return originalInterruptCurrent();
- };
- const drainQueue = async () => {
- while (!interrupts.exitRequested && !lastTurnInterrupted) {
- const nextPrompt = dequeue(session.queue);
- if (!nextPrompt) break;
- session.history.push({ role: "user", text: nextPrompt });
- const skillContext = session.pendingSkill;
- session.pendingSkill = null;
- await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
- }
- };
- const onSigint = () => {
- const action = interrupts.handleSigint();
- // External child TUIs can restore the shared terminal to cooked mode. In that
- // state Ctrl+C arrives as SIGINT instead of a raw keypress, so wake whichever
- // composer prompt is currently waiting instead of leaving it hung.
- if (action === "exit") rl.cancelCurrent({ echo: true });
- else if (action === "interrupt") rl.cancelCurrent({ echo: false });
- };
- process.on("SIGINT", onSigint);
- const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session);
- let restartRequested = false;
+ const altScreen = altScreenRequested({ argv, env: process.env, isTTY: process.stdout.isTTY });
+ if (altScreen.requested && !altScreen.ok) {
+ console.warn(`${C.dim}mso agent: alternate screen not enabled (${altScreen.reason})${C.reset}`);
+ }
+ let screen = null; let session = null; let rl = null;
+ let localBridge = null; let onSigint = null; let restartRequested = false;
try {
+ screen = startAltScreen({ requested: altScreen, output: process.stdout });
+ const restartSessionId = restartSessionArg(argv);
+ const requested = restartSessionId ? null : resumeArg(argv);
+ const restartUi = consumeRestartUiState();
+ const forcedPermission = argv.some((arg) => ["--yolo", "-yolo", "-y"].includes(arg))
+ ? "yolo"
+ : (permissionMode(restartUi.permission)?.id || "ask");
+ const [s, agentSession] = await Promise.all([state(), startupSession(requested, restartSessionId)]);
+ if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");
+ printBanner(s, agentSession);
+ session = {
+ state: s,
+ agentSession,
+ history: Array.isArray(agentSession.history) ? agentSession.history : [],
+ pendingSkill: null, activeSkill: null, lastInvokedSkill: null,
+ titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,
+ usage: { apiCalls: 0 }, lastRouting: null, lastElapsedMs: 0,
+ statusBar: restartUi.statusBar ?? true, permission: forcedPermission, pendingApproval: null,
+ // Ephemeral queue: held only in memory for this TUI process and not persisted to server state.
+ queue: createQueue(),
+ };
+ let recentSessions = session.agentSession ? [session.agentSession] : [];
+ // 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 });
+ rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onToggleStatusBar: () => { session.statusBar = !session.statusBar; } }); syncPromptHistory(rl, session);
+ let inboundRequestQueued = false;
+ localBridge = new LocalAgentBridge({
+ session,
+ composer: rl,
+ onRequest: () => {
+ // A local request otherwise only becomes model context on the next manual
+ // turn. Cancel the idle editor and let the main loop run it immediately.
+ inboundRequestQueued = true;
+ rl.cancelCurrent({ echo: false });
+ },
+ });
+ await localBridge.start();
+ const interrupts = new AgentInterruptManager({ output: process.stdout, colors: C });
+ let lastTurnInterrupted = false;
+ const originalBeginTurn = interrupts.beginTurn.bind(interrupts);
+ interrupts.beginTurn = () => {
+ const signal = originalBeginTurn();
+ lastTurnInterrupted = false;
+ signal.addEventListener("abort", () => {
+ lastTurnInterrupted = true;
+ }, { once: true });
+ return signal;
+ };
+ const originalInterruptCurrent = interrupts.interruptCurrent.bind(interrupts);
+ interrupts.interruptCurrent = () => {
+ lastTurnInterrupted = true;
+ return originalInterruptCurrent();
+ };
+ const drainQueue = async () => {
+ while (!interrupts.exitRequested && !lastTurnInterrupted) {
+ const nextPrompt = dequeue(session.queue);
+ if (!nextPrompt) break;
+ session.history.push({ role: "user", text: nextPrompt });
+ const skillContext = session.pendingSkill;
+ session.pendingSkill = null;
+ await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);
+ }
+ };
+ onSigint = () => {
+ const action = interrupts.handleSigint();
+ // External child TUIs can restore the shared terminal to cooked mode. In that
+ // state Ctrl+C arrives as SIGINT instead of a raw keypress, so wake whichever
+ // composer prompt is currently waiting instead of leaving it hung.
+ if (action === "exit") rl.cancelCurrent({ echo: true });
+ else if (action === "interrupt") rl.cancelCurrent({ echo: false });
+ };
+ process.on("SIGINT", onSigint);
+ const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session);
while (true) {
if (interrupts.exitRequested) break;
if (inboundRequestQueued) {
@@ -150,14 +159,7 @@ async function main() {
complete: completeSlash,
onTab: () => { session.permission = nextPermissionMode(session.permission).id; },
separator: () => composerSeparator(session, C, process.stdout.columns),
- footer: () => chromeLines({
- session,
- sessions: recentSessions,
- activeId: session?.agentSession?.id,
- colors: C,
- width: process.stdout.columns,
- rows: process.stdout.rows,
- }),
+ footer: chromeFooter,
});
if (answer === null) {
if (inboundRequestQueued) continue;
@@ -198,12 +200,13 @@ async function main() {
if (!lastTurnInterrupted) await drainQueue();
}
} finally {
- process.off("SIGINT", onSigint);
- 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) console.log(`${C.dim}session ${sessionTitle} · resume: mso --continue · switch: /sessions${C.reset}`);
- await localBridge.close({ ended: !restartRequested }).catch(() => undefined);
- rl.close();
+ 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();
+ screen?.dispose();
}
if (restartRequested) {
console.log(`${C.dim}↻ refreshing Agent runtime · keeping ${session.agentSession.title || "current session"}${C.reset}`);