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): opencode batch three, from starved flags to a written contract (#258)
Abdurrahman Fakhrulf9df3958103b
diff --git a/docs/AGENT-ACTIVITY-SIGNAL.md b/docs/AGENT-ACTIVITY-SIGNAL.mdindex 3d191207..0029bdd8 100644--- a/docs/AGENT-ACTIVITY-SIGNAL.md+++ b/docs/AGENT-ACTIVITY-SIGNAL.md@@ -69,3 +69,8 @@ The minimal server change and lifecycle markers have landed:- Write point 1 (turn start): inside `runInteractiveRound`, before `agentRound` begins, persists the session with `turnStartedAt = new Date().toISOString()`.- Write point 2 (turn end): inside the `finally` block of `runInteractiveRound`, clears `turnStartedAt` to `null` so interrupted or crashed turns never stick in the active state.- All bookkeeping writes catch and suppress errors so network or storage issues during bookkeeping never abort the agent round.++6. **TUI consumption and loop closure (`scripts/mso-agent-session-list.mjs`):**+ - Wired `turnActive` into `stateOf`: `turnActive: true` derives `working` (eliminating false idle during active turns), and `turnActive: false` derives `idle` (eliminating false working immediately post-turn).+ - Added `turnActive === true` to `needsAttention` and identified it in `attentionReason` as `turnActive: working`, enabling `/tabs next` and `/tabs prev` to navigate truthfully to active sessions.+ - Connected `turnActive` through `/tabs` table and tab row indicators, completing the loop across all TUI views without client-side timestamp arithmetic.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex e5c4c7c3..860dcc0b 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,6 +4,25 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → Account → About shows as “What's new”.+## 2026-11-03++**Added**++- `tui` opencode batch three, from starved flags to a written contract++**Other**++- feat/tui-session-export+- feat/tui-approval-summary+- feat/tui-transcript-search (conflicts kept both sides)+- feat/tui-keybind-help (conflicts kept both sides)+- feat/tui-pane-live-context (conflicts kept both sides)+- feat/tui-help-width+- feat/tui-compaction-live+- feat/tui-attention-wire+- feat/tabs-turnactive+- docs/tui-panel-contract+## 2026-11-02**Added**@@ -1506,20 +1525,3 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Docs**- `security` disclose scorecard posture gaps--## 2026-08-29--**Fixed**--- `security` keep path sinks in validated branches-- `security` make root containment explicit-- `security` close follow-up CodeQL flows--**Docs**--- `comparison` use explicit SEO-friendly ratings--**Chores**--- `deps` hold incompatible toolchain majors-- `deps` migrate to lucide-react 1.33.0diff --git a/docs/README.md b/docs/README.mdindex d068153b..b624332f 100644--- a/docs/README.md+++ b/docs/README.md@@ -65,6 +65,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`TUI-RENDERER-PLAN.md`](./TUI-RENDERER-PLAN.md) | What the TUI is today, why a retained renderer is the only path to panels and tabs, and the M0 to M8 order that keeps every gate green || [`TUI-HANDOVER.md`](./TUI-HANDOVER.md) | Where the TUI panel track stands, the state of the one in-progress branch, and what must be true before the alternate screen becomes the default || [`REA-OPENCODE-TUI.md`](./REA-OPENCODE-TUI.md) | Reverse-engineered opencode TUI study: OpenTUI engine evidence, settings/command registries, sidebar slots, tabs status, and fit for MSO |+| [`TUI-PANEL-CONTRACT.md`](./TUI-PANEL-CONTRACT.md) | The invariants a TUI change must not break, each with the failure that proved it: byte-identical defaults, no setting without a consumer, and why updatedAt is not an activity signal || [`AGENT-ACTIVITY-SIGNAL.md`](./AGENT-ACTIVITY-SIGNAL.md) | Why a live session activity signal cannot be derived today, the evidence per code path, and the smallest server change that would enable it || [`ORGANIZATION.md`](./ORGANIZATION.md) | Owner-private organization units, seats, reporting lines, live agent bindings, and workflow routing references || [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting |diff --git a/docs/TUI-PANEL-CONTRACT.md b/docs/TUI-PANEL-CONTRACT.mdnew file mode 100644index 00000000..ac9fd4fb--- /dev/null+++ b/docs/TUI-PANEL-CONTRACT.md@@ -0,0 +1,149 @@+# Panel contract: the rules a TUI change must not break++Written after three batches of panel work, because every one of them re-learned the same lessons the hard+way. This is not a tour of the code. It is the list of invariants that have already been broken once, with+the failure each one caused, so the next change can be checked against them instead of discovering them.++Read this before touching anything under `scripts/mso-agent-*`.++## 1. Defaults must be byte-identical++Any change that alters rendered output ships behind a default that reproduces today exactly. Prove it with a+fixture captured **before** the change, not by reasoning about it.++This is not caution theatre. Two features in this track nearly shipped a silently different footer and+transcript, and both were caught only because a byte fixture existed. A user who never asked for a feature+must not receive it.++Where it applies: `session.verbosity` (footer density, default `high`), `session.grouping` (tool+collapsing, default `none`), `tabs.indicators` (default `numbers`), `tabs.scope` (default `global`),+`mouse` (default `on`), `scroll.speed` (default `3`).++## 2. A setting with no consumer must not exist++`scripts/mso-agent-settings-entries.mjs` carries this rule at the top, and eleven settings passed it while+around a dozen candidates were refused. A registry listing switches that do nothing is worse than a short+registry, because it teaches the user that the settings panel is decoration.++The refusals, recorded so they are not re-litigated:++| Refused | Why |+|---|---|+| `diffs.wrap`, `diffs.view`, `diffs.tree`, `diffs.single` | every diff line is clipped by `fitCells`; the pane is 30 to 50 columns so a split is unreadable; the `files` pane already lists files; the pane shows one diff |+| sidebar slot `limit` | the context pane already shows `used/limit` with a bar, and no provider quota exists on a session |+| sidebar slot `footer` | `chromeLines` already renders a footer |+| image preview | the renderer is a line painter with no graphics protocol, and images carry no dimensions |+| `attention.volume` | BEL has no volume parameter |+| desktop notifications | OSC 777 corrupts frames on terminals that lack it |+| `scroll.acceleration` | no velocity exists to measure |++## 3. `updatedAt` is not an activity signal, and never was++`docs/AGENT-ACTIVITY-SIGNAL.md` is the full audit. The short version: `persistSession` runs at turn+**completion**, so a turn that just ended marks an idle session as working for sixty seconds, while a turn+streaming for three minutes still carries the previous timestamp and reads as idle. Both directions are+wrong, and the second is the common one.++The fix is server side: `turnStartedAt` written at turn start, cleared in `finally`, surfaced as+`turnActive`. Until a view can read `turnActive` or an explicit `status`, it renders **unknown**, not a+guess. `needsAttention` follows the same rule, which is why `/tabs next` reports `no sessions need+attention` rather than cycling.++## 4. One layout source, or the hit test drifts++`tabLayout` produces the segments; `tabRow`, `tabRailLines` and `tabAtPoint` all consume them. Splitting+this is how a click target stops agreeing with the painted cell, which already happened once.++The same rule now applies to geometry: `mso-agent-panel-geometry.mjs` owns every number that decides how+much terminal a user sees. Adding layout arithmetic to the paint loop is how that file reached 225 lines+and how two features could have disagreed about the transcript width.++## 5. A repaint must never create scrollback++The composer and the panel both assert this. Every repaint is a diff in place, never an append, and a+shrink clears the released rows while moving the cursor up rather than leaving them.++The bug that proved it matters: `reserveComposerRows` returned early when the new height was not larger, so+the reservation ratcheted up and never came down. Pressing Esc closed the completion menu but the prompt+never moved back up, and the gap sat there for the rest of the session.++## 6. Suspension must leave, not merely detach++A line-oriented prompt needs the terminal. `createPanelSuspension` leaves the alternate screen, turns mouse+reporting off and stops the input hook. Detaching the stream sink alone is not enough: the prompt was+painted into the alternate buffer and the next repaint erased it, so the user answered a question that had+already vanished.++Two paths matter and both are tested: resume must not resurrect mouse when the setting is off, and a prompt+that throws must still repaint.++## 7. Errors are never collapsed, hidden or guessed++Tool grouping collapses repeated calls into a count. It must never collapse a failure, because a count that+includes an error is a summary that lies. Errors flush out of the run and render on their own line.++The same principle covers the empty states: a pane with nothing to show says so in one dim line rather than+rendering a blank hole, because an empty panel is indistinguishable from a broken one.++## 8. The line ratchet is a design constraint, not a nuisance++220 lines per file, and eight modules are within one or two lines of it. When a change needs room, extract+something with a real boundary rather than compressing code into unreadable lines. The extractions this+track has done are all better code than what they replaced:++| Extracted | From |+|---|---|+| `mso-agent-panel-geometry.mjs` | the paint loop |+| `mso-agent-settings-entries.mjs` | the settings loader |+| `mso-agent-tabs-rail.mjs` | the chrome layout |+| `mso-agent-input-hook.mjs` | key and mouse interception |+| `mso-agent-turn-print.mjs` | the printer router |+| `mso-agent-panel-suspend.mjs` | terminal ownership |++## 9. Verify on a real pty, not only in unit tests++Two defects in this track were invisible to every fake-TTY test and only appeared when the actual binary ran+in a real terminal behind a real backend:++- `const screenLoop` declared inside `try` and read in `finally`, so **every exit** threw a+ `ReferenceError` and a clean Ctrl+C became exit code 1.+- A SIGTERM listener that **replaced** node's default termination, so the handler released the screen and+ left the process alive forever.++`scripts/mso-agent-pty.e2e.test.ts` exists for exactly this and should be run after any entrypoint change.++## 10. Local gates decide, CI confirms++`bash scripts/gates-12.sh full` mirrors the Actions verify job: 17 rows, 16 pass and one skip that+`verify-build.sh` enforces inside the same run. It caught an absolute home path the instance guard rejects,+a ratchet regression, and a stale changelog, each of which would otherwise have cost a CI round trip.++Two of its gates are load-sensitive: `tests + coverage` and `perf gate` fail above roughly load 7 and pass+below 4. A red result at high load is not a regression, and the way to tell is to re-run on a quiet host,+not to assume either way.++## 11. Squashing a batch is where work disappears++The batch that shipped eleven branches used `git reset --soft` to collapse them into one commit, and that+silently dropped **three** of them. A soft reset does not include changes from merge commits that are not+reachable by the reset target in the way a squash does. Their modules were missing from `main` while their+tests were present, so nothing looked broken.++Check a batch by file, not by test count:++```bash+for f in <the files the batch should have added>; do+ git cat-file -e origin/main:$f 2>/dev/null || echo "MISSING $f"+done+```++Use `git merge --squash` per branch, or cherry-pick an explicit range, rather than a soft reset over merges.++## 12. A refusal is worth as much as a feature++Five items in the last batch were refused rather than built, each with the file and line that decided it.+That is the correct outcome when the capability does not exist: a placeholder thumbnail, a status glyph+derived from a timestamp, or a volume slider for a bell with no volume are all worse than an honest absence,+because they assert something untrue about the system.++Record the refusal where the next person will look for the setting, not in a chat log.diff --git a/scripts/mso-agent-approval-summary.mjs b/scripts/mso-agent-approval-summary.mjsnew file mode 100644index 00000000..0134e2af--- /dev/null+++ b/scripts/mso-agent-approval-summary.mjs@@ -0,0 +1,127 @@+// Sanitizes target text to avoid escaping single-line TUI layouts or leaking credentials.+const SECRET_KEY = /(api[_-]?key|token|secret|password|passwd|credential|cookie|authorization|private[_-]?key)/i;+const SECRET_TEXT = /\b(?:authorization\s*:\s*)?bearer\s+[^\s,;]+|((?:api[_-]?key|token|secret|password|passwd|credential|authorization)\s*[=:]\s*)[^\s,;]+/gi;++function cleanTarget(value, max = 80) {+ // Normalize whitespace so multiline scripts do not push the prompt offscreen.+ const clean = String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim();+ // Strip sensitive tokens before printing to prevent terminal logs from leaking secrets.+ const safe = clean.replace(SECRET_TEXT, (match, prefix) => {+ if (prefix) return `${prefix}[redacted]`;+ if (/^authorization\s*:\s*bearer/i.test(match)) return "Authorization: Bearer [redacted]";+ return "Bearer [redacted]";+ });+ if (Array.from(safe).length <= max) return safe;+ return `${Array.from(safe).slice(0, Math.max(1, max - 1)).join("")}…`;+}++// Extracts the primary actionable target from tool input without guessing missing fields.+export function extractApprovalTarget(input = {}, tool = {}) {+ // Prefer explicit execution commands because they carry the highest risk profile.+ if (typeof input?.command === "string" && input.command.trim()) {+ return cleanTarget(input.command);+ }+ // File operations identify targets by path or source-destination pairs.+ if (typeof input?.path === "string" && input.path.trim()) {+ return cleanTarget(input.path);+ }+ if (typeof input?.from === "string" && typeof input?.to === "string") {+ return `${cleanTarget(input.from, 36)} -> ${cleanTarget(input.to, 36)}`;+ }+ // Named entities provide human-recognizable targets for messaging or agent operations.+ if (typeof input?.target === "string" && input.target.trim()) {+ return cleanTarget(input.target);+ }+ if (typeof input?.id === "string" && input.id.trim()) {+ return cleanTarget(input.id);+ }+ return "";+}++// Formats the human-readable repeat marker based on previous in-memory approvals.+export function approvalRepeatMarker(count) {+ const n = typeof count === "number" && Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0;+ // Zero previous approvals means this is the first time the action is confirmed.+ if (n <= 0) return "";+ if (n === 1) return "approved once already";+ if (n === 2) return "approved twice already";+ return `approved ${n} times already`;+}++/**+ * Builds the single-line summary above the approval prompt.+ * @param {any} tool+ * @param {any} [input]+ * @param {any} [approval]+ * @param {number} [count]+ */+export function formatApprovalSummary(tool, input = {}, approval = undefined, count = 0) {+ const toolName = String(tool?.name || "tool");+ const target = extractApprovalTarget(input, tool);+ const marker = approvalRepeatMarker(count);++ // Omit the 64-character raw digest here because it clutters the single-line view.+ // Full digest details remain available in the expanded approvalDetailLines.+ if (target && marker) return `${toolName}: ${target} (${marker})`;+ if (target) return `${toolName}: ${target}`;+ if (marker) return `${toolName} (${marker})`;+ return toolName;+}++// In-memory, session-scoped tracker that binds approval repetition to canonical digests.+export class ApprovalSummaryFormatter {+ constructor() {+ // Session-scoped map ensures resumed sessions start empty and never claim phantom approvals.+ this.approvedCounts = new Map();+ }++ /**+ * Resolves the canonical hex digest from either a raw string or an approval object.+ * @param {any} digestOrApproval+ */+ resolveDigest(digestOrApproval) {+ if (typeof digestOrApproval === "string") return digestOrApproval;+ if (digestOrApproval && typeof digestOrApproval.digest === "string") {+ return digestOrApproval.digest;+ }+ return "";+ }++ /**+ * Returns how many times this exact digest has been approved during this process run.+ * @param {any} digestOrApproval+ */+ getCount(digestOrApproval) {+ const digest = this.resolveDigest(digestOrApproval);+ if (!digest) return 0;+ return this.approvedCounts.get(digest) || 0;+ }++ /**+ * Records a granted approval to alert the user if the exact same call reoccurs.+ * @param {any} digestOrApproval+ */+ record(digestOrApproval) {+ const digest = this.resolveDigest(digestOrApproval);+ if (!digest) return 0;+ const next = (this.approvedCounts.get(digest) || 0) + 1;+ this.approvedCounts.set(digest, next);+ return next;+ }++ /**+ * Convenience method that formats the summary using current session counts.+ * @param {any} tool+ * @param {any} [input]+ * @param {any} [approval]+ */+ format(tool, input = {}, approval = undefined) {+ const count = this.getCount(approval);+ return formatApprovalSummary(tool, input, approval, count);+ }++ // Explicit reset hook used when starting fresh turns or executing tests.+ clear() {+ this.approvedCounts.clear();+ }+}diff --git a/scripts/mso-agent-approval-summary.test.ts b/scripts/mso-agent-approval-summary.test.tsnew file mode 100644index 00000000..46c4c57d--- /dev/null+++ b/scripts/mso-agent-approval-summary.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it, vi } from "vitest";+import { canonicalAgentApproval } from "../lib/agent/approval.mjs";+import {+ ApprovalSummaryFormatter,+ approvalRepeatMarker,+ extractApprovalTarget,+ formatApprovalSummary,+} from "./mso-agent-approval-summary.mjs";+import { requestExactToolApproval } from "./mso-agent-approval-ui.mjs";++describe("TUI approval summary and repetition tracking", () => {+ const toolA = { name: "exec_run", scope: "exec" };+ const inputA = { command: "npm test", token: "secret123" };+ const approvalA = canonicalAgentApproval(toolA.name, inputA);++ const toolB = { name: "fs_write", scope: "write" };+ const inputB = { path: "src/config.json", content: "{}" };+ const approvalB = canonicalAgentApproval(toolB.name, inputB);++ it("(1) first approval shows no repeat marker", () => {+ // Tests that the initial presentation of an action does not display phantom repeat indicators.+ const formatter = new ApprovalSummaryFormatter();+ const summary = formatter.format(toolA, inputA, approvalA);+ expect(summary).toBe("exec_run: npm test");+ expect(summary).not.toMatch(/approved|already|once|twice/i);+ });++ it("(2) second approval of the same digest shows it", () => {+ // Tests that once a digest has been allowed, subsequent identical prompts display repeat counts.+ const formatter = new ApprovalSummaryFormatter();+ formatter.record(approvalA);+ const second = formatter.format(toolA, inputA, approvalA);+ expect(second).toBe("exec_run: npm test (approved once already)");++ formatter.record(approvalA);+ const third = formatter.format(toolA, inputA, approvalA);+ expect(third).toBe("exec_run: npm test (approved twice already)");+ });++ it("(3) a different digest resets to no marker", () => {+ // Tests that repeat state is bound strictly to the canonical digest rather than consecutive calls.+ const formatter = new ApprovalSummaryFormatter();+ formatter.record(approvalA);+ const summaryB = formatter.format(toolB, inputB, approvalB);+ expect(summaryB).toBe("fs_write: src/config.json");+ expect(summaryB).not.toMatch(/approved|already/i);+ });++ it("(4) a resumed session starts with an empty counter, asserted by constructing a fresh formatter", () => {+ // Tests that resuming a session does not carry over in-memory counts from prior sessions.+ const priorFormatter = new ApprovalSummaryFormatter();+ priorFormatter.record(approvalA);+ priorFormatter.record(approvalA);+ expect(priorFormatter.getCount(approvalA)).toBe(2);++ const resumedFormatter = new ApprovalSummaryFormatter();+ expect(resumedFormatter.getCount(approvalA)).toBe(0);+ const resumedSummary = resumedFormatter.format(toolA, inputA, approvalA);+ expect(resumedSummary).toBe("exec_run: npm test");+ expect(resumedSummary).not.toMatch(/approved|already/i);+ });++ it("(5) the summary never contains the raw digest unless it was already shown today, and say what you chose", () => {+ // We chose to keep the summary digest-free because raw hashes clutter single-line prompts;+ // full digests remain available in the expandable detail section.+ const formatter = new ApprovalSummaryFormatter();+ const s1 = formatter.format(toolA, inputA, approvalA);+ formatter.record(approvalA);+ const s2 = formatter.format(toolA, inputA, approvalA);+ const s3 = formatter.format(toolB, inputB, approvalB);++ expect(s1).not.toContain(approvalA.digest);+ expect(s2).not.toContain(approvalA.digest);+ expect(s3).not.toContain(approvalB.digest);+ });++ it("extracts targets safely and redacts credentials from summary lines", () => {+ // Prevents sensitive command parameters from printing in unredacted summary logs.+ const target = extractApprovalTarget({ command: "curl -H 'Authorization: Bearer topsecret' https://api" });+ expect(target).toContain("Bearer [redacted]");+ expect(target).not.toContain("topsecret");++ const moveTarget = extractApprovalTarget({ from: "old.txt", to: "new.txt" });+ expect(moveTarget).toBe("old.txt -> new.txt");++ expect(extractApprovalTarget({}, { name: "sys_status" })).toBe("");+ expect(formatApprovalSummary({ name: "sys_status" })).toBe("sys_status");+ });++ it("handles repeat marker pluralization above two occurrences", () => {+ // Formats counts greater than two with generic numeric phrasing.+ expect(approvalRepeatMarker(0)).toBe("");+ expect(approvalRepeatMarker(1)).toBe("approved once already");+ expect(approvalRepeatMarker(2)).toBe("approved twice already");+ expect(approvalRepeatMarker(5)).toBe("approved 5 times already");+ });++ it("integrates with requestExactToolApproval without regressing the prompt cycle", async () => {+ // Tests end-to-end prompt suspension, summary printing, and approval recording.+ const formatter = new ApprovalSummaryFormatter();+ const printed: string[] = [];+ const print = (line: string) => printed.push(line);++ let allowDecision = true;+ const rl = {+ question: vi.fn(async (prompt: string | (() => string)) => {+ const text = typeof prompt === "function" ? prompt() : prompt;+ if (text.includes("Approval needed")) return "";+ return allowDecision ? "allow" : "deny";+ }),+ };++ // First prompt confirmation.+ const result1 = await requestExactToolApproval(rl, {+ tool: toolA,+ input: inputA,+ approval: approvalA,+ print,+ summaryFormatter: formatter,+ });+ expect(result1).toBe(true);+ expect(printed[0]).toBe("exec_run: npm test");++ // Second prompt confirmation with matching digest.+ printed.length = 0;+ const result2 = await requestExactToolApproval(rl, {+ tool: toolA,+ input: inputA,+ approval: approvalA,+ print,+ summaryFormatter: formatter,+ });+ expect(result2).toBe(true);+ expect(printed[0]).toBe("exec_run: npm test (approved once already)");++ // Denied prompt does not increment counter.+ allowDecision = false;+ printed.length = 0;+ const result3 = await requestExactToolApproval(rl, {+ tool: toolB,+ input: inputB,+ approval: approvalB,+ print,+ summaryFormatter: formatter,+ });+ expect(result3).toBe(false);+ expect(printed[0]).toBe("fs_write: src/config.json");+ expect(formatter.getCount(approvalB)).toBe(0);+ });+});diff --git a/scripts/mso-agent-approval-ui.mjs b/scripts/mso-agent-approval-ui.mjsindex 6ee806d0..87046e7f 100644--- a/scripts/mso-agent-approval-ui.mjs+++ b/scripts/mso-agent-approval-ui.mjs@@ -1,4 +1,5 @@import { withPanelSuspended } from "./mso-agent-turn-print.mjs";+import { ApprovalSummaryFormatter } from "./mso-agent-approval-summary.mjs";const SECRET_KEY = /(api[_-]?key|token|secret|password|passwd|credential|cookie|authorization|private[_-]?key)/i;const SECRET_TEXT = /((?:api[_-]?key|token|secret|password|passwd|credential|authorization)\s*[=:]\s*)[^\s,;]+|\bBearer\s+[^\s,;]+/gi;@@ -55,9 +56,27 @@ export function approvalDetailLines(tool, input, approval) {];}-export async function requestExactToolApproval(rl, { tool, input = {}, approval, onCancel = null, signal = null, colors = {}, print = console.log, screenLoop = null }) {+// Session-scoped approval formatter tracking confirmed tool calls in memory.+export const defaultApprovalSummaryFormatter = new ApprovalSummaryFormatter();++export async function requestExactToolApproval(rl, {+ tool,+ input = {},+ approval,+ onCancel = null,+ signal = null,+ colors = {},+ print = console.log,+ screenLoop = null,+ summaryFormatter = defaultApprovalSummaryFormatter,+}) {const loop = screenLoop || rl?.screenLoop;return withPanelSuspended(loop, async () => {+ // Print the summary line above the prompt to provide immediate context on repetition.+ if (summaryFormatter) {+ const summary = summaryFormatter.format(tool, input, approval);+ if (summary) print(summary);+ }let focused = false;const dim = colors.dim || "", reset = colors.reset || "", blue = colors.blue || "", bold = colors.bold || "";const status = () => `${blue}${bold}${approvalStatusLine(tool, input, focused)}${reset}${dim} · Tab focus · Enter details${reset} `;@@ -71,6 +90,11 @@ export async function requestExactToolApproval(rl, { tool, input = {}, approval,for (const line of approvalDetailLines(tool, input, approval)) print(line);const decision = String(await rl.question(" decision [allow/deny] › ", { history: false, onCancel }) ?? "").trim().toLowerCase();if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("turn interrupted");- return decision === "allow";+ const allowed = decision === "allow";+ // Only record approved calls when explicitly allowed by the operator.+ if (allowed && summaryFormatter && approval?.digest) {+ summaryFormatter.record(approval.digest);+ }+ return allowed;});}diff --git a/scripts/mso-agent-attention-loop.test.ts b/scripts/mso-agent-attention-loop.test.tsnew file mode 100644index 00000000..496157aa--- /dev/null+++ b/scripts/mso-agent-attention-loop.test.ts@@ -0,0 +1,130 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";+import { BEL } from "./mso-agent-attention.mjs";+import { mountScreenLoop, resumeScreenLoop, suspendScreenLoop } from "./mso-agent-screen-loop.mjs";++class FakeOutput extends EventEmitter {+ isTTY = true;+ columns = 80;+ rows = 24;+ chunks: string[] = [];+ write(str: string) {+ this.chunks.push(String(str));+ return true;+ }+}++function makeLoop(options: { attention?: string; getSessions?: () => any[] } = {}) {+ const output = new FakeOutput();+ const session = { agentSession: { id: "s1", name: "active" }, history: [], attention: options.attention };+ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: new EventEmitter() as never,+ getSessions: options.getSessions ?? (() => []),+ });+ return { output, session, loop };+}++describe("MSO Agent screen loop attention wiring", () => {+ it("1. setting off writes zero bytes for attention (assert byte-for-byte empty)", () => {+ // Mode off writes strictly zero bytes to dedicated attention sink and terminal stdout.+ const sink = { chunks: [] as string[], write(c: string) { this.chunks.push(c); return true; } };+ let sessions: any[] = [{ id: "s1", status: "idle" }, { id: "s2", status: "idle" }];+ const output = new FakeOutput();+ const session = { agentSession: { id: "s1", name: "active" }, history: [], attention: "off" };+ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: new EventEmitter() as never,+ attentionOutput: sink,+ getSessions: () => sessions,+ });++ sessions = [{ id: "s1", status: "idle" }, { id: "s2", status: "working" }];+ loop.sync();++ // Byte-for-byte assertion: attention sink received exactly zero bytes+ expect(sink.chunks.length).toBe(0);+ expect(sink.chunks.join("")).toBe("");++ // Stdout also contains zero BEL alert bytes+ expect(output.chunks.filter((c) => c.includes(BEL))).toEqual([]);+ expect(output.chunks.join("").includes(BEL)).toBe(false);+ loop.dispose();+ });++ it("2. one transition rings exactly once", () => {+ // Mode bell emits exactly one BEL byte when a background session enters attention state.+ let sessions: any[] = [{ id: "s1", status: "idle" }, { id: "s2", status: "idle" }];+ const { output, loop } = makeLoop({ attention: "bell", getSessions: () => sessions });++ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);++ sessions = [{ id: "s1", status: "idle" }, { id: "s2", status: "working" }];+ loop.sync();++ // Exactly one BEL byte emitted to terminal output+ expect(output.chunks.filter((c) => c === BEL)).toEqual([BEL]);+ loop.dispose();+ });++ it("3. a second sync with no change rings nothing", () => {+ // Hysteresis prevents bell fatigue: subsequent syncs with same state emit zero bells.+ let sessions: any[] = [{ id: "s1", status: "idle" }, { id: "s2", status: "idle" }];+ const { output, loop } = makeLoop({ attention: "bell", getSessions: () => sessions });++ sessions = [{ id: "s1", status: "idle" }, { id: "s2", status: "working" }];+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL).length).toBe(1);++ // Second sync with identical status emits no additional bell+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL).length).toBe(1);+ loop.dispose();+ });++ it("4. the active session never rings", () => {+ // Active session has user focus so its transitions must never trigger audio bells.+ let sessions: any[] = [{ id: "s1", status: "idle" }, { id: "s2", status: "idle" }];+ const { output, loop } = makeLoop({ attention: "bell", getSessions: () => sessions });++ // Active session s1 transitions to working+ sessions = [{ id: "s1", status: "working" }, { id: "s2", status: "idle" }];+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);++ // Active session s1 transitions to errored+ sessions = [{ id: "s1", status: "errored", error: true }, { id: "s2", status: "idle" }];+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);+ loop.dispose();+ });++ it("5. suspend then resume rings nothing", () => {+ // Leaving alternate screen suppresses bells; resume marks state so return sync stays silent.+ let sessions: any[] = [{ id: "s1", status: "idle" }, { id: "s2", status: "idle" }];+ const { output, loop } = makeLoop({ attention: "bell", getSessions: () => sessions });++ loop.sync();+ suspendScreenLoop(loop);++ sessions = [{ id: "s1", status: "idle" }, { id: "s2", status: "working" }];+ // Sync during suspension is suppressed+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);++ resumeScreenLoop(loop);+ // Sync upon resume is also suppressed+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);++ // Subsequent sync when s2 is still working remains silent+ loop.sync();+ expect(output.chunks.filter((c) => c === BEL)).toEqual([]);+ loop.dispose();+ });+});diff --git a/scripts/mso-agent-click-hint.mjs b/scripts/mso-agent-click-hint.mjsnew file mode 100644index 00000000..30db5cca--- /dev/null+++ b/scripts/mso-agent-click-hint.mjs@@ -0,0 +1,101 @@+// Pure decision logic and formatting for mouse click hints in the TUI panel.+// Informs users when a click in an interactive-looking region (tab rail or tab row)+// fails to resolve to an active tab, while keeping the transcript area quiet for text selection.++export const CLICK_HINT_TEXT = "Only session tabs are clickable; click a tab to switch.";++/**+ * Formats a single transcript hint line explaining what is clickable.+ * Uses muted tone when colors are available so it does not distract from transcript prose.+ *+ * @param {{ dim?: string, reset?: string }} [colors]+ * @returns {string}+ */+export function formatClickHint(colors = {}) {+ const dim = colors?.dim || "";+ const reset = dim ? (colors?.reset || "") : "";+ return `${dim}${CLICK_HINT_TEXT}${reset}`;+}++/**+ * Checks whether coordinate point falls inside an interactive region.+ *+ * Regions that look interactive:+ * 1. Tab rail column (vertical mode): x in [0, railWidth), y in [0, viewRows).+ * 2. Tab row band (horizontal mode): y === tabRowY, x in [0, cols).+ *+ * Clicks in the transcript area (y < viewRows and outside the rail column) are exempt+ * because users frequently click or drag to select terminal text, and emitting a hint+ * there would create visual noise during normal selection.+ *+ * @param {{ x: number, y: number }} point+ * @param {{ railWidth?: number, tabRowY?: number, viewRows?: number, cols?: number }} [geometry]+ * @returns {boolean}+ */+export function isInteractiveRegion(point, geometry = {}) {+ if (!point || typeof point !== "object") return false;+ const x = Number(point.x);+ const y = Number(point.y);+ if (!Number.isFinite(x) || !Number.isFinite(y)) return false;++ const railWidth = Math.max(0, Number(geometry?.railWidth) || 0);+ const viewRows = Math.max(0, Number(geometry?.viewRows) || 0);+ const tabRowY = typeof geometry?.tabRowY === "number" ? geometry.tabRowY : -1;+ const cols = Math.max(0, Number(geometry?.cols) || 80);++ // Vertical rail column: user clicked inside the tab column area.+ if (railWidth > 0) {+ return x >= 0 && x < railWidth && y >= 0 && y < viewRows;+ }++ // Horizontal tab row: user clicked along the tab row band.+ if (tabRowY >= 0 && y === tabRowY) {+ return x >= 0 && x < cols;+ }++ return false;+}++/**+ * Pure decision: should a click hint be displayed?+ *+ * Conditions:+ * - Must be a click event.+ * - Target tab must be null (a miss).+ * - Screen loop must not be suspended (prevents hints while a modal prompt owns the terminal).+ * - Rate limit: hintCount must be 0 (at most one hint per session to avoid nag spam).+ * - Click coordinate must be in an interactive region (rail column or tab row band).+ *+ * @param {{+ * event?: any,+ * geometry?: any,+ * targetId?: string | null,+ * hintCount?: number,+ * suspended?: boolean,+ * }} [params]+ * @returns {boolean}+ */+export function shouldShowClickHint({+ event,+ geometry,+ targetId = null,+ hintCount = 0,+ suspended = false,+} = {}) {+ // Only click events can produce a click hint.+ if (!event || event.kind !== "click") return false;++ // Never write hints while the panel is suspended for a modal command or prompt.+ if (suspended) return false;++ // Rate-limit to at most one hint per session to prevent repeated click noise.+ if (hintCount > 0) return false;++ // If a tab resolved, this is a successful switch, not a miss.+ if (targetId) return false;++ // Transcript clicks and other non-interactive areas must remain silent.+ if (!isInteractiveRegion({ x: event.x, y: event.y }, geometry)) return false;++ return true;+}diff --git a/scripts/mso-agent-click-hint.test.ts b/scripts/mso-agent-click-hint.test.tsnew file mode 100644index 00000000..85b4d428--- /dev/null+++ b/scripts/mso-agent-click-hint.test.ts@@ -0,0 +1,189 @@+import { EventEmitter } from "node:events";+import { describe, expect, it, vi } from "vitest";+import { CLICK_HINT_TEXT, formatClickHint, isInteractiveRegion, shouldShowClickHint } from "./mso-agent-click-hint.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";++class FakeOutput extends EventEmitter {+ isTTY = true;+ columns = 120;+ rows = 30;+ chunks: string[] = [];+ write(str: string) {+ this.chunks.push(String(str));+ return true;+ }+}++describe("MSO Agent mouse click region hint", () => {+ const sessions = [+ { id: "s1", name: "alpha" },+ { id: "s2", name: "beta" },+ { id: "s3", name: "gamma" },+ ];++ it("pure decision and formatter behavior", () => {+ expect(formatClickHint()).toBe(CLICK_HINT_TEXT);+ expect(formatClickHint({ dim: "\x1b[2m", reset: "\x1b[0m" })).toBe(`\x1b[2m${CLICK_HINT_TEXT}\x1b[0m`);++ const geomVertical = { railWidth: 20, viewRows: 15, tabRowY: -1, cols: 120 };+ // Inside rail column+ expect(isInteractiveRegion({ x: 0, y: 0 }, geomVertical)).toBe(true);+ expect(isInteractiveRegion({ x: 19, y: 14 }, geomVertical)).toBe(true);+ // Transcript area (x >= railWidth, y < viewRows)+ expect(isInteractiveRegion({ x: 20, y: 5 }, geomVertical)).toBe(false);+ expect(isInteractiveRegion({ x: 80, y: 5 }, geomVertical)).toBe(false);+ // Below rail+ expect(isInteractiveRegion({ x: 10, y: 15 }, geomVertical)).toBe(false);++ const geomHoriz = { railWidth: 0, viewRows: 15, tabRowY: 16, cols: 80 };+ // Tab row band+ expect(isInteractiveRegion({ x: 5, y: 16 }, geomHoriz)).toBe(true);+ // Transcript area+ expect(isInteractiveRegion({ x: 5, y: 10 }, geomHoriz)).toBe(false);+ });++ it("(1) a click on a valid tab still switches and prints nothing", () => {+ const onTabClick = vi.fn();+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session: any = { agentSession: { id: "s1", name: "alpha" }, history: [] };++ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: input as never,+ getSessions: () => sessions,+ onTabClick,+ tabsLayout: "vertical",+ });++ const printed: string[] = [];+ const origSink = session.printSink;+ session.printSink = (line: string) => {+ printed.push(line);+ origSink?.(line);+ };++ // Row 1 (y=1) is beta (@beta). Col 3 (x=2) is within "@beta" segment.+ input.emit("data", "\x1b[<0;3;2M");+ expect(onTabClick).toHaveBeenCalledWith("s2");+ expect(printed).toHaveLength(0);++ loop.dispose();+ });++ it("(2) a click in the rail band that resolves to nothing prints exactly one hint", () => {+ const onTabClick = vi.fn();+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session: any = { agentSession: { id: "s1", name: "alpha" }, history: [] };++ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: input as never,+ getSessions: () => sessions,+ onTabClick,+ tabsLayout: "vertical",+ });++ const printed: string[] = [];+ const origSink = session.printSink;+ session.printSink = (line: string) => {+ printed.push(line);+ origSink?.(line);+ };++ const geom = loop.geometry();+ // Click on the rail border gutter column (x = railWidth - 1, 1-based: railWidth)+ input.emit("data", `\x1b[<0;${geom.railWidth};1M`);++ expect(onTabClick).not.toHaveBeenCalled();+ expect(printed).toHaveLength(1);+ expect(printed[0]).toContain(CLICK_HINT_TEXT);++ // (3) a second such click prints nothing (rate limited to 1 hint per session)+ input.emit("data", `\x1b[<0;${geom.railWidth};1M`);+ expect(printed).toHaveLength(1);++ loop.dispose();+ });++ it("(4) a click in the transcript area prints nothing even the first time", () => {+ const onTabClick = vi.fn();+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session: any = { agentSession: { id: "s1", name: "alpha" }, history: [] };++ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: input as never,+ getSessions: () => sessions,+ onTabClick,+ tabsLayout: "vertical",+ });++ const printed: string[] = [];+ const origSink = session.printSink;+ session.printSink = (line: string) => {+ printed.push(line);+ origSink?.(line);+ };++ // Click at x=50, y=5 (transcript viewport area)+ input.emit("data", "\x1b[<0;51;6M");++ expect(onTabClick).not.toHaveBeenCalled();+ expect(printed).toHaveLength(0);++ loop.dispose();+ });++ it("(5) no hint while suspended", () => {+ const onTabClick = vi.fn();+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session: any = { agentSession: { id: "s1", name: "alpha" }, history: [] };++ const loop = mountScreenLoop({+ enabled: true,+ session,+ output: output as never,+ input: input as never,+ getSessions: () => sessions,+ onTabClick,+ tabsLayout: "vertical",+ });++ const printed: string[] = [];+ const origSink = session.printSink;+ session.printSink = (line: string) => {+ printed.push(line);+ origSink?.(line);+ };++ const geom = loop.geometry();+ loop.suspend();++ // While suspended, hook is disabled and suspend state prevents hint emission.+ input.emit("data", `\x1b[<0;${geom.railWidth};1M`);+ expect(printed).toHaveLength(0);++ // Decision function directly rejects suspended screen loop+ const shouldShow = shouldShowClickHint({+ event: { kind: "click", x: geom.railWidth - 1, y: 0 },+ geometry: geom,+ targetId: null,+ hintCount: 0,+ suspended: true,+ });+ expect(shouldShow).toBe(false);++ loop.resume();+ loop.dispose();+ });+});diff --git a/scripts/mso-agent-cmd-find.mjs b/scripts/mso-agent-cmd-find.mjsnew file mode 100644index 00000000..11d085b2--- /dev/null+++ b/scripts/mso-agent-cmd-find.mjs@@ -0,0 +1,137 @@+// Command handler for /find: locates transcript text and scrolls viewport.+import { C } from "./mso-agent-runtime.mjs";+import { createPrinter } from "./mso-agent-print.mjs";+import { getAllLines } from "./mso-agent-viewport.mjs";+import { transcriptLines } from "./mso-agent-transcript.mjs";+import { findMatches, offsetForLine } from "./mso-agent-find.mjs";++/**+ * Resolves the transcript lines to search across.+ * Viewport buffer lines take precedence when present to match visible rows.+ * Falls back to deriving transcript lines from session history.+ *+ * @param {object} session - Active session object.+ * @param {object} viewport - Viewport instance.+ * @returns {string[]} Lines of text.+ */+export function getSearchLines(session, viewport) {+ if (viewport) {+ const lines = getAllLines(viewport);+ if (lines.length > 0) return lines;+ }+ if (session) {+ return transcriptLines(session, { colors: session?.colors });+ }+ return [];+}++/**+ * Handles /find slash command:+ * - /find <query>: searches transcript, reports matches, jumps to first match.+ * - /find: reports match count for previous query or prompts for a query.+ * - /find --next (or repeated query): jumps to next match and wraps.+ *+ * @param {object} ctx - Command execution context.+ * @param {string[]} [args] - Command arguments.+ * @returns {Promise<string>} Handled status.+ */+export async function handleFindCommand(ctx, args = []) {+ const session = ctx?.session ?? ctx;+ const viewport = ctx?.viewport ?? ctx?.session?.screenLoop?.viewport ?? ctx?.session?.viewport;+ const colors = ctx?.C ?? ctx?.colors ?? C ?? {};+ const { print } = ctx?.printer ?? createPrinter(ctx);+ const { cyan = "", reset = "", dim = "" } = colors;++ const rawQuery = Array.isArray(args) ? args.join(" ").trim() : "";+ const sub = args[0]?.toLowerCase();+ const isNextFlag = sub === "--next" || sub === "-n";++ // Case 1: Bare /find with no argument+ if (!args.length) {+ const state = session?._findState;+ if (!state?.query) {+ print("no previous query: use /find <query>");+ return "handled";+ }+ const lines = getSearchLines(session, viewport);+ const matches = findMatches(lines, state.query);+ if (matches.length === 0) {+ print(`0 matches for "${state.query}"`);+ return "handled";+ }+ const current = Math.min(state.matchIndex, matches.length - 1);+ const lineNum = matches[current] + 1;+ const countLabel = `${matches.length} ${matches.length === 1 ? "match" : "matches"}`;+ print(`${cyan}${countLabel}${reset} for "${state.query}"${dim} (at match ${current + 1}/${matches.length}, line ${lineNum})${reset}`);+ return "handled";+ }++ // Case 2: Explicit /find --next to advance+ if (isNextFlag) {+ const state = session?._findState;+ if (!state?.query) {+ print("no previous query: use /find <query>");+ return "handled";+ }+ const lines = getSearchLines(session, viewport);+ const matches = findMatches(lines, state.query);+ if (matches.length === 0) {+ print(`0 matches for "${state.query}"`);+ return "handled";+ }+ state.matchIndex = (state.matchIndex + 1) % matches.length;+ state.matches = matches;+ const targetLine = matches[state.matchIndex];+ if (viewport) {+ viewport.offset = offsetForLine(viewport, targetLine);+ session?.screenLoop?.paint?.();+ }+ const countLabel = `${matches.length} ${matches.length === 1 ? "match" : "matches"}`;+ print(`${cyan}${countLabel}${reset} for "${state.query}"${dim} (match ${state.matchIndex + 1}/${matches.length}, line ${targetLine + 1})${reset}`);+ return "handled";+ }++ // Case 3: Empty query (e.g. /find "" or whitespace)+ if (!rawQuery) {+ print("empty query: use /find <query>");+ return "handled";+ }++ // Case 4: Search for query, moving to next match if query is repeated+ const lines = getSearchLines(session, viewport);+ const matches = findMatches(lines, rawQuery);++ if (matches.length === 0) {+ print(`0 matches for "${rawQuery}"`);+ return "handled";+ }++ const prior = session?._findState;+ const isRepeated = prior?.query?.toLowerCase() === rawQuery.toLowerCase();+ let nextIndex = 0;+ if (isRepeated && typeof prior?.matchIndex === "number") {+ // Advance to next match and wrap when repeating same query+ nextIndex = (prior.matchIndex + 1) % matches.length;+ } else {+ // Fresh query jumps to first match+ nextIndex = 0;+ }++ if (session) {+ session._findState = {+ query: rawQuery,+ matchIndex: nextIndex,+ matches,+ };+ }++ const targetLine = matches[nextIndex];+ if (viewport) {+ viewport.offset = offsetForLine(viewport, targetLine);+ session?.screenLoop?.paint?.();+ }++ const countLabel = `${matches.length} ${matches.length === 1 ? "match" : "matches"}`;+ print(`${cyan}${countLabel}${reset} for "${rawQuery}"${dim} (match ${nextIndex + 1}/${matches.length}, line ${targetLine + 1})${reset}`);+ return "handled";+}diff --git a/scripts/mso-agent-cmd-parity.mjs b/scripts/mso-agent-cmd-parity.mjsindex 63de6158..df461aa8 100644--- a/scripts/mso-agent-cmd-parity.mjs+++ b/scripts/mso-agent-cmd-parity.mjs@@ -7,6 +7,11 @@ import { createQueue, enqueue, queueClear, queueList } from "./mso-agent-queue.mimport { createStash, stashClear, stashList, stashPop, stashPush } from "./mso-agent-stash.mjs";import { uploadSessionImage } from "./mso-agent-image.mjs";import { createPrinter } from "./mso-agent-print.mjs";+import {+ formatExportMarkdown,+ parseExportArgs,+ writeExportFile,+} from "./mso-agent-export-markdown.mjs";export const SHARE_UNAVAILABLE_MESSAGE ="/share is unavailable because the server exposes only download of existing shares.";@@ -40,6 +45,24 @@ export async function handleParityCommand(ctx, cmd, args) {switch (cmd) {case "/export": {try {+ const parsed = parseExportArgs(args);+ if (parsed.markdown) {+ let target = session;+ if (parsed.ref && target?.agentSession?.id !== parsed.ref && target?.id !== parsed.ref) {+ if (typeof ctx.api === "function") {+ const res = await ctx.api(`/api/v1/agent-sessions?id=${encodeURIComponent(parsed.ref)}`);+ if (res?.session) target = res.session;+ }+ }+ const markdown = formatExportMarkdown(target);+ if (parsed.outFile) {+ writeExportFile(parsed.outFile, markdown, { force: parsed.force });+ print(`session exported to ${parsed.outFile}.`);+ } else {+ print(markdown);+ }+ return "handled";+ }const outIdx = args.indexOf("--out");const outFile = outIdx !== -1 && args[outIdx + 1] ? args[outIdx + 1] : null;const code = runCli(buildExportArgv(args));diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjsindex 57d6d541..15f42a7d 100644--- a/scripts/mso-agent-commands.mjs+++ b/scripts/mso-agent-commands.mjs@@ -14,6 +14,7 @@ export const COMMAND_MANIFEST = [{ name: "/permission", usage: "[mode]", description: "choose ask | auto-write | yolo" },{ name: "/context", description: "alias for /status" },{ name: "/diff", usage: "[ref] [--full]", description: "show diff viewer panel for artifact write action" },+ { name: "/find", usage: "[query]", description: "locate text in transcript and jump to match" },{ name: "/todos", usage: "[--all]", description: "show session checklist from todo_write" },{ name: "/pane", usage: "[kind|pin|unpin]", description: "cycle, set, or pin side pane (todos, diff, files, off)" },{ name: "/keybind", usage: "[sub]", description: "view keybindings (sub: reset, conflicts)" },@@ -71,6 +72,7 @@ import { handleJobsCommand } from "./mso-agent-jobs.mjs";import { handleTerminalCommand } from "./mso-agent-cmd-terminal.mjs";import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";import { handleQueueCommand } from "./mso-agent-cmd-queue.mjs";+import { handleFindCommand } from "./mso-agent-cmd-find.mjs";import { createPrinter } from "./mso-agent-print.mjs";export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };@@ -158,6 +160,7 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {if (parityOutcome !== null) return parityOutcome;if (cmd === "/jobs") return handleJobsCommand(ctx, args);+ if (cmd === "/find") return handleFindCommand(ctx, args);if (cmd === "/terminal" || cmd === "/term") return handleTerminalCommand(ctx, args);if (cmd === "/settings" || cmd === "/setting") return handleSettingsCommand(ctx, args);diff --git a/scripts/mso-agent-compaction-live.test.ts b/scripts/mso-agent-compaction-live.test.tsnew file mode 100644index 00000000..f7fc3290--- /dev/null+++ b/scripts/mso-agent-compaction-live.test.ts@@ -0,0 +1,152 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";++// Tracks screen rows by interpreting minimal cursor movements and line updates emitted by writeFrame.+function createTerminal(columns = 80, rows = 24) {+ const chunks: string[] = [];+ const screen: string[] = [];+ let currentRow = 0;++ const output = new EventEmitter();+ Object.assign(output, {+ columns,+ rows,+ isTTY: true,+ write(value: string) {+ const str = String(value);+ chunks.push(str);+ // \x1b[H resets cursor to home row (0,0) before redrawing frame.+ if (str === "\x1b[H") {+ currentRow = 0;+ } else if (str.startsWith("\x1b[") && str.endsWith("B")) {+ // \x1b[<n>B moves cursor down n rows.+ currentRow += parseInt(str.slice(2, -1), 10);+ } else if (str.startsWith("\r\x1b[2K")) {+ // \r\x1b[2K clears line and writes next content.+ screen[currentRow] = str.slice(5);+ }+ return true;+ },+ });++ return {+ output,+ input: new EventEmitter(),+ chunks,+ screen,+ // Extracts visible lines matching a substring to assert transcript line occurrences.+ linesMatching: (pattern: string | RegExp) =>+ screen.filter((line) => (typeof pattern === "string" ? line?.includes(pattern) : pattern.test(line))),+ };+}++const makeSession = (compactionCount = 0) => ({+ agentSession: {+ id: "session-live-test",+ name: "agent",+ title: "live test",+ compactionCount,+ compactThresholdTokens: 50000,+ estimatedTokens: 10000,+ },+ state: { config: { provider: "anthropic", model: "claude-3-opus" } },+ history: [{ role: "user", text: "initial user message" }],+ usage: { totalTokens: 100 },+ statusBar: true,+ permission: "ask",+});++describe("MSO Agent live compaction in TUI screen loop", () => {+ // Test 1: a simulated compactionCount increment between two syncs produces exactly one line.+ it("a simulated compactionCount increment between two syncs produces exactly one line", () => {+ const { output, input, linesMatching } = createTerminal();+ const session = makeSession(0);+ const loop = mountScreenLoop({ enabled: true, session, output, input });++ // Initial mount with count 0 captures baseline; no compaction notice is emitted yet.+ expect(linesMatching("[session compacted")).toHaveLength(0);++ // Simulating turn completion where session compactor incremented compactionCount to 1.+ session.agentSession.compactionCount = 1;+ loop.sync();++ // Exactly one notice line announcing compaction must now appear in the transcript rows.+ const notices = linesMatching("[session compacted");+ expect(notices).toHaveLength(1);+ expect(notices[0]).toContain("#1");+ expect(notices[0]).toContain("50k");++ loop.dispose();+ });++ // Test 2: a second sync with no change produces none.+ it("a second sync with no change produces none", () => {+ const { output, input, linesMatching } = createTerminal();+ const session = makeSession(0);+ const loop = mountScreenLoop({ enabled: true, session, output, input });++ // Increment compactionCount once and sync.+ session.agentSession.compactionCount = 1;+ loop.sync();+ expect(linesMatching("[session compacted")).toHaveLength(1);++ // Repainting or syncing again without count change must NOT produce a second line.+ loop.sync();+ loop.sync();+ expect(linesMatching("[session compacted")).toHaveLength(1);++ loop.dispose();+ });++ // Test 3: the notice survives the setLines recompute that follows it.+ it("the notice survives the setLines recompute that follows it", () => {+ const { output, input, linesMatching } = createTerminal();+ const session = makeSession(0);+ const loop = mountScreenLoop({ enabled: true, session, output, input });++ // Trigger initial live compaction notice.+ session.agentSession.compactionCount = 1;+ loop.sync();+ expect(linesMatching("[session compacted")).toHaveLength(1);++ // Next interaction adds new messages to history; sync calls setLines which recomputes transcript.+ // Notice must remain because sync composes [...transcriptLines, ...compaction.lines(colors)].+ session.history.push({ role: "assistant", text: "turn 2 response" });+ session.history.push({ role: "user", text: "turn 3 query" });+ loop.sync();++ // Notice line is still present in the viewport and was not wiped by setLines recompute.+ expect(linesMatching("[session compacted")).toHaveLength(1);+ expect(linesMatching("turn 2 response").length).toBeGreaterThan(0);++ loop.dispose();+ });++ // Test 4: a session with no compaction fields produces nothing and does not throw.+ it("a session with no compaction fields produces nothing and does not throw", () => {+ const { output, input, linesMatching } = createTerminal();+ const sessionWithoutCompaction = {+ agentSession: { id: "legacy-session-no-compaction", name: "agent" },+ history: [{ role: "user", text: "legacy message" }],+ state: {},+ usage: {},+ };++ // Mount must not throw when compaction fields are missing.+ let loop: any;+ expect(() => {+ loop = mountScreenLoop({ enabled: true, session: sessionWithoutCompaction, output, input });+ }).not.toThrow();++ // Multiple syncs must succeed gracefully without throwing or creating bogus notices.+ expect(() => {+ loop.sync();+ loop.sync();+ }).not.toThrow();++ expect(linesMatching("[session compacted")).toHaveLength(0);++ loop.dispose();+ });+});diff --git a/scripts/mso-agent-export-markdown.mjs b/scripts/mso-agent-export-markdown.mjsnew file mode 100644index 00000000..0b33d4a7--- /dev/null+++ b/scripts/mso-agent-export-markdown.mjs@@ -0,0 +1,193 @@+import fs from "node:fs";+import path from "node:path";++// Strips ANSI escape sequences so exported transcripts are clean readable Markdown.+export function stripAnsi(text) {+ if (!text) return "";+ // ESC followed by CSI, OSC, or bare ESC bytes+ return String(text).replace(/\x1b\[[0-9;]*[a-zA-Z]|\x1b\].*?\x07|\x1b/g, "");+}++// Collapses multi-line strings into a single line for compact tool rows.+export function collapseToOneLine(content, maxLen = 120) {+ if (content == null) return "(no output)";+ const str = typeof content === "object" ? JSON.stringify(content) : String(content);+ const flattened = str.replace(/[\r\n\t]+/g, " ").trim();+ if (!flattened) return "(empty)";+ if (flattened.length > maxLen) {+ return `${flattened.slice(0, maxLen - 3)}...`;+ }+ return flattened;+}++// Determines if a tool invocation failed so errors are never hidden.+export function isToolFailure(row, item) {+ if (row?.isError === true || item?.isError === true) return true;+ if (row?.error != null || item?.error != null) return true;+ if (row?.status === "error" || item?.status === "error") return true;+ if (typeof row?.exitCode === "number" && row.exitCode !== 0) return true;+ if (typeof item?.exitCode === "number" && item.exitCode !== 0) return true;+ return false;+}++// Extracts normalized metadata for session header generation.+export function extractSessionMeta(session) {+ const root = session?.session && typeof session.session === "object" ? session.session : session;+ const agentSession = root?.agentSession && typeof root.agentSession === "object" ? root.agentSession : root;+ const cfg = root?.state?.config || {};++ const name = String(agentSession?.name || root?.name || agentSession?.id || root?.id || "session").replace(/^@/, "");+ const title = String(agentSession?.title || root?.title || "MSO Agent session").trim();+ const model = String(agentSession?.model || root?.model || cfg.model || "unknown").trim();++ const history = Array.isArray(root?.history)+ ? root.history+ : Array.isArray(agentSession?.history)+ ? agentSession.history+ : Array.isArray(session)+ ? session+ : [];++ const turnCount = typeof agentSession?.historyTurns === "number"+ ? agentSession.historyTurns+ : typeof root?.historyTurns === "number"+ ? root.historyTurns+ : history.filter((r) => r?.role === "user").length;++ const time = String(+ agentSession?.updatedAt || root?.updatedAt ||+ agentSession?.createdAt || root?.createdAt ||+ root?.time || new Date().toISOString()+ );++ return { name, title, model, turnCount, time, history };+}++// Formats a tool history row: successful rows collapse to one line; failures stay expanded.+export function formatToolRow(row, lastToolCalls) {+ const results = Array.isArray(row?.results) ? row.results : [row];+ const lines = [];++ for (let idx = 0; idx < results.length; idx += 1) {+ const item = results[idx];+ const isErr = isToolFailure(row, item);+ const id = item?.id ? String(item.id) : "";+ const name = item?.name || item?.tool || row?.name || (id && lastToolCalls ? lastToolCalls.get(id) : null) || "tool";+ const rawContent = item?.content != null ? item.content : (item?.result != null ? item.result : (item?.error != null ? item.error : ""));++ if (isErr) {+ // Failed rows stay expanded because hiding error traces misrepresents session results.+ const errText = typeof rawContent === "object" ? JSON.stringify(rawContent, null, 2) : String(rawContent || "error");+ lines.push(`- **Tool** (${name}) [FAILED]:`);+ lines.push("```");+ lines.push(errText);+ lines.push("```");+ } else {+ // Successful tool executions collapse to one line to keep transcripts readable.+ lines.push(`- **Tool** (${name}): ${collapseToOneLine(rawContent)}`);+ }+ }++ return lines.join("\n");+}++// Formats an entire session into a Markdown document suitable for sharing.+export function formatExportMarkdown(session) {+ const { name, title, model, turnCount, time, history } = extractSessionMeta(session);+ const lines = [];++ // Header carries required provenance metadata.+ lines.push(`# Session: ${title}`);+ lines.push("");+ lines.push(`- **Session**: @${name}`);+ lines.push(`- **Title**: ${title}`);+ lines.push(`- **Model**: ${model}`);+ lines.push(`- **Turns**: ${turnCount}`);+ lines.push(`- **Time**: ${time}`);+ lines.push("");+ lines.push("---");+ lines.push("");++ const lastToolCalls = new Map();++ for (const row of history) {+ if (!row || typeof row !== "object") continue;++ if (row.role === "user") {+ lines.push("### User");+ lines.push("");+ lines.push(String(row.text ?? row.content ?? "").trim());+ lines.push("");+ } else if (row.role === "assistant") {+ // Map tool use IDs to tool names so subsequent tool result rows can resolve names.+ if (Array.isArray(row.toolUses)) {+ for (const call of row.toolUses) {+ if (call?.id) lastToolCalls.set(String(call.id), String(call.name || "tool"));+ }+ }+ lines.push("### Assistant");+ lines.push("");+ const text = String(row.text ?? row.content ?? "").trim();+ if (text) lines.push(text);+ lines.push("");+ } else if (row.role === "tool") {+ const formatted = formatToolRow(row, lastToolCalls);+ if (formatted) {+ lines.push(formatted);+ lines.push("");+ }+ } else if (row.role === "agent") {+ const sender = row.senderLabel ? `@${row.senderLabel}` : "Agent";+ lines.push(`### Agent (${sender})`);+ lines.push("");+ lines.push(String(row.text ?? row.content ?? "").trim());+ lines.push("");+ }+ }++ // Zero ANSI escapes are guaranteed across the entire formatted output.+ return stripAnsi(lines.join("\n").trimEnd()) + "\n";+}++// Parses slash command arguments for /export flags.+export function parseExportArgs(args = []) {+ const flags = {+ markdown: false,+ force: false,+ outFile: null,+ ref: null,+ };+ const list = Array.isArray(args) ? args : [args].filter(Boolean);+ for (let i = 0; i < list.length; i += 1) {+ const a = String(list[i] || "");+ if (a === "--markdown" || a === "-md") {+ flags.markdown = true;+ } else if (a === "--force" || a === "-f") {+ flags.force = true;+ } else if (a === "--out") {+ if (list[i + 1] && !list[i + 1].startsWith("-")) {+ flags.outFile = String(list[i + 1]);+ i += 1;+ }+ } else if (a.startsWith("--out=")) {+ flags.outFile = a.slice(6);+ } else if (!a.startsWith("-") && !flags.ref) {+ flags.ref = a;+ }+ }+ return flags;+}++// Safely writes markdown export to disk, refusing to clobber existing files without force.+export function writeExportFile(filePath, content, { force = false } = {}) {+ const resolved = path.resolve(filePath);+ if (fs.existsSync(resolved) && !force) {+ throw new Error(`file already exists: ${filePath} (use --force to overwrite)`);+ }+ const dir = path.dirname(resolved);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true });+ }+ fs.writeFileSync(resolved, content, "utf8");+ return resolved;+}diff --git a/scripts/mso-agent-export-markdown.test.ts b/scripts/mso-agent-export-markdown.test.tsnew file mode 100644index 00000000..94b54e2f--- /dev/null+++ b/scripts/mso-agent-export-markdown.test.ts@@ -0,0 +1,184 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { describe, expect, it, vi } from "vitest";+import {+ formatExportMarkdown,+ writeExportFile,+} from "./mso-agent-export-markdown.mjs";+import { handleParityCommand } from "./mso-agent-cmd-parity.mjs";++describe("MSO Agent session export markdown formatter", () => {+ it("1. produces a document with roles marked and one line per successful tool call", () => {+ // Validates that successful tool outputs collapse to a single line without hiding turn roles.+ const session = {+ name: "milo",+ title: "File Inspection Session",+ model: "gpt-6.1-sol",+ history: [+ { role: "user", text: "Please inspect directory" },+ {+ role: "assistant",+ text: "Inspecting files now",+ toolUses: [{ id: "call_1", name: "fs_list" }],+ },+ {+ role: "tool",+ name: "fs_list",+ isError: false,+ content: "file1.txt\nfile2.txt\nfile3.txt\nfile4.txt",+ },+ ],+ };++ const markdown = formatExportMarkdown(session);++ // Verify role markers exist for user, assistant, and tool+ expect(markdown).toContain("### User");+ expect(markdown).toContain("### Assistant");+ expect(markdown).toContain("- **Tool** (fs_list):");++ // The successful tool call must collapse to a single line without embedded newlines+ const lines = markdown.split("\n");+ const toolLine = lines.find((line) => line.startsWith("- **Tool** (fs_list):"));+ expect(toolLine).toBeDefined();+ expect(toolLine).not.toContain("\n");+ expect(toolLine).toContain("file1.txt");+ expect(toolLine).toContain("file4.txt");+ });++ it("2. keeps a failed tool call expanded across multiple lines", () => {+ // Failed tool rows must stay expanded because concealing stack traces misrepresents session state.+ const session = {+ name: "milo",+ title: "Failure Diagnosis",+ model: "gpt-6.1-sol",+ history: [+ { role: "user", text: "Run failing task" },+ {+ role: "tool",+ name: "exec_cmd",+ isError: true,+ content: "Command failed with exit code 1:\nLine 1 of error trace\nLine 2 of error trace",+ },+ ],+ };++ const markdown = formatExportMarkdown(session);++ // Header indicates failure and content remains multi-line+ expect(markdown).toContain("- **Tool** (exec_cmd) [FAILED]:");+ expect(markdown).toContain("Line 1 of error trace");+ expect(markdown).toContain("Line 2 of error trace");++ // Check that error details occupy distinct lines rather than being flattened+ const lines = markdown.split("\n");+ const failHeaderIdx = lines.findIndex((l) => l.includes("[FAILED]"));+ expect(failHeaderIdx).toBeGreaterThanOrEqual(0);+ const subsequent = lines.slice(failHeaderIdx + 1);+ expect(subsequent.some((l) => l.includes("Line 1 of error trace"))).toBe(true);+ expect(subsequent.some((l) => l.includes("Line 2 of error trace"))).toBe(true);+ });++ it("3. contains zero ANSI escape bytes in the output", () => {+ // Transcripts must be free of terminal styling escape bytes so they render cleanly in any viewer.+ const session = {+ name: "milo",+ title: "Color Scrubbing Test",+ model: "gpt-6.1-sol",+ history: [+ { role: "user", text: "\x1b[32mGreen user text\x1b[0m" },+ { role: "assistant", text: "\x1b[34mBlue assistant\x1b[0m" },+ {+ role: "tool",+ name: "colored_tool",+ content: "\x1b[31mRed error output\x1b[0m\n\x1b[33mYellow warning\x1b[0m",+ isError: true,+ },+ ],+ };++ const markdown = formatExportMarkdown(session);++ // Byte 0x1b / \u001b (escape) must not be present anywhere in the exported text+ expect(markdown.includes("\x1b")).toBe(false);+ expect(/\u001b/.test(markdown)).toBe(false);+ expect(markdown).toContain("Green user text");+ expect(markdown).toContain("Blue assistant");+ expect(markdown).toContain("Red error output");+ });++ it("4. refuses to overwrite an existing file without --force and overwrites with --force", () => {+ // File export must not destroy existing files accidentally without an explicit force override.+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-export-test-"));+ try {+ const outPath = path.join(tmpDir, "session.md");+ fs.writeFileSync(outPath, "initial content", "utf8");++ // Attempting to overwrite without force must throw an error+ expect(() => {+ writeExportFile(outPath, "new content", { force: false });+ }).toThrow(/already exists.*--force/);++ // Verify file content was not clobbered+ expect(fs.readFileSync(outPath, "utf8")).toBe("initial content");++ // Overwriting with force must succeed+ writeExportFile(outPath, "overwritten content", { force: true });+ expect(fs.readFileSync(outPath, "utf8")).toBe("overwritten content");+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ });++ it("5. carries session name, model, and turn count in the header", () => {+ // Provenance header must document identity, active model, and conversation length.+ const session = {+ name: "operator-session",+ title: "Deployment Audit",+ model: "claude-sonnet-4-6",+ history: [+ { role: "user", text: "Turn 1" },+ { role: "assistant", text: "Reply 1" },+ { role: "user", text: "Turn 2" },+ { role: "assistant", text: "Reply 2" },+ ],+ };++ const markdown = formatExportMarkdown(session);++ expect(markdown).toMatch(/- \*\*Session\*\*:.*@?operator-session/);+ expect(markdown).toMatch(/- \*\*Model\*\*:.*claude-sonnet-4-6/);+ expect(markdown).toMatch(/- \*\*Turns\*\*:.*2/);+ expect(markdown).toContain("Deployment Audit");+ });++ it("integrates with handleParityCommand for /export --markdown", async () => {+ // Tests that slash command routing invokes markdown export and writes safely.+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-parity-export-"));+ try {+ const outPath = path.join(tmpDir, "export.md");+ const session = {+ agentSession: { id: "ses-1", name: "milo", title: "TUI Export", model: "m-test" },+ history: [+ { role: "user", text: "Hello" },+ { role: "assistant", text: "Hi there" },+ ],+ };+ const printed: string[] = [];+ const ctx = {+ session,+ runCli: vi.fn(),+ printer: { print: (s: string) => printed.push(s) },+ C: {},+ };++ const outcome = await handleParityCommand(ctx, "/export", ["--markdown", "--out", outPath]);+ expect(outcome).toBe("handled");+ expect(fs.existsSync(outPath)).toBe(true);+ expect(fs.readFileSync(outPath, "utf8")).toContain("TUI Export");+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ }+ });+});diff --git a/scripts/mso-agent-find.mjs b/scripts/mso-agent-find.mjsnew file mode 100644index 00000000..3b822961--- /dev/null+++ b/scripts/mso-agent-find.mjs@@ -0,0 +1,56 @@+// Pure helpers for transcript search and viewport offset calculation.+import { stripAnsi } from "./tui/cells.mjs";+import { getAllLines } from "./mso-agent-viewport.mjs";++/**+ * Finds all 0-based line indices where plain text includes query (case-insensitive).+ * Strips ANSI escapes from each line before matching so styling does not prevent hits.+ *+ * @param {string[]} lines - Styled or plain transcript lines.+ * @param {string} query - Plain-text search query.+ * @returns {number[]} Array of matching line indices.+ */+export function findMatches(lines, query) {+ if (!Array.isArray(lines) || typeof query !== "string") return [];+ const target = query.trim().toLowerCase();+ // An empty or whitespace-only query matches nothing to prevent accidental whole-buffer hits.+ if (!target) return [];++ const results = [];+ for (let i = 0; i < lines.length; i += 1) {+ const plain = stripAnsi(lines[i]).toLowerCase();+ if (plain.includes(target)) {+ results.push(i);+ }+ }+ return results;+}++/**+ * Computes the viewport offset that places lineIndex inside the visible window.+ *+ * In mso-agent-viewport.mjs, offset 0 is follow mode (pinned to the bottom), and+ * visible lines start at `targetStart = total - r - offset`.+ * To center lineIndex in a window of height r, we target+ * `targetStart = lineIndex - Math.floor(r / 2)` clamped to [0, total - r].+ * Solving for offset: `offset = total - r - targetStart`.+ *+ * @param {object} viewport - Viewport instance containing buffer lines.+ * @param {number} lineIndex - 0-based target line index to make visible.+ * @param {number} [rows] - Optional visible row count override.+ * @returns {number} Clamped offset (>= 0) that makes lineIndex visible.+ */+export function offsetForLine(viewport, lineIndex, rows) {+ if (!viewport) return 0;+ const allLines = getAllLines(viewport);+ const total = allLines.length;+ const r = Math.max(0, Number(rows ?? viewport.rows) || 0);++ // If buffer is empty, height is zero, or all lines fit on screen, offset remains 0.+ if (total === 0 || r === 0 || total <= r) return 0;++ const idx = Math.max(0, Math.min(total - 1, Number(lineIndex) || 0));+ const half = Math.floor(r / 2);+ const targetStart = Math.max(0, Math.min(total - r, idx - half));+ return total - r - targetStart;+}diff --git a/scripts/mso-agent-find.test.ts b/scripts/mso-agent-find.test.tsnew file mode 100644index 00000000..f0097794--- /dev/null+++ b/scripts/mso-agent-find.test.ts@@ -0,0 +1,189 @@+import { describe, expect, it } from "vitest";+import { findMatches, offsetForLine } from "./mso-agent-find.mjs";+import { handleFindCommand } from "./mso-agent-cmd-find.mjs";+import {+ appendLines,+ createViewport,+ resetFollow,+ setLines,+ viewportWindow,+} from "./mso-agent-viewport.mjs";++describe("transcript search (/find)", () => {+ it("(1) three occurrences produce three indexes", () => {+ const lines = [+ "first line without keyword",+ "target occurrence one here",+ "some other text",+ "third line neutral",+ "target occurrence two here",+ "filler content",+ "more filler content",+ "almost at the end",+ "target occurrence three here",+ "final closing line",+ ];+ const indexes = findMatches(lines, "target");+ expect(indexes).toEqual([1, 4, 8]);+ });++ it("(2) matching ignores ANSI styling, proven with a line containing colour codes", () => {+ // Styling tags are interspersed across role markers and keywords.+ const styledLine = "\x1b[34m[user]\x1b[0m \x1b[1mhello\x1b[0m \x1b[32mworld\x1b[0m of agents";+ const plainLine = "just another plain line";+ const lines = [styledLine, plainLine];++ // Substring across boundaries that contain color escape codes matches plain text.+ expect(findMatches(lines, "hello world")).toEqual([0]);+ // Case-insensitive matching works with styled lines.+ expect(findMatches(lines, "[USER]")).toEqual([0]);+ expect(findMatches(lines, "WORLD OF AGENTS")).toEqual([0]);+ // Raw escape sequences themselves should not match plain text search.+ expect(findMatches(lines, "\x1b[34m")).toEqual([]);+ });++ it("(3) /find jumps to the first match and the offset makes it visible", async () => {+ const vp = createViewport({ rows: 10 });+ const buffer = Array.from({ length: 60 }, (_, i) => `line ${i}: message`);+ buffer[15] = "line 15: findme unique token";+ buffer[35] = "line 35: findme unique token";+ setLines(vp, buffer);++ const logged: string[] = [];+ const session = { _findState: null };+ const ctx = {+ session,+ viewport: vp,+ printer: { print: (msg: string) => logged.push(msg) },+ };++ // Before search: viewport is at offset 0 (pinned to bottom, lines 50..59 visible).+ expect(vp.offset).toBe(0);++ await handleFindCommand(ctx, ["findme"]);++ // First match is at index 15; offset must place line 15 within visible window.+ expect(logged[0]).toMatch(/2 matches.*match 1\/2.*line 16/);+ const win = viewportWindow(vp, 10);+ expect(win.start).toBeLessThanOrEqual(15);+ expect(win.end).toBeGreaterThan(15);+ expect(win.lines).toContain("line 15: findme unique token");+ });++ it("(4) repeated find wraps", async () => {+ const vp = createViewport({ rows: 10 });+ const buffer = Array.from({ length: 50 }, (_, i) => `entry ${i}`);+ buffer[10] = "entry 10: needle";+ buffer[25] = "entry 25: needle";+ buffer[40] = "entry 40: needle";+ setLines(vp, buffer);++ const logged: string[] = [];+ const session = { _findState: null };+ const ctx = {+ session,+ viewport: vp,+ printer: { print: (msg: string) => logged.push(msg) },+ };++ // First search jumps to match 1 (index 10).+ await handleFindCommand(ctx, ["needle"]);+ let win = viewportWindow(vp, 10);+ expect(win.start).toBeLessThanOrEqual(10);+ expect(win.end).toBeGreaterThan(10);+ expect(logged.at(-1)).toMatch(/3 matches.*match 1\/3.*line 11/);++ // Repeated search with same query jumps to match 2 (index 25).+ await handleFindCommand(ctx, ["needle"]);+ win = viewportWindow(vp, 10);+ expect(win.start).toBeLessThanOrEqual(25);+ expect(win.end).toBeGreaterThan(25);+ expect(logged.at(-1)).toMatch(/3 matches.*match 2\/3.*line 26/);++ // Search with --next jumps to match 3 (index 40).+ await handleFindCommand(ctx, ["--next"]);+ win = viewportWindow(vp, 10);+ expect(win.start).toBeLessThanOrEqual(40);+ expect(win.end).toBeGreaterThan(40);+ expect(logged.at(-1)).toMatch(/3 matches.*match 3\/3.*line 41/);++ // Next repeated find wraps back to match 1 (index 10).+ await handleFindCommand(ctx, ["needle"]);+ win = viewportWindow(vp, 10);+ expect(win.start).toBeLessThanOrEqual(10);+ expect(win.end).toBeGreaterThan(10);+ expect(logged.at(-1)).toMatch(/3 matches.*match 1\/3.*line 11/);+ });++ it("(5) a query with no match reports zero and does not scroll", async () => {+ const vp = createViewport({ rows: 10 });+ const buffer = Array.from({ length: 40 }, (_, i) => `item ${i}`);+ setLines(vp, buffer);+ vp.offset = 7; // User has scrolled up manually++ const logged: string[] = [];+ const session = { _findState: null };+ const ctx = {+ session,+ viewport: vp,+ printer: { print: (msg: string) => logged.push(msg) },+ };++ await handleFindCommand(ctx, ["nonexistent_query"]);+ expect(logged[0]).toBe('0 matches for "nonexistent_query"');+ // Scroll offset must not have changed.+ expect(vp.offset).toBe(7);+ });++ it("(6) an empty query is refused with a message", async () => {+ const vp = createViewport({ rows: 10 });+ setLines(vp, ["some line"]);++ const logged: string[] = [];+ const session = { _findState: null };+ const ctx = {+ session,+ viewport: vp,+ printer: { print: (msg: string) => logged.push(msg) },+ };++ // No prior query on session.+ await handleFindCommand(ctx, []);+ expect(logged[0]).toBe("no previous query: use /find <query>");++ // Empty string argument passed explicitly.+ await handleFindCommand(ctx, [""]);+ expect(logged[1]).toBe("empty query: use /find <query>");++ // Whitespace only argument.+ await handleFindCommand(ctx, [" "]);+ expect(logged[2]).toBe("empty query: use /find <query>");+ });++ it("setting an offset does not corrupt follow mode and returns cleanly on new prompt", () => {+ const vp = createViewport({ rows: 10 });+ const buffer = Array.from({ length: 60 }, (_, i) => `line ${i}`);+ setLines(vp, buffer);++ // Initially in follow mode (pinned to bottom, offset 0).+ expect(vp.offset).toBe(0);+ expect(viewportWindow(vp, 10).follow).toBe(true);++ // Find sets offset to inspect historical match at line 12.+ vp.offset = offsetForLine(vp, 12, 10);+ expect(vp.offset).toBeGreaterThan(0);+ // Follow mode is now off while the user browses the transcript.+ expect(viewportWindow(vp, 10).follow).toBe(false);++ // When the user submits a new prompt, follow mode is reset.+ resetFollow(vp);+ expect(vp.offset).toBe(0);+ expect(viewportWindow(vp, 10).follow).toBe(true);++ // New stream output arrives and remains visible at the bottom.+ appendLines(vp, ["line 60 (fresh response)"]);+ const win = viewportWindow(vp, 10);+ expect(win.follow).toBe(true);+ expect(win.lines.at(-1)).toBe("line 60 (fresh response)");+ });+});diff --git a/scripts/mso-agent-help-lines.mjs b/scripts/mso-agent-help-lines.mjsindex e4e28c56..990adfa9 100644--- a/scripts/mso-agent-help-lines.mjs+++ b/scripts/mso-agent-help-lines.mjs@@ -74,18 +74,32 @@ function formatKeyboard(keybinds, width, colors) {const dim = colors?.dim || "";const c = colors?.cyan || "";const lines = ["", `${b}Keyboard${r}`];- const interruptKey = prettyKey(keybinds?.interrupt || "ctrl+c");- const clearKey = prettyKey(keybinds?.clear_screen || "ctrl+l");+ const defaults = defaultKeybinds();++ // One-character asterisk marker flags any binding that differs from the default keymap.+ const mark = (action) => (keybinds?.[action] && keybinds[action] !== defaults[action] ? "*" : "");+ // Formats human-readable key with optional customization marker.+ const k = (action, fallback) => `${prettyKey(keybinds?.[action] || fallback)}${mark(action)}`;++ // Preserves canonical (empty prompt) annotation for completion/permission cycling.+ const completeLabel = `${k("complete", "tab")} (empty prompt)`;const entries = [- { label: interruptKey, desc: "clear input; empty prompt exits; active turn interrupts" },+ { label: k("interrupt", "ctrl+c"), desc: "clear input; empty prompt exits; active turn interrupts" },{ label: "Ctrl+D", desc: "delete right; empty prompt exits" },- { label: clearKey, desc: "clear/repaint terminal" },+ { label: k("clear_screen", "ctrl+l"), desc: "clear/repaint terminal" },+ { label: k("dismiss", "escape"), desc: "dismiss completion menu or cancel" },{ label: "Ctrl+W · Ctrl+U/K", desc: "delete word · delete to line start/end" },- { label: "↑/↓ or Ctrl+P/N", desc: "prompt history (durable after resume)" },+ { label: k("history_prev", "ctrl+p"), desc: "previous prompt in history (also ↑)" },+ { label: k("history_next", "ctrl+n"), desc: "next prompt in history (also ↓)" },{ label: "Ctrl+A/E · Ctrl+B/F", desc: "line start/end · left/right" },{ label: "Alt+B/F · Ctrl+←/→", desc: "move by word" },- { label: "Tab (empty prompt)", desc: "cycle permission in place: ask → auto → yolo" },+ { label: completeLabel, desc: "cycle permission in place: ask → auto → yolo" },+ { label: k("submit", "return"), desc: "submit prompt line or selected item" },];+ // Displays status bar toggle key only when user explicitly configures the optional binding.+ if (keybinds?.toggle_status_bar) {+ entries.push({ label: k("toggle_status_bar", ""), desc: "toggle compact status bar" });+ }for (const entry of entries) {if (entry.label.length + entry.desc.length + 4 <= width) {const pad = (entry.label.length < 20 && 20 + entry.desc.length + 4 <= width) ? 20 : entry.label.length;diff --git a/scripts/mso-agent-help-width.test.ts b/scripts/mso-agent-help-width.test.tsnew file mode 100644index 00000000..3bd6f396--- /dev/null+++ b/scripts/mso-agent-help-width.test.ts@@ -0,0 +1,90 @@+import process from "node:process";+import { describe, expect, it } from "vitest";+import { helpLines, printHelp } from "./mso-agent-help.mjs";++describe("MSO Agent help width adaptation and terminal wrapping", () => {+ it("(1) width 120 produces no line longer than 120 and fewer lines than width 60", () => {+ const lines120 = helpLines({ width: 120 });+ const lines60 = helpLines({ width: 60 });++ expect(lines120.length).toBeGreaterThan(0);+ for (const line of lines120) {+ expect(line.length).toBeLessThanOrEqual(120);+ }+ // Measured line counts prove wide terminals pack command descriptions on a single line+ // instead of wrapping them to a 60-column column.+ expect(lines120.length).toBeLessThan(lines60.length);+ });++ it("(2) width 40 still produces lines within 40 columns without arbitrary terminal breaks", () => {+ // We choose to allow narrow terminals to wrap down to 40 columns rather than forcing a 60 floor.+ // Enforcing a 60 floor on a 40-column terminal would cause the emulator to hard-break words.+ const lines40 = helpLines({ width: 40 });+ expect(lines40.length).toBeGreaterThan(0);+ for (const line of lines40) {+ expect(line.length, `line exceeded 40 chars: "${line}"`).toBeLessThanOrEqual(40);+ }+ });++ it("(3) printHelp with a session carrying a stale width still uses live stdout columns", () => {+ const originalColumns = process.stdout.columns;+ const printed: string[] = [];+ try {+ // Mock stdout columns to simulate a live 120-column terminal viewport.+ Object.defineProperty(process.stdout, "columns", {+ value: 120,+ configurable: true,+ });++ // Session carries a stale width of 40 from an earlier pane or split state.+ const staleSession = { width: 40 };+ printHelp({+ session: staleSession,+ write: (line: string) => printed.push(line),+ });++ const expected120 = helpLines({ width: 120 });+ // Proves printHelp preferred live stdout columns (70 lines) over stale session width (176 lines).+ expect(printed).toEqual(expected120);+ expect(printed.length).toBe(expected120.length);+ for (const line of printed) {+ expect(line.length).toBeLessThanOrEqual(120);+ }+ } finally {+ Object.defineProperty(process.stdout, "columns", {+ value: originalColumns,+ configurable: true,+ });+ }+ });++ it("(4) no ANSI escape codes emitted when no colors are passed", () => {+ const plainLines = helpLines({ width: 80 });+ for (const line of plainLines) {+ expect(line).not.toMatch(/\x1b\[/);+ }++ const emptyColorLines = helpLines({ width: 80, colors: {} });+ for (const line of emptyColorLines) {+ expect(line).not.toMatch(/\x1b\[/);+ }++ const printed: string[] = [];+ printHelp({+ width: 80,+ write: (line: string) => printed.push(line),+ });+ for (const line of printed) {+ expect(line).not.toMatch(/\x1b\[/);+ }+ });++ it("contains no em dash characters across all evaluated widths", () => {+ for (const w of [40, 60, 80, 120]) {+ const lines = helpLines({ width: w });+ for (const line of lines) {+ expect(line).not.toContain("\u2014");+ }+ }+ });+});diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjsindex d44d516c..af97372b 100644--- a/scripts/mso-agent-help.mjs+++ b/scripts/mso-agent-help.mjs@@ -1,7 +1,9 @@import process from "node:process";// Derives help lines and formatted text directly from command and settings registries.+// Commands like /find are declared in COMMAND_MANIFEST in mso-agent-commands.mjs.import { createPrinter } from "./mso-agent-print.mjs";import { helpLines } from "./mso-agent-help-lines.mjs";+import { getKeybinds } from "./mso-agent-keybinds.mjs";export { helpLines };@@ -11,14 +13,10 @@ export const HELP_TEXT = HELP_LINES.join("\n");export function printHelp(options = {}) {const printer = createPrinter(options);- // Re-render when caller passes terminal width or custom colors; fallback to canonical HELP_TEXT.const colors = options.colors || options.session?.colors;- // Fall back to the real terminal width, not a constant: a fixed 60 wrapped /help on every wide- // terminal, which is the opposite of what a help screen should do with space it has.- const width = options.width || options.session?.width || process.stdout?.columns;- if (width || colors) {- printer.printBlock(helpLines({ ...options, colors, width }).join("\n"));- } else {- printer.printBlock(HELP_TEXT);- }+ // Live terminal columns beat a stale session width, so a resize is respected the moment /help runs.+ const width = options.width || process.stdout?.columns || options.session?.width;+ // Effective keybinds, so a custom keymap is described instead of the shipped default.+ const keybinds = options.keybinds || getKeybinds();+ printer.printBlock(helpLines({ ...options, colors, width, keybinds }).join("\n"));}diff --git a/scripts/mso-agent-keybind-help.test.ts b/scripts/mso-agent-keybind-help.test.tsnew file mode 100644index 00000000..ac1ac968--- /dev/null+++ b/scripts/mso-agent-keybind-help.test.ts@@ -0,0 +1,153 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { helpLines, printHelp } from "./mso-agent-help.mjs";+import {+ defaultKeybinds,+ formatKeybindTable,+ getKeybinds,+ loadKeybinds,+} from "./mso-agent-keybinds.mjs";++function resetToDefaults() {+ // Resets module cache in keybinds loader to clean defaults to avoid test cross-pollution.+ loadKeybinds({+ path: "/clean/keybinds.json",+ readFile: () => {+ const err = new Error("ENOENT");+ // @ts-expect-error test error code+ err.code = "ENOENT";+ throw err;+ },+ });+}++function extractKeyboardSection(lines: string[]): string {+ // Isolate keyboard section lines so assertions evaluate keybind formatting without false positives.+ const idx = lines.findIndex((line) => line.trim() === "Keyboard");+ return idx >= 0 ? lines.slice(idx).join("\n") : "";+}++describe("MSO Agent keybind help parity", () => {+ afterEach(() => {+ resetToDefaults();+ });++ it("(1) with no keybind file, help shows defaults and no markers", () => {+ resetToDefaults();++ const kbText = extractKeyboardSection(helpLines({ keybinds: getKeybinds() }));++ // Shipped defaults must be displayed when no user configuration exists.+ expect(kbText).toContain("Ctrl+C");+ expect(kbText).toContain("Ctrl+L");+ expect(kbText).toContain("Escape");+ expect(kbText).toContain("Tab (empty prompt)");+ expect(kbText).toContain("Ctrl+P");+ expect(kbText).toContain("Ctrl+N");+ expect(kbText).toContain("Return");++ // Asterisk customization marker must not be present when using shipped defaults.+ expect(kbText).not.toContain("*");+ });++ it("(2) with a custom file changing one action, that action shows the custom key and a marker", () => {+ // Simulate user editing ~/.mso/keybinds.json to rebind clear_screen to ctrl+k.+ loadKeybinds({+ path: "/user/keybinds.json",+ readFile: () => JSON.stringify({ clear_screen: "ctrl+k" }),+ });++ const kbText = extractKeyboardSection(helpLines({ keybinds: getKeybinds() }));++ // Changed action reflects the effective key and displays the customization marker.+ expect(kbText).toContain("Ctrl+K*");++ // Unchanged actions retain their default keys without customization markers.+ expect(kbText).toContain("Ctrl+C");+ expect(kbText).not.toContain("Ctrl+C*");+ expect(kbText).toContain("Escape");+ expect(kbText).not.toContain("Escape*");++ // Marker count verifies that exactly one customization is flagged.+ const markerMatches = kbText.match(/\*/g) || [];+ expect(markerMatches.length).toBe(1);++ // Verify printHelp() passes effective keybinds down to printer output.+ const captured: string[] = [];+ const spy = vi.spyOn(console, "log").mockImplementation((msg) => {+ captured.push(String(msg));+ });+ try {+ printHelp();+ expect(captured.join("\n")).toContain("Ctrl+K*");+ } finally {+ spy.mockRestore();+ }+ });++ it("(3) a malformed file does not throw and shows no markers", () => {+ // Malformed JSON must be gracefully handled by falling back to shipped defaults.+ expect(() => {+ loadKeybinds({+ path: "/corrupt/keybinds.json",+ readFile: () => "{ broken json",+ });+ }).not.toThrow();++ let output = "";+ expect(() => {+ output = helpLines({ keybinds: getKeybinds() }).join("\n");+ }).not.toThrow();++ const kbText = extractKeyboardSection(output.split("\n"));++ // Help must display defaults without flagging them as custom.+ expect(kbText).toContain("Ctrl+C");+ expect(kbText).toContain("Ctrl+L");+ expect(kbText).not.toContain("*");+ });++ it("(4) the help keyboard section and formatKeybindTable agree on the effective key for every action, asserted action by action", () => {+ // Test agreement across both default bindings and multiple custom user bindings.+ const configs = [+ {+ name: "defaults",+ bindings: defaultKeybinds(),+ },+ {+ name: "customized",+ bindings: {+ interrupt: "ctrl+x",+ clear_screen: "ctrl+k",+ dismiss: "alt+q",+ complete: "ctrl+space",+ history_prev: "alt+p",+ history_next: "alt+n",+ submit: "return",+ },+ },+ ];++ for (const { bindings } of configs) {+ const table = formatKeybindTable(bindings);+ const kbText = extractKeyboardSection(helpLines({ keybinds: bindings }));++ for (const [action, rawKey] of Object.entries(bindings)) {+ // Table output contains normalized action identifier and key token.+ expect(table).toContain(action);+ expect(table).toContain(rawKey);++ // Convert normalized key token to human-readable form used in help lines.+ const pretty = rawKey+ .split("+")+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())+ .join("+");++ // The help keyboard section agrees on the effective key for every action.+ expect(+ kbText,+ `help keyboard section should contain key "${pretty}" for action "${action}"`+ ).toContain(pretty);+ }+ }+ });+});diff --git a/scripts/mso-agent-pane-context.mjs b/scripts/mso-agent-pane-context.mjsindex 635e3506..0d8691fe 100644--- a/scripts/mso-agent-pane-context.mjs+++ b/scripts/mso-agent-pane-context.mjs@@ -76,8 +76,12 @@ export function formatContextContent({ session }) {// history is the durable transcript, but a session that has run turns carries the provider's own// accounting in usage. Prefer the larger of the two: showing ~0 tokens next to a live model that// just billed 47k is the kind of number that teaches the user to distrust the pane.- const reported = Number(session?.usage?.totalTokens ?? session?.usage?.promptTokens ?? 0) || 0;- if (reported > ctx.used) ctx.used = reported;+ const reported = Number(session?.usage?.totalTokens ?? session?.usage?.promptTokens ?? session?.usage?.inputTokens ?? 0) || 0;+ if (reported > ctx.used) {+ ctx.used = reported;+ // Recompute percent so the proportion bar tracks provider-reported usage.+ if (ctx.limit > 0) ctx.percent = Math.min(999, Math.round((ctx.used / ctx.limit) * 100));+ }const turns = history.filter((row) => row?.role === "user").length || Number(session?.usage?.apiCalls || 0);const rows = [];diff --git a/scripts/mso-agent-pane-live.test.ts b/scripts/mso-agent-pane-live.test.tsnew file mode 100644index 00000000..5930c3a2--- /dev/null+++ b/scripts/mso-agent-pane-live.test.ts@@ -0,0 +1,194 @@+import { describe, expect, it, vi } from "vitest";+import { cellWidth, stripAnsi } from "./tui/cells.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";+import { paneLines } from "./mso-agent-pane.mjs";+import { formatContextContent } from "./mso-agent-pane-context.mjs";++class FakeTerminalOutput {+ columns = 120;+ rows = 24;+ isTTY = true;+ chunks: string[] = [];+ write(val: string) { this.chunks.push(String(val)); return true; }+}++describe("mso-agent-pane-live: live context and MCP pane rendering", () => {+ // Test 1: mutating session.usage.totalTokens between two syncs changes the rendered context line+ it("mutating session.usage.totalTokens between two syncs changes the rendered context line", () => {+ const output = new FakeTerminalOutput();+ const session: any = {+ paneKind: "context",+ state: { config: { provider: "anthropic", model: "claude-3-5-sonnet" }, modelMeta: { context: 100_000 } },+ history: [{ role: "user", text: "hello" }],+ usage: { totalTokens: 1_000 },+ };++ const beforeContent = formatContextContent({ session });+ const beforeRow = beforeContent.rows.find((r) => r.text.startsWith("tokens:"));+ expect(beforeRow?.text).toBe("tokens: ~1.0k / 100k");++ const loop = mountScreenLoop({ session, enabled: true, output: output as any });+ expect(stripAnsi(output.chunks.join(""))).toContain("tokens: ~1.0k / 100k");++ const writeIndex = output.chunks.length;+ session.usage.totalTokens = 42_000;+ loop.sync();++ const afterContent = formatContextContent({ session });+ const afterRow = afterContent.rows.find((r) => r.text.startsWith("tokens:"));+ expect(afterRow?.text).toBe("tokens: ~42k / 100k");+ expect(beforeRow?.text).not.toBe(afterRow?.text);++ const diff = stripAnsi(output.chunks.slice(writeIndex).join(""));+ expect(diff).toContain("tokens: ~42k / 100k");+ loop.dispose();+ });++ // Test 2: a compaction or a turn does not throw in the pane+ it("a compaction or a turn does not throw in the pane", () => {+ const output = new FakeTerminalOutput();+ const session: any = {+ paneKind: "context",+ state: { config: { provider: "openai", model: "gpt-4o" }, modelMeta: { context: 128_000 } },+ agentSession: { id: "sess-live", compactThresholdTokens: 50_000, estimatedTokens: 45_000, compactionCount: 0 },+ history: [{ role: "user", text: "start" }, { role: "assistant", text: "ok" }],+ usage: { totalTokens: 10_000, apiCalls: 1 },+ mcpServers: [{ name: "gw", toolCount: 5 }],+ };++ const loop = mountScreenLoop({ session, enabled: true, output: output as any });++ // Turn completion simulation+ expect(() => {+ session.history.push({ role: "user", text: "next" }, { role: "assistant", text: "done" });+ session.usage.totalTokens = 35_000;+ session.usage.apiCalls = 2;+ loop.sync();+ paneLines({ kind: "context", session, width: 42, rows: 20 });+ paneLines({ kind: "mcp", session, width: 42, rows: 20 });+ }).not.toThrow();++ // Compaction event simulation+ expect(() => {+ session.agentSession.compactionCount = 1;+ session.agentSession.estimatedTokens = 12_000;+ session.history = [{ role: "user", text: "compacted summary" }];+ session.usage.totalTokens = 15_000;+ loop.sync();+ paneLines({ kind: "context", session, width: 42, rows: 20 });+ paneLines({ kind: "mcp", session, width: 42, rows: 20 });+ }).not.toThrow();++ loop.dispose();+ });++ // Test 3: if you add an MCP refresh, a failed refresh keeps the previous list rather than blanking the pane+ it("if you add an MCP refresh, a failed refresh keeps the previous list rather than blanking the pane", async () => {+ const output = new FakeTerminalOutput();+ const session: any = {+ paneKind: "mcp",+ mcpServers: [+ { name: "github", toolCount: 8, connected: true },+ { name: "filesystem", toolCount: 4, connected: true },+ ],+ };++ const refreshMcp = vi.fn().mockRejectedValue(new Error("network error"));+ const loop = mountScreenLoop({ session, enabled: true, output: output as any, refreshMcp });++ const beforeLines = paneLines({ kind: "mcp", session, width: 42, rows: 10 });+ const beforeText = beforeLines.map((l) => stripAnsi(l)).join("\n");+ expect(beforeText).toContain("github (8 tools)");+ expect(beforeText).not.toContain("no MCP servers");++ // Trigger sync which calls the failing refresh+ loop.sync();+ await new Promise((r) => setTimeout(r, 10));+ expect(refreshMcp).toHaveBeenCalledTimes(1);++ // Assert previous list is kept and pane was not blanked+ expect(session.mcpServers).toEqual([+ { name: "github", toolCount: 8, connected: true },+ { name: "filesystem", toolCount: 4, connected: true },+ ]);+ const failedLines = paneLines({ kind: "mcp", session, width: 42, rows: 10 });+ expect(failedLines.map((l) => stripAnsi(l)).join("\n")).toContain("github (8 tools)");++ // Successful refresh replaces the server list+ const updated = [{ name: "docker", toolCount: 6, connected: true }];+ refreshMcp.mockResolvedValueOnce(updated);+ loop.sync();+ await new Promise((r) => setTimeout(r, 10));++ expect(session.mcpServers).toEqual(updated);+ const updatedLines = paneLines({ kind: "mcp", session, width: 42, rows: 10 });+ expect(updatedLines.map((l) => stripAnsi(l)).join("\n")).toContain("docker (6 tools)");+ loop.dispose();+ });++ // Test 4: the pane renders exactly rows lines and never exceeds width+ it("the pane renders exactly rows lines and never exceeds width", () => {+ const testCases: Array<{ kind: "context" | "mcp", session: any }> = [+ {+ kind: "context",+ session: {+ state: {+ config: { provider: "very-long-provider-name-that-overflows", model: "model-identifier-suffix" },+ modelMeta: { context: 200_000 },+ },+ history: [{ role: "user", text: "Long text ".repeat(40) }],+ usage: { totalTokens: 150_000 },+ systemTokens: 2_500,+ },+ },+ {+ kind: "context",+ session: { state: { config: {}, modelMeta: null }, history: [], usage: {} },+ },+ {+ kind: "mcp",+ session: {+ mcpServers: [+ { name: "日本語サーバー漢字名ツールテスト", toolCount: 42, connected: true },+ { name: "offline-server", status: "disconnected", toolCount: 0 },+ ],+ },+ },+ {+ kind: "mcp",+ session: { mcpServers: [] },+ },+ ];++ for (const { kind, session } of testCases) {+ for (const w of [30, 42, 50]) {+ for (const r of [1, 2, 3, 4, 10, 24]) {+ const lines = paneLines({ kind, session, width: w, rows: r });+ expect(lines.length).toBe(r);+ for (const line of lines) {+ expect(cellWidth(line)).toBe(w);+ }+ }+ }+ }+ });++ // Test 5: proportion bar tracks live usage when totalTokens increases+ it("proportion bar recomputes and tracks live usage updates", () => {+ const session: any = {+ paneKind: "context",+ state: { config: { provider: "openai", model: "gpt-4o" }, modelMeta: { context: 100_000 } },+ history: [{ role: "user", text: "short" }],+ usage: { totalTokens: 10_000 },+ };++ const before = formatContextContent({ session });+ const beforeBar = before.rows.find((r) => r.text.startsWith("bar:"));+ expect(beforeBar?.text).toContain("10%");++ session.usage.totalTokens = 80_000;+ const after = formatContextContent({ session });+ const afterBar = after.rows.find((r) => r.text.startsWith("bar:"));+ expect(afterBar?.text).toContain("80%");+ });+});diff --git a/scripts/mso-agent-panel-effects.mjs b/scripts/mso-agent-panel-effects.mjsnew file mode 100644index 00000000..17ef56cf--- /dev/null+++ b/scripts/mso-agent-panel-effects.mjs@@ -0,0 +1,35 @@+// Side effects the panel runs on sync and on click, kept apart from the paint loop so that file stays+// under the line ratchet and so each effect has one obvious home.+import { createPrinter } from "./mso-agent-print.mjs";+import { formatClickHint, shouldShowClickHint } from "./mso-agent-click-hint.mjs";++/**+ * A bounded MCP refresh: at most once in flight, never on paint, and a failure keeps the previous list+ * rather than blanking a pane that was already correct.+ */+export function createMcpRefresher({ session, getRefresh, onUpdated }) {+ let inFlight = false;+ return () => {+ const fn = getRefresh();+ if (typeof fn !== "function" || inFlight) return;+ inFlight = true;+ Promise.resolve(fn())+ .then((next) => { if (Array.isArray(next)) { session.mcpServers = next; onUpdated(); } })+ .catch(() => {})+ .finally(() => { inFlight = false; });+ };+}++/**+ * Tracks the one-shot click hint. State lives here rather than in the loop so the loop does not need a+ * counter, and so the rule (once per session, interactive regions only) is testable on its own.+ */+export function createClickHintReporter({ session, colors }) {+ let emitted = 0;+ return ({ event, geometry, targetId, suspended }) => {+ if (!shouldShowClickHint({ event, geometry, targetId, hintCount: emitted, suspended })) return false;+ emitted += 1;+ createPrinter({ session, colors }).print(formatClickHint(colors));+ return true;+ };+}diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjsindex f6949b29..0430ddeb 100644--- a/scripts/mso-agent-screen-loop.mjs+++ b/scripts/mso-agent-screen-loop.mjs@@ -12,6 +12,10 @@ import { paneLines } from "./mso-agent-pane.mjs";import { withPreamble } from "./mso-agent-banner-lines.mjs";import { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";import { createCompactionWatcher } from "./mso-agent-compaction.mjs";+import { createAttentionNotifier } from "./mso-agent-attention.mjs";+import { createClickHintReporter, createMcpRefresher } from "./mso-agent-panel-effects.mjs";+import { createPrinter } from "./mso-agent-print.mjs";+import { formatClickHint, shouldShowClickHint } from "./mso-agent-click-hint.mjs";export { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";/**@@ -20,40 +24,24 @@ export { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";* keeps running exactly as it did before this module existed.** @param {{- * session: any,- * enabled?: boolean,- * output?: any,- * input?: any,- * colors?: any,- * getSessions?: () => Array<any>,- * onTabClick?: (sessionId: string) => void | Promise<void>,- * composer?: any,- * preamble?: (() => Array<string> | null) | null,- * tabsLayout?: string | null,- * mouse?: string | boolean | null,- * tabsScope?: string | null,+ * session: any, enabled?: boolean, output?: any, input?: any, colors?: any,+ * getSessions?: () => Array<any>, onTabClick?: (sessionId: string) => void | Promise<void>,+ * composer?: any, preamble?: (() => Array<string> | null) | null, tabsLayout?: string | null,+ * mouse?: string | boolean | null, tabsScope?: string | null,+ * attention?: string | null, attentionOutput?: any,+ * refreshMcp?: (() => Promise<any> | any) | null,* }} options*/export function mountScreenLoop({- session,- enabled = false,- output = process.stdout,- input = process.stdin,- colors = {},- getSessions = () => [],- onTabClick,- composer = null,- preamble = null,- tabsLayout = null,- mouse = null,- tabsScope = null,+ session, enabled = false, output = process.stdout, input = process.stdin, colors = {},+ getSessions = () => [], onTabClick, composer = null, preamble = null, tabsLayout = null,+ mouse = null, tabsScope = null, attention = null, attentionOutput = null, refreshMcp = null,} = {}) {if (!enabled || !session) {return {active: false, session: null, paint() {}, sync() {}, suspend() {}, resume() {}, follow() {},geometry() { return { cols: 80, rows: 24, panel: [], viewRows: 0, tabRowY: 0, pWidth: 0, transWidth: 80, railWidth: 0, kind: null, promptRows: PROMPT_ROWS }; },setPromptRows() {}, setMouse() {}, dispose() {},- setPromptRows() {}, dispose() {},};}@@ -69,6 +57,12 @@ export function mountScreenLoop({const viewport = createViewport({ rows: output.rows || 24 });const compaction = createCompactionWatcher(session);+ // Attention alerts on background session transitions; inert when off to avoid terminal noise.+ const attentionNotifier = createAttentionNotifier({+ output: attentionOutput || output,+ getMode: () => attention || session?.attention || "off",+ getActiveId: () => session?.agentSession?.id ?? session?.id ?? null,+ });let painted = [];let promptReservation = PROMPT_ROWS;@@ -107,12 +101,18 @@ export function mountScreenLoop({output.write(`\x1b[${frame.length};1H`);};+ const reportClickHint = createClickHintReporter({ session, colors });+ const triggerMcpRefresh = createMcpRefresher({ session, getRefresh: () => refreshMcp || session?.refreshMcpServers, onUpdated: paint });+const sync = () => {commitStream(viewport);compaction.check(session, { colors });const trans = transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" });setLines(viewport, withPreamble(preamble?.() ?? null, [...trans, ...compaction.lines(colors)]));paint();+ // Background session attention: evaluated on sync when sessions list changes+ attentionNotifier.notify(getSessions());+ triggerMcpRefresh();};// Streaming text goes into the buffer and repaints, so a long answer does not wait for the turn to@@ -124,6 +124,7 @@ export function mountScreenLoop({const onResize = () => { viewport.rows = output.rows || 24; sync(); };output.on?.("resize", onResize);+const dispatchMouse = (event) => {// When mouse setting is off, ignore wheel and click completely so terminal selection works.if (!event || !mouseEnabled) return false;@@ -132,7 +133,8 @@ export function mountScreenLoop({return false;}if (event.kind === "click") {- const { cols, tabRowY, railWidth, viewRows } = geometry();+ const geom = geometry();+ const { cols, tabRowY, railWidth, viewRows } = geom;const hitOpts = railWidth > 0? { x: event.x, y: event.y, width: railWidth, rows: viewRows, orientation: "vertical" }: { x: event.x, y: event.y, width: cols, tabRow: tabRowY, orientation: "horizontal" };@@ -141,6 +143,8 @@ export function mountScreenLoop({Promise.resolve(onTabClick(targetId)).then(paint).catch(() => {});return true;}+ // One hint per session when a click lands in an interactive-looking area with no tab under it.+ reportClickHint({ event, geometry: geom, targetId, suspended: panelSuspend?.isSuspended?.() });return true;}return false;@@ -160,15 +164,21 @@ export function mountScreenLoop({session, output, hook, onRepaint: paint, onReset: () => { painted = []; },isMouseEnabled: () => mouseEnabled,});- const { suspend, resume } = panelSuspend;+ // Suspend suppresses bells; resume marks state so return repaint never rings+ const suspend = () => { attentionNotifier.suspend(); panelSuspend.suspend(); };+ const resume = () => { panelSuspend.resume(); attentionNotifier.resume(); };const initLines = transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" });setLines(viewport, withPreamble(preamble?.() ?? null, [...initLines, ...compaction.lines(colors)]));paint();const loop = {+ active: true, session, paint, sync, suspend, resume,active: true,session,+ // Exposed so /find can move the window: the viewport is a closure local, and a command cannot reach+ // it otherwise. Read only from commands; paint and sync remain the writers.+ viewport,paint,sync,suspend,@@ -183,12 +193,14 @@ export function mountScreenLoop({if (session) session.mouse = next ? "on" : "off";setMouseReporting(output, next);},+ attentionNotifier,dispose() {["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => detach(process, sig, onTeardown));output.off?.("resize", onResize);hook.dispose();disableMouse(output);compaction.reset();+ attentionNotifier.reset();delete session.streamSink; delete session.printSink;delete session.onComposerRows; delete session.screenLoop;// The panel owns the whole screen, so the inline transcript is repainted once on the way outdiff --git a/scripts/mso-agent-session-list.mjs b/scripts/mso-agent-session-list.mjsindex 39e32bcd..e4e17486 100644--- a/scripts/mso-agent-session-list.mjs+++ b/scripts/mso-agent-session-list.mjs@@ -26,6 +26,12 @@ export function stateOf(row, now = Date.now()) {if (["working", "busy", "running"].includes(String(row.status || ""))) return { state: "working", label: "working" };if (row.status === "idle") return { state: "idle", label: "idle" };+ // Live turn active signal from server summary. Unlike updatedAt, turnActive is set+ // at turn start and cleared at turn end, so true indicates active execution and+ // false truthfully indicates waiting at prompt without timestamp false-working.+ if (row.turnActive === true) return { state: "working", label: "working" };+ if (row.turnActive === false) return { state: "idle", label: "idle" };+// In the absence of an explicit status flag, derive state from the last recorded update.const rawTime = row.updatedAt || row.createdAt;const at = Date.parse(String(rawTime || ""));@@ -157,20 +163,24 @@ export function sessionTable(rows, { colors = {}, width = 80, activeId = null, n}export function needsAttention(row, _now = Date.now()) {- // Trusts only explicit server status. Timestamp derivation is inverted because updatedAt- // updates at turn completion, not during execution (docs/AGENT-ACTIVITY-SIGNAL.md).+ // Trusts only explicit server status and turnActive. Timestamp derivation is inverted because+ // updatedAt updates at turn completion, not during execution (docs/AGENT-ACTIVITY-SIGNAL.md).if (!row || typeof row !== "object") return false;const status = String(row.status || "");if (row.error || ["error", "errored", "failed"].includes(status)) return true;+ if (row.turnActive === true) return true;return ["working", "busy", "running"].includes(status);}export function attentionReason(row) {- // Reports explicit server status without implying unverified timestamp freshness.+ // Reports explicit server status or turnActive without implying unverified timestamp freshness.if (!row || typeof row !== "object") return "unknown";if (row.error || ["error", "errored", "failed"].includes(String(row.status || ""))) {return `status: ${row.status || "errored"}`;}+ if (row.turnActive === true) {+ return "turnActive: working";+ }return `status: ${String(row.status || "working")}`;}diff --git a/scripts/mso-agent-tabs-turnactive.test.ts b/scripts/mso-agent-tabs-turnactive.test.tsnew file mode 100644index 00000000..5e34cb10--- /dev/null+++ b/scripts/mso-agent-tabs-turnactive.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it, vi } from "vitest";+import {+ attentionReason,+ findAttentionSession,+ needsAttention,+ sessionTable,+ stateOf,+} from "./mso-agent-session-list.mjs";+import { handleTabs } from "./mso-agent-cmd-session.mjs";+import * as sessionUi from "./mso-agent-session-ui.mjs";++vi.mock("./mso-agent-session-ui.mjs", () => ({+ resumeInto: vi.fn().mockResolvedValue(true),+ persistSession: vi.fn(),+ renameCurrentSession: vi.fn(),+ renameCurrentSessionName: vi.fn(),+ startNewSession: vi.fn(),+ resumePicker: vi.fn(),+}));++describe("MSO Agent TUI turnActive live activity signal integration", () => {+ const now = 1_700_000_000_000;++ // Requirement 1: stateOf trusts turnActive: true as working regardless of updatedAt.+ it("stateOf reports working when turnActive is true, avoiding false idle", () => {+ // Session updated 10 minutes ago, but currently running an interactive turn.+ const activeLongTurn = {+ id: "s-long",+ name: "worker",+ turnActive: true,+ updatedAt: new Date(now - 600_000).toISOString(),+ };+ const res = stateOf(activeLongTurn, now);+ expect(res.state).toBe("working");+ expect(res.label).toBe("working");+ });++ // Requirement 2: stateOf trusts turnActive: false as idle regardless of fresh updatedAt.+ it("stateOf reports idle when turnActive is false, avoiding false working", () => {+ // Turn completed 2 seconds ago; agent is idle at the prompt waiting for input.+ const justFinishedTurn = {+ id: "s-fresh",+ name: "prompt-ready",+ turnActive: false,+ updatedAt: new Date(now - 2_000).toISOString(),+ };+ const res = stateOf(justFinishedTurn, now);+ expect(res.state).toBe("idle");+ expect(res.label).toBe("idle");+ });++ // Requirement 3: Explicit error and status take precedence over turnActive.+ it("stateOf preserves precedence for explicit status and errors over turnActive", () => {+ const erroredRow = {+ id: "s-err",+ name: "broken",+ turnActive: true,+ error: "execution failed",+ };+ expect(stateOf(erroredRow, now).state).toBe("errored");++ const waitingRow = {+ id: "s-wait",+ name: "prompt",+ turnActive: true,+ status: "waiting for input",+ };+ expect(stateOf(waitingRow, now).state).toBe("waiting");+ });++ // Requirement 4: Records without turnActive fall through to timestamp comparison or unknown.+ it("stateOf falls through to legacy timestamp comparison when turnActive is absent", () => {+ const legacyRecent = {+ id: "s-leg-recent",+ updatedAt: new Date(now - 10_000).toISOString(),+ };+ expect(stateOf(legacyRecent, now).state).toBe("working");++ const legacyOld = {+ id: "s-leg-old",+ updatedAt: new Date(now - 300_000).toISOString(),+ };+ expect(stateOf(legacyOld, now).state).toBe("idle");++ const legacyNoTimestamp = { id: "s-ghost", name: "ghost" };+ expect(stateOf(legacyNoTimestamp, now)).toEqual({ state: "unknown", label: "no activity data" });+ });++ // Requirement 5: needsAttention activates for turnActive: true and excludes absent / false.+ it("needsAttention triggers on turnActive: true and ignores timestamp-only rows", () => {+ expect(needsAttention({ id: "s1", turnActive: true }, now)).toBe(true);+ expect(needsAttention({ id: "s2", turnActive: false }, now)).toBe(false);++ // Row with neither status nor turnActive must NOT trigger attention, even if timestamp is fresh.+ const timestampOnlyRow = {+ id: "s3",+ updatedAt: new Date(now - 1_000).toISOString(),+ };+ expect(needsAttention(timestampOnlyRow, now)).toBe(false);++ // Ghost row without timestamp or status must not trigger attention.+ expect(needsAttention({ id: "s4" }, now)).toBe(false);+ });++ // Requirement 6: attentionReason names turnActive as the distinct signal source.+ it("attentionReason names turnActive when acting on live turn progress", () => {+ const activeRow = { id: "s-act", name: "eli", turnActive: true };+ expect(attentionReason(activeRow)).toBe("turnActive: working");++ const statusRow = { id: "s-stat", name: "milo", status: "working" };+ expect(attentionReason(statusRow)).toBe("status: working");++ const erroredRow = { id: "s-err", name: "nora", error: "crashed" };+ expect(attentionReason(erroredRow)).toBe("status: errored");+ });++ // Requirement 7: sessionTable renders truthful state based on turnActive.+ it("sessionTable renders working and idle states accurately from turnActive", () => {+ const sessions = [+ { id: "s1", name: "worker", title: "Active task", turnActive: true, updatedAt: new Date(now - 600_000).toISOString() },+ { id: "s2", name: "sleeper", title: "Idle task", turnActive: false, updatedAt: new Date(now - 1_000).toISOString() },+ ];+ const lines = sessionTable(sessions, { width: 80, activeId: "s1", now });+ expect(lines).toHaveLength(3);++ // Header, then row 1 (worker) and row 2 (sleeper)+ expect(lines[1]).toContain("working");+ expect(lines[2]).toContain("idle");+ });++ // Requirement 8: Default outputs stay byte-identical for rows that have neither field.+ it("sessionTable output stays byte-identical for rows having neither status nor turnActive", () => {+ const legacySessions = [+ { id: "s1", name: "alpha", title: "First task", updatedAt: "2026-11-02T12:00:00.000Z" },+ { id: "s2", name: "beta", title: "Second task", updatedAt: "2026-11-02T12:01:00.000Z" },+ ];+ const lines1 = sessionTable(legacySessions, { width: 80, activeId: "s1", now: 1_700_000_000_000 });+ const lines2 = sessionTable(legacySessions, { width: 80, activeId: "s1", now: 1_700_000_000_000 });+ expect(lines1).toEqual(lines2);+ });++ // Requirement 9: /tabs next navigates to turnActive session and announces turnActive reason.+ it("/tabs next navigates to turnActive session and reports turnActive source in notice", async () => {+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", turnActive: false },+ { id: "s2", name: "olive", updatedAt: new Date(now - 2_000).toISOString() }, // timestamp only: skipped+ { id: "s3", name: "milo", turnActive: true },+ { id: "s4", name: "nora", turnActive: false },+ ];+ const ctx = {+ rl: null,+ session: { agentSession: { id: "s1", name: "eli" } },+ sessions,+ now,+ C: {},+ write: (line: string) => printed.push(line),+ };++ const outcome = await handleTabs(ctx, ["next"]);+ expect(outcome).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s3");+ expect(printed.some((l) => l.includes("@milo") && l.includes("turnActive: working"))).toBe(true);+ });++ // Requirement 10: findAttentionSession wraps properly with turnActive sessions.+ it("findAttentionSession navigates turnActive sessions in forward and reverse directions", () => {+ const sessions = [+ { id: "s1", name: "active1", turnActive: true },+ { id: "s2", name: "idle1", turnActive: false },+ { id: "s3", name: "active2", turnActive: true },+ { id: "s4", name: "legacy", updatedAt: new Date(now - 1_000).toISOString() },+ ];++ const nextFrom1 = findAttentionSession(sessions, "s1", "next", now);+ expect(nextFrom1?.id).toBe("s3");++ const nextFrom3 = findAttentionSession(sessions, "s3", "next", now);+ expect(nextFrom3?.id).toBe("s1");++ const prevFrom3 = findAttentionSession(sessions, "s3", "prev", now);+ expect(prevFrom3?.id).toBe("s1");+ });+});