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): the opencode-inspired batch, nine branches in one change (#241)
Abdurrahman Fakhrulce4ae46cb97b
diff --git a/claude-skills/integrations/SKILL.md b/claude-skills/integrations/SKILL.mdindex b04a906f..7edd13b7 100644--- a/claude-skills/integrations/SKILL.md+++ b/claude-skills/integrations/SKILL.md@@ -34,34 +34,6 @@ Never ask the user to paste a token, API key, password, OAuth code, private setu5. Use `integration_manage` only for explicit metadata changes and confirmation-gated mutations.6. Re-read the connection after mutation and report its non-secret state.-## Pasted integration references--An owner may paste a reference instead of describing an integration. Three forms are equivalent, all-carrying `user` / `provider` / `connection`:--```-mso-integration:<user>/<provider>/<connection> <- preferred; not fetchable-https://<host>/integrations?user=…&provider=…&connection=…-<user>/<provider>/<connection>-```--When a prompt contains one:--1. Treat it as the **exact** credential user, provider and connection. Do not ask which integration- the owner means, and do not substitute a similarly named connection.-2. Pass those three values straight into `integration_query` / `integration_execute` /- `integration_manage`.-3. Do **not** fetch the URL form. The `/integrations` page is owner-gated (403, or a login redirect);- the query parameters in it are the answer, not a resource to GET.-4. Provider ids are canonical (`convex`, not the legacy `convex-cloud`). If a pasted id does not- resolve, say so and call `integration_query` for the catalog — do not guess a nearby provider.--Failure handling, one round trip only:--- `user_not_found` → `integration_query` for `view=users`, ask once which owner was meant.-- `connection_not_found` → `integration_query` for that owner's connections, ask once.-- Never fall back silently to another connection or to the default account.-## Tool routing- `integration_query`: catalog, users, named connections, source/auth instructions, folder/default resolution.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 2a1a3168..8b784124 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Added**+- `tui` the opencode-inspired batch, nine branches in one change- `tui` pin a pane slot without losing the cycle (#229)- `tui` a preferences registry, and settings that survive a restart (#231)- `tui` a vertical tab rail, from the same layout the horizontal row uses (#230)diff --git a/docs/REA-OPENCODE-TUI.md b/docs/REA-OPENCODE-TUI.mdnew file mode 100644index 00000000..9052b3da--- /dev/null+++ b/docs/REA-OPENCODE-TUI.md@@ -0,0 +1,204 @@+# REA: opencode TUI, what it is and what to learn from it++Reverse-engineered from the installed binary, not from screenshots. Every claim below has the probe+that produced it, because the point of this document is that the next person does not have to repeat+the extraction.++opencode is open source. Everything here is published, readable and freely usable, so this is a study+of a peer implementation rather than a reconstruction of something hidden. The sections that say do+not copy are about *fit*, not permission: a design that works in a native scene-graph renderer does+not automatically work in MSO's line painter, and shipping it anyway would cost capability for looks.+++## 0. Method, and what failed first++The `REA` skill is **not installed** on this machine. Checked: `~/.config/opencode/skills/`,+`~/.agents/skills/`, `~/.claude/skills/`, `~/.codex/`, and the recovery archive index. No skill by that+name exists. So this is the method applied directly rather than a skill invocation.++What the target actually is, established before reading anything into it:++```+$ ls -la ~/.local/bin/opencode+... -> ~/.opencode/bin/opencode++$ file ~/.opencode/bin/opencode+ELF 64-bit LSB executable # NOT a JS script with a shebang+$ du -h 241M+$ strings | grep -oE "Bun v[0-9.]+"+Bun v1.4.4 # Bun standalone executable+$ strings | grep -c bubbletea+0 # NOT Go/charmbracelet+```++**The TUI is OpenTUI, not bubbletea.** That single fact changes what is worth copying: OpenTUI is a+native FFI scene-graph renderer (Yoga layout, WebGPU-ish paint hooks, its own frame scheduler), which+is why opencode's transitions and mouse handling look the way they do. MSO's renderer is a+hand-written retained line painter, so the *architecture* is not portable; the *layout decisions* are.++Extraction: `strings -n 6` over the 241 MB ELF gives ~525k lines. Grep by feature name, never read+whole regions. The bundled JS appears as one enormous line per module, so `grep -o` with a bounded+context is the only usable probe.++## 1. The TUI library++```+$ strings | grep -oE "charmbracelet/[a-z]+" | sort -u -> (nothing)+$ strings | grep -iE "opentui" -> many hits+```++Evidence of the actual engine, quoted from the bundle:++- `yogaConfigCreateChecked`, `yogaNodeCalculateLayoutChecked`, `yogaNodeStyleSetEnumChecked`: Yoga+ flexbox for layout, the same engine React Native uses.+- `ot_scene_record_draw`, `ot_buffer_draw_box`, `ot_buffer_draw_text`: a retained **scene graph**, not+ a string builder. Rects are records in a buffer, painted natively.+- `"OpenTUI is not supported on the current platform: linux-x64"`: explicit platform gate.+- `OTUI_DEBUG_FFI`, `OTUI_TRACE_FFI` env vars: FFI call tracing, useful if we ever need to debug it.+- Renderer modes: `alternate-screen`, `split-footer`, with `capture-stdout` external output mode.+ `split-footer` is how opencode keeps its own bottom bar while external processes print above it.++**Consequence for MSO:** porting the engine is not the lesson; the engine is a different trade. What+transfers is that opencode treats the terminal as a paint surface with a reserved footer, and keeps+external process output (`split-footer` + `capture-stdout`) from corrupting it. MSO already does the+second half with `PROMPT_ROWS` and the suspended-panel path, so this confirms the existing direction+rather than proposing a rewrite.++## 2. The settings registry, which is the real design document++The single most useful find: opencode declares its entire TUI surface as a data table, and the UI is+generated from it. Quoted structure (`title`, `category`, `path`, `default`, `values`):++| Category | Setting | Path | Default |+|---|---|---|---|+| Appearance | Theme / Color mode / Animations | `theme.name`, `theme.mode`, `animations` | `opencode`, `system`, off |+| **Session** | **Sidebar** | `session.sidebar` | **`auto`** (hide \| auto, "shows when there is room") |+| Session | Scrollbar / Thinking / Markdown | `session.scrollbar`, `.thinking`, `.markdown` | off, hide, rendered |+| Session | Tool grouping / **Verbosity** | `session.grouping`, `session.verbosity` | `auto`, **`medium`** (low/medium/high) |+| Session | Transcript images / TPS | `session.image_preview`, `session.tps` | off, on |+| **Tabs** | **Mode / Scope / Layout / Indicators** | `tabs.mode`, `tabs.scope`, `tabs.layout`, `tabs.indicators` | `auto`, `cwd`, **`horizontal`**, **`status`** |+| Diffs | View / Wrapping / File tree / Single patch | `diffs.view`, `.wrap`, `.tree`, `.single` | auto, word, on, off |+| Input | Scroll speed / Acceleration / Mouse | `scroll.speed`, `.acceleration`, `mouse` | 3, off, **on** |+| Input | Editor context / Large pastes | `prompt.editor`, `prompt.paste` | on, compact |+| Alerts | Notifications / Sounds / Volume | `attention.notifications`, `.sound`, `.volume` | off, off, 0.4 |+| Terminal | Window title / Copy behavior | `terminal.title`, `terminal.copy` | on, select |+| Debug | Developer tools | `debug.devtools` | off |++Two entries answer questions the user asked directly:++- `tabs.layout` has values **`horizontal` | `vertical`**, and the description for `vertical` is+ literally *"tabs run along the top or down the side"* with keywords `sidebar`, `orientation`, `left`.+ So the vertical session rail in the screenshot is **the same tab list, moved to the left edge**, not+ a second component.+- `session.sidebar` is `auto` with *"shows when there is room"*. Same rule MSO's pane already uses+ (`paneWidth` returns 0 below 100 columns).++## 3. Sidebar slots++```+$ strings | grep -oE "opencode\.sidebar\.[a-z_]+" | sort -u+opencode.sidebar.context+opencode.sidebar.footer+opencode.sidebar.limit+opencode.sidebar.mcp+opencode.sidebar.todo+```++Five fixed slots, not one free-form panel: **context, mcp, todo, limit, footer**. That is a better+shape than MSO's current `paneKind` enum because each slot has one job and can be rendered+independently.++Note the split: `sidebar.context` is context usage, `sidebar.limit` is quota/rate limit, and+`sidebar.mcp` is MCP server state. MSO's `context` pane currently merges context usage and provider+identity, and has no quota concept.++## 4. Session status, and how tabs indicate it++`tabs.indicators` = `status` (default) | `numbers`. The description: *"whether tabs show status icons or+always numbers"*, keywords `tab numbers`, `number mode`, `status icons`.++Status vocabulary found in the bundle (bounded to the state field): `idle`, `busy`, `working`,+`waiting`, `streaming`, `thinking`. So opencode **does** carry a live per-session activity signal, which+is exactly what the MSO `/tabs` work had to work around: MSO's server exposes only `updatedAt`, so+`sessionTable` had to derive state from a 60-second threshold and print `no activity data` when it+could not tell.++That is the honest gap, and it is a **server-side** gap, not a UI one. Copying the icons without the+signal would produce a tab row that lies.++## 5. Command registry++Named commands, which is the shape a keybind file should mirror:++```+session.sidebar.toggle session.tab.next / .previous / .next_unread / .previous_unread+session.tab.close / .reopen session.timeline session.rename / .delete / .share / .unshare+session.copy / .move / .fork session.queued_prompts session.child.first session.parent+session.pin.toggle session.quick_switch.1 …+diff.toggle / .expand / .expand_all / .collapse / .switch_focus+diff.next_hunk / .previous_hunk / .next_file / .previous_file+diff.toggle_file_tree / .single_patch / .switch_source / .toggle_view+theme.switch / .switch_mode theme.mode.lock prompt.editor open.menu+```++Two worth stealing outright: **`session.tab.next_unread`** (jump to the next session that needs+attention, rather than cycling through idle ones) and **`session.queued_prompts`** (a visible queue,+which MSO already has in memory as `session.queue` but does not surface).++## 6. Terminal access, the surprising answer++`/terminal` as an opencode slash command **does not appear in the string table**. What does appear is:++- An experiment, `client-mcp`, described as *"Let the agent open terminals in this TUI (requires server+ support)"*, stored under `experimental["client-mcp"]`.+- `terminalSuspend`: a renderer control, i.e. the TUI suspends itself to hand the terminal away.+- One command id, `terminal.close`.++So opencode's model is **the agent opens a terminal as a tool**, rendered inside the TUI, rather than+the user typing `/terminal` to borrow the shell. MSO's `/terminal` (PR #224) does the suspend-and-hand-+over the other way round. Both are legitimate; they answer different needs:++| | opencode (`client-mcp`) | MSO `/terminal` |+|---|---|---|+| who drives | the agent, as a tool | the user, as a command |+| where output goes | into the TUI panel | to the real terminal |+| state after | panel keeps its layout | panel re-enters and repaints |++## 7. What to learn, ranked by value per line, and what MSO must not give up++Adopting each idea below is only worth it if the capability MSO already has survives. The third column+is the constraint that decides whether we may take it at all.++| # | Idea from opencode | MSO capability that must not regress |+|---|---|---|+| 1 | **Settings as one data table** (title, category, path, default, values) driving both the settings UI and the keybind hints | `/keybind` already writes `~/.mso/keybinds.json` and validates conflicts. A registry must wrap that file, not replace it: a user's existing keymap has to keep working byte for byte |+| 2 | **`tabs.layout: horizontal \| vertical`**, the vertical rail being the same tab list moved to the left edge | `tabLayout` is the single source of truth for both `tabRow` and `tabAtPoint`. A vertical variant must reuse it, or the click targets will drift from the painted row, which is the bug M4 already fixed once |+| 3 | **Sidebar slots as fixed roles** (context, mcp, todo, limit, footer) instead of a cycling kind | `/pane off` must stay one keystroke. Cycling is fast when you do not know what you want; slots are better once you do. Keep cycle, add pinning |+| 4 | **`session.tab.next_unread`** | The tab click and `/tabs <n>` switch paths must stay one function (`switchToSession`), including the todo-cache clear |+| 5 | **Surface the queued prompts** | `session.queue` already exists in memory and is drained per turn. Showing it must not change drain order or let a queued prompt jump the approval gate |++Three specific refusals, each because taking it would cost capability:++- **The OpenTUI engine.** MSO's renderer is line-based and dependency-free; the whole reason it exists is+ that `ink` drags 23 packages and `@opentui/core` needs Node 26.4 while the repo supports 22.12+. Layout+ ideas transfer, the runtime does not.+- **Status icons on tabs before the server has a signal.** opencode carries `idle`/`busy`/`working`/+ `waiting`/`streaming`/`thinking`. MSO's session API exposes only `updatedAt`, which is why `sessionTable`+ derives a 60 second threshold and prints `no activity data`. Drawing an icon from a timestamp would make+ the tab row assert something it cannot know. The fix is server side; until then the honest text stays.+- **`/terminal` as agent-owned panels.** opencode's `client-mcp` experiment lets the *agent* open terminals+ inside the TUI. MSO's `/terminal` (PR #224) hands the *user* the real terminal via the suspend path. They+ solve different problems, and replacing ours with theirs would remove the ability to drop into a real+ shell mid-session, including for things the agent should not mediate.++## 8. Reproducing this++```bash+strings -n 6 ~/.opencode/bin/opencode > /tmp/oc-strings.txt # 525k lines, ~1 min+grep -oE "opencode\.sidebar\.[a-z_]+" /tmp/oc-strings.txt | sort -u+grep -oE "\"tabs\"[^}]{0,120}" /tmp/oc-strings.txt+grep -iE "opentui|yoga" /tmp/oc-strings.txt | head+```++Do not `grep` without `-o` and a bounded context: individual module lines are megabytes long and will+flood the terminal. This happened twice while writing this document.diff --git a/docs/README.md b/docs/README.mdindex 2a7c5b4f..b5dec0da 100644--- a/docs/README.md+++ b/docs/README.md@@ -64,6 +64,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`TUI-PARITY-PLAN.md`](./TUI-PARITY-PLAN.md) | MSO Agent TUI parity program: per-item status, the server seam each item uses, and the items deliberately refused || [`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 || [`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 || [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |diff --git a/frontend/slices/integrations/app.test.ts b/frontend/slices/integrations/app.test.tsindex 4c79077c..26c680ff 100644--- a/frontend/slices/integrations/app.test.ts+++ b/frontend/slices/integrations/app.test.ts@@ -1,38 +1,18 @@+import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import { managerLocation } from "./app";+import { integrationsApp } from "./index";-// The integrations window renders an iframe. Every query parameter the user pasted has to survive-// into that iframe or a deep link silently lands on the generic manager page — which is exactly-// what happened before: only `transfer=1` was forwarded.--describe("managerLocation", () => {- it("forwards the connection deep-link parameters", () => {- expect(managerLocation("?user=dita&provider=convex&connection=dita-convex"))- .toBe("/integrations/manager?user=dita&provider=convex&connection=dita-convex");- });-- it("still forwards transfer", () => {- expect(managerLocation("?transfer=1")).toBe("/integrations/manager?transfer=1");- });-- it("keeps both when a deep link also asks for transfer", () => {- expect(managerLocation("?transfer=1&user=dita&provider=convex&connection=dita-convex"))- .toBe("/integrations/manager?transfer=1&user=dita&provider=convex&connection=dita-convex");+describe("native Integrations shell app", () => {+ it("has a dockable descriptor and a matching app catalog entry", () => {+ expect(integrationsApp.id).toBe("integrations");+ expect(integrationsApp.noDock).not.toBe(true);+ expect(readFileSync("frontend/slices/app-store/lib/system-catalog.ts", "utf8")).toContain('id: "integrations", title: "Integrations", kind: "app"');+ const manifest = readFileSync("frontend/slices/os-shell/shell.manifest.ts", "utf8");+ expect(manifest).toContain('pin(withSlug(integrationsApp, "connections"))');});-- it("drops anything that is not part of the allowlist", () => {- // `target` carried private capability material historically; it must not ride along.- expect(managerLocation("?target=secret-token&user=dita&provider=convex&connection=c"))- .toBe("/integrations/manager?user=dita&provider=convex&connection=c");- });-- it("emits no query string at all when nothing is forwarded", () => {- expect(managerLocation("")).toBe("/integrations/manager");- expect(managerLocation("?target=x")).toBe("/integrations/manager");- });-- it("preserves the hash", () => {- expect(managerLocation("?user=u&provider=p&connection=c", "#row"))- .toBe("/integrations/manager?user=u&provider=p&connection=c#row");+ it("keeps transfer and private fragment handoffs inside the existing manager", () => {+ expect(managerLocation("?transfer=1&untrusted=ignore", "#example-capability")).toBe("/integrations/manager?transfer=1#example-capability");+ expect(managerLocation("?target=https://untrusted.invalid")).toBe("/integrations/manager");});});diff --git a/frontend/slices/integrations/app.tsx b/frontend/slices/integrations/app.tsxindex c36fe5de..2d248730 100644--- a/frontend/slices/integrations/app.tsx+++ b/frontend/slices/integrations/app.tsx@@ -5,21 +5,10 @@ import { Button } from "@/components/ui/button";import { syncIntegrationFrameTokens } from "./frame-theme";import { ComposioSessionPanel } from "./composio-session-panel";-/** Parameters the manager iframe is allowed to receive. Everything else is dropped: this string- * becomes an iframe src, and historically `target` carried private capability material. */-const MANAGER_PARAMS = ["transfer", "user", "provider", "connection"] as const;--/** Preserve transfer/setup and connection deep links without putting private capabilities in React state. */+/** Preserve transfer/setup deep links without putting private capabilities in React state. */export function managerLocation(search: string, hash = "") {- const incoming = new URLSearchParams(search);- const forwarded = new URLSearchParams();- for (const key of MANAGER_PARAMS) {- const value = incoming.get(key);- // `transfer` is a flag; the rest are identifiers the reference format guarantees are safe.- if (value !== null && value !== "") forwarded.set(key, value);- }- const query = forwarded.toString();- return "/integrations/manager" + (query ? `?${query}` : "") + hash;+ const transfer = new URLSearchParams(search).get("transfer") === "1";+ return "/integrations/manager" + (transfer ? "?transfer=1" : "") + hash;}export default function IntegrationsApp() {diff --git a/lib/infra/connection-dispatch-convex.test.ts b/lib/infra/connection-dispatch-convex.test.tsindex bf240c9f..3a18c15d 100644--- a/lib/infra/connection-dispatch-convex.test.ts+++ b/lib/infra/connection-dispatch-convex.test.ts@@ -16,7 +16,7 @@ let execute: typeof import("./connection-dispatch").executeIntegrationAction;const CLOUD_PAT = "pat_synthetic_cloud_dispatch_1234567";const ADMIN_KEY = "synthetic_self_hosted_admin_dispatch_1234";-const operations = ["convex.customDomains.list", "convex.customDomain.ensure", "convex.canonical.get", "convex.canonical.set", "convex.env.presence", "convex.env.set", "convex.project.deploy", "convex.snapshot.import"];+const operations = ["convex.customDomains.list", "convex.customDomain.ensure", "convex.canonical.get", "convex.canonical.set", "convex.env.presence", "convex.project.deploy", "convex.snapshot.import"];async function seed(user: string, connection: string, method: string, values: Record<string, string>) {const { integrationManage } = await import("./connection-manage");@@ -51,7 +51,6 @@ const args: Record<string, Record<string, unknown>> = {"convex.canonical.get": { deploymentName: "happy-otter-123" },"convex.canonical.set": { deploymentName: "happy-otter-123", requestDestination: "convexCloud", url: null },"convex.env.presence": { deploymentName: "happy-otter-123", names: ["AUTH_SECRET"] },- "convex.env.set": { deploymentName: "happy-otter-123", name: "AUTH_SECRET", value: "test-secret", projectPath: "/srv/project" },"convex.project.deploy": { deploymentName: "happy-otter-123", projectPath: "/srv/project" },"convex.snapshot.import": { deploymentName: "happy-otter-123", projectPath: "/srv/project", snapshotPath: "/tmp/s.zip", mode: "append" },};diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.tsindex b4a1b174..79e8c32c 100644--- a/lib/infra/connection-dispatch.ts+++ b/lib/infra/connection-dispatch.ts@@ -1,5 +1,4 @@import { isGoogleProvider, GOOGLE_APP_PROVIDER, googlePublicOrigin } from "./google-native-config";-import { integrationDeepLink } from "./connection-reference";import { bindGoogleApp, disconnectGoogle, runNativeGoogle, nativeGoogleStatus, googleOperations } from "./google-native";import { integrationManage } from "./connection-manage";import { integrationQuery, withIntegrationSelection, resolveIntegration, directConnectionValues } from "./connection-service";@@ -8,7 +7,7 @@ import { composioKeyKind } from "./composio";import { callComposioConnectTool, listComposioConnectTools } from "./composio-connect";import { IntegrationError, identity, metadataOnly, type ConnectionSelector } from "./identity";import { importConvexCliPersonalConnection } from "./convex-cli-import";-import { listConvexCustomDomains, ensureConvexCustomDomain, getConvexCanonicalUrls, setConvexCanonicalUrl, getConvexEnvPresence, setConvexEnv, deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud";+import { listConvexCustomDomains, ensureConvexCustomDomain, getConvexCanonicalUrls, setConvexCanonicalUrl, getConvexEnvPresence, deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud";import { CONVEX_OPERATION_SUPPORT } from "./types";import { doctorInfraProvider, ensureDokployProject, listDokployApplications, listDokployDeployments, readDokployDeploymentLogs, listDokployGitProviders, listDokployGithubRepositories, ensureDokployGithubApplication, ensureDokployApplicationDomain, recoverDokployPublicGithubToHttpsGit, deployDokployApplication, configureDokployDockerfileBuild, listDokployProjects, listCloudflareZones, upsertCloudflareDns, upsertDokployPublicBuildEnv, upsertHostingerDns, listHostingerMailOrders, getHostingerMailPlan, listHostingerMail, listHostingerMailLogs, mutateHostingerMail } from "./clients";import { isInfraProviderId, canonicalProviderId, resolveProviderId, convexDeploymentKind } from "./catalog";@@ -31,7 +30,7 @@ export async function manageIntegrationAction(raw:Record<string,unknown>){if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection"].includes(k)))throw new IntegrationError("invalid_management_fields");const route=await resolveIntegration(String(a.provider),selectionFrom(a));- return{user:route.user,provider:a.provider,connection:route.id,authorization:"owner-browser-required",openPath:integrationDeepLink(googlePublicOrigin(),{user:route.user,provider:String(a.provider),connection:route.id})};+ return{user:route.user,provider:a.provider,connection:route.id,authorization:"owner-browser-required",openPath:googlePublicOrigin()+"/integrations?"+new URLSearchParams({provider:String(a.provider),user:route.user,connection:route.id})};}if(a.action!=="connection.authorize")return integrationManage(a);if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);@@ -48,14 +47,10 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){// Spread first so the operation itself and the confirmation flag cannot be overridden.return integrationManage({...demoArgs as Record<string,unknown>,action:operation,confirm:a.confirm===true});}- if(operation==="dokploy.application.publicEnv.upsert"||operation==="convex.env.set"){+ if(operation==="dokploy.application.publicEnv.upsert"){const {arguments:operationArgs,...meta}=a;metadataOnly(meta);const args=operationArgs;if(!args||typeof args!=="object"||Array.isArray(args))throw new IntegrationError("invalid_tool_arguments");- if(operation==="convex.env.set"){- if(Object.keys(args).some(k=>!["deploymentName","name","value","projectPath"].includes(k)))throw new IntegrationError("invalid_tool_arguments");- }else{- if(Object.keys(args).some(k=>!["applicationId","key","value","redeploy"].includes(k)))throw new IntegrationError("invalid_tool_arguments");- }+ if(Object.keys(args).some(k=>!["applicationId","key","value","redeploy"].includes(k)))throw new IntegrationError("invalid_tool_arguments");}else metadataOnly(a);if(Object.keys(a).some(k=>!["user","provider","connection","operation","arguments","tool","confirm"].includes(k)))throw new IntegrationError("invalid_execution_fields");const user=identity(a.user,"user"),provider=identity(a.provider,"provider"),connection=identity(a.connection,"connection"),selection={user,connection};@@ -92,7 +87,6 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){"convex.customDomain.ensure":{provider:"convex",fields:["deploymentName","domain","requestDestination"],run:()=>ensureConvexCustomDomain(args as {deploymentName:string;domain:string;requestDestination:"convexCloud"|"convexSite"})},"convex.canonical.get":{provider:"convex",fields:["deploymentName"],run:()=>getConvexCanonicalUrls(String((args as Record<string,unknown>).deploymentName))},"convex.env.presence":{provider:"convex",fields:["deploymentName","names"],run:()=>getConvexEnvPresence(args as {deploymentName:string;names:string[]})},- "convex.env.set":{provider:"convex",fields:["deploymentName","name","value","projectPath"],run:()=>setConvexEnv(args as {deploymentName?:string;name:string;value:string;projectPath?:string})},"convex.canonical.set":{provider:"convex",fields:["deploymentName","requestDestination","url"],run:()=>setConvexCanonicalUrl(args as {deploymentName:string;requestDestination:"convexCloud"|"convexSite";url?:string|null})},"convex.project.deploy":{provider:"convex",fields:["deploymentName","projectPath"],run:()=>deployConvexCloudProject(args as {deploymentName:string;projectPath:string})},"convex.snapshot.import":{provider:"convex",fields:["deploymentName","projectPath","snapshotPath","mode"],run:()=>importConvexCloudSnapshot(args as {deploymentName:string;projectPath:string;snapshotPath:string;mode:"replace-all"|"append"})},diff --git a/lib/infra/connection-reference.test.ts b/lib/infra/connection-reference.test.tsdeleted file mode 100644index 5e6346e5..00000000--- a/lib/infra/connection-reference.test.ts+++ /dev/null@@ -1,68 +0,0 @@-import { describe, expect, it } from "vitest";-import {- integrationDeepLink,- integrationReference,- parseIntegrationReference,-} from "./connection-reference";--// The point of this module is a reference an agent can act on without asking a follow-up question.-// So the tests pin both halves: the exact strings copied out, and the fact that parsing is strict-// enough to refuse anything ambiguous.--describe("integration reference", () => {- it("builds the paste form from the three identity parts", () => {- expect(integrationReference({ user: "dita", provider: "convex", connection: "dita-convex" }))- .toBe("mso-integration:dita/convex/dita-convex");- });-- it("canonicalises a legacy provider alias, or the reference will not resolve", () => {- // `convex-cloud` is the legacy id; the catalog resolves it to `convex`. A reference carrying- // the alias makes `catalog.find(p => p.id === provider)` fail and the UI silently fall back to- // the first provider in the list.- expect(integrationReference({ user: "dita", provider: "convex-cloud", connection: "c" }))- .toBe("mso-integration:dita/convex/c");- });-- it("builds the clickable form from the same parts", () => {- expect(integrationDeepLink("https://mso.example.com", { user: "dita", provider: "convex", connection: "dita-convex" }))- .toBe("https://mso.example.com/integrations?user=dita&provider=convex&connection=dita-convex");- });-- it("tolerates a trailing slash on the origin instead of emitting a double slash", () => {- expect(integrationDeepLink("https://mso.example.com/", { user: "u", provider: "p", connection: "c" }))- .toBe("https://mso.example.com/integrations?user=u&provider=p&connection=c");- });-- it.each([- ["token form", "mso-integration:dita/convex/dita-convex"],- ["bare triple", "dita/convex/dita-convex"],- ["full URL", "https://mso.example.com/integrations?user=dita&provider=convex&connection=dita-convex"],- ["URL with extra params", "https://mso.example.com/integrations?transfer=1&user=dita&provider=convex&connection=dita-convex"],- ])("parses the %s, so people can paste whichever they copied", (_label, input) => {- expect(parseIntegrationReference(input)).toEqual({ user: "dita", provider: "convex", connection: "dita-convex" });- });-- it("canonicalises on parse too", () => {- expect(parseIntegrationReference("mso-integration:dita/convex-cloud/dita-convex"))- .toEqual({ user: "dita", provider: "convex", connection: "dita-convex" });- });-- it.each([- ["empty", ""],- ["whitespace", " "],- ["only two parts", "dita/convex"],- ["four parts", "a/b/c/d"],- ["empty segment", "dita//dita-convex"],- ["URL missing a param", "https://mso.example.com/integrations?user=dita&provider=convex"],- ["unknown provider", "mso-integration:dita/not-a-provider/dita-convex"],- ["not a URL at all", "https://"],- ])("refuses %s", (_label, input) => {- expect(parseIntegrationReference(input)).toBeNull();- });-- it("round-trips through both forms", () => {- const ref = { user: "manef", provider: "convex", connection: "komunitas-tech" };- expect(parseIntegrationReference(integrationReference(ref))).toEqual(ref);- expect(parseIntegrationReference(integrationDeepLink("https://x.test", ref))).toEqual(ref);- });-});diff --git a/lib/infra/connection-reference.ts b/lib/infra/connection-reference.tsdeleted file mode 100644index eb8bb295..00000000--- a/lib/infra/connection-reference.ts+++ /dev/null@@ -1,92 +0,0 @@-// One addressable reference for an integration connection.-//-// Two forms, derived from the same identity, because they serve different readers:-//-// mso-integration:<user>/<provider>/<connection> <- paste this into an agent prompt-// https://<origin>/integrations?user=…&provider=…&connection=… <- click this-//-// Why two: the URL is fetchable, so an agent handed only a URL will try to GET it, hit the owner-// gate (403) or a login redirect, and burn a turn learning nothing. The token is deliberately not-// fetchable — it parses as three path segments and nothing else. The URL exists because a human-// still wants to click through to the row that was meant.-//-// Why all three components and not just the connection id: `connection` ids are per-user-// (`dita/dita-convex` vs `cloud/admin` can both be named `convex`), and `user` is part of the-// resolution input. The triple is the smallest thing that resolves unambiguously.-//-// Stability, verified in connection-manage.ts:-// - `connection` id survives rename (rename only touches `label`) -> safe-// - `user` id does NOT survive `user.rename` (it deletes the old key) -> a reference dies on-// rename, and that is correct: a stale reference should fail loudly, never resolve to a-// different user's connection-// - `uid` (uuid) is never used here: it is regenerated on duplicate/share/import-export, so it-// is not portable-import { canonicalProviderId, resolveProviderId } from "./catalog";-import { IntegrationError } from "./identity";--const TOKEN_PREFIX = "mso-integration:";--export type IntegrationRef = { user: string; provider: string; connection: string };--/** The paste-into-a-prompt form. Unfetchable on purpose. */-export function integrationReference(input: IntegrationRef): string {- return `${TOKEN_PREFIX}${input.user}/${canonicalProviderId(input.provider)}/${input.connection}`;-}--/** The clickable form. Query shape matches what the Google authorization path already emits. */-export function integrationDeepLink(origin: string, input: IntegrationRef): string {- const base = origin.replace(/\/+$/, "");- const query = new URLSearchParams({- user: input.user,- provider: canonicalProviderId(input.provider),- connection: input.connection,- });- return `${base}/integrations?${query.toString()}`;-}--/**- * Parse a pasted reference. Accepts the token form, a bare `user/provider/connection` triple, or a- * URL carrying all three query parameters — because people paste whichever they copied.- */-export function parseIntegrationReference(value: string): IntegrationRef | null {- const raw = value.trim();- if (!raw) return null;-- if (raw.startsWith(TOKEN_PREFIX)) {- const parts = raw.slice(TOKEN_PREFIX.length).split("/");- return parts.length === 3 ? triple(parts) : null;- }-- if (/^https?:\/\//i.test(raw)) {- try {- const params = new URL(raw).searchParams;- const user = params.get("user"), provider = params.get("provider"), connection = params.get("connection");- return user && provider && connection ? triple([user, provider, connection]) : null;- } catch {- return null;- }- }-- // A bare triple only. Anything containing a scheme was handled above; do not let a malformed URL- // fall through and be read as `provider/model/path`.- const parts = raw.split("/");- return parts.length === 3 && !raw.includes("://") ? triple(parts) : null;-}--/** The identity regex forbids `/`, so three segments never need escaping. */-function triple(parts: string[]): IntegrationRef | null {- const [user, provider, connection] = parts.map((part) => part.trim());- if (!user || !provider || !connection) return null;- try {- // Reject anything the store would refuse anyway, so a malformed paste fails here with a clear- // answer instead of surfacing as `user_not_found` three calls later.- // `canonicalProviderId` only folds the legacy alias; `resolveProviderId` is what actually- // rejects an id the catalog does not know.- const id = resolveProviderId(provider);- if (!id) return null;- return { user, provider: id, connection };- } catch (error) {- if (error instanceof IntegrationError) return null;- throw error;- }-}diff --git a/lib/infra/connection-registry.test.ts b/lib/infra/connection-registry.test.tsindex 512ed131..2e6ff183 100644--- a/lib/infra/connection-registry.test.ts+++ b/lib/infra/connection-registry.test.ts@@ -97,7 +97,6 @@ describe("integration connection registry", () => {"convex.customDomain.ensure","convex.customDomains.list","convex.env.presence",- "convex.env.set","convex.project.deploy","convex.snapshot.import",]);diff --git a/lib/infra/connection-registry.ts b/lib/infra/connection-registry.tsindex 58ea508e..fa9ccee4 100644--- a/lib/infra/connection-registry.ts+++ b/lib/infra/connection-registry.ts@@ -3,7 +3,6 @@ import { isGoogleProvider, GOOGLE_APP_PROVIDER, googleRedirectUri, googlePublicOimport { canonicalProviderId, convexDeploymentKind, listInfraProviderDefinitions, getInfraProviderDefinition, resolveProviderId } from "./catalog";import { setupFields, setupGuidance, setupMethods, type SetupMethod } from "./setup-guidance";import { IntegrationError, type ConnectionSource, type IntegrationConnection } from "./identity";-import { integrationReference } from "./connection-reference";/** Convex keeps every pre-collapse method id; `admin` is the self-hosted shape. */const CONVEX_METHODS = ["personal", "deployment", "admin"] as const;/**@@ -63,7 +62,7 @@ function sourceLabel(provider:string,id:ConnectionSource){export function connectionCatalog(){return listInfraProviderDefinitions().map(p=>({id:p.id,title:p.title,description:p.description,...googleCatalogInfo(p.id),sources:connectionSources(p.id).map(id=>({id,label:sourceLabel(p.id,id),methods:connectionMethods(p.id,id)}))}));}export function connectionSummary(user:string,c:IntegrationConnection,isDefault=false,values:Record<string,string>=c.values){const method=connectionMethod(c.provider,c.source,c.authMethod),missing=method.fields.filter(f=>f.required&&!values[f.key]).map(f=>f.key);- return {user,id:c.id,label:c.label,provider:c.provider,reference:integrationReference({user,provider:c.provider,connection:c.id}),source:c.source,authMethod:c.authMethod,scope:c.scope,revision:c.revision,isDefault,missing,fields:method.fields.map(f=>({...f,stored:Boolean(values[f.key])})),state:c.source==="direct"?(missing.length?"incomplete":c.lastCheck?(c.lastCheck.revision===c.revision?c.lastCheck.result:"configured"):c.verifiedAt?"verified":"configured"):c.external?.status??"authorization-required",verifiedAt:c.verifiedAt??null,lastCheck:c.lastCheck?.revision===c.revision?c.lastCheck:null,sharedFrom:c.sharedFrom??null,external:c.external??null};+ return {user,id:c.id,label:c.label,provider:c.provider,source:c.source,authMethod:c.authMethod,scope:c.scope,revision:c.revision,isDefault,missing,fields:method.fields.map(f=>({...f,stored:Boolean(values[f.key])})),state:c.source==="direct"?(missing.length?"incomplete":c.lastCheck?(c.lastCheck.revision===c.revision?c.lastCheck.result:"configured"):c.verifiedAt?"verified":"configured"):c.external?.status??"authorization-required",verifiedAt:c.verifiedAt??null,lastCheck:c.lastCheck?.revision===c.revision?c.lastCheck:null,sharedFrom:c.sharedFrom??null,external:c.external??null};}export const composioDefinition=(provider:string)=>COMPOSIO[provider];export const nativeDefinition=(provider:string)=>NATIVE[provider];diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.tsindex 583f49ea..12af5ad0 100644--- a/lib/infra/connection-ui.ts+++ b/lib/infra/connection-ui.ts@@ -175,7 +175,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){const rows=snapshot.connections.filter(c=>c.provider===provider.id);if(rows.length){const count=rows.filter(ready).length;detail.append(n("p",rows.length+" connection"+(rows.length===1?"":"s")+" · "+count+" verified","identity-summary-line"));}if(!rows.length){const empty=n("div",undefined,"identity-empty");empty.append(n("h3","Connect "+provider.title),n("p",user?"Add an account to start using "+provider.title+" in your projects.":bridge.manage?"Select a credential owner to add an account.":"Read the setup guide below, then sign in to connect your account."));const start=b("Add "+provider.title+" account",newConnection,"primary");start.disabled=!user||!bridge.manage;if(bridge.manage)empty.append(start);detail.append(empty);const help=n("details");help.append(n("summary","Connection methods & setup guides"));for(const s of provider.sources)for(const m of s.methods){const info=n("section");info.append(n("h3",s.label+" · "+m.label));guide(m,info);help.append(info)}detail.append(help)}- for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);if(initial.connection===c.id)card.dataset.reference="focused";card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of [human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.append(n("summary","More"));more.append(secondary);+ for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of [human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.append(n("summary","More"));more.append(secondary);if(provider.nativeGoogle&&!provider.configurationOnly){mountNativeGoogleConnection(card,c,{n,b,user,provider,catalog,snapshot,bridge,status,reload,selectProvider});detail.append(card);continue}const open=b(c.source==="direct"?(c.fields.some(f=>f.stored)?"Update credentials":"Finish setup"):"Authorize",()=>{if(c.source==="direct")void bridge.openSetup({user,provider:provider.id,connection:c.id}).catch(e=>status.textContent=textError(e));else external(c)});open.disabled=!bridge.manage;if(!c.sharedFrom)actions.append(open);const verify=b("Verify",async()=>{try{status.textContent="Checking selected connection…";const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});await reload();status.textContent=(result.ok===true?"Verified: ":"Status: ")+result.detail}catch(e){status.textContent=textError(e)}});verify.disabled=!bridge.execute;actions.append(verify);diff --git a/lib/infra/convex-cloud-core.ts b/lib/infra/convex-cloud-core.tsindex e08333cc..c5a3fd03 100644--- a/lib/infra/convex-cloud-core.ts+++ b/lib/infra/convex-cloud-core.ts@@ -69,20 +69,8 @@ export function convexAuthHeaders(token: string, scheme: "Bearer" | "Convex") {export function convexManagementUrl(name: string, suffix: string) {return `https://api.convex.dev/v1/deployments/${encodeURIComponent(convexDeploymentName(name))}/${suffix}`;}-/** A Convex deployment can live outside the US region, and the host then carries it:- * `laudable-bat-171.ap-southeast-2.convex.cloud`. Omitting the region answers 404, which is how- * this was found — verified live against an ap-southeast-2 prod deployment on 2026-11-02.- * `region` is optional so existing US callers are unchanged. */-const REGION_RE = /^[a-z]{2}(?:-[a-z]+)+-\d{1,2}$/;-export function convexDeploymentUrl(name: string, suffix: string, region?: string) {- const host = region ? `${convexDeploymentName(name)}.${convexRegion(region)}` : convexDeploymentName(name);- return `https://${host}.convex.cloud/api/v1/${suffix}`;-}-export function convexRegion(value: unknown): string {- if (typeof value !== "string") throw new IntegrationError("invalid_convex_region");- const clean = value.trim().toLowerCase();- if (!REGION_RE.test(clean)) throw new IntegrationError("invalid_convex_region");- return clean;+export function convexDeploymentUrl(name: string, suffix: string) {+ return `https://${convexDeploymentName(name)}.convex.cloud/api/v1/${suffix}`;}export async function convexCheckedJson(provider: string,@@ -93,24 +81,14 @@ export async function convexCheckedJson(let response;try {response = await request(url, init, TIMEOUT_MS, fetchImpl);- } catch (cause) {- // Keep the cause as redactable detail: dropping it made a live env-write failure- // indistinguishable from a network error, and hid the value-redaction test's subject.- const error = new IntegrationError(`${provider}_request_failed`, 502);- const detail = cause instanceof Error ? cause.message : String(cause);- if (detail) Object.assign(error, { detail });- throw error;+ } catch {+ throw new IntegrationError(`${provider}_request_failed`, 502);}- if (!response.ok) {- const error = new IntegrationError(+ if (!response.ok)+ throw new IntegrationError(`${provider}_http_${response.status}`,response.status >= 500 ? 502 : 409,);- // Bodies carry the server's reason, which is what a caller needs; the transport used to drop it.- const detail = typeof response.body === "string" ? response.body : JSON.stringify(response.body ?? "");- if (detail && detail !== "{}") Object.assign(error, { detail: detail.slice(0, 500) });- throw error;- }return response.body;}export function parseConvexDomains(value: unknown): ConvexCustomDomain[] {diff --git a/lib/infra/convex-cloud.ts b/lib/infra/convex-cloud.tsindex 638e5936..c22b2fca 100644--- a/lib/infra/convex-cloud.ts+++ b/lib/infra/convex-cloud.ts@@ -8,6 +8,5 @@ export {} from "./convex-canonical";export { getConvexEnvPresence } from "./convex-env-presence";-export { setConvexEnv, setConvexEnvs, removeConvexEnvs } from "./convex-env-write";export { deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud-runner";diff --git a/lib/infra/convex-env-write.test.ts b/lib/infra/convex-env-write.test.tsdeleted file mode 100644index cccdb1d2..00000000--- a/lib/infra/convex-env-write.test.ts+++ /dev/null@@ -1,139 +0,0 @@-import { describe, expect, it, vi } from "vitest";--// Contract for writing Convex deployment env vars over HTTP.-//-// Two things here were learned the hard way against a live deployment (laudable-bat-171,-// ap-southeast-2, 2026-11-02) rather than from docs:-//-// 1. A deployment deploy key authenticates `update_environment_variables` directly. Minting an-// ephemeral key from a personal token, and shelling out to `convex env set`, were both-// unnecessary — and the CLI path additionally required a project checkout that a credential-// connection does not have.-// 2. A deployment outside the US needs its region in the host or every call answers 404.--const KEY = "prod:laudable-bat-171|" + "A".repeat(40);--async function seeded(values: Record<string, string> = {}) {- vi.resetModules();- const store = await import("./store");- vi.spyOn(store, "readInfraProvider").mockResolvedValue({- deployKey: KEY,- deploymentName: "laudable-bat-171",- ...values,- });- return import("./convex-env-write");-}--function okJson() {- return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });-}--describe("convex env write", () => {- it("writes with the deployment key itself, over HTTP, to the region-qualified host", async () => {- const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());-- const result = await setConvexEnv({ name: "AUTH_GOOGLE_ID", value: "s3cret" }, fetchImpl as never);-- expect(result).toEqual({ deploymentName: "laudable-bat-171", name: "AUTH_GOOGLE_ID", set: true });- const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit];- // The region must be in the hostname; without it a non-US deployment answers 404.- expect(url).toBe("https://laudable-bat-171.ap-southeast-2.convex.cloud/api/v1/update_environment_variables");- expect((init.headers as Record<string, string>).authorization).toBe(`Convex ${KEY}`);- expect(JSON.parse(String(init.body))).toEqual({ changes: [{ name: "AUTH_GOOGLE_ID", value: "s3cret" }] });- });-- it("falls back to the US host when no region is configured", async () => {- const { setConvexEnv } = await seeded();- const fetchImpl = vi.fn(async () => okJson());- await setConvexEnv({ name: "A", value: "b" }, fetchImpl as never);- expect((fetchImpl.mock.calls[0] as unknown as [string])[0])- .toBe("https://laudable-bat-171.convex.cloud/api/v1/update_environment_variables");- });-- it("never returns the value", async () => {- const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });- const result = await setConvexEnv({ name: "A", value: "do-not-echo-me" }, (async () => okJson()) as never);- expect(JSON.stringify(result)).not.toContain("do-not-echo-me");- });-- it("redacts the value when the server echoes it back in a rejection", async () => {- // The realistic shape: Convex answers 4xx with a body quoting what it refused.- const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = async () =>- new Response(JSON.stringify({ code: "BadRequest", message: "invalid value s3cret-value" }), {- status: 400,- headers: { "content-type": "application/json" },- });-- const error = await setConvexEnv({ name: "A", value: "s3cret-value" }, fetchImpl as never).catch((e) => e);- expect(error.code).toBe("convex_deployment_http_400");- // Whatever the shape, the secret must not be reachable from the error.- expect(JSON.stringify({ ...error, message: error.message })).not.toContain("s3cret-value");- expect(String(error.detail)).toContain("[REDACTED_VALUE]");- });-- it("refuses a value over 8 KiB without making a request", async () => {- const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());- await expect(setConvexEnv({ name: "A", value: "x".repeat(8 * 1024 + 1) }, fetchImpl as never))- .rejects.toMatchObject({ code: "convex_env_value_too_large" });- expect(fetchImpl).not.toHaveBeenCalled();- });-- it("refuses an invalid name without making a request", async () => {- const { setConvexEnv } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());- await expect(setConvexEnv({ name: "1BAD NAME", value: "v" }, fetchImpl as never))- .rejects.toMatchObject({ code: "invalid_convex_env_name" });- expect(fetchImpl).not.toHaveBeenCalled();- });-- it("names the missing field when the connection has no deployment", async () => {- vi.resetModules();- const store = await import("./store");- vi.spyOn(store, "readInfraProvider").mockResolvedValue({ deployKey: KEY, deploymentName: "" });- const { setConvexEnv } = await import("./convex-env-write");- await expect(setConvexEnv({ name: "A", value: "v" }, (async () => okJson()) as never))- .rejects.toMatchObject({ code: "convex_deployment_name_required", status: 409 });- });-- it("requires a deploy key", async () => {- vi.resetModules();- const store = await import("./store");- vi.spyOn(store, "readInfraProvider").mockResolvedValue({ deploymentName: "d" });- const { setConvexEnv } = await import("./convex-env-write");- await expect(setConvexEnv({ name: "A", value: "v" }, (async () => okJson()) as never))- .rejects.toMatchObject({ code: "convex_deploy_key_required", status: 409 });- });-- it("sends a batch as one request", async () => {- const { setConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());- const result = await setConvexEnvs(- { changes: [{ name: "A", value: "1" }, { name: "B", value: "2" }] },- fetchImpl as never,- );- expect(fetchImpl).toHaveBeenCalledTimes(1);- expect(result.names).toEqual(["A", "B"]);- expect(JSON.parse(String((fetchImpl.mock.calls[0] as unknown as [string, RequestInit])[1].body)))- .toEqual({ changes: [{ name: "A", value: "1" }, { name: "B", value: "2" }] });- });-- it("deletes with delete:true and no value, which is the shape the API accepts", async () => {- const { removeConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());- await removeConvexEnvs({ names: ["A", "A", "B"] }, fetchImpl as never);- expect(JSON.parse(String((fetchImpl.mock.calls[0] as unknown as [string, RequestInit])[1].body)))- .toEqual({ changes: [{ name: "A", delete: true }, { name: "B", delete: true }] });- });-- it("rejects an over-wide batch instead of sending it", async () => {- const { setConvexEnvs } = await seeded({ deploymentRegion: "ap-southeast-2" });- const fetchImpl = vi.fn(async () => okJson());- const changes = Array.from({ length: 33 }, (_, i) => ({ name: `K${i}`, value: "v" }));- await expect(setConvexEnvs({ changes }, fetchImpl as never))- .rejects.toMatchObject({ code: "invalid_convex_env_changes" });- expect(fetchImpl).not.toHaveBeenCalled();- });-});diff --git a/lib/infra/convex-env-write.ts b/lib/infra/convex-env-write.tsdeleted file mode 100644index 943ccf5d..00000000--- a/lib/infra/convex-env-write.ts+++ /dev/null@@ -1,143 +0,0 @@-// Write, update and delete Convex deployment environment variables.-//-// DESIGN CORRECTION, from a live deployment (`laudable-bat-171`, 2026-11-02). An earlier version of-// this file minted an ephemeral deploy key from the personal token and shelled out to-// `convex env set --from-file`. Both halves were unnecessary:-//-// POST https://<deployment>.convex.cloud/api/v1/update_environment_variables-// authorization: Convex <deploy key> <- the key itself, no minting needed-// { "changes": [ { "name": "K", "value": "V" } ] }-//-// Verified against the live deployment: create 200, update 200, delete 200, list reflects each-// change. A deployment deploy key (`prod:<name>|…`) carries `deployment:env:write` for its own-// deployment, so no personal token, no ephemeral key, and no CLI project checkout are required.-//-// That matters beyond convenience: the CLI path required a project directory with-// `node_modules/.bin/convex`, which a credential connection does not have. The HTTP path works for-// the thing the connection actually is.-//-// Value redaction stays: callers must never see the value back, in output or in an error.-import { IntegrationError } from "./identity";-import { readInfraProvider } from "./store";-import {- convexAuthHeaders,- convexCheckedJson,- convexDeploymentName,- convexDeploymentUrl,- type FetchLike,-} from "./convex-cloud-core";--const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;-/** Convex caps a single value at 8 KiB. */-const MAX_ENV_VALUE_BYTES = 8 * 1024;--function envName(value: unknown): string {- if (typeof value !== "string" || !ENV_NAME.test(value.trim()))- throw new IntegrationError("invalid_convex_env_name");- return value.trim();-}--function envValue(value: unknown): string {- if (typeof value !== "string") throw new IntegrationError("invalid_convex_env_value");- if (Buffer.byteLength(value, "utf8") > MAX_ENV_VALUE_BYTES)- throw new IntegrationError("convex_env_value_too_large");- return value;-}--/** Keep a caller-supplied secret out of anything that can be surfaced. */-function redact(error: unknown, value: string): void {- if (!error || !value || typeof error !== "object") return;- const target = error as Record<string, unknown>;- for (const key of ["message", "detail"] as const) {- if (typeof target[key] === "string" && (target[key] as string).includes(value))- target[key] = (target[key] as string).split(value).join("[REDACTED_VALUE]");- }-}--/** Run a request and scrub every given secret out of whatever it throws.- * Wrapping here rather than around each call site keeps the guarantee in one place: the transport- * rethrows a normalised error, so a call-site-local catch would otherwise miss the value. */-async function withRedaction(secrets: string[], run: () => Promise<void>): Promise<void> {- try {- await run();- } catch (error) {- for (const secret of secrets) redact(error, secret);- throw error;- }-}--async function deploymentFor(input: { deploymentName?: string }): Promise<{ name: string; key: string; region?: string }> {- const values = await readInfraProvider("convex-cloud");- const key = values.deployKey;- if (!key) throw new IntegrationError("convex_deploy_key_required", 409);- const chosen =- (typeof input.deploymentName === "string" && input.deploymentName.trim()) ||- (typeof values.deploymentName === "string" && values.deploymentName.trim()) ||- "";- if (!chosen) throw new IntegrationError("convex_deployment_name_required", 409);- // A non-US deployment needs its region in the host; without it every call answers 404.- const region = typeof values.deploymentRegion === "string" && values.deploymentRegion.trim()- ? values.deploymentRegion.trim()- : undefined;- return { name: convexDeploymentName(chosen), key, region };-}--/** One POST carrying every change. `delete` removes a name; `value` sets it. */-async function postChanges(- deployment: string,- key: string,- changes: Array<{ name: string; value?: string; delete?: true }>,- fetchImpl: FetchLike,- region?: string,-): Promise<void> {- await convexCheckedJson(- "convex_deployment",- convexDeploymentUrl(deployment, "update_environment_variables", region),- {- method: "POST",- headers: convexAuthHeaders(key, "Convex"),- body: JSON.stringify({ changes }),- },- fetchImpl,- );-}--export type ConvexEnvChange = { name: string; value: string };--/** Set one value. Never returns it. */-export async function setConvexEnv(- input: { deploymentName?: string; name: string; value: string },- fetchImpl: FetchLike = fetch,-) {- const name = envName(input.name);- const value = envValue(input.value);- const { name: deployment, key, region } = await deploymentFor(input);- await withRedaction([value], () => postChanges(deployment, key, [{ name, value }], fetchImpl, region));- return { deploymentName: deployment, name, set: true as const };-}--/** Set several at once — one request, which is what Convex's API is shaped for. */-export async function setConvexEnvs(- input: { deploymentName?: string; changes: ConvexEnvChange[] },- fetchImpl: FetchLike = fetch,-) {- if (!Array.isArray(input.changes) || input.changes.length < 1 || input.changes.length > 32)- throw new IntegrationError("invalid_convex_env_changes");- const changes = input.changes.map((row) => ({ name: envName(row.name), value: envValue(row.value) }));- const { name: deployment, key, region } = await deploymentFor(input);- await withRedaction(changes.map((row) => row.value), () => postChanges(deployment, key, changes, fetchImpl, region));- return { deploymentName: deployment, names: changes.map((row) => row.name), set: true as const };-}--/** Remove names. Convex deletes on `delete: true` with no value. */-export async function removeConvexEnvs(- input: { deploymentName?: string; names: string[] },- fetchImpl: FetchLike = fetch,-) {- if (!Array.isArray(input.names) || input.names.length < 1 || input.names.length > 32)- throw new IntegrationError("invalid_convex_env_names");- const names = [...new Set(input.names.map(envName))];- const { name: deployment, key, region } = await deploymentFor(input);- await postChanges(deployment, key, names.map((name) => ({ name, delete: true as const })), fetchImpl, region);- return { deploymentName: deployment, names, removed: true as const };-}diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.tsindex b01573d2..333967df 100644--- a/lib/infra/setup-browser.ts+++ b/lib/infra/setup-browser.ts@@ -1,6 +1,6 @@export const INTEGRATION_BROWSER_SCRIPT=String.raw`(async()=>{- const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup",params=new URLSearchParams(location.search);let cleanup=()=>{},state={...(params.get("user")?{user:params.get("user")}:{ }),...(params.get("provider")?{provider:params.get("provider")}:{ }),...(params.get("section")==="ai-providers"?{section:"ai-providers"}:{}),...(params.get("connection")?{connection:params.get("connection")}:{})},authController,wantsTransfer=params.get("transfer")==="1";+ const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup",params=new URLSearchParams(location.search);let cleanup=()=>{},state={...(params.get("user")?{user:params.get("user")}:{ }),...(params.get("provider")?{provider:params.get("provider")}:{ }),...(params.get("section")==="ai-providers"?{section:"ai-providers"}:{})},authController,wantsTransfer=params.get("transfer")==="1";const error=data=>{const e=new Error(data.error||"integration_operation_failed");e.code=data.error;return e};async function json(url,init){const r=await fetch(url,{credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",...init});const data=await r.json();if(!r.ok)throw error(data);return data}const post=(mode,input)=>json("/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode,...input})});diff --git a/lib/infra/types.ts b/lib/infra/types.tsindex fc335739..6f28b452 100644--- a/lib/infra/types.ts+++ b/lib/infra/types.ts@@ -24,7 +24,6 @@ export const CONVEX_OPERATION_IDS = ["convex.canonical.get","convex.canonical.set","convex.env.presence",- "convex.env.set","convex.project.deploy","convex.snapshot.import",] as const;@@ -80,12 +79,6 @@ export const CONVEX_OPERATION_SUPPORT: readonly ConvexOperationSupport[] = [selfHosted: "unsupported",reason: "Reads environment names with an ephemeral deploy key minted by the Convex Cloud management API; no self-hosted equivalent is wired yet.",},- {- operation: "convex.env.set",- cloud: "supported",- selfHosted: "unsupported",- reason: "Sets environment variables with an ephemeral deploy key minted by the Convex Cloud management API; no self-hosted equivalent is wired yet.",- },{operation: "convex.project.deploy",cloud: "supported",diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.tsindex 93eb2ba4..5e476a3a 100644--- a/lib/mcp/tools-integrations.ts+++ b/lib/mcp/tools-integrations.ts@@ -23,7 +23,7 @@ export const INTEGRATION_TOOLS:McpTool[]=[{name:"integration_execute",title:"Use Integration",scope:"exec",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},audit:{action:"infra.write",targetArg:"connection"},limit:{key:"integration.execute",max:30,windowMs:60000},description:"Execute using an explicit user/provider/named connection. Verify or inspect its route; bounded direct operations reject external backends. Composio tool execution requires an ACTIVE connected account and a toolkit-prefixed tool. Native-MCP returns the provider route without copying OAuth tokens. Native Google supports the bounded read operations listed in its catalog without Composio. Non-verification operations require confirm=true. No credentials in arguments.",chatgptDescription:"Use a named connection.",- inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.gitProviders.list","dokploy.github.repositories.list","dokploy.application.ensureGithub","dokploy.domain.ensure","dokploy.deployments.list","dokploy.deployment.logs","dokploy.git.recover","dokploy.application.deploy","dokploy.dockerfile","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.env.presence","convex.env.set","convex.canonical.set","convex.project.deploy","convex.snapshot.import","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","mcp.tools.list","mcp.tool","composio.tool","google.bind","google.disconnect","google.operations.list",...GOOGLE_READ_OPERATIONS.map(operation=>operation.name)]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,+ inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.gitProviders.list","dokploy.github.repositories.list","dokploy.application.ensureGithub","dokploy.domain.ensure","dokploy.deployments.list","dokploy.deployment.logs","dokploy.git.recover","dokploy.application.deploy","dokploy.dockerfile","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.env.presence","convex.canonical.set","convex.project.deploy","convex.snapshot.import","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","mcp.tools.list","mcp.tool","composio.tool","google.bind","google.disconnect","google.operations.list",...GOOGLE_READ_OPERATIONS.map(operation=>operation.name)]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await executeIntegrationAction(a)}),},];diff --git a/scripts/mso-agent-cmd-queue.mjs b/scripts/mso-agent-cmd-queue.mjsnew file mode 100644index 00000000..bb3623c8--- /dev/null+++ b/scripts/mso-agent-cmd-queue.mjs@@ -0,0 +1,161 @@+// Ephemeral prompt queue commands: list, drop, clear, and enqueue follow-up turns.+import { C } from "./mso-agent-runtime.mjs";+import { createPrinter } from "./mso-agent-print.mjs";+import {+ createQueue,+ enqueue,+ queueClear,+} from "./mso-agent-queue.mjs";++// Queues with 5 or more items require explicit confirmation before clearing+// to prevent accidental loss of extensive queued work while keeping small queues friction-free.+export const CLEAR_THRESHOLD = 5;++// Mirror the queue accessor from mso-agent-queue so mutations stay synchronized+// directly on the shared in-memory queue referenced by the main drain loop.+function getQueueItems(queue) {+ if (Array.isArray(queue)) return queue;+ if (queue && Array.isArray(queue.items)) return queue.items;+ return null;+}++export function formatQueueItem(item, maxWidth = 70) {+ let display = "";+ if (typeof item === "string") {+ display = item;+ } else if (item && typeof item === "object") {+ // Reveal underlying structure honestly when queue items contain attached skills or images+ // instead of calling String(item) which produces an unhelpful [object Object].+ const tags = [];+ if (item.skill) {+ const name = typeof item.skill === "string" ? item.skill : item.skill.name || "unknown";+ tags.push(`skill: ${name}`);+ }+ if (Array.isArray(item.images) && item.images.length) {+ tags.push(`${item.images.length} ${item.images.length === 1 ? "image" : "images"}`);+ }+ const text = typeof item.text === "string" ? item.text : (typeof item.prompt === "string" ? item.prompt : "");+ if (tags.length && text) {+ display = `[${tags.join(", ")}] ${text}`;+ } else if (tags.length) {+ display = `[${tags.join(", ")}]`;+ } else if (text) {+ display = `[object] ${text}`;+ } else {+ try {+ display = JSON.stringify(item);+ } catch {+ display = "[unserializable object]";+ }+ }+ } else {+ display = String(item ?? "");+ }++ const flattened = display.replace(/[\r\n]+/g, " ").trim();+ if (flattened.length <= maxWidth) return flattened;+ return `${flattened.slice(0, Math.max(0, maxWidth - 1))}…`;+}++export function formatQueueBlock(items, { maxWidth = 72, colors = {} } = {}) {+ const list = Array.isArray(items) ? items : (items && Array.isArray(items.items) ? items.items : []);+ if (!list.length) {+ return "queue empty (no pending prompts)";+ }+ const { dim = "", reset = "", bold = "" } = colors;+ const count = list.length;+ const header = `Queued prompts (${count} pending):`;+ const lines = [bold ? `${bold}${header}${reset}` : header];+ for (let i = 0; i < list.length; i++) {+ const num = `${i + 1}.`;+ const formatted = formatQueueItem(list[i], maxWidth);+ lines.push(` ${dim ? `${dim}${num}${reset}` : num} ${formatted}`);+ }+ return lines.join("\n");+}++export async function handleQueueCommand(ctx, args = []) {+ const session = ctx?.session ?? ctx;+ const colors = ctx?.C ?? ctx?.colors ?? C ?? {};+ const { print, printBlock } = ctx?.printer ?? createPrinter(ctx);+ const queue = session?.queue || (session.queue = createQueue());+ const items = getQueueItems(queue) || [];+ const sub = args[0]?.toLowerCase();++ // Listing pending prompts: '/queue' or '/queue list'+ if (!args.length || (args.length === 1 && sub === "list")) {+ if (!items.length) {+ print("queue empty (no pending prompts)");+ return "handled";+ }+ const block = formatQueueBlock(items, { colors });+ printBlock(block);+ return "handled";+ }++ // Dropping an item: '/queue drop <position>'+ if (sub === "drop") {+ if (args.length < 2) {+ print("usage: /queue drop <position>");+ return "handled";+ }+ const pos = Number.parseInt(args[1], 10);+ if (!Number.isInteger(pos)) {+ print(`invalid position "${args[1]}": must be a positive integer`);+ return "handled";+ }+ if (pos < 1 || pos > items.length) {+ const count = items.length;+ if (count === 0) {+ print("cannot drop item: queue is empty");+ } else {+ print(`cannot drop item ${pos}: queue has ${count} ${count === 1 ? "item" : "items"} (valid: 1..${count})`);+ }+ return "handled";+ }+ // Splice in-place so drainQueue dequeues remaining items in untouched FIFO order without index gaps.+ const [removed] = items.splice(pos - 1, 1);+ const summary = formatQueueItem(removed, 60);+ print(`dropped item ${pos}: "${summary}" (${items.length} pending)`);+ return "handled";+ }++ // Clearing the queue: '/queue clear [--yes]'+ if (sub === "clear") {+ const count = items.length;+ if (count === 0) {+ print("queue empty (0 items cleared)");+ return "handled";+ }+ const hasYes = args.slice(1).some((arg) => {+ const lower = arg.toLowerCase();+ return lower === "--yes" || lower === "-y";+ });+ if (count >= CLEAR_THRESHOLD && !hasYes) {+ print(`queue holds ${count} items; run '/queue clear --yes' to confirm clearing.`);+ return "handled";+ }+ const dropped = queueClear(queue);+ print(`cleared ${dropped} queued ${dropped === 1 ? "item" : "items"}.`);+ return "handled";+ }++ // Running the queue manually: '/queue run' triggers the turn loop to drain immediately.+ if (args.length === 1 && sub === "run") {+ return "drain";+ }++ // Enqueue follow-up prompt: '/queue <text>' or '/queue add <text>'+ const text = (sub === "add" ? args.slice(1) : args).join(" ").trim();+ if (!text && sub === "add") {+ print("usage: /queue add <prompt>");+ return "handled";+ }+ const res = enqueue(queue, text);+ if (!res.ok) {+ if (res.capped) print(`queue full (cap is ${res.cap} items)`);+ return "handled";+ }+ print(`queued (${res.count} pending)`);+ return "handled";+}diff --git a/scripts/mso-agent-cmd-queue.test.ts b/scripts/mso-agent-cmd-queue.test.tsnew file mode 100644index 00000000..8696188b--- /dev/null+++ b/scripts/mso-agent-cmd-queue.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";+import {+ formatQueueItem,+ handleQueueCommand,+} from "./mso-agent-cmd-queue.mjs";+import { createQueue, dequeue, enqueue } from "./mso-agent-queue.mjs";++function makeContext(initialItems: unknown[] = []) {+ const queue = createQueue();+ for (const item of initialItems) {+ if (typeof item === "string") {+ enqueue(queue, item);+ } else {+ // Direct push simulates objects queued with attached skills or images.+ (queue as { items: unknown[] }).items.push(item);+ }+ }+ const lines: string[] = [];+ const session = { queue };+ const printer = {+ print: (line: string) => lines.push(String(line)),+ printBlock: (block: string) => {+ for (const line of String(block).split("\n")) lines.push(line);+ },+ printLines: (arr: string[]) => lines.push(...arr),+ colors: {},+ };+ return {+ ctx: { session, printer, C: {} },+ queue,+ session,+ lines,+ };+}++describe("MSO Agent queue slash command", () => {+ it("1. listing preserves FIFO order and numbers them", async () => {+ const { ctx, lines } = makeContext(["first turn", "second turn", "third turn"]);+ await handleQueueCommand(ctx, []);++ expect(lines[0]).toContain("3 pending");+ expect(lines[1]).toMatch(/^\s*1\.\s+first turn/);+ expect(lines[2]).toMatch(/^\s*2\.\s+second turn/);+ expect(lines[3]).toMatch(/^\s*3\.\s+third turn/);+ });++ it("2. /queue drop 2 removes exactly the second and leaves the rest in order", async () => {+ const { ctx, queue, lines } = makeContext(["alpha", "beta", "gamma"]);+ await handleQueueCommand(ctx, ["drop", "2"]);++ expect(lines.some((l) => l.includes("dropped item 2") && l.includes("beta"))).toBe(true);+ // Assert FIFO drain order is intact for the remaining items in session.queue.+ expect(dequeue(queue)).toBe("alpha");+ expect(dequeue(queue)).toBe("gamma");+ expect(dequeue(queue)).toBeNull();+ });++ it("3. an out of range index is refused with a message", async () => {+ const { ctx, queue, lines } = makeContext(["one", "two"]);++ await handleQueueCommand(ctx, ["drop", "0"]);+ expect(lines[lines.length - 1]).toMatch(/cannot drop item 0.*valid: 1\.\.2/i);++ await handleQueueCommand(ctx, ["drop", "5"]);+ expect(lines[lines.length - 1]).toMatch(/cannot drop item 5.*valid: 1\.\.2/i);++ // Queue items remain untouched when drop is refused.+ expect(queue.items).toEqual(["one", "two"]);+ });++ it("4. /queue clear with 3 items clears without confirmation", async () => {+ const { ctx, queue, lines } = makeContext(["a", "b", "c"]);+ await handleQueueCommand(ctx, ["clear"]);++ expect(lines[0]).toBe("cleared 3 queued items.");+ expect(queue.items).toHaveLength(0);+ });++ it("5. /queue clear with 5 items refuses without --yes and states the count", async () => {+ const items = ["p1", "p2", "p3", "p4", "p5"];+ const { ctx, queue, lines } = makeContext(items);++ await handleQueueCommand(ctx, ["clear"]);+ expect(lines[0]).toContain("5 items");+ expect(lines[0]).toContain("/queue clear --yes");+ expect(queue.items).toHaveLength(5);++ // With explicit confirmation argument, queue is emptied.+ await handleQueueCommand(ctx, ["clear", "--yes"]);+ expect(lines[1]).toBe("cleared 5 queued items.");+ expect(queue.items).toHaveLength(0);+ });++ it("6. an empty queue lists a clear message rather than an empty table", async () => {+ const { ctx, lines } = makeContext([]);+ await handleQueueCommand(ctx, []);++ expect(lines).toHaveLength(1);+ expect(lines[0]).toBe("queue empty (no pending prompts)");+ expect(lines[0]).not.toContain("┌");+ expect(lines[0]).not.toContain("pending):");+ });++ it("7. honesty rule: structured objects reveal actual contents instead of [object Object]", () => {+ const skillItem = { skill: { name: "design" }, text: "redesign hero section" };+ const imageItem = { images: ["preview.png"], prompt: "analyze this layout" };+ const rawObject = { foo: "bar" };++ expect(formatQueueItem(skillItem)).toContain("[skill: design] redesign hero section");+ expect(formatQueueItem(imageItem)).toContain("[1 image] analyze this layout");+ expect(formatQueueItem(rawObject)).toBe('{"foo":"bar"}');+ });+});diff --git a/scripts/mso-agent-cmd-session.mjs b/scripts/mso-agent-cmd-session.mjsindex ab0a5828..8c8c81d4 100644--- a/scripts/mso-agent-cmd-session.mjs+++ b/scripts/mso-agent-cmd-session.mjs@@ -1,10 +1,6 @@import {- persistSession,- renameCurrentSession,- renameCurrentSessionName,- resumeInto,- startNewSession,- resumePicker,+ persistSession, renameCurrentSession, renameCurrentSessionName,+ resumeInto, startNewSession, resumePicker,} from "./mso-agent-session-ui.mjs";import { api, listCliSessions, state } from "./mso-agent-api.mjs";import { C } from "./mso-agent-runtime.mjs";@@ -12,9 +8,10 @@ import { clearTodos, formatTodoBlock, latestTodos } from "./mso-agent-todos.mjs"import { handleKeybindCommand } from "./mso-agent-keybinds.mjs";import { visibleSessionRows } from "./mso-agent-sessions.mjs";import { tabsToSwitch } from "./mso-agent-chrome.mjs";-import { sessionTable } from "./mso-agent-session-list.mjs";+import { attentionReason, findAttentionSession, sessionTable } from "./mso-agent-session-list.mjs";import { cyclePane, paneKinds } from "./mso-agent-pane.mjs";import { createPrinter } from "./mso-agent-print.mjs";+import { clean } from "./tui/cells.mjs";export async function handleTodos(ctx, args = []) {const { C: colors = C } = ctx;@@ -44,17 +41,28 @@ export async function switchToSession(rl, session, sessionId) {export async function handleTabs(ctx, args = []) {const { rl, session, C: colors = C } = ctx;const { print } = createPrinter(ctx);- const rows = visibleSessionRows(await listCliSessions(20));+ const rows = visibleSessionRows(ctx.sessions || await listCliSessions(20));if (!args.length) {const width = Number(ctx.width || process.stdout.columns) || 80;- const lines = sessionTable(rows, {- colors,- width,- activeId: session?.agentSession?.id,- });+ const lines = sessionTable(rows, { colors, width, activeId: session?.agentSession?.id });for (const line of lines) print(line);return "handled";}+ const sub = String(args[0] || "").toLowerCase();+ if (sub === "next" || sub === "prev" || sub === "previous") {+ const activeId = session?.agentSession?.id;+ const now = Number(ctx.now) || Date.now();+ const target = findAttentionSession(rows, activeId, sub, now);+ if (!target) {+ print("no sessions need attention");+ return "handled";+ }+ const rawName = clean(target?.name || target?.agentSession?.name || "agent").replace(/^@/, "");+ const reason = attentionReason(target, now);+ print(`${colors.c || ""}jumped to @${rawName} (${reason})${colors.reset || ""}`);+ await switchToSession(rl, session, target.id);+ return "refresh";+ }const target = tabsToSwitch(rows, args);if (!target) {print(`could not resolve session: ${args.join(" ")}`);@@ -116,18 +124,10 @@ export async function handlePane(ctx, args = []) {}export async function handleSessionCommand(ctx, cmd, args) {- if (cmd === "/todos") {- return handleTodos(ctx, args);- }- if (cmd === "/pane") {- return handlePane(ctx, args);- }- if (cmd === "/keybind" || cmd === "/keybinds") {- return handleKeybindCommand(ctx, args);- }- if (cmd === "/tabs" || cmd === "/tab") {- return handleTabs(ctx, args);- }+ if (cmd === "/todos") return handleTodos(ctx, args);+ if (cmd === "/pane") return handlePane(ctx, args);+ if (cmd === "/keybind" || cmd === "/keybinds") return handleKeybindCommand(ctx, args);+ if (cmd === "/tabs" || cmd === "/tab") return handleTabs(ctx, args);const { rl, session, C: colors = C } = ctx;const { print } = createPrinter(ctx);switch (cmd) {@@ -193,12 +193,7 @@ export async function handleSessionCommand(ctx, cmd, args) {}case "/clear":clearTodos();- Object.assign(session, {- history: [],- pendingSkill: null,- activeSkill: null,- lastInvokedSkill: null,- });+ Object.assign(session, { history: [], pendingSkill: null, activeSkill: null, lastInvokedSkill: null });rl.replaceHistory([]);await persistSession(session);print("conversation and prompt history cleared.");diff --git a/scripts/mso-agent-cmd-settings.mjs b/scripts/mso-agent-cmd-settings.mjsindex 1f904e73..eac02b7e 100644--- a/scripts/mso-agent-cmd-settings.mjs+++ b/scripts/mso-agent-cmd-settings.mjs@@ -23,6 +23,14 @@ export async function handleSettingsCommand(ctx, args = []) {if (session) {if (settings.pane) session.paneKind = settings.pane;if (settings.statusbar) session.statusBar = settings.statusbar === "on";+ // Propagate reset tab layout so the running screen loop repaints with defaults+ const tabsLayout = settings["tabs.layout"] ?? settings.layout;+ if (tabsLayout) session.tabsLayout = tabsLayout;+ if (settings.minwidth != null) session.paneMinColumns = Number(settings.minwidth);+ if (settings.grouping) session.grouping = settings.grouping;+ session.screenLoop?.sync?.();+ // Propagate verbosity to session so status footer updates immediately+ if (settings.verbosity) session.verbosity = settings.verbosity;}print(`reset settings to defaults from ${filePath}`);printBlock(formatSettingsTable(SETTINGS, settings, { colors, width }));@@ -52,28 +60,57 @@ export async function handleSettingsCommand(ctx, args = []) {const entry = resolved.entry;if (args.length === 1) {const current = getSettings()[entry.key] ?? entry.default;- const allowed = entry.values ? ` (options: ${entry.values.join(", ")})` : "";+ const allowed = entry.values+ ? ` (options: ${entry.values.join(", ")})`+ : typeof entry.min === "number" && typeof entry.max === "number"+ ? ` (range: ${entry.min}-${entry.max})`+ : "";print(`${entry.key} = ${current}${allowed}: ${entry.description}`);return "handled";}- const requestedValue = String(args[1]).toLowerCase().trim();- if (entry.values && !entry.values.includes(requestedValue)) {- print(- `${colors.warn || ""}invalid value "${args[1]}" for ${entry.key}; valid options: ${entry.values.join(", ")}${colors.reset || ""}`- );- return "handled";+ const rawArg = String(args[1] ?? "").trim();+ const requestedValue = rawArg.toLowerCase();+ let valueToSave = requestedValue;++ if (entry.values) {+ if (!entry.values.includes(requestedValue)) {+ print(+ `${colors.warn || ""}invalid value "${args[1]}" for ${entry.key}; valid options: ${entry.values.join(", ")}${colors.reset || ""}`+ );+ return "handled";+ }+ } else if (typeof entry.min === "number" && typeof entry.max === "number") {+ // Numeric settings clamp against valid terminal bounds to prevent pane crowding+ const num = Number(rawArg);+ if (!Number.isFinite(num) || num < entry.min || num > entry.max) {+ print(+ `${colors.warn || ""}invalid value "${args[1]}" for ${entry.key}; accepted range is ${entry.min} to ${entry.max}${colors.reset || ""}`+ );+ return "handled";+ }+ valueToSave = Math.round(num);}- saveSettings({ [entry.key]: requestedValue }, { path: filePath });+ saveSettings({ [entry.key]: valueToSave }, { path: filePath });// Apply to running session if presentif (session) {if (entry.key === "pane") session.paneKind = requestedValue;if (entry.key === "statusbar") session.statusBar = requestedValue === "on";+ // Sync tab rail orientation immediately so users see layout change without restart+ if (entry.key === "layout") session.tabsLayout = requestedValue;+ if (entry.key === "minwidth") session.paneMinColumns = valueToSave;+ if (entry.key === "grouping") {+ session.grouping = requestedValue;+ // Repaint immediately so grouping change reflects on screen without restart+ session.screenLoop?.sync?.();+ }+ // Propagate verbosity to session so status footer updates immediately+ if (entry.key === "verbosity") session.verbosity = requestedValue;}- print(`${colors.cyan || ""}setting ${entry.key} = ${requestedValue}${colors.reset || ""}`);+ print(`${colors.cyan || ""}setting ${entry.key} = ${valueToSave}${colors.reset || ""}`);return "handled";}@@ -84,4 +121,11 @@ export function applySettings(session, settings = getSettings()) {if (!session || !settings) return;if (settings.pane) session.paneKind = settings.pane;if (settings.statusbar) session.statusBar = settings.statusbar === "on";+ // The screen loop reads session.tabsLayout to switch between horizontal row and vertical rail+ const tabsLayout = settings["tabs.layout"] ?? settings.layout;+ if (tabsLayout) session.tabsLayout = tabsLayout;+ if (settings.minwidth != null) session.paneMinColumns = Number(settings.minwidth);+ if (settings.grouping) session.grouping = settings.grouping;+ // Apply saved verbosity preference to session at startup+ if (settings.verbosity) session.verbosity = settings.verbosity;}diff --git a/scripts/mso-agent-commands.mjs b/scripts/mso-agent-commands.mjsindex f096582f..4016be5b 100644--- a/scripts/mso-agent-commands.mjs+++ b/scripts/mso-agent-commands.mjs@@ -20,6 +20,7 @@ import { handleSessionCommand } from "./mso-agent-cmd-session.mjs";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 { createPrinter } from "./mso-agent-print.mjs";export { SHARE_UNAVAILABLE_MESSAGE, buildExportArgv };@@ -101,6 +102,8 @@ export async function handleSlash(rl, line, session, { runTurn, runSubagent }) {const inspectOutcome = await handleInspectCommand(ctx, cmd, args);if (inspectOutcome !== null) return inspectOutcome;+ if (cmd === "/queue") return handleQueueCommand(ctx, args);+const parityOutcome = await handleParityCommand(ctx, cmd, args);if (parityOutcome !== null) return parityOutcome;diff --git a/scripts/mso-agent-help.mjs b/scripts/mso-agent-help.mjsindex 62ce2e45..a137ec20 100644--- a/scripts/mso-agent-help.mjs+++ b/scripts/mso-agent-help.mjs@@ -6,7 +6,7 @@ export const HELP_LINES = [" /restart soft-reload Agent runtime; keep this session"," /session [query] open picker or resume latest/index/id/@name/title (alias: /sessions)"," /resume [query] alias-style resume command; bare opens same picker",- " /tabs [n|name] list session tabs or switch by index or @name",+ " /tabs [n|name|next|prev] list tabs, switch by index/@name, or jump active"," /rename <name> rename the short @agent handle"," /title <text> rename the session title/description"," /export [ref] [--out f] export session transcript to stdout or a file",@@ -42,7 +42,7 @@ export const HELP_LINES = [" /skills [query] browse available slash skills"," /skill <id> [prompt] select exact skill id (ambiguity escape hatch)"," /<skill> [prompt] select for next message, or run prompt now",- " /queue [sub|prompt] queue follow-up prompt; list, run, or clear",+ " /queue [drop|clear|prompt] list, drop, clear, or queue follow-up prompts"," /stash [pop|clear|text] park prompt; /stash pop prints stashed prompt to terminal"," /image <path> attach a local image to the next prompt"," /clear clear this session conversation",diff --git a/scripts/mso-agent-mcp-servers.mjs b/scripts/mso-agent-mcp-servers.mjsnew file mode 100644index 00000000..dd15b04c--- /dev/null+++ b/scripts/mso-agent-mcp-servers.mjs@@ -0,0 +1,107 @@+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { api } from "./mso-agent-api.mjs";++// The pane in scripts/mso-agent-pane-context.mjs expects an array of server objects:+// { name: string, toolCount?: number, tools?: unknown[] | number, connected?: boolean, status?: string, error?: unknown }+// Real sources (API endpoint, .mcp.json, ~/.mso/mcp.json) provide:+// - Object map: { mcpServers: { [name]: { command?, args?, url?, toolCount?, tools? } } }+// - Array: Array<{ name?: string, id?: string, toolCount?: number, tools?: unknown[], ... }>+// This mapping function adapts in ONE place: it converts dictionaries or arrays into the+// array shape expected by the pane. Non-visual fields (command, args, env, url, cwd, headers)+// are dropped. Servers without a tool count are preserved with connected status (not marked offline).+export function mapMcpServers(raw) {+ if (raw == null || typeof raw !== "object") return null;++ let list = null;+ if (Array.isArray(raw)) {+ list = raw;+ } else if (Array.isArray(raw.mcpServers)) {+ list = raw.mcpServers;+ } else if (Array.isArray(raw.servers)) {+ list = raw.servers;+ } else if (raw.mcpServers && typeof raw.mcpServers === "object" && !Array.isArray(raw.mcpServers)) {+ list = Object.entries(raw.mcpServers).map(([name, conf]) => ({+ name,+ ...(conf && typeof conf === "object" ? conf : {}),+ }));+ } else if (raw.servers && typeof raw.servers === "object" && !Array.isArray(raw.servers)) {+ list = Object.entries(raw.servers).map(([name, conf]) => ({+ name,+ ...(conf && typeof conf === "object" ? conf : {}),+ }));+ } else {+ // Avoid mistaking OAuth client storage for server configuration+ const keys = Object.keys(raw);+ const isStoreEnvelope = keys.some((k) => ["clients", "tokens", "codes", "refreshTokens"].includes(k));+ if (isStoreEnvelope) return null;+ list = Object.entries(raw).map(([name, conf]) => ({+ name,+ ...(conf && typeof conf === "object" ? conf : {}),+ }));+ }++ return list.map((server) => {+ const name = String(server?.name || server?.id || "server");+ const item = { name };+ if (typeof server?.toolCount === "number") {+ item.toolCount = server.toolCount;+ } else if (Array.isArray(server?.tools)) {+ item.tools = server.tools;+ } else if (typeof server?.tools === "number") {+ item.tools = server.tools;+ }+ if (typeof server?.connected === "boolean") item.connected = server.connected;+ if (server?.status) item.status = server.status;+ if (server?.state) item.state = server.state;+ if (server?.error) item.error = server.error;+ if (server?.isError) item.isError = server.isError;+ return item;+ });+}++// Fetches or reads MCP server configuration once at startup.+// Never called inside a render function to avoid network/disk overhead during keystroke repaints.+export async function fetchMcpServers(options = {}) {+ const apiFn = options.apiFn || api;++ // 1. Try reading from server API endpoint if available.+ try {+ const data = await apiFn("/api/v1/mcp/server");+ if (data != null) {+ const mapped = mapMcpServers(data);+ if (mapped !== null) return mapped;+ }+ } catch {+ // API endpoint does not exist or server is unreachable; fall through to local files.+ }++ // 2. Try reading from local config files.+ const customFile = options.filePath || process.env.OS_MCP_STORE;+ const candidateFiles = customFile+ ? [customFile]+ : [+ path.join(os.homedir(), ".mso", "mcp.json"),+ path.join(options.cwd || process.cwd(), ".mcp.json"),+ ];++ const readFileFn = options.readFile || fs.readFile;++ for (const filePath of candidateFiles) {+ try {+ const rawText = await readFileFn(filePath, "utf8");+ const parsed = JSON.parse(rawText);+ if (parsed && typeof parsed === "object") {+ if (parsed.mcpServers !== undefined || parsed.servers !== undefined) {+ const mapped = mapMcpServers(parsed);+ if (mapped !== null) return mapped;+ }+ }+ } catch {+ // File missing or unreadable; check next candidate.+ }+ }++ return null;+}diff --git a/scripts/mso-agent-mcp-servers.test.ts b/scripts/mso-agent-mcp-servers.test.tsnew file mode 100644index 00000000..0a654a82--- /dev/null+++ b/scripts/mso-agent-mcp-servers.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from "vitest";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { fetchMcpServers, mapMcpServers } from "./mso-agent-mcp-servers.mjs";+import { formatMcpContent } from "./mso-agent-pane-context.mjs";+import { paneLines } from "./mso-agent-pane.mjs";+import { stripAnsi } from "./tui/cells.mjs";++const __dirname = path.dirname(fileURLToPath(import.meta.url));++describe("mso-agent-mcp-servers", () => {+ // Test requirement 1: Mapping produces the exact shape the pane accepts,+ // asserted against a fixture copied from the real pane's expectations in mso-agent-pane-kinds.test.ts.+ it("mapping produces the exact shape the pane accepts against fixture from pane expectations", () => {+ // Fixture copied directly from scripts/mso-agent-pane-kinds.test.ts (line 25).+ const paneFixture = [+ { name: "github", toolCount: 12 },+ { name: "filesystem", tools: 4 },+ ];++ // Raw configuration map as found in standard MCP configs or API responses.+ const rawConfig = {+ mcpServers: {+ github: { command: "node", args: ["./gh.js"], toolCount: 12 },+ filesystem: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem"], tools: 4 },+ },+ };++ const mapped = mapMcpServers(rawConfig);+ expect(mapped).toEqual(paneFixture);++ // Verify formatMcpContent accepts the mapped output on session.mcpServers.+ const paneContent = formatMcpContent({ session: { mcpServers: mapped }, mcpServers: null });+ expect(paneContent.emptyText).toBeNull();+ expect(paneContent.rows).toEqual([+ { text: "github (12 tools)", tone: "normal" },+ { text: "filesystem (4 tools)", tone: "normal" },+ ]);+ });++ // Test requirement 2: A server without a tool count still renders as connected.+ it("a server without a tool count still renders as connected", () => {+ const rawWithoutCounts = {+ mcpServers: {+ sqlite: { command: "sqlite3", args: ["test.db"] },+ },+ };++ const mapped = mapMcpServers(rawWithoutCounts);+ expect(mapped).toEqual([{ name: "sqlite" }]);++ // The pane formats the server with (0 tools) and tone: normal, rather than (offline) and tone: dim.+ const paneContent = formatMcpContent({ session: { mcpServers: mapped }, mcpServers: null });+ expect(paneContent.rows).toEqual([+ { text: "sqlite (0 tools)", tone: "normal" },+ ]);++ const lines = paneLines({+ kind: "mcp",+ mcpServers: mapped,+ width: 40,+ rows: 6,+ });+ const rendered = lines.map((l) => stripAnsi(l)).join("\n");+ expect(rendered).toContain("sqlite (0 tools)");+ expect(rendered).not.toContain("offline");+ });++ // Test requirement 3: A fetch failure returns null and does not throw.+ it("a fetch failure returns null and does not throw", async () => {+ const failingApi = vi.fn().mockRejectedValue(new Error("network failure"));+ const failingReadFile = vi.fn().mockRejectedValue(new Error("ENOENT: no such file"));++ const result = await fetchMcpServers({+ apiFn: failingApi,+ filePath: "/nonexistent/mcp.json",+ readFile: failingReadFile,+ });++ expect(result).toBeNull();+ });++ // Test requirement 4: An empty list returns an empty array, not null, so the pane can+ // distinguish "none configured" from "could not read".+ it("an empty list returns an empty array, not null", async () => {+ // 4a. API returns empty list+ const emptyApi = vi.fn().mockResolvedValue({ servers: [] });+ const apiResult = await fetchMcpServers({ apiFn: emptyApi });+ expect(apiResult).toEqual([]);++ // 4b. Local config file defines empty servers+ const emptyFileRead = vi.fn().mockResolvedValue(JSON.stringify({ mcpServers: {} }));+ const fileResult = await fetchMcpServers({+ apiFn: vi.fn().mockRejectedValue(new Error("404")),+ filePath: "/tmp/fake-empty-mcp.json",+ readFile: emptyFileRead,+ });+ expect(fileResult).toEqual([]);+ });++ // Proof requirement: No network call inside a render path.+ it("proves no render module imports the fetch function", () => {+ const paneSource = fs.readFileSync(path.join(__dirname, "mso-agent-pane.mjs"), "utf8");+ const paneContextSource = fs.readFileSync(path.join(__dirname, "mso-agent-pane-context.mjs"), "utf8");+ const screenLoopSource = fs.readFileSync(path.join(__dirname, "mso-agent-screen-loop.mjs"), "utf8");++ expect(paneSource).not.toContain("fetchMcpServers");+ expect(paneSource).not.toContain("mso-agent-mcp-servers");+ expect(paneContextSource).not.toContain("fetchMcpServers");+ expect(paneContextSource).not.toContain("mso-agent-mcp-servers");+ expect(screenLoopSource).not.toContain("fetchMcpServers");+ expect(screenLoopSource).not.toContain("mso-agent-mcp-servers");+ });+});diff --git a/scripts/mso-agent-next-unread.test.ts b/scripts/mso-agent-next-unread.test.tsnew file mode 100644index 00000000..ca5d4005--- /dev/null+++ b/scripts/mso-agent-next-unread.test.ts@@ -0,0 +1,213 @@+import { describe, expect, it, vi } from "vitest";+import { needsAttention, attentionReason, findAttentionSession } from "./mso-agent-session-list.mjs";+import { handleTabs, handleSessionCommand } 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 session unread and attention navigation", () => {+ // The premise was corrected after docs/AGENT-ACTIVITY-SIGNAL.md: updatedAt is written at turn+ // COMPLETION, so a fresh timestamp means the turn just ended, not that work is happening. Only an+ // explicit status is trusted.+ it("needsAttention trusts only an explicit status, never a timestamp", () => {+ const now = 1_700_000_000_000;+ // Updated 5s ago is within the 60s activity threshold.+ // A turn that just finished leaves a fresh timestamp while the agent sits idle at the prompt.+ const justFinished = { id: "s-active", name: "milo", updatedAt: new Date(now - 5_000).toISOString() };+ expect(needsAttention(justFinished, now)).toBe(false);+ // A turn streaming for three minutes still carries the previous turn's timestamp.+ const stillWorking = { id: "s-busy", name: "lara", updatedAt: new Date(now - 180_000).toISOString() };+ expect(needsAttention(stillWorking, now)).toBe(false);+ // An explicit status is the only trustworthy source.+ expect(needsAttention({ id: "s-x", name: "eli", status: "working" }, now)).toBe(true);++ // Updated 10m ago has expired past the 60s activity threshold.+ const row10m = { id: "s-idle", name: "olive", updatedAt: new Date(now - 600_000).toISOString() };+ expect(needsAttention(row10m, now)).toBe(false);++ // Missing activity data is excluded: jumping on a guess violates honesty.+ const rowNoTime = { id: "s-ghost", name: "ghost" };+ expect(needsAttention(rowNoTime, now)).toBe(false);++ // Explicit error states also require operator attention.+ const rowErr = { id: "s-err", name: "broken", error: "Turn execution failed" };+ expect(needsAttention(rowErr, now)).toBe(true);+ });++ // Requirement 2: /tabs next finds the next working session and skips idle ones.+ it("/tabs next finds the next working session and skips idle ones", async () => {+ const now = 1_700_000_000_000;+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", status: "idle" },+ { id: "s2", name: "olive", status: "idle" },+ { id: "s3", name: "milo", status: "working" },+ { id: "s4", name: "nora", status: "idle" },+ ];+ 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("working"))).toBe(true);+ });++ // Requirement 3: /tabs next wraps once across the list.+ it("/tabs next wraps once from the end of the list", async () => {+ const now = 1_700_000_000_000;+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", status: "working" },+ { id: "s2", name: "olive", status: "idle" },+ { id: "s3", name: "nora", status: "idle" },+ ];+ // Active on s2: next checks s3 (idle), then wraps to s1 (working).+ const ctx = {+ rl: null,+ session: { agentSession: { id: "s2", name: "olive" } },+ 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, "s1");+ expect(printed.some((l) => l.includes("@eli") && l.includes("working"))).toBe(true);+ });++ // Requirement 4: when none need attention it reports and does not switch.+ it("reports and does not switch when no sessions need attention", async () => {+ const now = 1_700_000_000_000;+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", status: "idle" },+ { id: "s2", name: "olive", status: "idle" },+ { id: "s3", name: "ghost" },+ ];+ const ctx = {+ rl: null,+ session: { agentSession: { id: "s2", name: "olive" } },+ sessions,+ now,+ C: {},+ write: (line: string) => printed.push(line),+ };++ const outcome = await handleTabs(ctx, ["next"]);+ expect(outcome).toBe("handled");+ expect(resumeSpy).not.toHaveBeenCalled();+ expect(printed).toContain("no sessions need attention");+ });++ // Requirement 5: /tabs prev mirrors navigation in reverse.+ it("/tabs prev mirrors navigation in reverse and wraps backward", async () => {+ const now = 1_700_000_000_000;+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", status: "working" },+ { id: "s2", name: "olive", status: "idle" },+ { id: "s3", name: "milo", status: "idle" },+ { id: "s4", name: "nora", status: "working" },+ ];+ // Active on s3: prev checks s2 (idle), then finds s1 (working).+ const ctx = {+ rl: null,+ session: { agentSession: { id: "s3", name: "milo" } },+ sessions,+ now,+ C: {},+ write: (line: string) => printed.push(line),+ };++ const outcome = await handleTabs(ctx, ["prev"]);+ expect(outcome).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s1");+ expect(printed.some((l) => l.includes("@eli") && l.includes("working"))).toBe(true);++ // Active on s1: prev wraps backward to s4 (working).+ printed.length = 0;+ resumeSpy.mockClear();+ ctx.session.agentSession.id = "s1";+ ctx.session.agentSession.name = "eli";++ const outcomeWrap = await handleTabs(ctx, ["prev"]);+ expect(outcomeWrap).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s4");+ expect(printed.some((l) => l.includes("@nora") && l.includes("working"))).toBe(true);+ });++ // Requirement 6: /tabs 2 and /tabs <name> still switch as before.+ it("/tabs 2 and /tabs <name> switch directly by index or name", async () => {+ const resumeSpy = vi.spyOn(sessionUi, "resumeInto").mockClear();+ const printed: Array<string> = [];+ const sessions = [+ { id: "s1", name: "eli", title: "First session" },+ { id: "s2", name: "olive", title: "Second session" },+ { id: "s3", name: "milo", title: "Third session" },+ ];+ const ctx = {+ rl: null,+ session: { agentSession: { id: "s1", name: "eli" } },+ sessions,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Switching by numeric 1-based index: /tabs 2+ const resNum = await handleTabs(ctx, ["2"]);+ expect(resNum).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s2");++ // Switching by name: /tabs milo+ resumeSpy.mockClear();+ const resName = await handleTabs(ctx, ["milo"]);+ expect(resName).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s3");++ // Route through handleSessionCommand+ resumeSpy.mockClear();+ const resRouter = await handleSessionCommand(ctx, "/tabs", ["2"]);+ expect(resRouter).toBe("refresh");+ expect(resumeSpy).toHaveBeenCalledWith(null, ctx.session, "s2");++ // Invalid target reports could not resolve+ printed.length = 0;+ const resInvalid = await handleTabs(ctx, ["99"]);+ expect(resInvalid).toBe("handled");+ expect(printed).toContain("could not resolve session: 99");+ });++ it("findAttentionSession pure resolution produces identical output for identical input", () => {+ const now = 1_700_000_000_000;+ const sessions = [+ { id: "s1", name: "eli", status: "working" },+ { id: "s2", name: "olive", status: "idle" },+ ];++ const res1 = findAttentionSession(sessions, "s2", "next", now);+ const res2 = findAttentionSession(sessions, "s2", "next", now);+ expect(res1).toBe(res2);+ expect(res1?.id).toBe("s1");+ expect(attentionReason(res1)).toBe("status: working");+ });+});diff --git a/scripts/mso-agent-palette.mjs b/scripts/mso-agent-palette.mjsnew file mode 100644index 00000000..8901b2a2--- /dev/null+++ b/scripts/mso-agent-palette.mjs@@ -0,0 +1,112 @@+import { stateOf } from "./mso-agent-session-list.mjs";+import { clean } from "./tui/cells.mjs";++// Evaluates candidate relevance against normalized query string.+// Rank 1: Prefix on name.+// Rank 2: Substring on name (non-prefix).+// Rank 3: Substring on description or keywords.+// Returns null when no criteria match.+function matchScore(name, desc, keywords, q) {+ if (!q) return 1;+ if (name.startsWith(q)) return 1;+ if (name.includes(q)) return 2;+ if (desc.includes(q)) return 3;+ if (keywords.some((k) => k.includes(q))) return 3;+ return null;+}++/**+ * @param {{+ * commands?: Array<any>,+ * settings?: Array<any> | (() => Array<any>),+ * sessions?: Array<any> | (() => Array<any>),+ * query?: string,+ * colors?: Record<string, string>,+ * }} [options]+ * @returns {Array<any>}+ */+export function paletteItems({+ commands = [],+ settings = [],+ sessions = [],+ query = "",+ colors = {},+} = {}) {+ void colors;+ const raw = String(query ?? "").trim();+ const q = raw.toLowerCase().replace(/^\//, "");++ const commandList = Array.isArray(commands) ? commands : [];+ const settingList = typeof settings === "function" ? settings() : (Array.isArray(settings) ? settings : []);+ const sessionList = typeof sessions === "function" ? sessions() : (Array.isArray(sessions) ? sessions : []);++ const matchingCommands = [];+ for (let idx = 0; idx < commandList.length; idx++) {+ const cmd = commandList[idx];+ if (!cmd || !cmd.text) continue;+ const name = (cmd.name || cmd.text || "").replace(/^\//, "").toLowerCase();+ const desc = String(cmd.meta || cmd.description || "").toLowerCase();+ const keywords = Array.isArray(cmd.keywords) ? cmd.keywords.map((k) => String(k).toLowerCase()) : [];+ const score = matchScore(name, desc, keywords, q);+ if (score !== null) {+ matchingCommands.push({ item: cmd, score, order: 0, idx });+ }+ }++ const matchingSettings = [];+ for (let idx = 0; idx < settingList.length; idx++) {+ const setting = settingList[idx];+ if (!setting || (!setting.key && !setting.name)) continue;+ const key = String(setting.key || setting.name || "");+ const name = key.toLowerCase();+ const desc = String(setting.description || setting.meta || "").toLowerCase();+ const keywords = Array.isArray(setting.keywords) ? setting.keywords.map((k) => String(k).toLowerCase()) : [];+ const score = matchScore(name, desc, keywords, q);+ if (score !== null) {+ // Append a trailing space so the user can inspect or type a value without blind application.+ const item = {+ text: `/settings ${key} `,+ meta: String(setting.description || ""),+ kind: "setting",+ };+ matchingSettings.push({ item, score, order: 1, idx });+ }+ }++ const matchingSessions = [];+ for (let idx = 0; idx < sessionList.length; idx++) {+ const sess = sessionList[idx];+ if (!sess) continue;+ const rawName = clean(sess.name || sess.agentSession?.name || "").replace(/^@/, "");+ const title = clean(sess.title || sess.agentSession?.title || "");+ const stateInfo = stateOf(sess);+ const name = rawName.toLowerCase();+ const desc = `${title} ${stateInfo.label}`.toLowerCase();+ const keywords = [stateInfo.state.toLowerCase(), stateInfo.label.toLowerCase()];+ const score = matchScore(name, desc, keywords, q);+ if (score !== null) {+ const label = `@${rawName || "agent"}`;+ const meta = `${label} · ${stateInfo.label}${title ? ` · ${title}` : ""}`;+ // Sessions switch by 1-based index matching TUI tab row conventions.+ const item = {+ text: `/tabs ${idx + 1}`,+ meta,+ kind: "session",+ };+ matchingSessions.push({ item, score, order: 2, idx });+ }+ }++ // Cap settings and sessions to 5 entries each, preserving score and relative order.+ matchingSettings.sort((a, b) => a.score - b.score || a.idx - b.idx);+ const cappedSettings = matchingSettings.slice(0, 5);++ matchingSessions.sort((a, b) => a.score - b.score || a.idx - b.idx);+ const cappedSessions = matchingSessions.slice(0, 5);++ // Merge and rank: score (1 < 2 < 3), then category (commands < settings < sessions), then input index.+ const merged = [...matchingCommands, ...cappedSettings, ...cappedSessions];+ merged.sort((a, b) => a.score - b.score || a.order - b.order || a.idx - b.idx);++ return merged.map((entry) => entry.item);+}diff --git a/scripts/mso-agent-palette.test.ts b/scripts/mso-agent-palette.test.tsnew file mode 100644index 00000000..e627989a--- /dev/null+++ b/scripts/mso-agent-palette.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";+import { paletteItems } from "./mso-agent-palette.mjs";+import { slashCompletionItems } from "./mso-agent-slash.mjs";++describe("TUI palette matching, ranking, and capping", () => {+ // Requirement 1: name matches must rank above description-only matches.+ it("ranks a query matching a command name above a description match", () => {+ const commands = [+ { text: "/context", meta: "Show context/token/session status", kind: "command" },+ { text: "/status", meta: "Show model, auth, context, tokens", kind: "command" },+ ];+ const items = paletteItems({ commands, query: "status" });+ expect(items).toHaveLength(2);+ // /status matches command name prefix (rank 1), /context matches description (rank 3).+ expect(items[0].text).toBe("/status");+ expect(items[1].text).toBe("/context");+ });++ // Requirement 2: matching on description alone must still surface the candidate.+ it("returns an item when a query matches only its description", () => {+ const commands = [+ { text: "/export", meta: "Export session transcript to stdout or a file", kind: "command" },+ ];+ const items = paletteItems({ commands, query: "transcript" });+ expect(items).toHaveLength(1);+ expect(items[0].text).toBe("/export");+ expect(items[0].kind).toBe("command");+ });++ // Requirement 3: an unmatched query must produce an empty list, not a fallback list.+ it("returns an empty array when nothing matches, avoiding fallback lists", () => {+ const commands = [{ text: "/help", meta: "Show commands and shortcuts", kind: "command" }];+ const settings = [{ key: "pane", description: "Side pane content to display" }];+ const sessions = [{ name: "alpha", title: "Project Alpha", status: "idle" }];++ const items = paletteItems({ commands, settings, sessions, query: "nonexistent_query" });+ expect(items).toEqual([]);+ });++ // Requirement 4: settings and sessions must be capped at 5 each to prevent overflowing the composer.+ it("caps sessions at 5 and settings at 5 while keeping all matching commands", () => {+ const commands = Array.from({ length: 12 }, (_, i) => ({+ text: `/cmd${i}`,+ meta: `Command description ${i}`,+ kind: "command",+ }));+ const settings = Array.from({ length: 8 }, (_, i) => ({+ key: `setting${i}`,+ description: `Setting description ${i}`,+ }));+ const sessions = Array.from({ length: 9 }, (_, i) => ({+ name: `agent${i}`,+ title: `Session title ${i}`,+ status: "idle",+ }));++ const items = paletteItems({ commands, settings, sessions, query: "" });+ const commandItems = items.filter((item) => item.kind === "command");+ const settingItems = items.filter((item) => item.kind === "setting");+ const sessionItems = items.filter((item) => item.kind === "session");++ expect(commandItems).toHaveLength(12);+ expect(settingItems).toHaveLength(5);+ expect(sessionItems).toHaveLength(5);+ });++ // Requirement 5: legacy callers without new sources receive identical unregressed results.+ it("returns exactly what it returned before against a fixture when no new sources are passed", () => {+ const skills = {+ skills: [+ { id: "global-design", name: "design", trust: "local", description: "global design helper" },+ ],+ };+ const legacyFixture = [+ { text: "/session", meta: "Open the recent-session picker", kind: "command" },+ ];+ const result = slashCompletionItems(skills, "/sess", "/home/operator");+ expect(result).toEqual(legacyFixture);+ });++ // Requirement 6: setting and session items must match the slash completion item shape key by key.+ it("returns items matching the slash item shape key by key", () => {+ const slashItem = slashCompletionItems({ skills: [] }, "/help", "/home/operator")[0];+ const slashKeys = Object.keys(slashItem).sort();++ const settings = [{ key: "pane", description: "Side pane content to display" }];+ const sessions = [{ name: "worker", title: "Build site", status: "idle" }];+ const commands = [{ text: "/help", meta: "Show commands", kind: "command" }];++ const items = paletteItems({ commands, settings, sessions, query: "" });+ expect(items.length).toBeGreaterThanOrEqual(3);++ for (const item of items) {+ const itemKeys = Object.keys(item).sort();+ expect(itemKeys).toEqual(slashKeys);+ }+ });++ // Ranked query demonstration for "pan".+ it("ranks setting pane prefix above description match for query pan", () => {+ const settings = [{ key: "pane", description: "Side pane content to display", keywords: ["sidebar"] }];+ const commands = [{ text: "/diff", meta: "Show unified diff in pane", kind: "command" }];+ const items = paletteItems({ commands, settings, query: "pan" });++ expect(items).toHaveLength(2);+ // Setting pane matches prefix on name (rank 1), command diff matches description (rank 3).+ expect(items[0]).toEqual({+ text: "/settings pane ",+ meta: "Side pane content to display",+ kind: "setting",+ });+ expect(items[1]).toEqual({+ text: "/diff",+ meta: "Show unified diff in pane",+ kind: "command",+ });+ });++ // Ranked query demonstration for "work".+ it("ranks session worker prefix above session working description for query work", () => {+ const sessions = [+ { name: "agent", title: "Refactor", status: "working" },+ { name: "worker", title: "Build site", status: "idle" },+ ];+ const items = paletteItems({ sessions, query: "work" });++ expect(items).toHaveLength(2);+ // Worker matches prefix on name (rank 1), agent matches state label "working" in description (rank 3).+ expect(items[0].text).toBe("/tabs 2");+ expect(items[0].kind).toBe("session");+ expect(items[0].meta).toContain("@worker");+ expect(items[1].text).toBe("/tabs 1");+ expect(items[1].kind).toBe("session");+ expect(items[1].meta).toContain("@agent");+ });+});diff --git a/scripts/mso-agent-pane-width.test.ts b/scripts/mso-agent-pane-width.test.tsnew file mode 100644index 00000000..ed76eca0--- /dev/null+++ b/scripts/mso-agent-pane-width.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from "vitest";+import { paneWidth } from "./mso-agent-pane.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";+import {+ SETTINGS,+ defaultSettings,+ formatSettingsTable,+ loadSettings,+} from "./mso-agent-settings.mjs";+import {+ applySettings,+ handleSettingsCommand,+} from "./mso-agent-cmd-settings.mjs";++describe("TUI pane width configuration end to end", () => {+ it("1. default is 100 and paneWidth(120) unchanged", () => {+ // Verifies default configuration preserves existing baseline behaviour+ const defaults: Record<string, any> = defaultSettings();+ expect(defaults.minwidth).toBe(100);++ // Byte-identical check: 120 * 0.35 = 42 without options+ const widthUnconfigured = paneWidth(120);+ expect(widthUnconfigured).toBe(42);++ const widthExplicitDefault = paneWidth(120, { minColumns: 100 });+ expect(widthExplicitDefault).toBe(42);+ });++ it("2. paneWidth(90) is 0 with the default and non-zero with minColumns: 80", () => {+ // 90 columns is below default threshold 100, yielding 0 width+ expect(paneWidth(90)).toBe(0);+ expect(paneWidth(90, { minColumns: 100 })).toBe(0);++ // Lowering threshold to 80 allows narrower terminal to allocate 31 columns+ const widthLowered = paneWidth(90, { minColumns: 80 });+ expect(widthLowered).toBe(31);+ expect(widthLowered).toBeGreaterThan(0);++ // Integration check: mountScreenLoop reflects session.paneMinColumns+ const fakeStdout = {+ isTTY: true,+ columns: 90,+ rows: 24,+ write() {},+ };+ const defaultSession = { paneKind: "todos" };+ const loopDefault = mountScreenLoop({+ session: defaultSession,+ enabled: true,+ output: fakeStdout,+ input: { on() {}, off() {} },+ });+ expect(loopDefault.geometry().pWidth).toBe(0);+ loopDefault.dispose();++ const customSession = { paneKind: "todos", paneMinColumns: 80 };+ const loopCustom = mountScreenLoop({+ session: customSession,+ enabled: true,+ output: fakeStdout,+ input: { on() {}, off() {} },+ });+ expect(loopCustom.geometry().pWidth).toBe(31);+ loopCustom.dispose();+ });++ it("3. the setting rejects 59 and 201 with a range message", async () => {+ // Verify CLI rejects bounds below 60 and above 200 with an informative range message+ const printed: string[] = [];+ const ctx = {+ session: {},+ C: {},+ write: (line: string) => printed.push(line),+ };++ await handleSettingsCommand(ctx, ["minwidth", "59"]);+ const reject59 = printed[printed.length - 1];+ expect(reject59).toContain("invalid value \"59\" for minwidth");+ expect(reject59).toContain("accepted range is 60 to 200");++ await handleSettingsCommand(ctx, ["minwidth", "201"]);+ const reject201 = printed[printed.length - 1];+ expect(reject201).toContain("invalid value \"201\" for minwidth");+ expect(reject201).toContain("accepted range is 60 to 200");++ // Also verify settings file loader rejects out-of-range bounds+ const loaded59 = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ minwidth: 59 }),+ });+ expect(loaded59.minwidth).toBe(100);+ expect(loaded59.warnings.some((w: string) => w.includes("invalid value \"59\""))).toBe(true);++ const loaded201 = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ minwidth: 201 }),+ });+ expect(loaded201.minwidth).toBe(100);+ expect(loaded201.warnings.some((w: string) => w.includes("invalid value \"201\""))).toBe(true);+ });++ it("4. applySettings sets the session field from a saved file", () => {+ // Config loader handles both setting key and dotted path notation+ const loadedFromPath = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ "session.pane_min_columns": 85 }),+ });+ expect(loadedFromPath.minwidth).toBe(85);++ const session: any = {};+ applySettings(session, loadedFromPath);+ expect(session.paneMinColumns).toBe(85);++ const loadedFromKey = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ minwidth: 75 }),+ });+ expect(loadedFromKey.minwidth).toBe(75);++ applySettings(session, loadedFromKey);+ expect(session.paneMinColumns).toBe(75);+ });++ it("5. a numeric entry renders in the settings table within width", () => {+ // Table layout fits within restricted column width without line overflow+ const formattedNarrow = formatSettingsTable(SETTINGS, defaultSettings(), { width: 50 });+ const narrowLines = formattedNarrow.split("\n");+ for (const line of narrowLines) {+ expect(line.length).toBeLessThanOrEqual(50);+ }++ const formattedNormal = formatSettingsTable(+ SETTINGS,+ { minwidth: 80 },+ { width: 80 },+ );+ expect(formattedNormal).toContain("minwidth");+ expect(formattedNormal).toContain("80");+ const normalLines = formattedNormal.split("\n");+ for (const line of normalLines) {+ expect(line.length).toBeLessThanOrEqual(80);+ }+ });+});diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjsindex 9b23817e..7c1751dd 100644--- a/scripts/mso-agent-screen-loop.mjs+++ b/scripts/mso-agent-screen-loop.mjs@@ -104,7 +104,8 @@ export function mountScreenLoop({const viewRows = Math.max(0, rows - panel.length - reservation);const tabRowY = railWidth > 0 ? -1 : viewRows + (hasSep ? 1 : 0);const kind = session?.paneKind && session.paneKind !== "off" ? session.paneKind : null;- const pWidth = kind ? paneWidth(cols) : 0;+ // Pass configured threshold so terminals narrower than 100 columns can show the pane+ const pWidth = kind ? paneWidth(cols, { minColumns: session?.paneMinColumns ?? 100 }) : 0;const transWidth = cols - pWidth - railWidth;return { cols, rows, panel, viewRows, tabRowY, pWidth, transWidth, railWidth, kind, promptRows: reservation };};@@ -126,7 +127,7 @@ export function mountScreenLoop({const sync = () => {commitStream(viewport);- setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth })));+ setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" })));paint();};@@ -179,7 +180,7 @@ export function mountScreenLoop({const suspend = panelSuspend.suspend;const resume = panelSuspend.resume;- setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth })));+ setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" })));paint();const loop = {diff --git a/scripts/mso-agent-session-list.mjs b/scripts/mso-agent-session-list.mjsindex 192fd5ae..68afbe6b 100644--- a/scripts/mso-agent-session-list.mjs+++ b/scripts/mso-agent-session-list.mjs@@ -17,23 +17,12 @@ export function stateOf(row, now = Date.now()) {}// Explicit failure or error status takes precedence.- if (row.error || ["error", "errored", "failed"].includes(String(row.status || ""))) {- return { state: "errored", label: "errored" };- }-+ if (row.error || ["error", "errored", "failed"].includes(String(row.status || ""))) return { state: "errored", label: "errored" };// Explicit waiting or prompt-ready state.- if (["waiting", "waiting for input"].includes(String(row.status || ""))) {- return { state: "waiting", label: "waiting for input" };- }-+ if (["waiting", "waiting for input"].includes(String(row.status || ""))) return { state: "waiting", label: "waiting for input" };// Explicit running or busy status flag.- if (["working", "busy", "running"].includes(String(row.status || ""))) {- return { state: "working", label: "working" };- }-- if (row.status === "idle") {- return { state: "idle", label: "idle" };- }+ if (["working", "busy", "running"].includes(String(row.status || ""))) return { state: "working", label: "working" };+ if (row.status === "idle") 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;@@ -114,15 +103,9 @@ export function sessionTable(rows, { colors = {}, width = 80, activeId = null, nconst nameW = Math.max(8, Math.min(16, Math.floor(available * 0.26)));const titleW = Math.max(4, available - nameW - stateW - actW);- const cBold = colors?.bold || "";- const cBlue = colors?.blue || "";- const cDim = colors?.dim || "";- const cReset = colors?.reset || "";-- const hName = formatCell(" NAME", nameW);- const hTitle = formatCell("TITLE", titleW);- const hState = formatCell("STATE", stateW);- const hAct = formatCell("ACTIVITY", actW);+ const cBold = colors?.bold || "", cBlue = colors?.blue || "", cDim = colors?.dim || "", cReset = colors?.reset || "";+ const hName = formatCell(" NAME", nameW), hTitle = formatCell("TITLE", titleW);+ const hState = formatCell("STATE", stateW), hAct = formatCell("ACTIVITY", actW);const headerLine = cBold? `${cBold}${hName.visible}${cReset}${hName.pad}${sep}${cBold}${hTitle.visible}${cReset}${hTitle.pad}${sep}${cBold}${hState.visible}${cReset}${hState.pad}${sep}${cBold}${hAct.visible}${cReset}${hAct.pad}`@@ -143,28 +126,87 @@ export function sessionTable(rows, { colors = {}, width = 80, activeId = null, nconst stamp = row?.updatedAt || row?.createdAt;const actText = stamp ? formatSessionModified(stamp, now) : "unknown";- const cellName = formatCell(nameText, nameW);- const cellTitle = formatCell(titleText, titleW);- const cellState = formatCell(stateInfo.label, stateW);- const cellAct = formatCell(actText, actW);-+ const cellName = formatCell(nameText, nameW), cellTitle = formatCell(titleText, titleW);+ const cellState = formatCell(stateInfo.label, stateW), cellAct = formatCell(actText, actW);const sc = stateColor(stateInfo.state, colors);- const nameStyled = isCurrent && cBold- ? `${cBold}${cBlue}${cellName.visible}${cReset}${cellName.pad}`- : `${cellName.visible}${cellName.pad}`;- const titleStyled = isCurrent && cBold- ? `${cBold}${cellTitle.visible}${cReset}${cellTitle.pad}`- : `${cellTitle.visible}${cellTitle.pad}`;- const stateStyled = sc && cReset- ? `${sc}${cellState.visible}${cReset}${cellState.pad}`- : `${cellState.visible}${cellState.pad}`;- const actStyled = cDim && cReset- ? `${cDim}${cellAct.visible}${cReset}${cellAct.pad}`- : `${cellAct.visible}${cellAct.pad}`;+ const nameStyled = isCurrent && cBold ? `${cBold}${cBlue}${cellName.visible}${cReset}${cellName.pad}` : `${cellName.visible}${cellName.pad}`;+ const titleStyled = isCurrent && cBold ? `${cBold}${cellTitle.visible}${cReset}${cellTitle.pad}` : `${cellTitle.visible}${cellTitle.pad}`;+ const stateStyled = sc && cReset ? `${sc}${cellState.visible}${cReset}${cellState.pad}` : `${cellState.visible}${cellState.pad}`;+ const actStyled = cDim && cReset ? `${cDim}${cellAct.visible}${cReset}${cellAct.pad}` : `${cellAct.visible}${cellAct.pad}`;lines.push(`${nameStyled}${sep}${titleStyled}${sep}${stateStyled}${sep}${actStyled}`);});return lines;}++/**+ * Pure predicate determining whether a session row needs attention.+ * A session needs attention if its derived state is "working" (updated within the+ * threshold) or carries an explicit error state ("errored").+ * We intentionally exclude "unknown": missing activity data means we do not know,+ * and jumping to a session on a guess is the dishonesty the table avoids.+ *+ * @param {any} row+ * @param {number} [now]+ * @returns {boolean}+ */+export function needsAttention(row, _now = Date.now()) {+ // Deliberately does NOT use stateOf. That function derives working/idle from updatedAt, and updatedAt+ // is written at turn COMPLETION, not during a turn (persistSession runs at the end, see+ // docs/AGENT-ACTIVITY-SIGNAL.md). So the timestamp derivation is inverted: a session whose turn just+ // ended reads as working for 60 seconds, and a session streaming for three minutes reads as idle.+ // Jumping on that would send the user to the wrong session, which is worse than not jumping.+ //+ // Only an explicit status is trusted here, because only an explicit status came from the server+ // saying so. Absent one, the honest answer is "cannot tell", and this returns false.+ if (!row || typeof row !== "object") return false;+ const status = String(row.status || "");+ if (row.error || ["error", "errored", "failed"].includes(status)) return true;+ return ["working", "busy", "running"].includes(status);+}++/**+ * Honest description of why the session was selected, avoiding unearned certainty.+ *+ * @param {any} row+ * @param {number} [now]+ * @returns {string}+ */+export function attentionReason(row) {+ // Reports the reason needsAttention returned true, and nothing else. It must not mention a+ // timestamp, because needsAttention does not consider timestamps: saying "updated 12s ago" would+ // imply the jump was based on freshness, which is the inverted signal this deliberately avoids.+ if (!row || typeof row !== "object") return "unknown";+ if (row.error || ["error", "errored", "failed"].includes(String(row.status || ""))) {+ return `status: ${row.status || "errored"}`;+ }+ return `status: ${String(row.status || "working")}`;+}++/**+ * Stable pure resolution of the next or previous session needing attention.+ * Walks forward or backward from the active session index, wrapping once.+ *+ * @param {Array<any>} rows+ * @param {string | number | null} [activeId]+ * @param {"next" | "prev" | "previous"} [direction]+ * @param {number} [now]+ * @returns {any | null}+ */+export function findAttentionSession(rows, activeId = null, direction = "next", now = Date.now()) {+ if (!Array.isArray(rows) || rows.length === 0) return null;+ const isPrev = direction === "prev" || direction === "previous";+ const currentIdx = rows.findIndex((r) => isSessionActive(r, activeId));+ const count = rows.length;+ const start = currentIdx >= 0 ? currentIdx : (isPrev ? 0 : -1);+ const limit = currentIdx >= 0 ? count - 1 : count;+ for (let step = 1; step <= limit; step++) {+ const offset = isPrev ? -step : step;+ const idx = ((start + offset) % count + count) % count;+ if (needsAttention(rows[idx], now)) return rows[idx];+ }+ return null;+}+diff --git a/scripts/mso-agent-settings-entries.mjs b/scripts/mso-agent-settings-entries.mjsnew file mode 100644index 00000000..d1c7a99f--- /dev/null+++ b/scripts/mso-agent-settings-entries.mjs@@ -0,0 +1,39 @@+// The registry entries, kept apart from the loader so the loader stays under the line ratchet.+// Every entry here must have a real consumer: a setting that changes nothing is worse than no setting,+// because it teaches the user that the settings panel is decoration.++export const SETTINGS = [+ {+ category: "Session", key: "pane", path: "session.pane",+ description: "Side pane content to display", default: "off",+ values: ["todos", "diff", "files", "mcp", "context", "off"],+ keywords: ["sidebar", "panel", "paneKind"],+ },+ {+ category: "Session", key: "statusbar", path: "session.status_bar",+ description: "Dynamic status bar at bottom of prompt", default: "on",+ values: ["on", "off"], keywords: ["status", "bar", "statusbar"],+ },+ {+ category: "Tabs", key: "layout", path: "tabs.layout",+ description: "Tab bar layout orientation", default: "horizontal",+ values: ["horizontal", "vertical"],+ keywords: ["sidebar", "rail", "tabs", "tabLayout"],+ },+ {+ category: "Session", key: "minwidth", path: "session.pane_min_columns",+ description: "Minimum terminal width to show side pane", default: 100,+ min: 60, max: 200, keywords: ["minwidth", "min_columns", "pane_min_columns"],+ },+ {+ category: "Session", key: "grouping", path: "session.grouping",+ description: "Collapse repeated tool calls in transcript", default: "none",+ values: ["none", "auto"], keywords: ["group", "grouping", "collapse"],+ },+ {+ category: "Session", key: "verbosity", path: "session.verbosity",+ // Honesty rule: controls footer density only, not transcript detail+ description: "Status footer density (low, medium, high); does not affect transcript detail", default: "high",+ values: ["low", "medium", "high"], keywords: ["verbosity", "status", "footer", "density"],+ },+];diff --git a/scripts/mso-agent-settings-tabs.test.ts b/scripts/mso-agent-settings-tabs.test.tsnew file mode 100644index 00000000..80acb652--- /dev/null+++ b/scripts/mso-agent-settings-tabs.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";+import {+ SETTINGS,+ defaultSettings,+ formatSettingsTable,+ loadSettings,+} from "./mso-agent-settings.mjs";+import { applySettings, handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";++describe("tabs.layout preference registry integration", () => {+ it("1. the entry appears in the table and in defaultSettings()", () => {+ const defaults: Record<string, any> = defaultSettings();+ // Default layout must default to horizontal row so existing behavior is preserved+ expect(defaults.layout).toBe("horizontal");++ const entry = SETTINGS.find((e) => e.key === "layout");+ expect(entry).toBeDefined();+ expect(entry?.category).toBe("Tabs");+ expect(entry?.path).toBe("tabs.layout");+ expect(entry?.values).toEqual(["horizontal", "vertical"]);+ expect(entry?.keywords).toContain("sidebar");+ expect(entry?.keywords).toContain("rail");++ const table = formatSettingsTable(SETTINGS, defaults, { width: 80 });+ expect(table).toContain("layout");+ expect(table).toContain("horizontal");+ expect(table).toContain("Tab bar layout orientation");+ });++ it("2. /settings layout vertical sets session.tabsLayout in live session", async () => {+ const printed: string[] = [];+ const session: Record<string, any> = { tabsLayout: "horizontal" };+ const ctx = {+ session,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Setting layout should immediately update session without waiting for restart+ await handleSettingsCommand(ctx, ["layout", "vertical"]);+ expect(session.tabsLayout).toBe("vertical");+ expect(printed.some((line) => line.includes("setting layout = vertical"))).toBe(true);++ // Using the full dotted path tabs.layout should also resolve and set session+ await handleSettingsCommand(ctx, ["tabs.layout", "horizontal"]);+ expect(session.tabsLayout).toBe("horizontal");+ expect(printed.some((line) => line.includes("setting layout = horizontal"))).toBe(true);+ });++ it("3. applySettings sets tabsLayout from a saved file", () => {+ // When saved with dotted path key in settings JSON file+ const loadedFromPath = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ "tabs.layout": "vertical" }),+ });+ const sessionA: Record<string, any> = {};+ applySettings(sessionA, loadedFromPath);+ expect(sessionA.tabsLayout).toBe("vertical");++ // When saved with simple key in settings JSON file+ const loadedFromKey = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ layout: "vertical" }),+ });+ const sessionB: Record<string, any> = {};+ applySettings(sessionB, loadedFromKey);+ expect(sessionB.tabsLayout).toBe("vertical");++ // Direct object passed to applySettings+ const sessionC: Record<string, any> = {};+ applySettings(sessionC, { "tabs.layout": "vertical" });+ expect(sessionC.tabsLayout).toBe("vertical");+ });++ it("4. an invalid value is refused with the valid list, not silently coerced", async () => {+ const printed: string[] = [];+ const session: Record<string, any> = { tabsLayout: "horizontal" };+ const ctx = {+ session,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Refuse invalid layout option without altering running session+ await handleSettingsCommand(ctx, ["layout", "diagonal"]);+ expect(session.tabsLayout).toBe("horizontal");+ const warning = printed.find((line) => line.includes("invalid value"));+ expect(warning).toBeDefined();+ expect(warning).toContain("horizontal, vertical");+ });++ it("5. the other two entries still work alongside layout", async () => {+ const printed: string[] = [];+ const session: Record<string, any> = {+ paneKind: "off",+ statusBar: true,+ tabsLayout: "horizontal",+ };+ const ctx = {+ session,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Update pane+ await handleSettingsCommand(ctx, ["pane", "diff"]);+ expect(session.paneKind).toBe("diff");++ // Update statusbar+ await handleSettingsCommand(ctx, ["statusbar", "off"]);+ expect(session.statusBar).toBe(false);++ // Apply settings containing all three+ const targetSession: Record<string, any> = {};+ applySettings(targetSession, {+ pane: "todos",+ statusbar: "on",+ layout: "vertical",+ });+ expect(targetSession.paneKind).toBe("todos");+ expect(targetSession.statusBar).toBe(true);+ expect(targetSession.tabsLayout).toBe("vertical");+ });+});diff --git a/scripts/mso-agent-settings.mjs b/scripts/mso-agent-settings.mjsindex 48adf624..02303474 100644--- a/scripts/mso-agent-settings.mjs+++ b/scripts/mso-agent-settings.mjs@@ -11,19 +11,8 @@ import {// Preferences registry: non-keybind TUI preferences with live behavior today.// Evaluated candidates without active consumers are omitted to avoid phantom settings.-export const SETTINGS = [- {- category: "Session", key: "pane", path: "session.pane",- description: "Side pane content to display", default: "off",- values: ["todos", "diff", "files", "mcp", "context", "off"],- keywords: ["sidebar", "panel", "paneKind"],- },- {- category: "Session", key: "statusbar", path: "session.status_bar",- description: "Dynamic status bar at bottom of prompt", default: "on",- values: ["on", "off"], keywords: ["status", "bar", "statusbar"],- },-];+import { SETTINGS } from "./mso-agent-settings-entries.mjs";+export { SETTINGS };let cachedState = null;const readTextFile = /** @type {(p: string, enc?: string) => string} */ ((p, enc = "utf8") => fs.readFileSync(p, enc));@@ -81,6 +70,12 @@ export function loadSettings({ path: filePath = defaultSettingsPath(), readFileif (entry.values && !entry.values.includes(val)) {warnings.push(`invalid value "${val}" for ${entry.key}, falling back to default "${entry.default}"`);resolved[entry.key] = entry.default;+ } else if (typeof entry.min === "number" && typeof entry.max === "number") {+ // Enforce numeric range so terminal narrowness cannot collapse or dominate the transcript+ const num = Number(val);+ const bad = !Number.isFinite(num) || num < entry.min || num > entry.max;+ if (bad) warnings.push(`invalid value "${val}" for ${entry.key}, falling back to default "${entry.default}"`);+ resolved[entry.key] = bad ? entry.default : Math.round(num);} else {resolved[entry.key] = val;}diff --git a/scripts/mso-agent-slash.mjs b/scripts/mso-agent-slash.mjsindex 598befa6..7dfbf72d 100644--- a/scripts/mso-agent-slash.mjs+++ b/scripts/mso-agent-slash.mjs@@ -1,4 +1,6 @@import process from "node:process";+import { paletteItems } from "./mso-agent-palette.mjs";+import { SETTINGS } from "./mso-agent-settings.mjs";import {currentSkillProject,resolveSlashSkill,@@ -163,6 +165,7 @@ export function slashCompletionItems(input,cwd = process.cwd(),session = /** @type {any} */ (null),+ options = /** @type {any} */ (null),) {const text = String(input || "").trimStart();if (!text.startsWith("/") || /\s/.test(text)) return [];@@ -183,5 +186,17 @@ export function slashCompletionItems(...projectSkills.filter((item) => !builtinNames.has(item.text)),...globalSkills.filter((item) => !builtinNames.has(item.text)),];- return all.filter((item) => item.text.toLowerCase().startsWith(query));+ // Backward compatibility: when new sources are not passed, retain exact legacy filtering.+ if (!options || (options.settings === undefined && options.sessions === undefined)) {+ return all.filter((item) => item.text.toLowerCase().startsWith(query));+ }+ const settings = options.settings === true ? SETTINGS : (options.settings || []);+ const sessions = typeof options.sessions === "function" ? options.sessions() : (options.sessions || []);+ return paletteItems({+ commands: all,+ settings,+ sessions,+ query: text,+ colors: options.colors,+ });}diff --git a/scripts/mso-agent-status-verbosity.test.ts b/scripts/mso-agent-status-verbosity.test.tsnew file mode 100644index 00000000..56efa3f2--- /dev/null+++ b/scripts/mso-agent-status-verbosity.test.ts@@ -0,0 +1,149 @@+import os from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { composerFooter } from "./mso-agent-layout.mjs";+import { resolveVerbosity, statusParts } from "./mso-agent-status.mjs";+import { SETTINGS, loadSettings } from "./mso-agent-settings.mjs";+import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";++const colors = { blue: "", bold: "", reset: "", dim: "", c: "", cyan: "", warn: "", err: "" };++function makeSession(verbosity?: string, cwd?: string): any {+ return {+ permission: "ask",+ statusBar: true,+ verbosity,+ history: [+ { role: "user", text: "hello" },+ { role: "assistant", text: "hi" },+ { role: "user", text: "do something" },+ ],+ usage: { inputTokens: 1200, outputTokens: 350, totalTokens: 1550 },+ state: {+ config: { provider: "openai-codex", model: "gpt-5.6-terra" },+ modelMeta: { context: 128000 },+ },+ agentSession: {+ id: "session-test-id",+ name: "agent",+ title: "Review auth",+ compactThresholdTokens: 700000,+ estimatedTokens: 120,+ },+ cwd: cwd || path.join(os.homedir(), "projects", "mso"),+ };+}++describe("MSO Agent status verbosity setting", () => {+ // Test 1: High verbosity (default) must reproduce existing footer output exactly+ it("default high produces byte-identical footer to recorded fixtures at 60, 100, 160 columns", () => {+ const fixture60 = "mode ask · openai-codex/gpt-5.6-terra · ctx ~27/128k 0% ·…";+ const fixture100 = "mode ask · openai-codex/gpt-5.6-terra · ctx ~27/128k 0% · session ~120/700k · tokens 1.6k · turns…";+ const fixture160 = "mode ask · openai-codex/gpt-5.6-terra · ctx ~27/128k 0% · session ~120/700k · tokens 1.6k · turns 2 · session Review auth · ~/projects/mso · Tab cycle";++ // Unset verbosity uses default high+ const sessionDefault = makeSession(undefined);+ expect(composerFooter(sessionDefault, colors, 60)).toBe(fixture60);+ expect(composerFooter(sessionDefault, colors, 100)).toBe(fixture100);+ expect(composerFooter(sessionDefault, colors, 160)).toBe(fixture160);++ // Explicit high matches recorded fixtures byte-for-byte+ const sessionHigh = makeSession("high");+ expect(composerFooter(sessionHigh, colors, 60)).toBe(fixture60);+ expect(composerFooter(sessionHigh, colors, 100)).toBe(fixture100);+ expect(composerFooter(sessionHigh, colors, 160)).toBe(fixture160);+ });++ // Test 2: Low verbosity drops static metadata (model, cwd) while preserving live state+ it("low drops provider/model and cwd and still shows mode, context and turns", () => {+ const sessionLow = makeSession("low");+ const parts = statusParts(sessionLow);+ const joined = parts.join(" · ");++ // Model and cwd must be omitted to save space on narrow terminals+ expect(joined).not.toContain("openai-codex/gpt-5.6-terra");+ expect(joined).not.toContain("~/projects/mso");++ // Live conversation telemetry must be preserved+ expect(joined).toContain("ctx ~27/128k 0%");+ expect(joined).toContain("turns 2");++ // Composer footer must show permission mode, context, turns, and omit model and cwd+ const footer = composerFooter(sessionLow, colors, 100);+ expect(footer).toContain("mode ask");+ expect(footer).toContain("ctx ~27/128k 0%");+ expect(footer).toContain("turns 2");+ expect(footer).not.toContain("openai-codex/gpt-5.6-terra");+ expect(footer).not.toContain("~/projects/mso");+ });++ // Test 3: Medium verbosity drops only cwd+ it("medium drops only cwd", () => {+ const sessionMedium = makeSession("medium");+ const parts = statusParts(sessionMedium);+ const joined = parts.join(" · ");++ // Model remains visible in medium+ expect(joined).toContain("openai-codex/gpt-5.6-terra");+ // Only cwd is dropped+ expect(joined).not.toContain("~/projects/mso");++ // Other status chips remain intact+ expect(joined).toContain("ctx ~27/128k 0%");+ expect(joined).toContain("turns 2");+ expect(joined).toContain("session Review auth");++ const footer = composerFooter(sessionMedium, colors, 160);+ expect(footer).toContain("mode ask");+ expect(footer).toContain("openai-codex/gpt-5.6-terra");+ expect(footer).not.toContain("~/projects/mso");+ });++ // Test 4: Unknown setting values are rejected and safely fall back+ it("an unknown value is refused", async () => {+ // Registry definition specifies valid values+ const entry = SETTINGS.find((s) => s.key === "verbosity");+ expect(entry).toBeDefined();+ expect(entry?.values).toEqual(["low", "medium", "high"]);+ expect(entry?.default).toBe("high");++ // CLI settings command refuses invalid value+ const printed: string[] = [];+ const fakeCtx: any = {+ session: makeSession("high"),+ C: {},+ width: 80,+ write: (msg: string) => printed.push(msg),+ };+ await handleSettingsCommand(fakeCtx, ["verbosity", "ultra"]);+ expect(printed.some((msg) => msg.includes('invalid value "ultra" for verbosity'))).toBe(true);+ expect(fakeCtx.session.verbosity).toBe("high");++ // Loading settings from disk with invalid value falls back to default with a warning+ const loaded = loadSettings({+ path: "/fake/settings.json",+ readFile: () => JSON.stringify({ verbosity: "invalid-level" }),+ });+ expect(loaded.verbosity).toBe("high");+ expect(loaded.warnings.some((w: string) => w.includes('invalid value "invalid-level" for verbosity'))).toBe(true);++ // Pure helper falls back to high+ expect(resolveVerbosity({ verbosity: "unknown" })).toBe("high");+ expect(resolveVerbosity(null, { verbosity: "unknown" })).toBe("high");+ });++ // Test 5: Footer never exceeds the requested terminal width in any verbosity mode+ it("the footer never exceeds the requested width in any mode", () => {+ const modes = ["low", "medium", "high"];+ const widths = [30, 45, 60, 80, 100, 120, 160];++ for (const mode of modes) {+ const session = makeSession(mode);+ for (const w of widths) {+ const line = composerFooter(session, colors, w);+ // Visible character width must never exceed the target column limit+ expect(Array.from(line).length).toBeLessThanOrEqual(w);+ }+ }+ });+});diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjsindex de9c82de..822404c7 100644--- a/scripts/mso-agent-status.mjs+++ b/scripts/mso-agent-status.mjs@@ -60,7 +60,19 @@ function skillStatus(session) {return null;}-export function statusParts(session, cwd = process.cwd()) {+// Resolves status verbosity level: "low", "medium", or "high" (default).+// Falls back to "high" for unknown values so footer rendering never breaks.+export function resolveVerbosity(session, options = {}) {+ const raw = options?.verbosity || session?.verbosity || session?.statusVerbosity;+ const v = String(raw || "").toLowerCase().trim();+ if (v === "low" || v === "medium") return v;+ return "high";+}++export function statusParts(session, cwd = process.cwd(), options = {}) {+ const opts = (typeof cwd === "object" && cwd !== null) ? cwd : options;+ const targetCwd = (typeof cwd === "string" && cwd !== process.cwd()) ? cwd : (session?.cwd || cwd);+ const verbosity = resolveVerbosity(session, opts);const provider = String(session?.state?.config?.provider || "—");const model = String(session?.state?.config?.model || "—");const ctx = contextStatus(session?.history, session?.state?.modelMeta);@@ -71,8 +83,14 @@ export function statusParts(session, cwd = process.cwd()) {const elapsed = Number(session?.lastElapsedMs || 0);const skill = skillStatus(session);const routing = session?.lastRouting || null;+ // Mid-conversation situational awareness prioritizes mode, context usage,+ // and turn count. Working directory is static context that clutters narrow+ // viewports, so "medium" drops cwd first. Model and provider are also static,+ // so "low" drops provider/model and cwd while preserving live context and turns.+ const showModel = verbosity !== "low";+ const showCwd = verbosity === "high";return [- `${provider}/${model}`,+ showModel ? `${provider}/${model}` : null,skill ? `skill ${skill.state === "invoked" ? "✓" : "◆"} /${skill.name}${skill.state === "queued" ? " queued" : skill.state === "invoking" ? " invoking" : ""}` : null,ctx.limit ? `ctx ~${compactNumber(ctx.used)}/${compactNumber(ctx.limit)} ${ctx.percent}%` : `ctx ~${compactNumber(ctx.used)}/?`,session?.agentSession?.compactThresholdTokens ? `session ~${compactNumber(session.agentSession.estimatedTokens)}/${compactNumber(session.agentSession.compactThresholdTokens)}` : null,@@ -84,7 +102,7 @@ export function statusParts(session, cwd = process.cwd()) {elapsed > 0 ? `${(elapsed / 1000).toFixed(elapsed >= 10_000 ? 0 : 1)}s` : null,`@${sessionName}`,`session ${sessionTitle}`,- homeShort(cwd),+ showCwd ? homeShort(targetCwd) : null,].filter(Boolean);}diff --git a/scripts/mso-agent-transcript-grouping.test.ts b/scripts/mso-agent-transcript-grouping.test.tsnew file mode 100644index 00000000..a937a901--- /dev/null+++ b/scripts/mso-agent-transcript-grouping.test.ts@@ -0,0 +1,154 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";+import { groupToolRows, transcriptLines } from "./mso-agent-transcript.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";+import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";++class FakeOutput extends EventEmitter {+ isTTY = true;+ columns = 80;+ rows = 24;+ chunks: string[] = [];+ write(str: string) {+ this.chunks.push(String(str));+ return true;+ }+}++function makeFixture() {+ return {+ history: [+ { role: "user", text: "Please read the files" },+ {+ role: "assistant",+ text: "Reading three files",+ toolUses: [+ { id: "call_1", name: "fs_read", input: { path: "a.txt" } },+ { id: "call_2", name: "fs_read", input: { path: "b.txt" } },+ { id: "call_3", name: "fs_read", input: { path: "c.txt" } },+ ],+ },+ {+ role: "tool",+ results: [+ { id: "call_1", content: "alpha" },+ { id: "call_2", content: "beta" },+ { id: "call_3", content: "gamma" },+ ],+ },+ ],+ };+}++describe("MSO Agent Transcript Tool Grouping", () => {+ it("1. default output is identical to before for a fixture with repeated tool calls, matching recorded expected string", () => {+ const fixture = makeFixture();+ const expected = [+ "[user] Please read the files",+ "[assistant] Reading three files",+ '[assistant] call fs_read {"path":"a.txt"}',+ '[assistant] call fs_read {"path":"b.txt"}',+ '[assistant] call fs_read {"path":"c.txt"}',+ "[tool] fs_read: alpha",+ "[tool] fs_read: beta",+ "[tool] fs_read: gamma",+ ];+ // With no options passed, transcriptLines behaves identically to before+ expect(transcriptLines(fixture)).toEqual(expected);+ // Passing groupTools: false explicitly yields the exact same array+ expect(transcriptLines(fixture, { groupTools: false })).toEqual(expected);+ });++ it("2. auto collapses consecutive same-tool rows into one counted row", () => {+ const fixture = makeFixture();+ const lines = transcriptLines(fixture, { groupTools: true, maxPerTool: 1 });+ expect(lines).toContain("[tool] fs_read (3 calls)");+ expect(lines).not.toContain("[tool] fs_read: alpha");+ expect(lines).not.toContain("[tool] fs_read: beta");+ expect(lines).not.toContain("[tool] fs_read: gamma");+ expect(lines[0]).toBe("[user] Please read the files");+ });++ it("3. an error row is never collapsed regardless of the setting", () => {+ const fixtureWithError = {+ history: [+ {+ role: "assistant",+ toolUses: [+ { id: "call_1", name: "fs_read" },+ { id: "call_2", name: "fs_read" },+ { id: "call_3", name: "fs_read" },+ ],+ },+ {+ role: "tool",+ results: [+ { id: "call_1", content: "alpha" },+ { id: "call_2", content: "error: file not found", isError: true },+ { id: "call_3", content: "gamma" },+ ],+ },+ ],+ };+ // Tool call with failure rendered under groupTools: true must remain visible+ const lines = transcriptLines(fixtureWithError, { groupTools: true });+ expect(lines.some((l) => l.includes("error: file not found"))).toBe(true);+ expect(lines).not.toContain("[tool] fs_read (3 calls)");++ // Raw string row grouping test verifying error lines break consecutive groups+ const rawLines = [+ "[tool] fs_read: alpha",+ "[tool] fs_read: beta",+ "[tool] fs_read: error: permission denied",+ "[tool] fs_read: delta",+ "[tool] fs_read: epsilon",+ ];+ const grouped = groupToolRows(rawLines, { maxPerTool: 1 });+ expect(grouped).toContain("[tool] fs_read: error: permission denied");+ expect(grouped).toContain("[tool] fs_read (2 calls)");+ });++ it("4. the setting is read from the session at both call sites (initial set and sync)", () => {+ const sessionAuto: any = { ...makeFixture(), grouping: "auto" };+ const output1 = new FakeOutput();+ const loop1 = mountScreenLoop({ enabled: true, session: sessionAuto, output: output1 as never, input: new EventEmitter() as never });+ // Call site 1 (initial mount): reads session.grouping === 'auto'+ expect(output1.chunks.join("")).toContain("fs_read (3 calls)");+ loop1.dispose();++ const sessionNone: any = { ...makeFixture(), grouping: "none" };+ const output2 = new FakeOutput();+ const loop2 = mountScreenLoop({ enabled: true, session: sessionNone, output: output2 as never, input: new EventEmitter() as never });+ expect(output2.chunks.join("")).not.toContain("fs_read (3 calls)");++ // Call site 2 (sync): re-reads session.grouping on sync+ sessionNone.grouping = "auto";+ output2.chunks = [];+ loop2.sync();+ expect(output2.chunks.join("")).toContain("fs_read (3 calls)");+ loop2.dispose();+ });++ it("5. changing the setting and repainting changes the output without a restart", async () => {+ const session: any = { ...makeFixture(), grouping: "none" };+ const output = new FakeOutput();+ const loop = mountScreenLoop({ enabled: true, session, output: output as never, input: new EventEmitter() as never });+ expect(output.chunks.join("")).not.toContain("fs_read (3 calls)");++ const ctx = { session, C: {}, width: 80, write: () => {} };+ output.chunks = [];+ await handleSettingsCommand(ctx, ["grouping", "auto"]);++ // Setting updated on session and screenLoop.sync() was called immediately+ expect(session.grouping).toBe("auto");+ expect(output.chunks.join("")).toContain("fs_read (3 calls)");++ output.chunks = [];+ await handleSettingsCommand(ctx, ["grouping", "none"]);+ expect(session.grouping).toBe("none");+ expect(output.chunks.join("")).not.toContain("fs_read (3 calls)");+ expect(output.chunks.join("")).toContain("fs_read: alpha");++ loop.dispose();+ });+});diff --git a/scripts/mso-agent-transcript.mjs b/scripts/mso-agent-transcript.mjsindex ffce80c8..c3658994 100644--- a/scripts/mso-agent-transcript.mjs+++ b/scripts/mso-agent-transcript.mjs@@ -103,12 +103,15 @@ export function transcriptLines(session, { colors, width, groupTools = false, maif (!results.length) lines.push(`${prefix}${row.name || "tool"}: (no result)`);for (let rIdx = 0; rIdx < results.length; rIdx += 1) {const item = results[rIdx];+ const isErr = Boolean(item?.isError || item?.error || row.isError || row.error);const id = item?.id ? String(item.id) : "";const toolName = item?.name || item?.tool || row.name || (id ? lastToolCalls.get(id) : null) || lastToolCallList[rIdx]?.name || "tool";const pl = formatToolPayload(toolName, item, colors, clipLimit, width);- if (pl.length === 1) lines.push(`${prefix}${toolName}: ${pl[0]}`);+ // Error tag ensures tool calls with an isError flag render visibly even if payload lacks an error prefix+ const errTag = isErr && !/\b(error|failed|failure)\b/i.test(pl[0] || "") ? " (error)" : "";+ if (pl.length === 1) lines.push(`${prefix}${toolName}${errTag}: ${pl[0]}`);else {- lines.push(`${prefix}${toolName}:`);+ lines.push(`${prefix}${toolName}${errTag}:`);for (const line of pl) lines.push(line.startsWith(" ") ? line : ` ${line}`);}}@@ -139,7 +142,9 @@ export function groupToolRows(lines, { maxPerTool = 1 } = {}) {grp = []; cur = null;};for (const r of lines) {- const name = r?.role === "tool" ? (r.name || r.results?.[0]?.name || "tool") : null;+ // Failed tool calls must never be hidden into a count summary+ const isErr = Boolean(r?.isError || r?.error || r?.results?.some((x) => x?.isError || x?.error));+ const name = r?.role === "tool" && !isErr ? (r.name || r.results?.[0]?.name || "tool") : null;if (name) {if (cur === name) grp.push(r);else { flush(); cur = name; grp = [r]; }@@ -161,7 +166,9 @@ export function groupToolRows(lines, { maxPerTool = 1 } = {}) {for (const line of lines) {const plain = String(line || "").replace(/\x1b\[[0-9;]*m/g, "");const m = plain.match(/^\[([a-zA-Z0-9_-]+)\]\s+([a-zA-Z0-9_.-]+)(?::|\s|\(|$)/);- if (m && m[1] === "tool") {+ // Explicit errors must never be collapsed into a count line+ const isErr = m && m[1] === "tool" && (plain.includes("(error)") || /^\[[a-zA-Z0-9_-]+\]\s+[a-zA-Z0-9_.-]+:\s*(?:error|failed|failure)\b/i.test(plain));+ if (m && m[1] === "tool" && !isErr) {const tool = m[2];const pfx = (line.match(/^([^\s]+)\s+/) || [])[0] || "[tool] ";if (curTool === tool) {diff --git a/scripts/mso-agent.mjs b/scripts/mso-agent.mjsindex 6b208c64..15a92674 100644--- a/scripts/mso-agent.mjs+++ b/scripts/mso-agent.mjs@@ -6,6 +6,7 @@ import { slashCompletionItems } from "./mso-agent-slash.mjs";import { persistSession, restartSessionArg, resumeArg, startupSession, syncPromptHistory } from "./mso-agent-session-ui.mjs";import { C, printBanner } from "./mso-agent-runtime.mjs";import { listCliSessions, state } from "./mso-agent-api.mjs";+import { fetchMcpServers } from "./mso-agent-mcp-servers.mjs";import { handleSlash } from "./mso-agent-commands.mjs";import { nextPermissionMode, permissionMode } from "./mso-agent-permissions.mjs";import { consumeRestartUiState, relaunchCurrentAgentSession } from "./mso-agent-lifecycle.mjs";@@ -40,8 +41,7 @@ async function main() {}// Declared out here, not inside the try: the finally block disposes them, and a `const` inside// the try is not in scope there. A ReferenceError in finally replaced the real exit status.- let screenLoop = null;- let screen = null; let session = null; let rl = null;+ let screenLoop = null; let screen = null; let session = null; let rl = null;let localBridge = null; let onSigint = null; let restartRequested = false;try {screen = startAltScreen({ requested: altScreen, output: process.stdout });@@ -51,12 +51,13 @@ async function main() {const forcedPermission = argv.some((arg) => ["--yolo", "-yolo", "-y"].includes(arg))? "yolo": (permissionMode(restartUi.permission)?.id || "ask");- const [s, agentSession] = await Promise.all([state(), startupSession(requested, restartSessionId)]);+ const [s, agentSession, mcpServers] = await Promise.all([state(), startupSession(requested, restartSessionId), fetchMcpServers()]);if (!agentSession || agentSession.source !== "cli") throw new Error("could not establish a CLI MSO Agent session");const bannerLines = altScreen.ok ? captureBanner(printBanner, s, agentSession) : (printBanner(s, agentSession), null);session = {state: s,agentSession,+ mcpServers,history: Array.isArray(agentSession.history) ? agentSession.history : [],pendingSkill: null, activeSkill: null, lastInvokedSkill: null,titleOverride: (requested || restartSessionId) ? (agentSession.title || null) : null,@@ -136,7 +137,7 @@ async function main() {else if (action === "interrupt") rl.cancelCurrent({ echo: false });};process.on("SIGINT", onSigint);- const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session);+ const completeSlash = (line) => slashCompletionItems(session.state.skills, line, process.cwd(), session, { settings: true, sessions: () => recentSessions });while (true) {if (interrupts.exitRequested) break;if (inboundRequestQueued) {