Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(tui): a transcript model, because scrollback is the only transcript that exists (#187)

Abdurrahman Fakhrul19c7dceb5570
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d2102175..9baf3558 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**
-- `agent` /jobs, so background subagents are visible instead of fire and forget
+- `tui` a transcript model, because scrollback is the only transcript that exists
+- `agent` /jobs, so background subagents are visible instead of fire and forget (#183)
- `tui` configurable keybinds, with the defaults kept byte-identical (#182)
- `agent` show the todo checklist in the TUI and in the status row (#179)
diff --git a/scripts/mso-agent-transcript.mjs b/scripts/mso-agent-transcript.mjs
new file mode 100644
index 00000000..ffce80c8
--- /dev/null
+++ b/scripts/mso-agent-transcript.mjs
@@ -0,0 +1,206 @@
+import { formatEditDiff } from "./mso-agent-edit-diff.mjs";
+import { formatTodoBlock } from "./mso-agent-todos.mjs";
+import { formatDiffBody } from "./mso-agent-diff.mjs";
+
+const DEFAULT_CLIP_CHARS = 1000;
+
+function safeJson(value) {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
+ try { return JSON.parse(trimmed); } catch { return null; }
+}
+
+function getHistory(session) {
+ if (Array.isArray(session)) return session;
+ if (Array.isArray(session?.history)) return session.history;
+ if (Array.isArray(session?.agentSession?.history)) return session.agentSession.history;
+ return [];
+}
+
+function rolePrefix(role, colors) {
+ if (!colors || Object.keys(colors).length === 0) return `[${role}] `;
+ const reset = colors.reset || "";
+ const tone = role === "user" ? (colors.blue || colors.c || "")
+ : role === "assistant" ? (colors.cyan || colors.c || "")
+ : role === "tool" ? (colors.warn || colors.dim || "")
+ : role === "agent" ? (colors.c || colors.cyan || "")
+ : (colors.dim || "");
+ return tone ? `${tone}[${role}]${reset} ` : `[${role}] `;
+}
+
+function pushMultiline(lines, prefix, text) {
+ const parts = String(text ?? "").replace(/\r/g, "").split("\n");
+ if (parts.length) lines.push(`${prefix}${parts[0]}`);
+ for (let j = 1; j < parts.length; j += 1) lines.push(` ${parts[j]}`);
+}
+
+function formatCallArgs(input) {
+ if (!input || typeof input !== "object" || Object.keys(input).length === 0) return "";
+ try {
+ const raw = JSON.stringify(input);
+ return raw.length > 60 ? ` ${raw.slice(0, 57)}...` : ` ${raw}`;
+ } catch { return ""; }
+}
+
+function formatCompactedPlaceholder(payload) {
+ const handles = Array.isArray(payload?.handles) && payload.handles.length
+ ? `: ${payload.handles.map((h) => h?.path || h?.jobId || h?.artifactId || h?.kind).filter(Boolean).join(", ")}`
+ : "";
+ const note = payload?.instruction ? ` (${payload.instruction})` : "";
+ return `[compacted replay${handles}]${note}`;
+}
+
+function formatToolPayload(toolName, result, colors, clipLimit, width) {
+ if (!result || typeof result !== "object") return ["(no result)"];
+ if (result.msoReplay === true) return [formatCompactedPlaceholder(safeJson(result.content) || result)];
+ const raw = typeof result.content === "string" ? result.content : result.content != null ? JSON.stringify(result.content) : "";
+ if (!raw) return ["(no result)"];
+ const parsed = safeJson(raw);
+ if (parsed?.msoReplay === true) return [formatCompactedPlaceholder(parsed)];
+ if (parsed && typeof parsed.diff === "string") {
+ const editLines = formatEditDiff(parsed, { colors });
+ if (editLines) return editLines.split("\n");
+ }
+ if (parsed && Array.isArray(parsed.items)) {
+ const todoLines = formatTodoBlock(parsed, { colors, columns: width });
+ if (todoLines) return todoLines.split("\n");
+ }
+ if (raw.startsWith("diff --git") || raw.startsWith("@@ ")) {
+ const diffLines = formatDiffBody(raw, { colors });
+ if (diffLines) return diffLines.split("\n").map((l) => ` ${l}`);
+ }
+ const clipped = raw.length > clipLimit ? `${raw.slice(0, clipLimit)} ... [clipped]` : raw;
+ return clipped.replace(/\r/g, "").split("\n");
+}
+
+export function transcriptLines(session, { colors, width, groupTools = false, maxPerTool = 1, clipLimit = DEFAULT_CLIP_CHARS } = {}) {
+ const history = getHistory(session);
+ const lines = [];
+ let lastToolCalls = new Map();
+ let lastToolCallList = [];
+
+ for (let i = 0; i < history.length; i += 1) {
+ const row = history[i];
+ if (!row || typeof row !== "object") continue;
+
+ if (row.role === "user") {
+ pushMultiline(lines, rolePrefix("user", colors), typeof row.text === "string" ? row.text : (row.text != null ? String(row.text) : ""));
+ } else if (row.role === "assistant") {
+ lastToolCalls = new Map();
+ lastToolCallList = Array.isArray(row.toolUses) ? row.toolUses : [];
+ for (const call of lastToolCallList) if (call?.id) lastToolCalls.set(String(call.id), String(call.name || "tool"));
+ const prefix = rolePrefix("assistant", colors);
+ const text = typeof row.text === "string" ? row.text : (row.text != null ? String(row.text) : "");
+ if (text.trim()) pushMultiline(lines, prefix, text);
+ for (const call of lastToolCallList) {
+ if (!call || typeof call !== "object") continue;
+ lines.push(`${prefix}call ${String(call.name || "tool")}${formatCallArgs(call.input)}`);
+ }
+ } else if (row.role === "tool") {
+ const prefix = rolePrefix("tool", colors);
+ const results = Array.isArray(row.results) ? row.results : (row.result != null || row.content != null ? [row] : []);
+ if (!results.length) lines.push(`${prefix}${row.name || "tool"}: (no result)`);
+ for (let rIdx = 0; rIdx < results.length; rIdx += 1) {
+ const item = results[rIdx];
+ const id = item?.id ? String(item.id) : "";
+ const toolName = item?.name || item?.tool || row.name || (id ? lastToolCalls.get(id) : null) || lastToolCallList[rIdx]?.name || "tool";
+ const pl = formatToolPayload(toolName, item, colors, clipLimit, width);
+ if (pl.length === 1) lines.push(`${prefix}${toolName}: ${pl[0]}`);
+ else {
+ lines.push(`${prefix}${toolName}:`);
+ for (const line of pl) lines.push(line.startsWith(" ") ? line : ` ${line}`);
+ }
+ }
+ } else if (row.role === "agent") {
+ const sender = row.senderLabel ? `@${row.senderLabel}: ` : "";
+ pushMultiline(lines, rolePrefix("agent", colors), `${sender}${typeof row.text === "string" ? row.text : (row.text != null ? String(row.text) : "")}`);
+ } else {
+ const text = typeof row.text === "string" ? row.text : (row.content ? String(row.content) : "");
+ if (text) pushMultiline(lines, rolePrefix(String(row.role || "unknown"), colors), text);
+ }
+ }
+
+ return groupTools ? groupToolRows(lines, { maxPerTool }) : lines;
+}
+
+// Collapsing consecutive rows of the same tool is the right default because
+// autonomous agent turns often invoke dozens of repetitive tool calls in loops
+// (e.g. read files or stat paths). Collapsing them preserves scrollback budget.
+export function groupToolRows(lines, { maxPerTool = 1 } = {}) {
+ if (!Array.isArray(lines) || !lines.length) return [];
+ if (typeof lines[0] === "object" && lines[0] !== null && "role" in lines[0]) {
+ const out = [];
+ let cur = null, grp = [];
+ const flush = () => {
+ if (!grp.length) return;
+ if (grp.length > maxPerTool) out.push({ role: "tool", name: cur, count: grp.length, collapsed: true });
+ else out.push(...grp);
+ grp = []; cur = null;
+ };
+ for (const r of lines) {
+ const name = r?.role === "tool" ? (r.name || r.results?.[0]?.name || "tool") : null;
+ if (name) {
+ if (cur === name) grp.push(r);
+ else { flush(); cur = name; grp = [r]; }
+ } else { flush(); out.push(r); }
+ }
+ flush();
+ return out;
+ }
+
+ const out = [];
+ let curTool = null, curPrefix = "", curLines = [], toolCount = 0;
+ const flush = () => {
+ if (!curLines.length) return;
+ if (toolCount > maxPerTool) out.push(`${curPrefix}${curTool} (${toolCount} calls)`);
+ else out.push(...curLines);
+ curTool = null; curPrefix = ""; curLines = []; toolCount = 0;
+ };
+
+ for (const line of lines) {
+ const plain = String(line || "").replace(/\x1b\[[0-9;]*m/g, "");
+ const m = plain.match(/^\[([a-zA-Z0-9_-]+)\]\s+([a-zA-Z0-9_.-]+)(?::|\s|\(|$)/);
+ if (m && m[1] === "tool") {
+ const tool = m[2];
+ const pfx = (line.match(/^([^\s]+)\s+/) || [])[0] || "[tool] ";
+ if (curTool === tool) {
+ toolCount += 1;
+ curLines.push(line);
+ } else {
+ flush();
+ curTool = tool; curPrefix = pfx; curLines = [line]; toolCount = 1;
+ }
+ } else if (curLines.length && String(line).startsWith(" ")) {
+ curLines.push(line);
+ } else {
+ flush();
+ out.push(line);
+ }
+ }
+ flush();
+ return out;
+}
+
+export function transcriptStats(session) {
+ const history = getHistory(session);
+ let userTurns = 0, assistantTurns = 0, assistantToolCalls = 0, standaloneToolResults = 0;
+
+ for (let i = 0; i < history.length; i += 1) {
+ const row = history[i];
+ if (!row || typeof row !== "object") continue;
+ if (row.role === "user") userTurns += 1;
+ else if (row.role === "assistant") {
+ assistantTurns += 1;
+ if (Array.isArray(row.toolUses)) assistantToolCalls += row.toolUses.length;
+ } else if (row.role === "tool") {
+ const prev = i > 0 ? history[i - 1] : null;
+ const count = Array.isArray(row.results) ? row.results.length : 1;
+ if (!prev || prev.role !== "assistant" || !Array.isArray(prev.toolUses) || !prev.toolUses.length) {
+ standaloneToolResults += count;
+ }
+ }
+ }
+
+ return { rows: history.length, userTurns, assistantTurns, toolCalls: assistantToolCalls + standaloneToolResults };
+}
diff --git a/scripts/mso-agent-transcript.test.ts b/scripts/mso-agent-transcript.test.ts
new file mode 100644
index 00000000..4479c650
--- /dev/null
+++ b/scripts/mso-agent-transcript.test.ts
@@ -0,0 +1,165 @@
+import { describe, expect, it } from "vitest";
+import { groupToolRows, transcriptLines, transcriptStats } from "./mso-agent-transcript.mjs";
+
+describe("mso-agent-transcript", () => {
+ it("1. a realistic session with a user row, an assistant row with toolUses, and several tool rows renders in order with distinguishable prefixes and no ANSI when no palette is passed", () => {
+ const session = {
+ history: [
+ { role: "user", text: "Please list the files and check git status." },
+ {
+ role: "assistant",
+ text: "I will list the directory and check git status.",
+ toolUses: [
+ { id: "call_1", name: "fs_list", input: { path: "src" } },
+ { id: "call_2", name: "git_status", input: {} },
+ ],
+ },
+ {
+ role: "tool",
+ results: [
+ { id: "call_1", content: "index.ts\napp.ts" },
+ { id: "call_2", content: "clean" },
+ ],
+ },
+ ],
+ };
+ const lines = transcriptLines(session);
+ expect(lines[0]).toBe("[user] Please list the files and check git status.");
+ expect(lines[1]).toBe("[assistant] I will list the directory and check git status.");
+ expect(lines[2]).toBe('[assistant] call fs_list {"path":"src"}');
+ expect(lines[3]).toBe("[assistant] call git_status");
+ expect(lines.some((line) => line.startsWith("[tool] fs_list:"))).toBe(true);
+ expect(lines.some((line) => line.startsWith("[tool] git_status:"))).toBe(true);
+ for (const line of lines) expect(/\x1b\[[0-9;]*m/.test(line)).toBe(false);
+ });
+
+ it("2. consecutive tool rows of the same tool collapse into one counted row, and the count is right", () => {
+ const lines = [
+ "[user] Read configuration",
+ "[tool] fs_read: config1",
+ "[tool] fs_read: config2",
+ "[tool] fs_read: config3",
+ "[user] Done",
+ ];
+ const collapsed = groupToolRows(lines, { maxPerTool: 1 });
+ expect(collapsed).toContain("[tool] fs_read (3 calls)");
+ expect(collapsed).not.toContain("[tool] fs_read: config1");
+ expect(collapsed[0]).toBe("[user] Read configuration");
+ expect(collapsed[collapsed.length - 1]).toBe("[user] Done");
+
+ const session = {
+ history: [
+ {
+ role: "assistant",
+ toolUses: [{ id: "c1", name: "fs_read" }, { id: "c2", name: "fs_read" }, { id: "c3", name: "fs_read" }],
+ },
+ {
+ role: "tool",
+ results: [{ id: "c1", content: "d1" }, { id: "c2", content: "d2" }, { id: "c3", content: "d3" }],
+ },
+ ],
+ };
+ expect(transcriptLines(session, { groupTools: true, maxPerTool: 1 })).toContain("[tool] fs_read (3 calls)");
+ });
+
+ it("3. an assistant row with text but no tools still renders its text", () => {
+ const session = { history: [{ role: "assistant", text: "Everything has been resolved successfully." }] };
+ expect(transcriptLines(session)).toEqual(["[assistant] Everything has been resolved successfully."]);
+ });
+
+ it("4. an agent row renders with its own prefix", () => {
+ const session = {
+ history: [{ role: "agent", text: "Task completed by subagent.", senderLabel: "worker-1" }],
+ };
+ const lines = transcriptLines(session);
+ expect(lines.length).toBe(1);
+ expect(lines[0].startsWith("[agent] ")).toBe(true);
+ expect(lines[0]).toContain("@worker-1: Task completed by subagent.");
+ });
+
+ it("5. malformed rows (null, {}, a row with a non-string content, a tool row with no result, a huge result over a clip threshold) do not throw, and the huge result is clipped with a visible marker", () => {
+ const huge = "A".repeat(5000);
+ const session = {
+ history: [
+ null, {},
+ { role: "user", text: 12345 },
+ { role: "tool" },
+ { role: "tool", results: [] },
+ { role: "tool", results: [null, {}] },
+ { role: "tool", results: [{ id: "c_huge", name: "sys_log", content: huge }] },
+ ],
+ };
+ let lines: string[] = [];
+ expect(() => { lines = transcriptLines(session as any, { clipLimit: 500 }); }).not.toThrow();
+ expect(lines.some((l) => l.includes("[user] 12345"))).toBe(true);
+ expect(lines.some((l) => l.includes("[tool] tool: (no result)"))).toBe(true);
+ const hugeLine = lines.find((l) => l.includes("sys_log"));
+ expect(hugeLine).toBeDefined();
+ expect(hugeLine!).toContain("[clipped]");
+ expect(hugeLine!.length).toBeLessThan(1000);
+ });
+
+ it("6. transcriptStats counts match the fixture", () => {
+ const session = {
+ history: [
+ { role: "user", text: "First prompt" },
+ { role: "assistant", text: "Looking into it", toolUses: [{ id: "1", name: "fs_read" }, { id: "2", name: "fs_write" }] },
+ { role: "tool", results: [{ id: "1", content: "ok" }, { id: "2", content: "written" }] },
+ { role: "user", text: "Second prompt" },
+ { role: "assistant", text: "Finished work", toolUses: [{ id: "3", name: "git_diff" }] },
+ { role: "tool", results: [{ id: "3", content: "diff" }] },
+ { role: "agent", text: "background task done", senderLabel: "worker" },
+ ],
+ };
+ expect(transcriptStats(session)).toEqual({ rows: 7, userTurns: 2, assistantTurns: 2, toolCalls: 3 });
+ });
+
+ it("7. determinism: calling twice returns deeply equal arrays", () => {
+ const session = {
+ history: [
+ { role: "user", text: "Verify deterministic output" },
+ { role: "assistant", text: "Running checks", toolUses: [{ id: "c1", name: "test_tool", input: { flag: true } }] },
+ { role: "tool", results: [{ id: "c1", content: "result value" }] },
+ ],
+ };
+ expect(transcriptLines(session)).toEqual(transcriptLines(session));
+ });
+
+ it("8. a tool row whose result is already a compacted placeholder (the shape stored by the context module) renders the placeholder rather than undefined", () => {
+ const payload = {
+ msoReplay: true, rawResultBytes: 4096,
+ handles: [{ kind: "file", path: "/repo/src/app.ts", rereadWith: "read_pipeline" }],
+ instruction: "Re-read only the needed handle with the bounded read/status surface.",
+ };
+ const session = {
+ history: [
+ { role: "assistant", text: "", toolUses: [{ id: "r1", name: "fs_read", input: { path: "/repo/src/app.ts" } }] },
+ { role: "tool", results: [{ id: "r1", isError: false, msoReplay: true, content: JSON.stringify(payload) }] },
+ ],
+ };
+ const lines = transcriptLines(session);
+ const toolLine = lines.find((l) => l.startsWith("[tool] fs_read"));
+ expect(toolLine).toBeDefined();
+ expect(toolLine).toContain("compacted replay");
+ expect(toolLine).toContain("/repo/src/app.ts");
+ expect(toolLine).toContain("Re-read only the needed handle");
+ expect(lines.every((l) => !l.includes("undefined"))).toBe(true);
+ });
+
+ it("reuses formatEditDiff, formatTodoBlock, and formatDiffBody when tool results match", () => {
+ const edit = { path: "/repo/src/main.ts", written: true, diff: "--- a/src/main.ts\n+++ b/src/main.ts\n@@ -1 +1 @@\n-old\n+new\n" };
+ const todo = { items: [{ status: "completed", content: "step one" }], summary: { count: 1, completed: 1 } };
+ const diff = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n-old\n+new";
+ const session = {
+ history: [
+ { role: "tool", name: "fs_edit", results: [{ id: "e", content: JSON.stringify(edit) }] },
+ { role: "tool", name: "agent_todo", results: [{ id: "t", content: JSON.stringify(todo) }] },
+ { role: "tool", name: "git_diff", results: [{ id: "d", content: diff }] },
+ ],
+ };
+ const lines = transcriptLines(session);
+ expect(lines.some((l) => l.includes("edit main.ts"))).toBe(true);
+ expect(lines.some((l) => l.includes("[x] step one"))).toBe(true);
+ expect(lines.some((l) => l.includes("diff --git a/f"))).toBe(true);
+ });
+});