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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(tui): a transcript viewport with a scrollbar, so the alternate screen has a reason (#193)
Abdurrahman Fakhrule8ca9cf34daf
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 8c1f4ac5..068f40d8 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` an alternate screen behind a flag, with teardown on every exit path+- `tui` a transcript viewport with a scrollbar, so the alternate screen has a reason+- `tui` an alternate screen behind a flag, with teardown on every exit path (#192)- `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)diff --git a/docs/TUI-RENDERER-PLAN.md b/docs/TUI-RENDERER-PLAN.mdindex cf2e75b6..b8c2f33b 100644--- a/docs/TUI-RENDERER-PLAN.md+++ b/docs/TUI-RENDERER-PLAN.md@@ -593,7 +593,7 @@ those two, and mouse/scrollbar/splits are additive after M5.| 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 #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 |+| M6 | Transcript viewport and scrollbar | DONE | PR #193; 2000-line cap, follow mode, PgUp/PgDn/Ctrl+G/End, entrypoint 218 to 196 lines || 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-oneshot-run.mjs b/scripts/mso-agent-oneshot-run.mjsnew file mode 100644index 00000000..948813b5--- /dev/null+++ b/scripts/mso-agent-oneshot-run.mjs@@ -0,0 +1,40 @@+import process from "node:process";+import { state } from "./mso-agent-api.mjs";+import { persistSession, resumeArg, startupSession } from "./mso-agent-session-ui.mjs";+import { agentRound } from "./mso-agent-turn.mjs";++// One-shot runs without a composer, without a viewport and without the alternate screen: it is+// one prompt in, text or JSON out, so it stays here rather than inside the interactive entrypoint.+export async function runOneShot(opts) {+ const requested = resumeArg(process.argv.slice(2));+ const [s, agentSession] = await Promise.all([state(), startupSession(requested)]);+ if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");+ const session = {+ state: s, agentSession, history: Array.isArray(agentSession.history) ? agentSession.history : [],+ pendingSkill: null, activeSkill: null, lastInvokedSkill: null,+ titleOverride: requested ? (agentSession.title || null) : null,+ usage: { apiCalls: 0 }, lastRouting: null, lastElapsedMs: 0, statusBar: false,+ permission: "ask", pendingApproval: null,+ };+ session.history.push({ role: "user", text: opts.prompt });+ // `--thinking` is a REPORTING flag only: the stream exposes reasoning token counts,+ // not reasoning text, so nothing here changes the turn. Passing `thinking` into+ // agentRound would be dead config, so the flag is consumed in the payload below.+ const result = await agentRound(null, session, null, undefined, null, { quiet: true, approvalScope: opts.approvalScope });+ await persistSession(session);+ const payload = {+ ok: true, sessionId: session.agentSession.id,+ model: `${s.config?.provider || ""}/${s.config?.model || ""}`.replace(/^\//, ""),+ approvalScope: opts.approvalScope, text: result?.text || "", rounds: result?.rounds || 0,+ toolCalls: result?.calls || [], usage: result?.usage || session.usage, routing: session.lastRouting, elapsedMs: result?.elapsedMs || session.lastElapsedMs,+ // Prove what was actually attached instead of leaving --file unverifiable.+ ...(opts.files?.length ? { files: opts.files } : {}),+ // `--thinking` surfaces the reasoning ACCOUNTING the provider really reported.+ // Streams capture reasoning tokens, not reasoning text, so claiming a reasoning+ // block here would be invented output.+ ...(opts.thinking ? { thinking: true, reasoningTokens: (result?.usage ?? session.usage)?.reasoningTokens ?? null } : {}),+ ...(result?.turnLimitReached ? { turnLimitReached: true } : {}),+ };+ if (opts.json) process.stdout.write(`${JSON.stringify(payload)}\n`);+ else process.stdout.write(`${payload.text}${payload.text.endsWith("\n") || !payload.text ? "" : "\n"}`);+}diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjsnew file mode 100644index 00000000..2e5d6ab0--- /dev/null+++ b/scripts/mso-agent-screen-loop.mjs@@ -0,0 +1,139 @@+import process from "node:process";+import { chromeLines } from "./mso-agent-chrome.mjs";+import { composerSeparator } from "./mso-agent-layout.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";+import { renderViewport } from "./mso-agent-viewport-render.mjs";++// Rows kept below the panel for the composer prompt. The composer paints its own rows and cannot+// report them back, so the panel reserves a fixed block instead of guessing per repaint.+const PROMPT_ROWS = 3;++/**+ * Owns the alternate-screen panel: the transcript viewport, its chrome, and the key interception+ * that scrolls it. Everything here is inert when the alternate screen is off, so the inline path+ * keeps running exactly as it did before this module existed.+ *+ * @param {{+ * session: any,+ * enabled?: boolean,+ * output?: any,+ * input?: any,+ * colors?: any,+ * getSessions?: () => Array<any>,+ * }} options+ */+export function mountScreenLoop({+ session,+ enabled = false,+ output = process.stdout,+ input = process.stdin,+ colors = {},+ getSessions = () => [],+} = {}) {+ if (!enabled || !session) {+ return {+ active: false,+ paint() {},+ sync() {},+ follow() {},+ dispose() {},+ };+ }++ const viewport = createViewport({ rows: output.rows || 24 });+ let painted = [];+ let keysPatched = false;+ let originalEmit = null;++ const geometry = () => {+ const cols = Math.max(20, Number(output.columns) || 80);+ const rows = Math.max(6, Number(output.rows) || 24);+ const chrome = chromeLines({+ session,+ sessions: getSessions(),+ activeId: session.agentSession?.id,+ colors,+ width: cols,+ rows: null,+ });+ const separator = composerSeparator(session, colors, cols);+ // The separator belongs to the panel in this mode; the composer is told to draw none.+ const panel = [typeof separator === "string" ? separator : "", ...chrome].filter((line) => line.length > 0);+ return { cols, rows, panel, viewRows: Math.max(0, rows - panel.length - PROMPT_ROWS) };+ };++ // Repaints from the top of the screen and leaves the cursor where the composer expects to start,+ // because the composer paints relative to the cursor and cannot be told where to begin.+ const paint = () => {+ if (output?.isTTY !== true) return;+ const { cols, panel, viewRows } = geometry();+ const body = renderViewport(viewport, { colors, width: cols, rows: viewRows });+ const frame = [...body, ...panel, ""];+ output.write("\x1b[H");+ painted = writeFrame(output, painted, frame);+ output.write(`\x1b[${frame.length};1H`);+ };++ const sync = () => {+ commitStream(viewport);+ setLines(viewport, transcriptLines(session, { colors, width: output.columns || 80 }));+ paint();+ };++ // Streaming text goes into the buffer and repaints, so a long answer does not wait for the turn+ // to end before it becomes visible.+ session.streamSink = {+ write(chunk) {+ appendStream(viewport, chunk);+ paint();+ },+ };++ const onResize = () => {+ viewport.rows = output.rows || 24;+ paint();+ };+ output.on?.("resize", onResize);++ // readline emits keypress on stdin, and the composer is one of its listeners. Intercepting emit+ // is the only way to consume a key before the composer acts on it 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 === "keypress" && args[1] && handleViewportKey(viewport, args[1], { rows: geometry().viewRows })) {+ paint();+ return true;+ }+ return Reflect.apply(originalEmit, this, [event, ...args]);+ };+ }++ setLines(viewport, transcriptLines(session, { colors, width: output.columns || 80 }));+ paint();++ return {+ active: true,+ paint,+ sync,+ follow: () => resetFollow(viewport),+ dispose() {+ output.off?.("resize", onResize);+ if (keysPatched) input.emit = originalEmit;+ if (session.streamSink) delete session.streamSink;+ // 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 = [];+ },+ };+}diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjsindex d0e97807..84e76261 100644--- a/scripts/mso-agent-turn.mjs+++ b/scripts/mso-agent-turn.mjs@@ -19,6 +19,9 @@ import { parseTodoCall, printTodoBlock, rememberTodos } from "./mso-agent-todos.function lazyAssistantOutput(session, options = {}) {if (options.quiet) return null;+ // The alternate-screen panel installs a sink so streamed text lands in the viewport buffer+ // instead of being appended to scrollback that is not visible.+ if (session?.streamSink) return session.streamSink;let opened = false;return {write(value) {diff --git a/scripts/mso-agent-viewport-render.mjs b/scripts/mso-agent-viewport-render.mjsnew file mode 100644index 00000000..ec797344--- /dev/null+++ b/scripts/mso-agent-viewport-render.mjs@@ -0,0 +1,79 @@+import { cellWidth, stripAnsi } from "./tui/cells.mjs";+import { getAllLines, viewportWindow } from "./mso-agent-viewport.mjs";++// Produces a vertical scrollbar column with thumb and track characters matching offset position.+export function scrollbarColumn(viewport, rows, { width = 1 } = {}) {+ const r = Math.max(0, Number(rows ?? viewport?.rows) || 0);+ const w = Math.max(0, Number(width) || 0);+ const allLines = getAllLines(viewport);+ const total = allLines.length;+ if (r <= 0 || w < 1 || total <= r) return [];++ const clampedOffset = Math.max(0, Math.min(viewport.offset, total - r));+ const targetStart = total - r - clampedOffset;+ const thumbHeight = Math.max(1, Math.min(r, Math.round((r / total) * r)));+ const maxThumbTop = r - thumbHeight;+ const thumbTop = maxThumbTop > 0+ ? Math.max(0, Math.min(maxThumbTop, Math.round((targetStart / (total - r)) * maxThumbTop)))+ : 0;++ const column = [];+ for (let i = 0; i < r; i++) {+ column.push(i >= thumbTop && i < thumbTop + thumbHeight ? "█" : "│");+ }+ return column;+}++// Clips content line to target width, handling wide CJK boundaries and appending ellipsis cleanly.+function fitViewportLine(rawText, targetWidth) {+ if (targetWidth <= 0) return "";+ const plainText = stripAnsi(rawText).replace(/[\r\n\t]+/g, " ");+ const currentWidth = cellWidth(plainText);+ if (currentWidth <= targetWidth) {+ return rawText + " ".repeat(targetWidth - currentWidth);+ }++ let accumulated = "", usedWidth = 0;+ for (const ch of plainText) {+ const chWidth = cellWidth(ch);+ if (usedWidth + chWidth > targetWidth) break;+ accumulated += ch;+ usedWidth += chWidth;+ }++ if (usedWidth < currentWidth && targetWidth > 0) {+ while (accumulated && cellWidth(accumulated) > Math.max(0, targetWidth - 1)) {+ accumulated = Array.from(accumulated).slice(0, -1).join("");+ }+ accumulated += "…";+ usedWidth = cellWidth(accumulated);+ }+ return accumulated + " ".repeat(Math.max(0, targetWidth - usedWidth));+}++// Renders the viewport lines padded or clipped to width with optional scrollbar in the final column.+export function renderViewport(viewport, { colors = {}, width = 80, rows = 24 } = {}) {+ const r = Math.max(0, Number(rows ?? viewport?.rows) || 0);+ const w = Math.max(0, Number(width) || 0);+ if (r === 0 || w === 0) return [];++ const { lines: visible } = viewportWindow(viewport, r);+ const scrollbar = scrollbarColumn(viewport, r, { width: 1 });+ const hasScrollbar = Array.isArray(scrollbar) && scrollbar.length === r;+ const contentWidth = hasScrollbar ? Math.max(0, w - 1) : w;+ const cDim = colors?.dim || "", cReset = colors?.reset || "";++ const out = [];+ for (let i = 0; i < r; i++) {+ const raw = i < visible.length ? visible[i] : "";+ const content = fitViewportLine(raw, contentWidth);+ if (hasScrollbar) {+ const barChar = scrollbar[i];+ const styledBar = cDim ? `${cDim}${barChar}${cReset}` : barChar;+ out.push(`${content}${styledBar}`);+ } else {+ out.push(content);+ }+ }+ return out;+}diff --git a/scripts/mso-agent-viewport.mjs b/scripts/mso-agent-viewport.mjsnew file mode 100644index 00000000..e7dd6710--- /dev/null+++ b/scripts/mso-agent-viewport.mjs@@ -0,0 +1,159 @@+import { windowFor } from "./tui/cells.mjs";++const DEFAULT_MAX_LINES = 2000;++// Committed lines plus the in-flight stream line. Exported because the renderer needs the same+// definition and a second copy would drift.+export function getAllLines(viewport) {+ if (!viewport) return [];+ if (typeof viewport.stream === "string" && viewport.stream.length > 0) {+ return [...viewport.lines, viewport.stream];+ }+ return viewport.lines;+}++// Bounded viewport buffer holding committed history and partial in-flight stream text.+// Offset 0 denotes follow mode (pinned to the bottom).+export function createViewport({ rows = 24, maxLines = DEFAULT_MAX_LINES } = {}) {+ return {+ lines: [], stream: "", offset: 0,+ rows: Math.max(0, Number(rows) || 24),+ maxLines: Math.max(10, Number(maxLines) || DEFAULT_MAX_LINES),+ droppedCount: 0,+ };+}++// Resets scroll offset to zero to re-enable follow mode when a new prompt is submitted.+export function resetFollow(viewport) {+ if (viewport) viewport.offset = 0;+}++// Appends complete lines to the buffer, preserving viewport position if scrolled up.+export function appendLines(viewport, lines) {+ if (!viewport || !lines) return;+ const input = Array.isArray(lines) ? lines : [lines];+ const flattened = [];+ for (const item of input) {+ const parts = String(item ?? "").replace(/\r/g, "").split("\n");+ for (const p of parts) flattened.push(p);+ }+ if (flattened.length === 0) return;+ if (viewport.offset > 0) viewport.offset += flattened.length;+ for (const line of flattened) viewport.lines.push(line);++ enforceCap(viewport);+}++// Drops the oldest lines past the cap and leaves a marker, so a long session cannot exhaust+// memory and the reader can still see that something was dropped.+function enforceCap(viewport) {+ if (viewport.lines.length <= viewport.maxLines) return;+ const excess = viewport.lines.length - viewport.maxLines + 1;+ viewport.droppedCount += excess;+ viewport.lines.splice(0, excess);+ const dropMarker = `[... ${viewport.droppedCount} earlier lines dropped ...]`;+ if (viewport.lines.length > 0 && viewport.lines[0].startsWith("[... ") && viewport.lines[0].endsWith(" dropped ...]")) {+ viewport.lines[0] = dropMarker;+ } else {+ viewport.lines.unshift(dropMarker);+ }+ const maxOffset = Math.max(0, getAllLines(viewport).length - viewport.rows);+ viewport.offset = Math.min(viewport.offset, maxOffset);+}++// Replaces the committed lines with a transcript derived again from history. Replacing, not+// appending, because the transcript is recomputed every turn and history can be compacted or+// resumed: an appended buffer would duplicate lines or keep ones that no longer exist.+export function setLines(viewport, lines) {+ if (!viewport) return;+ const flat = [];+ for (const item of Array.isArray(lines) ? lines : [lines]) {+ for (const part of String(item ?? "").replace(/\r/g, "").split("\n")) flat.push(part);+ }+ const wasFollowing = viewport.offset === 0;+ viewport.lines = flat;+ viewport.droppedCount = 0;+ enforceCap(viewport);+ if (wasFollowing) viewport.offset = 0;+}++// Ingests streaming chunks, buffering partial trailing lines without committing them prematurely.+export function appendStream(viewport, chunk) {+ if (!viewport) return;+ const combined = (viewport.stream || "") + String(chunk ?? "").replace(/\r/g, "");+ const parts = combined.split("\n");+ viewport.stream = parts.pop() ?? "";+ if (parts.length > 0) appendLines(viewport, parts);+}++// Commits any pending stream text as a permanent line once turn generation concludes.+export function commitStream(viewport) {+ if (!viewport) return;+ if (typeof viewport.stream === "string" && viewport.stream.length > 0) {+ const trailing = viewport.stream;+ viewport.stream = "";+ appendLines(viewport, [trailing]);+ }+}++// Computes the visible window using windowFor semantics to prevent duplicate boundary code.+export function viewportWindow(viewport, rows) {+ const r = Math.max(0, Number(rows ?? viewport?.rows) || 0);+ const allLines = getAllLines(viewport);+ const total = allLines.length;++ if (r === 0 || total === 0) {+ return { lines: [], offset: 0, total, follow: viewport?.offset === 0, start: 0, end: 0 };+ }+ if (total <= r) {+ return { lines: [...allLines], offset: 0, total, follow: true, start: 0, end: total };+ }++ const maxOffset = total - r;+ const clampedOffset = Math.max(0, Math.min(viewport.offset, maxOffset));+ const targetStart = total - r - clampedOffset;+ const { start, end } = windowFor(allLines, targetStart + Math.floor(r / 2), r);+ return {+ lines: allLines.slice(start, end),+ offset: clampedOffset,+ total,+ follow: clampedOffset === 0,+ start,+ end,+ };+}++// Handles scroll navigation keys, returning true only if the key was recognized and consumed.+export function handleViewportKey(viewport, key, { rows } = {}) {+ if (!viewport || !key || typeof key !== "object") return false;+ const r = Math.max(1, Number(rows ?? viewport.rows) || 1);+ const total = getAllLines(viewport).length;+ const maxOffset = Math.max(0, total - r);+ const halfPage = Math.max(1, Math.floor(r / 2));++ if (key.name === "pageup") {+ viewport.offset = Math.min(maxOffset, viewport.offset + r);+ return true;+ }+ if (key.name === "pagedown") {+ viewport.offset = Math.max(0, viewport.offset - r);+ return true;+ }+ if (key.ctrl && (key.name === "g" || key.name === "G") && !key.shift) {+ viewport.offset = maxOffset;+ return true;+ }+ if (((key.ctrl && key.shift) && (key.name === "g" || key.name === "G")) || key.name === "end") {+ viewport.offset = 0;+ return true;+ }+ if (key.ctrl && key.name === "u") {+ viewport.offset = Math.min(maxOffset, viewport.offset + halfPage);+ return true;+ }+ if (key.ctrl && key.name === "d") {+ viewport.offset = Math.max(0, viewport.offset - halfPage);+ return true;+ }+ return false;+}diff --git a/scripts/mso-agent-viewport.test.ts b/scripts/mso-agent-viewport.test.tsnew file mode 100644index 00000000..1dd383cb--- /dev/null+++ b/scripts/mso-agent-viewport.test.ts@@ -0,0 +1,207 @@+import { describe, expect, it } from "vitest";+import { cellWidth } from "./tui/cells.mjs";+import {+ appendLines, appendStream, commitStream, createViewport, handleViewportKey,+ resetFollow, setLines, viewportWindow,+} from "./mso-agent-viewport.mjs";+import { renderViewport, scrollbarColumn } from "./mso-agent-viewport-render.mjs";++describe("mso-agent-viewport", () => {+ it("1. appending lines keeps follow mode pinned to the bottom", () => {+ const vp = createViewport({ rows: 5 });+ appendLines(vp, ["line 1", "line 2", "line 3"]);+ expect(vp.offset).toBe(0);+ const win1 = viewportWindow(vp, 5);+ expect(win1.follow).toBe(true);+ expect(win1.lines).toEqual(["line 1", "line 2", "line 3"]);++ appendLines(vp, ["line 4", "line 5", "line 6", "line 7"]);+ expect(vp.offset).toBe(0);+ const win2 = viewportWindow(vp, 5);+ expect(win2.follow).toBe(true);+ expect(win2.lines).toEqual(["line 3", "line 4", "line 5", "line 6", "line 7"]);+ });++ it("2. scrolling up leaves follow mode and the window does not move when new lines arrive", () => {+ const vp = createViewport({ rows: 5 });+ appendLines(vp, Array.from({ length: 20 }, (_, i) => `item ${i + 1}`));+ expect(vp.offset).toBe(0);++ const consumed = handleViewportKey(vp, { name: "pageup" }, { rows: 5 });+ expect(consumed).toBe(true);+ expect(vp.offset).toBe(5);++ const winBefore = viewportWindow(vp, 5);+ expect(winBefore.follow).toBe(false);+ expect(winBefore.lines).toEqual(["item 11", "item 12", "item 13", "item 14", "item 15"]);++ appendLines(vp, ["new 1", "new 2", "new 3", "new 4"]);+ expect(vp.offset).toBe(9);+ const winAfter = viewportWindow(vp, 5);+ expect(winAfter.follow).toBe(false);+ expect(winAfter.lines).toEqual(["item 11", "item 12", "item 13", "item 14", "item 15"]);+ });++ it("3. scrolling back to the bottom restores follow mode", () => {+ const vp = createViewport({ rows: 5 });+ appendLines(vp, Array.from({ length: 20 }, (_, i) => `row ${i}`));+ handleViewportKey(vp, { name: "pageup" }, { rows: 5 });+ expect(viewportWindow(vp, 5).follow).toBe(false);++ const consumed = handleViewportKey(vp, { name: "end" }, { rows: 5 });+ expect(consumed).toBe(true);+ expect(vp.offset).toBe(0);+ const win = viewportWindow(vp, 5);+ expect(win.follow).toBe(true);+ expect(win.lines).toEqual(["row 15", "row 16", "row 17", "row 18", "row 19"]);++ vp.offset = 10;+ resetFollow(vp);+ expect(vp.offset).toBe(0);+ expect(viewportWindow(vp, 5).follow).toBe(true);+ });++ it("4. viewportWindow returns at most rows lines and reports the right offset and total", () => {+ const vp = createViewport({ rows: 4 });+ appendLines(vp, ["alpha", "beta", "gamma", "delta", "epsilon", "zeta"]);+ expect(viewportWindow(vp, 0).lines).toEqual([]);++ const win = viewportWindow(vp, 4);+ expect(win.lines).toHaveLength(4);+ expect(win.lines).toEqual(["gamma", "delta", "epsilon", "zeta"]);+ expect(win.total).toBe(6);+ expect(win.offset).toBe(0);++ vp.offset = 1;+ const scrolled = viewportWindow(vp, 4);+ expect(scrolled.lines).toEqual(["beta", "gamma", "delta", "epsilon"]);+ expect(scrolled.offset).toBe(1);+ expect(scrolled.total).toBe(6);+ });++ it("5. the scrollbar is exactly rows lines, is empty when everything fits, and its thumb position tracks the offset", () => {+ const vp = createViewport({ rows: 10 });+ appendLines(vp, ["line 1", "line 2"]);++ expect(scrollbarColumn(vp, 10)).toEqual([]);++ appendLines(vp, Array.from({ length: 40 }, (_, i) => `item ${i}`));+ const barBottom = scrollbarColumn(vp, 10);+ expect(barBottom).toHaveLength(10);+ expect(barBottom[9]).toBe("█");++ handleViewportKey(vp, { ctrl: true, name: "g" }, { rows: 10 });+ const barTop = scrollbarColumn(vp, 10);+ expect(barTop).toHaveLength(10);+ expect(barTop[0]).toBe("█");++ vp.offset = Math.floor((42 - 10) / 2);+ const barMid = scrollbarColumn(vp, 10);+ expect(barMid).toHaveLength(10);+ expect(barMid.slice(1, 9).some((ch) => ch === "█")).toBe(true);+ });++ it("6. renderViewport clips long lines to width and never returns a line wider than width, including when a wide CJK character sits at the boundary", () => {+ const vp = createViewport({ rows: 3 });+ appendLines(vp, ["short", "東京特許許可局局長", "abcdefghijklmnopqrstuvwxyz"]);++ const rendered = renderViewport(vp, { width: 10, rows: 3 });+ expect(rendered).toHaveLength(3);+ for (const line of rendered) {+ expect(cellWidth(line)).toBeLessThanOrEqual(10);+ expect(line).not.toContain("\n");+ expect(line).not.toContain("\r");+ }++ const vpBoundary = createViewport({ rows: 1 });+ appendLines(vpBoundary, ["🌸🌸🌸🌸🌸"]);+ const renderedBoundary = renderViewport(vpBoundary, { width: 7, rows: 1 });+ expect(renderedBoundary).toHaveLength(1);+ expect(cellWidth(renderedBoundary[0])).toBeLessThanOrEqual(7);+ });++ it("7. PgUp, PgDn, Ctrl+G and End move as specified and consume the key; an unrelated key is not consumed", () => {+ const vp = createViewport({ rows: 10 });+ appendLines(vp, Array.from({ length: 50 }, (_, i) => `row ${i}`));++ expect(handleViewportKey(vp, { name: "a" }, { rows: 10 })).toBe(false);+ expect(handleViewportKey(vp, { name: "return" }, { rows: 10 })).toBe(false);+ expect(vp.offset).toBe(0);++ expect(handleViewportKey(vp, { name: "pageup" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(10);++ expect(handleViewportKey(vp, { name: "pagedown" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(0);++ expect(handleViewportKey(vp, { ctrl: true, name: "g" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(40);++ expect(handleViewportKey(vp, { ctrl: true, shift: true, name: "g" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(0);++ expect(handleViewportKey(vp, { ctrl: true, name: "u" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(5);++ expect(handleViewportKey(vp, { ctrl: true, name: "d" }, { rows: 10 })).toBe(true);+ expect(vp.offset).toBe(0);+ });++ it("8. a resize from 30 rows to 8 rows keeps the buffer intact and the offset clamped", () => {+ const vp = createViewport({ rows: 30 });+ appendLines(vp, Array.from({ length: 40 }, (_, i) => `msg ${i}`));+ expect(vp.lines).toHaveLength(40);++ const win30 = viewportWindow(vp, 30);+ expect(win30.lines).toHaveLength(30);++ const win8 = viewportWindow(vp, 8);+ expect(win8.lines).toHaveLength(8);+ expect(vp.lines).toHaveLength(40);+ });++ it("9. the buffer drops the oldest lines past its cap and marks the drop", () => {+ const vp = createViewport({ rows: 5, maxLines: 15 });+ appendLines(vp, Array.from({ length: 25 }, (_, i) => `entry ${i}`));++ expect(vp.lines.length).toBeLessThanOrEqual(15);+ expect(vp.droppedCount).toBeGreaterThan(0);+ expect(vp.lines[0]).toMatch(/\[\.\.\. \d+ earlier lines dropped \.\.\.\]/);+ });++ it("10. a streaming chunk that has not been committed appears as a partial line without breaking the window arithmetic", () => {+ const vp = createViewport({ rows: 5 });+ appendLines(vp, ["line 1", "line 2"]);++ appendStream(vp, "partial stream text");+ const win = viewportWindow(vp, 5);+ expect(win.total).toBe(3);+ expect(win.lines).toEqual(["line 1", "line 2", "partial stream text"]);++ commitStream(vp);+ expect(vp.lines).toEqual(["line 1", "line 2", "partial stream text"]);+ expect(vp.stream).toBe("");+ expect(viewportWindow(vp, 5).total).toBe(3);+ });++ it("11. setLines replaces the transcript instead of appending a duplicate copy", () => {+ const vp = createViewport({ rows: 5 });+ setLines(vp, ["[user] one", "[assistant] two"]);+ expect(vp.lines).toEqual(["[user] one", "[assistant] two"]);+ setLines(vp, ["[user] one", "[assistant] two", "[tool] three"]);+ expect(vp.lines).toEqual(["[user] one", "[assistant] two", "[tool] three"]);+ expect(vp.offset).toBe(0);+ });++ it("12. setLines keeps a scrolled-up reader where they were and still applies the cap", () => {+ const vp = createViewport({ rows: 4, maxLines: 10 });+ setLines(vp, Array.from({ length: 30 }, (_, i) => `row ${i}`));+ expect(vp.lines.length).toBeLessThanOrEqual(10);+ expect(vp.lines[0]).toContain("earlier lines dropped");+ handleViewportKey(vp, { name: "pageup" }, { rows: 4 });+ const offset = vp.offset;+ setLines(vp, Array.from({ length: 30 }, (_, i) => `next ${i}`));+ expect(vp.offset).toBeLessThanOrEqual(offset);+ expect(vp.lines.at(-1)).toBe("next 29");+ });+});diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex dccb5575..6eaca6da 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -12,7 +12,9 @@ import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-import { oneShotHelp, parseOneShot } from "./mso-agent-oneshot.mjs";import { LocalAgentBridge, handleLocalAgentMentionInput, runForegroundSubagent } from "./mso-agent-collaboration.mjs";import { composerPrompt, composerSeparator } from "./mso-agent-layout.mjs";-import { agentRound, executeTool, renderInteractionFailure, runInteractiveRound } from "./mso-agent-turn.mjs";+import { executeTool, renderInteractionFailure, runInteractiveRound } from "./mso-agent-turn.mjs";+import { runOneShot } from "./mso-agent-oneshot-run.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";import { pathToFileURL } from "node:url";import { createQueue, dequeue } from "./mso-agent-queue.mjs";import { pendingImageBlock } from "./mso-agent-image.mjs";@@ -20,41 +22,6 @@ import { altScreenRequested, startAltScreen } from "./mso-agent-altscreen.mjs";import { visibleSessionRows } from "./mso-agent-sessions.mjs";import { chromeLines } from "./mso-agent-chrome.mjs";-async function runOneShot(opts) {- const requested = resumeArg(process.argv.slice(2));- const [s, agentSession] = await Promise.all([state(), startupSession(requested)]);- if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");- const session = {- state: s, agentSession, history: Array.isArray(agentSession.history) ? agentSession.history : [],- pendingSkill: null, activeSkill: null, lastInvokedSkill: null,- titleOverride: requested ? (agentSession.title || null) : null,- usage: { apiCalls: 0 }, lastRouting: null, lastElapsedMs: 0, statusBar: false,- permission: "ask", pendingApproval: null,- };- session.history.push({ role: "user", text: opts.prompt });- // `--thinking` is a REPORTING flag only: the stream exposes reasoning token counts,- // not reasoning text, so nothing here changes the turn. Passing `thinking` into- // agentRound would be dead config, so the flag is consumed in the payload below.- const result = await agentRound(null, session, null, undefined, null, { quiet: true, approvalScope: opts.approvalScope });- await persistSession(session);- const payload = {- ok: true, sessionId: session.agentSession.id,- model: `${s.config?.provider || ""}/${s.config?.model || ""}`.replace(/^\//, ""),- approvalScope: opts.approvalScope, text: result?.text || "", rounds: result?.rounds || 0,- toolCalls: result?.calls || [], usage: result?.usage || session.usage, routing: session.lastRouting, elapsedMs: result?.elapsedMs || session.lastElapsedMs,- // Prove what was actually attached instead of leaving --file unverifiable.- ...(opts.files?.length ? { files: opts.files } : {}),- // `--thinking` surfaces the reasoning ACCOUNTING the provider really reported.- // Streams capture reasoning tokens, not reasoning text, so claiming a reasoning- // block here would be invented output.- ...(opts.thinking ? { thinking: true, reasoningTokens: (result?.usage ?? session.usage)?.reasoningTokens ?? null } : {}),- ...(result?.turnLimitReached ? { turnLimitReached: true } : {}),- };- if (opts.json) process.stdout.write(`${JSON.stringify(payload)}\n`);- else process.stdout.write(`${payload.text}${payload.text.endsWith("\n") || !payload.text ? "" : "\n"}`);-}--async function main() {const argv = process.argv.slice(2);if (argv.includes("--help") || argv.includes("-h")) { process.stdout.write(`${oneShotHelp()}\n`); return; }@@ -97,7 +64,8 @@ async function main() {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);+ const screenLoop = mountScreenLoop({ session, enabled: altScreen.ok, output: process.stdout, input: process.stdin, colors: C, getSessions: () => recentSessions });+ rl = new AgentComposer({ input: process.stdin, output: process.stdout, colors: C, onToggleStatusBar: () => { session.statusBar = !session.statusBar; screenLoop.paint(); } }); syncPromptHistory(rl, session);let inboundRequestQueued = false;localBridge = new LocalAgentBridge({session,@@ -134,6 +102,7 @@ async function main() {const skillContext = session.pendingSkill;session.pendingSkill = null;await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);+ screenLoop.sync();}};onSigint = () => {@@ -151,21 +120,26 @@ async function main() {if (inboundRequestQueued) {inboundRequestQueued = false;await runInteractiveRound(rl, session, null, interrupts, localBridge);+ screenLoop.sync();continue;}let line = "";try {+ screenLoop.paint();const answer = await rl.question(() => composerPrompt(session, C), {complete: completeSlash,onTab: () => { session.permission = nextPermissionMode(session.permission).id; },- separator: () => composerSeparator(session, C, process.stdout.columns),- footer: chromeFooter,+ // The panel already draws the separator and the footer above the prompt, so drawing+ // them twice would push the prompt off the reserved rows.+ separator: () => (screenLoop.active ? "" : composerSeparator(session, C, process.stdout.columns)),+ footer: () => (screenLoop.active ? "" : chromeFooter()),});if (answer === null) {if (inboundRequestQueued) continue;break;}line = answer.trim();+ screenLoop.follow();} catch { break; }if (!line) continue;if (line.startsWith("/")) {@@ -183,10 +157,11 @@ async function main() {renderInteractionFailure(error, session, {}, C);await persistSession(session).catch(() => undefined);}+ screenLoop.sync();if (interrupts.exitRequested) break;continue;}- if (await handleLocalAgentMentionInput(session, line, C)) continue;+ if (await handleLocalAgentMentionInput(session, line, C)) { screenLoop.sync(); continue; }// Attached images belong to the NEXT prompt only. Format them into the user// message once, then clear, so a stale image can never ride along silently.const images = Array.isArray(session.pendingImages) ? session.pendingImages : [];@@ -195,7 +170,9 @@ async function main() {if (images.length) session.pendingImages = [];const skillContext = session.pendingSkill;session.pendingSkill = null;+ screenLoop.sync();await runInteractiveRound(rl, session, skillContext, interrupts, localBridge);+ screenLoop.sync();if (interrupts.exitRequested) break;if (!lastTurnInterrupted) await drainQueue();}@@ -206,6 +183,7 @@ async function main() {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();+ screenLoop?.dispose();screen?.dispose();}if (restartRequested) {