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): one print sink, so command output lands in the panel instead of on top of it (#202)

Abdurrahman Fakhrul4d7562b1cda8
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b4d93f24..c203897a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `tui` one print sink, so command output lands in the panel instead of on top of it
- `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)
- `tui` a transcript viewport with a scrollbar, so the alternate screen has a reason (#193)
@@ -17,8 +18,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
-- `tui` the two bugs a real pty found, and the test that found them
-- `tui` the two bugs a real pty found, both invisible to the unit tests
+- `tui` the two bugs a real pty found, and the test that found them (#201)
- `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)
diff --git a/scripts/mso-agent-cmd-inspect.mjs b/scripts/mso-agent-cmd-inspect.mjs
index 6509c4c5..6a9fa8d0 100644
--- a/scripts/mso-agent-cmd-inspect.mjs
+++ b/scripts/mso-agent-cmd-inspect.mjs
@@ -8,9 +8,11 @@ import { handleFilesCommand } from "./mso-agent-files.mjs";
import { printSkills } from "./mso-agent-skills.mjs";
import { state } from "./mso-agent-api.mjs";
import { C } from "./mso-agent-runtime.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export async function handleInspectCommand(ctx, cmd, args) {
const { rl, session, runCli, C: colors = C } = ctx;
+ const { print } = createPrinter(ctx);
switch (cmd) {
case "/status":
case "/context":
@@ -22,7 +24,7 @@ export async function handleInspectCommand(ctx, cmd, args) {
case "/permission": {
const direct = args.length ? permissionMode(args.join(" ")) : null;
if (args.length && !direct) {
- console.log("usage: /permission [ask|auto-write|yolo]");
+ print("usage: /permission [ask|auto-write|yolo]");
return "handled";
}
if (direct) session.permission = direct.id;
@@ -41,7 +43,7 @@ export async function handleInspectCommand(ctx, cmd, args) {
session.permission =
permissionMode(selected)?.id || session.permission;
}
- console.log(`permission ${session.permission}`);
+ print(`permission ${session.permission}`);
return "handled";
}
case "/statusbar": {
@@ -49,7 +51,7 @@ export async function handleInspectCommand(ctx, cmd, args) {
if (value === "off") session.statusBar = false;
else if (value === "on") session.statusBar = true;
else session.statusBar = !session.statusBar;
- console.log(`status bar ${session.statusBar ? "on" : "off"}`);
+ print(`status bar ${session.statusBar ? "on" : "off"}`);
return "handled";
}
case "/models":
@@ -74,7 +76,7 @@ export async function handleInspectCommand(ctx, cmd, args) {
return "refresh";
case "/provider":
if (!args[0])
- console.log("usage: /provider dokploy|cloudflare|hostinger");
+ print("usage: /provider dokploy|cloudflare|hostinger");
else runCli(["provider", "set", args[0]]);
session.state = await state();
return "refresh";
@@ -83,7 +85,7 @@ export async function handleInspectCommand(ctx, cmd, args) {
return "handled";
case "/tools":
for (const tool of session.state.tools)
- console.log(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
+ print(` ${String(tool.scope).padEnd(5)} ${tool.name}`);
return "handled";
case "/files":
await handleFilesCommand(args, session);
diff --git a/scripts/mso-agent-cmd-parity.mjs b/scripts/mso-agent-cmd-parity.mjs
index 60c59a8b..63de6158 100644
--- a/scripts/mso-agent-cmd-parity.mjs
+++ b/scripts/mso-agent-cmd-parity.mjs
@@ -6,6 +6,7 @@ import { applyTheme, currentThemeName, themeNames } from "./mso-agent-ui.mjs";
import { createQueue, enqueue, queueClear, queueList } from "./mso-agent-queue.mjs";
import { createStash, stashClear, stashList, stashPop, stashPush } from "./mso-agent-stash.mjs";
import { uploadSessionImage } from "./mso-agent-image.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export const SHARE_UNAVAILABLE_MESSAGE =
"/share is unavailable because the server exposes only download of existing shares.";
@@ -35,6 +36,7 @@ export function buildExportArgv(refOrArgs, maybeOut) {
export async function handleParityCommand(ctx, cmd, args) {
const { session, runCli, C: colors = C } = ctx;
+ const { print } = createPrinter(ctx);
switch (cmd) {
case "/export": {
try {
@@ -42,8 +44,8 @@ export async function handleParityCommand(ctx, cmd, args) {
const outFile = outIdx !== -1 && args[outIdx + 1] ? args[outIdx + 1] : null;
const code = runCli(buildExportArgv(args));
if (code === 0) {
- if (outFile) console.log(`session exported to ${outFile}.`);
- else console.log("session export written to stdout.");
+ if (outFile) print(`session exported to ${outFile}.`);
+ else print("session export written to stdout.");
}
} catch (error) {
console.error(`${colors.err}${safeErrorSummary(error)}${colors.reset}`);
@@ -53,7 +55,7 @@ export async function handleParityCommand(ctx, cmd, args) {
case "/share": {
try {
// Server exposes only download of existing temp shares; no route creates them.
- console.log(SHARE_UNAVAILABLE_MESSAGE);
+ print(SHARE_UNAVAILABLE_MESSAGE);
} catch (error) {
console.error(`${colors.err}${safeErrorSummary(error)}${colors.reset}`);
}
@@ -61,7 +63,7 @@ export async function handleParityCommand(ctx, cmd, args) {
}
case "/reasoning": {
session.showReasoning = toggleReasoning(session.showReasoning, args[0]);
- console.log(`reasoning ${session.showReasoning ? "on" : "off"}`);
+ print(`reasoning ${session.showReasoning ? "on" : "off"}`);
return "handled";
}
case "/theme": {
@@ -72,13 +74,13 @@ export async function handleParityCommand(ctx, cmd, args) {
const names = themeNames().join(", ");
const disabled = Boolean(process.env.NO_COLOR || !process.stdout.isTTY);
const reason = disabled ? "colour disabled (NO_COLOR or not a TTY)" : "";
- if (reason) console.log(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}(${reason}) · available: ${names}${colors.reset}`);
- else console.log(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}· available: ${names}${colors.reset}`);
+ if (reason) print(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}(${reason}) · available: ${names}${colors.reset}`);
+ else print(`${colors.bold}theme ${current}${colors.reset} ${colors.dim}· available: ${names}${colors.reset}`);
return "handled";
}
const result = applyTheme(target);
- if (!result.changed && result.reason) console.log(`${colors.dim}${result.reason}${colors.reset}`);
- else console.log(`${colors.bold}theme ${result.theme}${colors.reset}`);
+ if (!result.changed && result.reason) print(`${colors.dim}${result.reason}${colors.reset}`);
+ else print(`${colors.bold}theme ${result.theme}${colors.reset}`);
return "handled";
}
case "/queue": {
@@ -86,13 +88,13 @@ export async function handleParityCommand(ctx, cmd, args) {
const sub = args[0]?.toLowerCase();
if (!args.length || (args.length === 1 && sub === "list")) {
const items = queueList(queue);
- if (!items.length) console.log("queue empty");
- else items.forEach((item, index) => console.log(`${index + 1}. ${item}`));
+ if (!items.length) print("queue empty");
+ else items.forEach((item, index) => print(`${index + 1}. ${item}`));
return "handled";
}
if (args.length === 1 && sub === "clear") {
const dropped = queueClear(queue);
- console.log(`cleared ${dropped} queued ${dropped === 1 ? "item" : "items"}.`);
+ print(`cleared ${dropped} queued ${dropped === 1 ? "item" : "items"}.`);
return "handled";
}
if (args.length === 1 && sub === "run") {
@@ -101,10 +103,10 @@ export async function handleParityCommand(ctx, cmd, args) {
const text = args.join(" ").trim();
const res = enqueue(queue, text);
if (!res.ok) {
- if (res.capped) console.log(`queue full (cap is ${res.cap} items)`);
+ if (res.capped) print(`queue full (cap is ${res.cap} items)`);
return "handled";
}
- console.log(`queued (${res.count} pending)`);
+ print(`queued (${res.count} pending)`);
return "handled";
}
case "/stash": {
@@ -112,51 +114,51 @@ export async function handleParityCommand(ctx, cmd, args) {
const sub = args[0]?.toLowerCase();
if (!args.length || (args.length === 1 && sub === "list")) {
const items = stashList(stash);
- if (!items.length) console.log("stash empty");
- else items.forEach((item, index) => console.log(`${index + 1}. ${item}`));
+ if (!items.length) print("stash empty");
+ else items.forEach((item, index) => print(`${index + 1}. ${item}`));
return "handled";
}
if (args.length === 1 && sub === "pop") {
const text = stashPop(stash);
if (!text) {
- console.log("stash empty");
+ print("stash empty");
return "handled";
}
- console.log(text);
- console.log("pop returned to the prompt is not automatic; prompt was printed, not inserted.");
+ print(text);
+ print("pop returned to the prompt is not automatic; prompt was printed, not inserted.");
return "handled";
}
if (args.length === 1 && sub === "clear") {
const dropped = stashClear(stash);
- console.log(`cleared ${dropped} stashed ${dropped === 1 ? "item" : "items"}.`);
+ print(`cleared ${dropped} stashed ${dropped === 1 ? "item" : "items"}.`);
return "handled";
}
const text = args.join(" ").trim();
const res = stashPush(stash, text);
if (!res.ok) {
- if (res.capped) console.log(`stash full (cap is ${res.cap} items)`);
+ if (res.capped) print(`stash full (cap is ${res.cap} items)`);
return "handled";
}
- console.log(`stashed (${res.count})`);
+ print(`stashed (${res.count})`);
return "handled";
}
case "/image": {
const filePath = args.join(" ").trim();
if (!filePath) {
- console.log("usage: /image <path>");
+ print("usage: /image <path>");
return "handled";
}
if (!session?.agentSession?.artifacts?.directory) {
- console.log("session artifacts directory is unavailable; cannot attach image.");
+ print("session artifacts directory is unavailable; cannot attach image.");
return "handled";
}
try {
const uploaded = await uploadSessionImage(session, filePath);
const images = session.pendingImages || (session.pendingImages = []);
images.push(uploaded);
- console.log(`attached for next prompt (${images.length})`);
+ print(`attached for next prompt (${images.length})`);
} catch (err) {
- console.log(`image upload failed: ${err instanceof Error ? err.message : String(err)}`);
+ print(`image upload failed: ${err instanceof Error ? err.message : String(err)}`);
}
return "handled";
}
diff --git a/scripts/mso-agent-cmd-session.mjs b/scripts/mso-agent-cmd-session.mjs
index 9a95846f..d3133cc4 100644
--- a/scripts/mso-agent-cmd-session.mjs
+++ b/scripts/mso-agent-cmd-session.mjs
@@ -13,19 +13,21 @@ import { handleKeybindCommand } from "./mso-agent-keybinds.mjs";
import { visibleSessionRows } from "./mso-agent-sessions.mjs";
import { tabsToSwitch } from "./mso-agent-chrome.mjs";
import { cyclePane, paneKinds } from "./mso-agent-pane.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export async function handleTodos(ctx, args = []) {
const { C: colors = C } = ctx;
+ const { print, printBlock } = createPrinter(ctx);
const state = latestTodos();
if (!state || (!state.items?.length && !state.summary)) {
- console.log("no todo list in this session yet: the agent writes one with todo_write");
+ print("no todo list in this session yet: the agent writes one with todo_write");
return "handled";
}
const showAll = args.includes("--all");
const maxItems = showAll ? Number.POSITIVE_INFINITY : 12;
const block = formatTodoBlock(state, { colors, maxItems });
- if (block) console.log(block);
- else console.log("no todo list in this session yet: the agent writes one with todo_write");
+ if (block) printBlock(block);
+ else print("no todo list in this session yet: the agent writes one with todo_write");
return "handled";
}
@@ -40,25 +42,26 @@ export async function switchToSession(rl, session, sessionId) {
export async function handleTabs(ctx, args = []) {
const { rl, session, C: colors = C } = ctx;
+ const { print } = createPrinter(ctx);
const rows = visibleSessionRows(await listCliSessions(20));
if (!args.length) {
if (!rows.length) {
- console.log("No active sessions.");
+ print("No active sessions.");
return "handled";
}
- console.log(`${colors.bold || ""}Sessions${colors.reset || ""}`);
+ print(`${colors.bold || ""}Sessions${colors.reset || ""}`);
rows.forEach((row, idx) => {
const isCurrent = String(row.id) === String(session?.agentSession?.id);
const mark = isCurrent ? `${colors.blue || ""}${colors.bold || ""}●${colors.reset || ""}` : " ";
const name = `@${row.name || "agent"}`;
const title = row.title || "MSO Agent session";
- console.log(` ${mark} ${idx + 1}. ${name} · ${title}${isCurrent ? " (current)" : ""}`);
+ print(` ${mark} ${idx + 1}. ${name} · ${title}${isCurrent ? " (current)" : ""}`);
});
return "handled";
}
const target = tabsToSwitch(rows, args);
if (!target) {
- console.log(`could not resolve session: ${args.join(" ")}`);
+ print(`could not resolve session: ${args.join(" ")}`);
return "handled";
}
await switchToSession(rl, session, target.id);
@@ -67,21 +70,22 @@ export async function handleTabs(ctx, args = []) {
export async function handlePane(ctx, args = []) {
const { session, C: colors = C } = ctx;
+ const { print } = createPrinter(ctx);
const kinds = paneKinds();
if (!args.length) {
const current = session?.paneKind || "off";
const next = cyclePane(current);
if (session) session.paneKind = next;
- console.log(`${colors.c || ""}side pane: ${next}${colors.reset || ""}`);
+ print(`${colors.c || ""}side pane: ${next}${colors.reset || ""}`);
return "handled";
}
const requested = String(args[0]).toLowerCase();
if (kinds.includes(requested)) {
if (session) session.paneKind = requested;
- console.log(`${colors.c || ""}side pane: ${requested}${colors.reset || ""}`);
+ print(`${colors.c || ""}side pane: ${requested}${colors.reset || ""}`);
return "handled";
}
- console.log(`usage: /pane [todos|diff|files|off] (current: ${session?.paneKind || "off"})`);
+ print(`usage: /pane [todos|diff|files|off] (current: ${session?.paneKind || "off"})`);
return "handled";
}
@@ -99,6 +103,7 @@ export async function handleSessionCommand(ctx, cmd, args) {
return handleTabs(ctx, args);
}
const { rl, session, C: colors = C } = ctx;
+ const { print } = createPrinter(ctx);
switch (cmd) {
case "/new":
await startNewSession(rl, session, args.join(" "));
@@ -116,19 +121,19 @@ export async function handleSessionCommand(ctx, cmd, args) {
return "refresh";
case "/rename": {
const name = args.join(" ").trim();
- if (!name) console.log("usage: /rename <short-name>");
+ if (!name) print("usage: /rename <short-name>");
else {
const renamed = await renameCurrentSessionName(session, name);
- console.log(`${colors.c}✓ session name: @${renamed}${colors.reset}`);
+ print(`${colors.c}✓ session name: @${renamed}${colors.reset}`);
}
return "handled";
}
case "/title": {
const title = args.join(" ").trim();
- if (!title) console.log("usage: /title <session name>");
+ if (!title) print("usage: /title <session name>");
else {
const renamed = await renameCurrentSession(session, title);
- console.log(`${colors.c}✓ session title: ${renamed}${colors.reset}`);
+ print(`${colors.c}✓ session title: ${renamed}${colors.reset}`);
}
return "handled";
}
@@ -150,10 +155,10 @@ export async function handleSessionCommand(ctx, cmd, args) {
const before = res?.beforeTokens ?? 0;
const after = res?.afterTokens ?? before;
if (res?.archived) {
- console.log(`${colors.c}compacted context: ${before} → ${after} tokens (archive written)${colors.reset}`);
+ print(`${colors.c}compacted context: ${before} → ${after} tokens (archive written)${colors.reset}`);
} else {
const reason = res?.archiveReason || "context already minimal";
- console.log(`${colors.dim}${reason}: ${before} → ${after} tokens (no archive written)${colors.reset}`);
+ print(`${colors.dim}${reason}: ${before} → ${after} tokens (no archive written)${colors.reset}`);
}
} catch (error) {
console.error(`${colors.err}${error instanceof Error ? error.message : String(error)}${colors.reset}`);
@@ -170,7 +175,7 @@ export async function handleSessionCommand(ctx, cmd, args) {
});
rl.replaceHistory([]);
await persistSession(session);
- console.log("conversation and prompt history cleared.");
+ print("conversation and prompt history cleared.");
return "handled";
case "/exit":
case "/quit":
diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjs
index 356fb8a9..80024ee7 100644
--- a/scripts/mso-agent-commands.mjs
+++ b/scripts/mso-agent-commands.mjs
@@ -18,6 +18,7 @@ import {
import { handleInspectCommand } from "./mso-agent-cmd-inspect.mjs";
import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";
import { handleJobsCommand } from "./mso-agent-jobs.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };
@@ -50,9 +51,10 @@ async function selectSlashSkill(rl, session, requested, prompt, runTurn) {
const scope = loaded.project?.name
? `project ${loaded.project.name}`
: "global";
+ const { print } = createPrinter({ session, colors: C });
if (!prompt.trim()) {
session.pendingSkill = loaded;
- console.log(
+ print(
`${C.warn}${C.bold}◆ /${loaded.name} queued${C.reset}${C.dim} · next message · ${scope}${C.reset}`,
);
return "handled";
@@ -78,6 +80,7 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
const local = await handleLocalCommand(cmd, args, session, { runCli, runSubagent });
if (local) return local;
+ const printer = createPrinter({ session, colors: C });
const ctx = {
rl,
session,
@@ -87,6 +90,7 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
api,
state,
C,
+ printer,
};
const sessionOutcome = await handleSessionCommand(ctx, cmd, args);
@@ -102,11 +106,11 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {
switch (cmd) {
case "/help":
- printHelp();
+ printHelp({ session });
return "handled";
case "/skill":
if (!args[0]) {
- console.log("usage: /skill <name-or-exact-id> [prompt]");
+ printer.print("usage: /skill <name-or-exact-id> [prompt]");
return "handled";
}
return selectSlashSkill(
diff --git a/scripts/mso-agent-diff.mjs b/scripts/mso-agent-diff.mjs
index 52643315..950d105f 100644
--- a/scripts/mso-agent-diff.mjs
+++ b/scripts/mso-agent-diff.mjs
@@ -3,6 +3,7 @@ import { C } from "./mso-agent-runtime.mjs";
import { api } from "./mso-agent-api.mjs";
import { sectionBlock } from "./mso-agent-layout.mjs";
import { safeErrorSummary } from "./mso-agent-errors.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export function diffLineCap(rows = process.stdout?.rows || 24) {
const terminalRows = Number(rows) || 24;
@@ -104,9 +105,9 @@ export async function handleDiffCommand(session, args = [], options = {}) {
const positional = args.filter((arg) => arg !== "--full" && !arg.startsWith("-"));
let actionRef = positional[0]?.trim() || null;
const sessionId = session?.agentSession?.id;
- const print = options.print || console.log;
- const error = options.error || console.error;
const colors = options.colors || C;
+ const print = options.print || createPrinter({ session, colors }).printBlock;
+ const error = options.error || console.error;
const fetchApi = options.api || api;
if (!sessionId) {
diff --git a/scripts/mso-agent-files.mjs b/scripts/mso-agent-files.mjs
index 8abe56e8..d2c4eef2 100644
--- a/scripts/mso-agent-files.mjs
+++ b/scripts/mso-agent-files.mjs
@@ -5,6 +5,7 @@ import { api } from "./mso-agent-api.mjs";
import { C, fit } from "./mso-agent-ui.mjs";
import { AgentApiError, safeErrorSummary } from "./mso-agent-errors.mjs";
import { sectionDivider } from "./mso-agent-layout.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
// Terminal height minus header, divider, and prompt margin, clamped [5, 60].
export function computeRows(terminalRows = 24) {
@@ -124,7 +125,7 @@ export function formatEntries(entries, { columns = 80, rows = 60, path = "", col
// Bounded read-only view of target or working directory.
export async function handleFilesCommand(args = [], session = null, options = {}) {
const callApi = options.apiFn || api;
- const print = options.print || console.log;
+ const print = options.print || createPrinter({ session, colors: C }).printBlock;
const printErr = options.printErr || console.error;
const rawTarget = args.join(" ").trim();
const targetPath = expandPath(rawTarget);
diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjs
index 833ca7f0..1371e187 100644
--- a/scripts/mso-agent-help.mjs
+++ b/scripts/mso-agent-help.mjs
@@ -1,3 +1,5 @@
+import { createPrinter } from "./mso-agent-print.mjs";
+
export const HELP_LINES = [
" /help show slash commands and keyboard shortcuts",
" /new [title] create and switch to a fresh durable session",
@@ -58,6 +60,7 @@ export const HELP_LINES = [
export const HELP_TEXT = HELP_LINES.join("\n");
-export function printHelp() {
- console.log(HELP_TEXT);
+export function printHelp(options = {}) {
+ const printer = createPrinter(options);
+ printer.printBlock(HELP_TEXT);
}
diff --git a/scripts/mso-agent-jobs.mjs b/scripts/mso-agent-jobs.mjs
index 488b866e..2a6f1438 100644
--- a/scripts/mso-agent-jobs.mjs
+++ b/scripts/mso-agent-jobs.mjs
@@ -1,5 +1,6 @@
import { api, C } from "./mso-agent-runtime.mjs";
import { executeTool } from "./mso-agent-turn.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
export function formatElapsed(ms) {
if (typeof ms !== "number" || Number.isNaN(ms) || ms <= 0) return "0s";
@@ -113,14 +114,16 @@ export function formatJobDetail(job, { colors = {}, now = Date.now() } = {}) {
return lines.join("\n");
}
-export function printJobs(jobs, { colors, maxItems, print = console.log, now } = {}) {
+export function printJobs(jobs, { colors, maxItems, print, now, session } = {}) {
const formatted = formatJobsBlock(jobs, { colors, maxItems, now });
- print(formatted);
+ const doPrint = print || createPrinter({ session, colors }).printBlock;
+ doPrint(formatted);
return formatted;
}
export async function handleJobsCommand(ctx, args = []) {
const { api: request = api, session, rl, C: colors = C } = ctx;
+ const { print, printBlock } = createPrinter(ctx);
const sessionId = session?.agentSession?.id;
const subcommand = args[0];
@@ -134,7 +137,7 @@ export async function handleJobsCommand(ctx, args = []) {
console.error(`${colors.err || ""}${out?.result || "could not list subagent jobs"}${colors.reset || ""}`);
return "handled";
}
- printJobs(parseJobsResult(out.result), { colors });
+ printJobs(parseJobsResult(out.result), { colors, print: printBlock, session });
} catch (err) {
console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
}
@@ -143,16 +146,16 @@ export async function handleJobsCommand(ctx, args = []) {
if (subcommand === "cancel") {
const jobId = args[1]?.trim();
- if (!jobId) { console.log("usage: /jobs cancel <id>"); return "handled"; }
- if (!sessionId) { console.log("cannot cancel: active agent session required for tool approval"); return "handled"; }
+ if (!jobId) { print("usage: /jobs cancel <id>"); return "handled"; }
+ if (!sessionId) { print("cannot cancel: active agent session required for tool approval"); return "handled"; }
try {
const tool = session?.state?.tools?.find((t) => t.name === "agent_subagent_cancel") || { name: "agent_subagent_cancel", scope: "exec" };
const call = { id: `slash_cancel_${Date.now()}`, name: "agent_subagent_cancel", input: { job_id: jobId } };
const outcome = await executeTool(rl, tool, call, session.agentSession, session.permission, undefined, null, { approvalState: session });
- if (!outcome?.ok) { console.log(outcome?.result || "cancel failed"); return "handled"; }
+ if (!outcome?.ok) { print(outcome?.result || "cancel failed"); return "handled"; }
const job = parseJobResult(outcome.result);
- if (job) console.log(formatJobDetail(job, { colors }));
- else console.log(outcome.result || "job cancelled");
+ if (job) printBlock(formatJobDetail(job, { colors }));
+ else print(outcome.result || "job cancelled");
} catch (err) {
console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
}
@@ -170,8 +173,8 @@ export async function handleJobsCommand(ctx, args = []) {
return "handled";
}
const job = parseJobResult(out.result);
- if (job) console.log(formatJobDetail(job, { colors }));
- else console.log(out.result || `job ${jobId} not found`);
+ if (job) printBlock(formatJobDetail(job, { colors }));
+ else print(out.result || `job ${jobId} not found`);
} catch (err) {
console.error(`${colors.err || ""}${err instanceof Error ? err.message : String(err)}${colors.reset || ""}`);
}
diff --git a/scripts/mso-agent-keybinds.mjs b/scripts/mso-agent-keybinds.mjs
index 9dcb349b..a242e434 100644
--- a/scripts/mso-agent-keybinds.mjs
+++ b/scripts/mso-agent-keybinds.mjs
@@ -1,6 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { createPrinter } from "./mso-agent-print.mjs";
// Supported actions and human descriptions. Actions without reachable handlers are excluded.
export const ACTIONS = {
@@ -110,8 +111,7 @@ function settle(bindings, warnings, filePath) {
* @returns {{ bindings: Record<string, string>, warnings: string[] }}
*/
export function loadKeybinds({ path: filePath = defaultKeybindsPath(), readFile = readTextFile } = {}) {
- const defaults = defaultKeybinds();
- const warnings = [];
+ const defaults = defaultKeybinds(), warnings = [];
let raw = "";
try {
raw = readFile(filePath, "utf8");
@@ -190,30 +190,30 @@ export function formatKeybindTable(bindings, { colors = {} } = {}) {
export async function handleKeybindCommand(ctx, args = []) {
const { C: colors = {} } = ctx;
+ const { print, printBlock } = createPrinter(ctx);
const sub = String(args[0] || "").toLowerCase().trim();
const filePath = defaultKeybindsPath();
if (sub === "reset") {
const { bindings } = resetKeybinds({ path: filePath });
- console.log(`reset keybinds to defaults from ${filePath}`);
- console.log(formatKeybindTable(bindings, { colors }));
+ print(`reset keybinds to defaults from ${filePath}`);
+ printBlock(formatKeybindTable(bindings, { colors }));
return "handled";
}
if (sub === "conflicts") {
const conflicts = detectConflicts(getKeybinds());
- if (!conflicts.length) {
- console.log("no keybind conflicts detected");
- } else {
- console.log(`${colors.warn || ""}keybind conflicts detected:${colors.reset || ""}`);
- for (const item of conflicts) console.log(` "${item.key}" bound to: ${item.actions.join(", ")}`);
+ if (!conflicts.length) print("no keybind conflicts detected");
+ else {
+ print(`${colors.warn || ""}keybind conflicts detected:${colors.reset || ""}`);
+ for (const item of conflicts) print(` "${item.key}" bound to: ${item.actions.join(", ")}`);
}
return "handled";
}
const warnings = getKeybindWarnings();
- for (const w of warnings) console.log(`${colors.warn || ""}warning:${colors.reset || ""} ${w}`);
- console.log(`config: ${filePath}`);
- console.log(formatKeybindTable(getKeybinds(), { colors }));
+ for (const w of warnings) print(`${colors.warn || ""}warning:${colors.reset || ""} ${w}`);
+ print(`config: ${filePath}`);
+ printBlock(formatKeybindTable(getKeybinds(), { colors }));
return "handled";
}
diff --git a/scripts/mso-agent-print.mjs b/scripts/mso-agent-print.mjs
new file mode 100644
index 00000000..33421f36
--- /dev/null
+++ b/scripts/mso-agent-print.mjs
@@ -0,0 +1,55 @@
+// Routes command and inspection output to session.printSink when installed
+// (used by panel mode to append lines into the transcript viewport), or falls
+// back to the standard terminal writer in inline mode.
+
+export function createPrinter(options = {}) {
+ // Support passing either an options bag ({ session, colors, write }) or a context directly.
+ const session = options?.session ?? (options?.agentSession || options?.history ? options : null);
+ const colors = options?.colors ?? options?.C ?? {};
+ const write = options?.write ?? console.log;
+
+ function print(line = "") {
+ const sink = session?.printSink;
+ if (sink) {
+ try {
+ if (typeof sink === "function") {
+ sink(line);
+ return;
+ }
+ if (typeof sink.write === "function") {
+ sink.write(line);
+ return;
+ }
+ } catch {
+ // A failing sink must fall back to write: losing an error message is worse than an ugly one.
+ }
+ }
+ write(line);
+ }
+
+ function printLines(lines) {
+ if (!lines) return;
+ for (const line of lines) {
+ print(line);
+ }
+ }
+
+ function printBlock(block) {
+ if (block == null) return;
+ const str = typeof block === "string" ? block : String(block);
+ const lines = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
+ for (const line of lines) {
+ print(line);
+ }
+ }
+
+ print.lines = printLines;
+ print.block = printBlock;
+
+ return {
+ print,
+ printLines,
+ printBlock,
+ colors,
+ };
+}
diff --git a/scripts/mso-agent-print.test.ts b/scripts/mso-agent-print.test.ts
new file mode 100644
index 00000000..5671c040
--- /dev/null
+++ b/scripts/mso-agent-print.test.ts
@@ -0,0 +1,147 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import { createPrinter } from "./mso-agent-print.mjs";
+import { handleTodos } from "./mso-agent-cmd-session.mjs";
+import { handleJobsCommand, printJobs } from "./mso-agent-jobs.mjs";
+import { rememberTodos, resetTodosForTesting } from "./mso-agent-todos.mjs";
+
+describe("mso-agent-print", () => {
+ beforeEach(() => {
+ resetTodosForTesting();
+ });
+
+ // Test 1: no sink configured routes to writer unchanged.
+ it("routes print, printLines, and printBlock to writer in order when no sink installed", () => {
+ const captured: string[] = [];
+ const write = (line: string) => captured.push(line);
+ const printer = createPrinter({ write });
+
+ printer.print("line 1");
+ printer.printLines(["line 2", "line 3"]);
+ printer.printBlock("line 4\nline 5");
+
+ expect(captured).toEqual(["line 1", "line 2", "line 3", "line 4", "line 5"]);
+ });
+
+ // Test 2: sink installed on session receives lines, writer receives nothing.
+ it("routes output to session.printSink when installed, leaving writer untouched", () => {
+ const capturedWriter: string[] = [];
+ const capturedSink: string[] = [];
+ const session: Record<string, any> = {
+ printSink: (line: string) => capturedSink.push(line),
+ };
+ const printer = createPrinter({
+ session,
+ write: (line: string) => capturedWriter.push(line),
+ });
+
+ printer.print("message 1");
+ printer.printLines(["message 2", "message 3"]);
+
+ expect(capturedSink).toEqual(["message 1", "message 2", "message 3"]);
+ expect(capturedWriter).toEqual([]);
+ });
+
+ // Test 3: a multi-line block split on newlines arrives as individual lines at the sink.
+ it("splits a multi-line block into individual lines at the sink", () => {
+ const capturedSink: string[] = [];
+ const session: Record<string, any> = {
+ printSink: (line: string) => capturedSink.push(line),
+ };
+ const printer = createPrinter({ session });
+
+ printer.printBlock("alpha\nbeta\ngamma");
+
+ expect(capturedSink).toEqual(["alpha", "beta", "gamma"]);
+ expect(capturedSink.length).toBe(3);
+ });
+
+ // Test 4: a failing sink must not drop the message and must fall back to writer.
+ it("falls back to writer when session.printSink throws so lines are never lost", () => {
+ const capturedWriter: string[] = [];
+ const session: Record<string, any> = {
+ printSink: () => {
+ throw new Error("simulated sink failure");
+ },
+ };
+ const printer = createPrinter({
+ session,
+ write: (line: string) => capturedWriter.push(line),
+ });
+
+ printer.print("critical message");
+ printer.printBlock("block line 1\nblock line 2");
+
+ expect(capturedWriter).toEqual(["critical message", "block line 1", "block line 2"]);
+ });
+
+ // Test 5: removing the sink dynamically restores writing to the fallback writer.
+ it("restores writer when printSink is removed from the session", () => {
+ const capturedWriter: string[] = [];
+ const capturedSink: string[] = [];
+ const session: Record<string, any> = {
+ printSink: (line: string) => capturedSink.push(line),
+ };
+ const printer = createPrinter({
+ session,
+ write: (line: string) => capturedWriter.push(line),
+ });
+
+ printer.print("to sink");
+ expect(capturedSink).toEqual(["to sink"]);
+ expect(capturedWriter).toEqual([]);
+
+ delete session.printSink;
+
+ printer.print("to writer");
+ expect(capturedWriter).toEqual(["to writer"]);
+ });
+
+ // Test 6: migrated slash commands produce exact expected output with no sink.
+ it("migrated /todos command produces byte-identical output with no sink installed", async () => {
+ const captured: string[] = [];
+ const write = (line: string) => captured.push(line);
+ const ctx = {
+ C: {},
+ session: {},
+ write,
+ };
+
+ // When no checklist exists, /todos writes a fixed explanatory prompt.
+ await handleTodos(ctx, []);
+ expect(captured).toEqual([
+ "no todo list in this session yet: the agent writes one with todo_write",
+ ]);
+
+ captured.length = 0;
+ rememberTodos({
+ items: [
+ { content: "implement print sink", status: "completed" },
+ { content: "verify byte equality", status: "in_progress" },
+ ],
+ summary: null,
+ });
+
+ await handleTodos(ctx, []);
+ expect(captured).toEqual([
+ " [x] implement print sink",
+ " [~] verify byte equality",
+ ]);
+ });
+
+ it("migrated /jobs command produces exact output with no sink installed", async () => {
+ const captured: string[] = [];
+ const write = (line: string) => captured.push(line);
+ const ctx = {
+ C: {},
+ session: null,
+ write,
+ };
+
+ await handleJobsCommand(ctx, ["cancel"]);
+ expect(captured).toEqual(["usage: /jobs cancel <id>"]);
+
+ const directOutput = printJobs([], { colors: {}, print: write });
+ expect(directOutput).toBe("no background subagent jobs found");
+ expect(captured[1]).toBe("no background subagent jobs found");
+ });
+});
diff --git a/scripts/mso-agent-skills.mjs b/scripts/mso-agent-skills.mjs
index 4ec8305b..e5cce68c 100644
--- a/scripts/mso-agent-skills.mjs
+++ b/scripts/mso-agent-skills.mjs
@@ -1,5 +1,6 @@
import path from "node:path";
import process from "node:process";
+import { createPrinter } from "./mso-agent-print.mjs";
function skillRows(skillsData) {
return Array.isArray(skillsData?.skills) ? skillsData.skills : [];
@@ -31,11 +32,12 @@ function skillStateVisual(state, C) {
return { marker: "◇", label: "ready", color: C.blue };
}
-export function beginSkillInvocation(session, skill, C) {
+export function beginSkillInvocation(session, skill, C, options = {}) {
if (!skill) return;
session.activeSkill = skill;
const scope = skill.project?.name ? `project ${skill.project.name}` : "global";
- console.log(`${C.c}${C.bold}◆ skill /${skill.name} invoking${C.reset}${C.dim} · ${scope} · ${skill.trust || "trusted"}${C.reset}`);
+ const { print } = createPrinter({ session, colors: C, write: options?.print });
+ print(`${C.c}${C.bold}◆ skill /${skill.name} invoking${C.reset}${C.dim} · ${scope} · ${skill.trust || "trusted"}${C.reset}`);
}
export function endSkillInvocation(session, skill) {
@@ -114,16 +116,18 @@ export async function loadSlashSkill(api, sessionId, skill) {
}
-export function printSkillChoices(rows, C) {
+export function printSkillChoices(rows, C, options = {}) {
if (!rows?.length) return;
- console.log(`${C.warn}skill name is project-specific or ambiguous; choose one exact id:${C.reset}`);
+ const { print } = createPrinter({ colors: C, session: options?.session, write: options?.print });
+ print(`${C.warn}skill name is project-specific or ambiguous; choose one exact id:${C.reset}`);
for (const skill of rows.slice(0, 20)) {
const project = skill.project?.name ? ` · ${skill.project.name}` : " · global";
- console.log(` /skill ${skill.id}${project}`);
+ print(` /skill ${skill.id}${project}`);
}
}
-export function printSkills(session, C, query = "", cwd = process.cwd()) {
+export function printSkills(session, C, query = "", cwd = process.cwd(), options = {}) {
+ const { print } = createPrinter({ session, colors: C, write: options?.print });
const all = skillRows(session.state.skills);
const q = query.trim().toLowerCase();
const current = currentSkillProject(session.state.skills, cwd);
@@ -136,7 +140,7 @@ export function printSkills(session, C, query = "", cwd = process.cwd()) {
const bp = current && b.project?.id === current.id ? 0 : b.project ? 2 : 1;
return ap - bp || String(a.name || a.id).localeCompare(String(b.name || b.id));
});
- if (current) console.log(`${C.bold}Current project skills:${C.reset} ${current.name} · ${current.path}`);
+ if (current) print(`${C.bold}Current project skills:${C.reset} ${current.name} · ${current.path}`);
const visible = rows.slice(0, 80);
for (const skill of visible) {
const scope = skill.project?.name ? `project:${skill.project.name}` : "global";
@@ -146,8 +150,8 @@ export function printSkills(session, C, query = "", cwd = process.cwd()) {
const description = skill.description
? ` — ${String(skill.description).replace(/[\r\n\t]+/g, " ").slice(0, 120)}`
: "";
- console.log(` ${visual.color}${visual.marker} /${skill.name}${C.reset} ${C.dim}${visual.label} · ${scope}${trust ? ` · ${trust}` : ""}${C.reset}${description}`);
+ print(` ${visual.color}${visual.marker} /${skill.name}${C.reset} ${C.dim}${visual.label} · ${scope}${trust ? ` · ${trust}` : ""}${C.reset}${description}`);
}
- if (rows.length > visible.length) console.log(`${C.dim}… ${rows.length - visible.length} more; refine with /skills <query>${C.reset}`);
- console.log(`${C.dim}Use /<skill> [prompt], or /skill <exact-id> [prompt] for an ambiguous project skill.${C.reset}`);
+ if (rows.length > visible.length) print(`${C.dim}… ${rows.length - visible.length} more; refine with /skills <query>${C.reset}`);
+ print(`${C.dim}Use /<skill> [prompt], or /skill <exact-id> [prompt] for an ambiguous project skill.${C.reset}`);
}
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index 25406c08..de9c82de 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -3,6 +3,7 @@ import path from "node:path";
import { projectHistoryForModel } from "./mso-agent-context.mjs";
import { addProviderUsage } from "../lib/ai/provider-usage.mjs";
import { todoStatusChip } from "./mso-agent-todos.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
function compactNumber(value) {
const n = Number(value || 0);
@@ -119,13 +120,14 @@ function detailedStatus(session, cwd = process.cwd()) {
};
}
-export function printDetailedStatus(session, C, cwd = process.cwd()) {
+export function printDetailedStatus(session, C, cwd = process.cwd(), options = {}) {
const row = detailedStatus(session, cwd);
- console.log(`${C.bold}MSO Agent status${C.reset}`);
- console.log(` model ${row.provider}/${row.model}`);
- console.log(` auth ${row.providerAuth}`);
- console.log(` context ~${row.contextEstimatedTokens}${row.contextWindow ? ` / ${row.contextWindow} (${row.contextPercent}%)` : " / ?"}${row.contextOmittedRows ? ` · ${row.contextOmittedRows} older rows projected out` : ""}`);
- if (row.sessionCompactThresholdTokens) console.log(` session ~${row.sessionEstimatedTokens} / ${row.sessionCompactThresholdTokens} stored · lifetime ~${row.sessionLifetimeEstimatedTokens} · ${row.sessionCompactionCount} compactions · ${row.sessionArchiveCount} archives`);
+ const { print } = createPrinter({ session, colors: C, write: options?.print });
+ print(`${C.bold}MSO Agent status${C.reset}`);
+ print(` model ${row.provider}/${row.model}`);
+ print(` auth ${row.providerAuth}`);
+ print(` context ~${row.contextEstimatedTokens}${row.contextWindow ? ` / ${row.contextWindow} (${row.contextPercent}%)` : " / ?"}${row.contextOmittedRows ? ` · ${row.contextOmittedRows} older rows projected out` : ""}`);
+ if (row.sessionCompactThresholdTokens) print(` session ~${row.sessionEstimatedTokens} / ${row.sessionCompactThresholdTokens} stored · lifetime ~${row.sessionLifetimeEstimatedTokens} · ${row.sessionCompactionCount} compactions · ${row.sessionArchiveCount} archives`);
if ((row.providerReportedUsage.totalTokens ?? 0) > 0 || (row.providerReportedUsage.inputTokens ?? 0) > 0 || (row.providerReportedUsage.outputTokens ?? 0) > 0) {
const u = row.providerReportedUsage;
const parts = [
@@ -137,15 +139,15 @@ export function printDetailedStatus(session, C, cwd = process.cwd()) {
u.reasoningTokens != null ? `${u.reasoningTokens} reasoning` : null,
u.accountingMode ? `mode ${u.accountingMode}` : null,
].filter(Boolean);
- console.log(` tokens ${parts.join(" · ")}`);
- } else console.log(" tokens provider has not reported usage in this process; context remains estimated");
- if (row.skill) console.log(` skill ${row.skill.state} /${row.skill.name}`);
- console.log(` permission ${row.permission}`);
- console.log(` turns ${row.turns}`);
- console.log(` session ${row.session}`);
- console.log(` name @${row.name || "agent"}`);
- console.log(` title ${row.title || "MSO Agent session"}`);
- console.log(` cwd ${row.cwd}`);
- if (row.artifacts?.directory) console.log(` temp ${row.artifacts.directory}`);
- if (row.artifacts?.manifestPath) console.log(` artifacts ${row.artifacts.manifestPath}`);
+ print(` tokens ${parts.join(" · ")}`);
+ } else print(" tokens provider has not reported usage in this process; context remains estimated");
+ if (row.skill) print(` skill ${row.skill.state} /${row.skill.name}`);
+ print(` permission ${row.permission}`);
+ print(` turns ${row.turns}`);
+ print(` session ${row.session}`);
+ print(` name @${row.name || "agent"}`);
+ print(` title ${row.title || "MSO Agent session"}`);
+ print(` cwd ${row.cwd}`);
+ if (row.artifacts?.directory) print(` temp ${row.artifacts.directory}`);
+ if (row.artifacts?.manifestPath) print(` artifacts ${row.artifacts.manifestPath}`);
}
diff --git a/scripts/mso-agent-todos.mjs b/scripts/mso-agent-todos.mjs
index 1b11d85c..d594cfd6 100644
--- a/scripts/mso-agent-todos.mjs
+++ b/scripts/mso-agent-todos.mjs
@@ -1,5 +1,6 @@
import process from "node:process";
import { fit } from "./mso-agent-ui.mjs";
+import { createPrinter } from "./mso-agent-print.mjs";
const VALID_STATUSES = new Set(["pending", "in_progress", "completed"]);
@@ -176,15 +177,16 @@ export function todoStatusChip(state = cachedTodos) {
/**
* Print the formatted todo block via a designated sink.
*/
-export function printTodoBlock(state, { colors, maxItems, print = console.log, activity } = {}) {
+export function printTodoBlock(state, { colors, maxItems, print, activity, session } = {}) {
const formatted = formatTodoBlock(state, { colors, maxItems });
if (!formatted) return false;
+ const doPrint = print || createPrinter({ session, colors }).printBlock;
if (activity?.live) {
activity.clear();
const tone = colors?.c || colors?.cyan || "";
const reset = colors?.reset || "";
- print(`${tone} ✓ todo_write${reset}`);
+ doPrint(`${tone} ✓ todo_write${reset}`);
}
- print(formatted);
+ doPrint(formatted);
return true;
}