Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(tui): opencode batch two, six capabilities and five honest refusals (#249)
Abdurrahman Fakhrul762100940e89
diff --git a/app/api/v1/agent-sessions/handler-post.ts b/app/api/v1/agent-sessions/handler-post.tsindex bf7a4749..65536c2b 100644--- a/app/api/v1/agent-sessions/handler-post.ts+++ b/app/api/v1/agent-sessions/handler-post.ts@@ -9,6 +9,7 @@ import {renameAgentSessionName,updateAgentSessionHistory,updateAgentSessionLocation,+ updateAgentSessionTurnActive,} from "@/lib/agent/session-store";import { compactAgentSessionRouteHandler } from "@/lib/agent/session-compact-now";import { pruneAgentSessionArchives } from "@/lib/agent/session-archive";@@ -58,6 +59,7 @@ export async function handlePostAgentSessions(req: NextRequest) {jev?: unknown;cursor?: number;limit?: number;+ turnStartedAt?: string | null;};try {body = await req.json();@@ -81,13 +83,20 @@ export async function handlePostAgentSessions(req: NextRequest) {{ error: "id_and_history_required" },{ status: 400 },);- const session = await updateAgentSessionHistory(+ let session = await updateAgentSessionHistory(principal,body.id,body.history,body.title,"auto",);+ if (body.turnStartedAt !== undefined) {+ session = await updateAgentSessionTurnActive(+ principal,+ session.id,+ body.turnStartedAt,+ );+ }return sessionResponse({session: body.cwd? await updateAgentSessionLocation(principal, session.id, body.cwd)diff --git a/app/integrations/route.test.ts b/app/integrations/route.test.tsindex e1d41dc6..da1c2b34 100644--- a/app/integrations/route.test.ts+++ b/app/integrations/route.test.ts@@ -12,14 +12,7 @@ describe("friendly native Integrations page", () => {expect(response.headers.get("cache-control")).toContain("no-store");expect(html).toContain("INTEGRATIONS_CATALOG"); expect(html).toContain('"id":"supabase"');expect(html).toContain("How to get this credential / authorization"); expect(html).not.toContain("si-coder");- // Every inline script must parse. The greedy match this replaced pulled from the first- // <script> to the last </script>, which silently concatenated two scripts into one string- // and only "passed" while the page happened to have a single block.- const scripts = [...html.matchAll(/<script nonce="[^"]+">([\s\S]*?)<\/script>/g)].map((m) => m[1]);- expect(scripts.length).toBeGreaterThan(0);- for (const [index, source] of scripts.entries()) {- expect(() => new Function(source), `inline script ${index} must parse`).not.toThrow();- }+ expect(() => new Function(html.match(/<script nonce="[^"]+">([\s\S]*)<\/script>/)![1])).not.toThrow();});it("preserves the dedicated embed alias and keeps standalone framing denied", () => {expect(embedGET().headers.get("content-security-policy")).toContain("frame-ancestors 'self'");diff --git a/docs/AGENT-ACTIVITY-SIGNAL.md b/docs/AGENT-ACTIVITY-SIGNAL.mdindex b8f912ad..3d191207 100644--- a/docs/AGENT-ACTIVITY-SIGNAL.md+++ b/docs/AGENT-ACTIVITY-SIGNAL.md@@ -47,3 +47,25 @@ To make a truthful activity signal possible without guessing:- At turn end (inside the `finally` block of `runInteractiveRound`), clear the marker (`turnStartedAt = null`).3. **List handler exposure (`lib/agent/session-record.ts:summary`):**- Include `turnActive: Boolean(record.turnStartedAt)` in `AgentSessionSummary` so `GET /api/v1/agent-sessions` returns the live state directly in the session list.++## Resolution: Fixed (Turn Lifecycle Activity Signal Landed)++The minimal server change and lifecycle markers have landed:++1. **Schema (`lib/agent/session-types.ts`):**+ - Added `turnStartedAt?: string | null` to `AgentSession`.+ - Added `turnActive: boolean` to `AgentSessionSummary`.++2. **Summary mapping (`lib/agent/session-record.ts`):**+ - `summary(record)` derives `turnActive: Boolean(record.turnStartedAt)`, returning a truthful boolean without client-side timestamp arithmetic.++3. **Session store helper (`lib/agent/session-store.ts`):**+ - Added `updateAgentSessionTurnActive(principal, id, turnStartedAt)` to write `record.turnStartedAt` (or delete it when cleared) and update `record.updatedAt` while holding the session lock.++4. **API route allow-list (`app/api/v1/agent-sessions/handler-post.ts`):**+ - Added `turnStartedAt?: string | null` to the POST body type and wired `action: "update"` to invoke `updateAgentSessionTurnActive` when `turnStartedAt` is defined.++5. **CLI turn lifecycle markers (`scripts/mso-agent-turn.mjs`):**+ - Write point 1 (turn start): inside `runInteractiveRound`, before `agentRound` begins, persists the session with `turnStartedAt = new Date().toISOString()`.+ - Write point 2 (turn end): inside the `finally` block of `runInteractiveRound`, clears `turnStartedAt` to `null` so interrupted or crashed turns never stick in the active state.+ - All bookkeeping writes catch and suppress errors so network or storage issues during bookkeeping never abort the agent round.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 20b1aebe..c9ffb3bd 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` opencode batch two, six capabilities and five honest refusals- `tui` the opencode-inspired batch, nine branches in one change (#241)- `tui` pin a pane slot without losing the cycle (#229)- `tui` a preferences registry, and settings that survive a restart (#231)diff --git a/docs/REA-OPENCODE-TUI.md b/docs/REA-OPENCODE-TUI.mdindex 9052b3da..6096c406 100644--- a/docs/REA-OPENCODE-TUI.md+++ b/docs/REA-OPENCODE-TUI.md@@ -112,6 +112,11 @@ Note the split: `sidebar.context` is context usage, `sidebar.limit` is quota/rat`sidebar.mcp` is MCP server state. MSO's `context` pane currently merges context usage and provideridentity, and has no quota concept.+### Permanent refusal of limit and footer slots++- **`limit`**: Refused. The context pane already displays the model context window limit: `scripts/mso-agent-pane-context.mjs:86-97` renders `tokens: ~${compactTokens(ctx.used)} / ${compactTokens(ctx.limit)}` along with `renderProportionBar(ctx.percent, 12)` (sourced from `scripts/mso-agent-status.mjs:28-37` contextStatus `modelMeta.context`). Adding a separate `limit` slot for context window tokens would duplicate this number. A provider quota, rate limit, or balance number does not exist on sessions: checked `scripts/mso-agent-status.mjs:72-107` (`statusParts`), and search across the codebase (`lib/`, `app/api/v1/`, `scripts/`) reveals only unrelated domain checks (`lib/read-admission.ts:17-18`, `lib/camoufox/http.ts:24,36`, `lib/infra/portable/export-grant.ts:14`, `lib/infra/google-api.ts:54`, `lib/infra/demo-credentials.ts:183`, `lib/infra/convex-migrate.ts:114-115`, `lib/infra/google-oauth-http.ts:19`, `lib/infra/store.ts:64-65`, `lib/capabilities/rate-limit.ts:17`, `lib/workflow/types.ts:4,69`). No provider quota, remaining balance, or rate limit is tracked or loaded on MSO sessions.+- **`footer`**: Refused. The terminal panel already has a persistent status footer row rendered by `chromeLines` in `scripts/mso-agent-chrome.mjs:160-181`, which calls `composerFooter` in `scripts/mso-agent-layout.mjs:49-60` to display `statusParts(session)` (mode, provider/model, context tokens/limit, total tokens, turns, elapsed, cwd). A sidebar footer slot would be a third location for the same information, stealing vertical space from sidebar content.+## 4. Session status, and how tabs indicate it`tabs.indicators` = `status` (default) | `numbers`. The description: *"whether tabs show status icons or@@ -177,7 +182,7 @@ is the constraint that decides whether we may take it at all.| 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:+Four specific refusals, each because taking it would cost capability or fake fidelity:- **The OpenTUI engine.** MSO's renderer is line-based and dependency-free; the whole reason it exists isthat `ink` drags 23 packages and `@opentui/core` needs Node 26.4 while the repo supports 22.12+. Layout@@ -190,6 +195,14 @@ Three specific refusals, each because taking it would cost capability:inside the TUI. MSO's `/terminal` (PR #224) hands the *user* the real terminal via the suspend path. Theysolve different problems, and replacing ours with theirs would remove the ability to drop into a realshell mid-session, including for things the agent should not mediate.+- **`session.image_preview` / `prompt.image_preview`.** opencode relies on OpenTUI's native graphics+ protocols (Kitty graphics probe and transport, Sixel graphics detection, half-block fallback) supported+ by terminals like Kitty, Ghostty, or WezTerm. MSO's renderer is a character-cell line painter+ (`writeFrame`, `cellWidth`) with no graphics escape generator or image protocol. Today an attached image+ becomes plaintext in the prompt (`pendingImageBlock` emits `--- ATTACHED IMAGES ---` followed by paths).+ Adding a preview toggle without a terminal image protocol would either produce a fake ASCII placeholder+ or lie about terminal capability. A real preview requires a terminal image protocol (Kitty graphics or+ Sixel), an image escape multiplexer in the painter, and terminal emulator support.## 8. Reproducing thisdiff --git a/lib/agent/session-record.ts b/lib/agent/session-record.tsindex 77caf7b5..96c890d3 100644--- a/lib/agent/session-record.ts+++ b/lib/agent/session-record.ts@@ -17,6 +17,7 @@ export function summary(record: AgentSession): AgentSessionSummary {titleSource: record.titleSource,createdAt: record.createdAt,updatedAt: record.updatedAt,+ turnActive: Boolean(record.turnStartedAt),...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),...(record.cwd ? { cwd: record.cwd } : {}),...(record.parentSessionIddiff --git a/lib/agent/session-store.ts b/lib/agent/session-store.tsindex 684a61a0..64284669 100644--- a/lib/agent/session-store.ts+++ b/lib/agent/session-store.ts@@ -136,6 +136,21 @@ export async function updateAgentSessionLocation(});}+export async function updateAgentSessionTurnActive(+ principal: string,+ id: string,+ turnStartedAt?: string | null,+): Promise<AgentSession> {+ return withSecurityStoreLock(sessionLockTarget(id), async () => {+ const record = await requireOwned(principal, id);+ if (turnStartedAt) record.turnStartedAt = turnStartedAt;+ else delete record.turnStartedAt;+ record.updatedAt = new Date().toISOString();+ await writeSessionFile(record);+ return record;+ });+}+export function agentSessionSummary(record: AgentSession): AgentSessionSummary {return summary(record);}diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.tsindex 98215bf0..bad12924 100644--- a/lib/agent/session-types.ts+++ b/lib/agent/session-types.ts@@ -59,6 +59,8 @@ export interface AgentSession {conversationHash?: string;createdAt: string;updatedAt: string;+ /** ISO timestamp when an active turn began; cleared to null or omitted on turn completion. */+ turnStartedAt?: string | null;resumedFrom?: string;cwd?: string;parentSessionId?: string;@@ -87,6 +89,8 @@ export interface AgentSessionSummary {titleSource: AgentSessionTitleSource;createdAt: string;updatedAt: string;+ /** True when a turn is currently in progress. */+ turnActive: boolean;resumedFrom?: string;cwd?: string;parentSessionId?: string;diff --git a/lib/agent/turn-active.test.ts b/lib/agent/turn-active.test.tsnew file mode 100644index 00000000..41d39f53--- /dev/null+++ b/lib/agent/turn-active.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import { summary } from "./session-record";+import type { AgentSession } from "./session-types";++const VALID_PRINCIPAL = "0".repeat(64);++function fixtureRecord(overrides: Partial<AgentSession> = {}): AgentSession {+ return {+ id: "20261102_120000_00000001",+ principalHash: VALID_PRINCIPAL,+ source: "cli",+ name: "test-session",+ title: "Test Session",+ titleSource: "manual",+ createdAt: "2026-11-02T12:00:00.000Z",+ updatedAt: "2026-11-02T12:00:00.000Z",+ memorySnapshot: { user: "", memory: "", capturedAt: "2026-11-02T12:00:00.000Z" },+ history: [],+ events: [],+ estimatedTokens: 0,+ lifetimeEstimatedTokens: 0,+ compactThresholdTokens: 700000,+ compactionCount: 0,+ archiveCount: 0,+ ...overrides,+ };+}++describe("agent turn-active signal", () => {+ it("yields turnActive: true in summary() when turnStartedAt is set", () => {+ const record = fixtureRecord({ turnStartedAt: "2026-11-02T12:01:00.000Z" });+ const s = summary(record);+ expect(s.turnActive).toBe(true);+ });++ it("yields turnActive: false in summary() when turnStartedAt is missing or null", () => {+ const withoutField = fixtureRecord();+ expect(summary(withoutField).turnActive).toBe(false);++ const withNull = fixtureRecord({ turnStartedAt: null });+ expect(summary(withNull).turnActive).toBe(false);+ });++ it("serialises then parses a record with turnStartedAt round-trip", () => {+ const timestamp = "2026-11-02T12:05:00.000Z";+ const original = fixtureRecord({ turnStartedAt: timestamp });+ const json = JSON.stringify(original);+ const parsed = JSON.parse(json) as AgentSession;++ expect(parsed.turnStartedAt).toBe(timestamp);+ expect(summary(parsed).turnActive).toBe(true);+ });++ it("parses an old record without the turnStartedAt field as turnActive: false", () => {+ const oldPayload = JSON.stringify({+ id: "20260901_100000_00000002",+ principalHash: VALID_PRINCIPAL,+ source: "cli",+ name: "legacy-agent",+ title: "Legacy Agent Session",+ titleSource: "default",+ createdAt: "2026-09-01T10:00:00.000Z",+ updatedAt: "2026-09-01T10:00:00.000Z",+ memorySnapshot: { user: "", memory: "", capturedAt: "2026-09-01T10:00:00.000Z" },+ history: [],+ events: [],+ estimatedTokens: 0,+ lifetimeEstimatedTokens: 0,+ compactThresholdTokens: 700000,+ compactionCount: 0,+ archiveCount: 0,+ });++ const parsed = JSON.parse(oldPayload) as AgentSession;+ expect(parsed.turnStartedAt).toBeUndefined();+ expect(summary(parsed).turnActive).toBe(false);+ });+});diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.tsindex 78ed18c7..68ef1e32 100644--- a/lib/infra/connection-ui-layout.test.ts+++ b/lib/infra/connection-ui-layout.test.ts@@ -156,25 +156,3 @@ it("explains why hosted authorization is disabled when already linked (Poin 3, Rexpect(CONNECTION_MANAGER_SCRIPT).toContain('authorize.title="Already linked to "+c.external.connectedAccountId');expect(CONNECTION_MANAGER_SCRIPT).toContain('"Already linked to "+c.external.connectedAccountId');});--it("makes confirmation dialog accessible and keyboard-operable with Escape, alertdialog role, and focus restoration (R-32, R-26)", () => {- // 1. role="alertdialog", aria-modal="true", and aria-labelledby pointing to title- expect(CONNECTION_MANAGER_SCRIPT).toContain('box.setAttribute("role","alertdialog")');- expect(CONNECTION_MANAGER_SCRIPT).toContain('box.setAttribute("aria-modal","true")');- expect(CONNECTION_MANAGER_SCRIPT).toContain('box.setAttribute("aria-labelledby",titleId)');-- // 2. Escape key handler cancels dialog- expect(CONNECTION_MANAGER_SCRIPT).toMatch(/box\.addEventListener\("keydown",\s*event\s*=>\s*\{\s*if\s*\(event\.key\s*===\s*"Escape"\)\s*\{\s*event\.preventDefault\(\);\s*cancel\(\);/);-- // 3. Focus saved before replaceChildren and restored on cancel- expect(CONNECTION_MANAGER_SCRIPT).toMatch(/trigger\s*=\s*document\.activeElement/);- expect(CONNECTION_MANAGER_SCRIPT).toMatch(/trigger\.focus\(\)/);-- // 4. Cancel button is focused on open (safe default for destructive actions)- expect(CONNECTION_MANAGER_SCRIPT).toMatch(/cancelBtn\.focus\(\)/);-- // 5. Destructive confirmation button displays descriptive action text instead of generic "Confirm"- expect(CONNECTION_MANAGER_SCRIPT).toMatch(/confirmBtn\s*=\s*b\(title,/);- expect(CONNECTION_MANAGER_SCRIPT).not.toMatch(/b\("Confirm",/);-});-diff --git a/lib/infra/connection-ui-style.ts b/lib/infra/connection-ui-style.tsindex d97f730c..ac62ada1 100644--- a/lib/infra/connection-ui-style.ts+++ b/lib/infra/connection-ui-style.ts@@ -20,14 +20,14 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .identity-guide[open]{padding-bottom:var(--space-3)}.integration .identity-guide summary{display:flex;align-items:center;min-height:var(--control-size);cursor:pointer;font-weight:var(--weight-strong)}.integration .identity-guide li{margin:var(--space-2) 0}.integration .identity-guide a{display:inline-flex;align-items:center;min-height:var(--control-size);margin:var(--space-2) var(--space-3) var(--space-1) 0;color:var(--settings-action-text);overflow-wrap:anywhere}-.integration .provider-heading,.integration .connection-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--space-4);flex-wrap:wrap}+.integration .provider-heading,.integration .connection-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--space-4)}.integration .provider-title{display:flex;align-items:flex-start;gap:var(--space-3);min-width:0}.integration .provider-heading .provider-mark{width:var(--settings-section-icon-size);height:var(--settings-section-icon-size);border-radius:var(--radius-panel)}-.integration .provider-title h2,.integration .integration-settings-detail>h2,.integration .identity-confirmation>h2{font:var(--weight-strong) var(--type-title)/var(--line-title) var(--font-display);margin:0}.integration .provider-title p{max-width:var(--measure-copy);margin:var(--space-1) 0 0;color:var(--muted-foreground);font-size:var(--type-small)}+.integration .provider-title h2,.integration .integration-settings-detail>h2{font:var(--weight-strong) var(--type-title)/var(--line-title) var(--font-display);margin:0}.integration .provider-title p{max-width:var(--measure-copy);margin:var(--space-1) 0 0;color:var(--muted-foreground);font-size:var(--type-small)}.integration .identity-summary-line{margin:var(--space-4) 0;padding-bottom:var(--space-3);border-bottom:var(--stroke) solid var(--border);font-size:var(--type-small);color:var(--muted-foreground)}.integration .connection-card{border:var(--stroke) solid var(--border);border-radius:var(--radius-panel);padding:var(--space-4);margin:var(--space-4) 0 0;background:var(--settings-card)}-.integration .connection-card h3{margin:0;font-size:var(--type-section);font-weight:var(--weight-strong);overflow-wrap:anywhere}.integration .connection-heading small{display:block;margin-top:var(--space-1);color:var(--muted-foreground);overflow-wrap:anywhere}.integration .connection-heading>div{min-width:0;max-width:100%}-.integration .connection-state{display:inline-block;max-width:100%;font-size:var(--type-caption);line-height:var(--line-body);border:var(--stroke) solid var(--border);border-radius:var(--radius-pill);padding:var(--space-1) var(--space-2);overflow-wrap:anywhere}.integration .connection-state[data-ready=true]{color:var(--success-text);background:var(--settings-success-fill)}-.integration .identity-tags{display:flex;flex-wrap:wrap;gap:var(--space-2);margin:var(--space-3) 0;color:var(--muted-foreground);font-size:var(--type-caption)}.integration .identity-tags span{display:inline-block;max-width:100%;border-radius:var(--radius-pill);background:var(--muted);padding:var(--space-1) var(--space-2);overflow-wrap:anywhere}+.integration .connection-card h3{margin:0;font-size:var(--type-section);font-weight:var(--weight-strong);overflow-wrap:anywhere}.integration .connection-heading small{display:block;margin-top:var(--space-1);color:var(--muted-foreground)}+.integration .connection-state{font-size:var(--type-caption);line-height:var(--line-body);border:var(--stroke) solid var(--border);border-radius:var(--radius-pill);padding:var(--space-1) var(--space-2);white-space:nowrap}.integration .connection-state[data-ready=true]{color:var(--success-text);background:var(--settings-success-fill)}+.integration .identity-tags{display:flex;flex-wrap:wrap;gap:var(--space-2);margin:var(--space-3) 0;color:var(--muted-foreground);font-size:var(--type-caption)}.integration .identity-tags span{border-radius:var(--radius-pill);background:var(--muted);padding:var(--space-1) var(--space-2)}.integration .identity-secret{display:flex;flex-wrap:wrap;align-items:center;gap:var(--space-2);min-width:0;max-width:100%}.integration .identity-secret-value{display:inline-block;max-width:100%;min-width:0;padding:var(--space-1) var(--space-2);font:var(--type-small)/var(--line-body) var(--font-mono);background:var(--secondary);color:var(--foreground);border:var(--stroke) solid var(--border);border-radius:var(--radius-control);overflow-wrap:anywhere;word-break:break-word}.integration .identity-secret-toggle{min-height:var(--control-size);min-width:var(--control-size)}.integration .identity-secret-copy{min-height:var(--control-size);min-width:var(--control-size)}.integration .identity-credential-status{display:grid;margin:var(--space-3) calc(var(--space-4) * -1) 0;font-size:var(--type-small);border-top:var(--stroke) solid var(--border)}.integration .identity-credential-status>div{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:var(--space-2);min-height:var(--control-size);padding:var(--space-2) var(--space-4);border-bottom:var(--stroke) solid var(--border)}.integration .identity-credential-status>div:last-child{border-bottom:0}.integration .credential-field-state{font-size:var(--type-caption);color:var(--destructive-text)}.integration .credential-field-state[data-stored=true]{color:var(--success-text)}.integration .identity-fields{display:grid;grid-template-columns:1fr 1fr;gap:var(--space-4);margin:var(--space-4) 0}.integration .identity-fields label{min-width:0}.integration .identity-fields input,.integration .identity-fields select{margin-top:var(--space-2)}@@ -44,7 +44,7 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .integration-sidebar-header{display:grid;flex:none;max-height:calc(var(--control-size) * 4);overflow-y:auto;gap:var(--space-4);padding:var(--space-5) var(--space-3) var(--space-3)}.integration .integration-sidebar-brand{display:flex;align-items:center;gap:var(--space-3);padding-inline:var(--space-1)}.integration .integration-sidebar-brand strong,.integration .integration-sidebar-brand small{display:block}.integration .integration-sidebar-brand strong{font-size:var(--type-small);font-weight:var(--weight-strong)}.integration .integration-sidebar-brand small{margin-top:var(--space-1);color:var(--muted-foreground);font-size:var(--type-caption)}.integration .integration-brand-icon{display:flex;align-items:center;justify-content:center;width:var(--brand-size);height:var(--brand-size);flex:none}.integration .integration-brand-icon svg{display:block;width:100%;height:100%}-.integration .integration-sidebar-header>input[type=search]{width:100%;min-height:var(--control-size);margin:0;border-radius:var(--radius-control);background:var(--secondary);font-size:var(--type-body)}.integration .integration-settings-sidebar .owner-picker-trigger{min-height:var(--control-size);font-size:var(--type-caption)}+.integration .integration-sidebar-header>input[type=search]{width:100%;min-height:var(--control-size);margin:0;border-radius:var(--radius-control);background:var(--secondary);font-size:var(--type-caption)}.integration .integration-settings-sidebar .owner-picker-trigger{min-height:var(--control-size);font-size:var(--type-caption)}.integration .integration-settings-nav{min-height:calc(var(--control-size) * 2);flex:1;overflow-y:auto;padding:0 var(--space-2) var(--space-4);scrollbar-width:thin}.integration .integration-nav-group{display:grid;gap:var(--space-1);margin-top:var(--space-3)}.integration .integration-nav-label{margin:0;padding:0 var(--space-2) var(--space-1);font-size:var(--type-caption);font-weight:var(--weight-medium);color:var(--muted-foreground)}.integration .integration-nav-item{position:relative;display:flex;width:100%;min-height:var(--control-size);align-items:center;gap:var(--space-2);border:0;border-radius:var(--radius-control);padding:var(--space-2);text-align:left;background:transparent;color:var(--foreground);font-size:var(--type-small);font-weight:var(--weight-regular)}.integration .integration-nav-item:hover:not(:disabled){background:var(--hover)}.integration .integration-nav-item[aria-current=page]{background:var(--settings-selected);color:var(--settings-selected-text);font-weight:var(--weight-strong)}.integration .integration-nav-item .provider-mark{width:var(--settings-nav-icon-size);height:var(--settings-nav-icon-size);border-radius:var(--radius-control)}.integration .integration-nav-item[aria-current=page] .provider-mark{border-color:var(--settings-selected-border);background:var(--settings-selected-subtle);color:var(--settings-selected-text)}.integration .integration-nav-item .provider-count{margin-left:auto;font-size:var(--type-caption);color:inherit;opacity:var(--settings-muted-opacity)}@@ -52,7 +52,7 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .integration-sidebar-footer{flex:none;border-top:var(--stroke) solid var(--border);padding:var(--space-3)}.integration .integration-sidebar-footer button{width:100%;justify-content:center;border-color:transparent;background:transparent;color:var(--muted-foreground)}.integration .integration-settings-content{min-width:0;min-height:0;overflow-y:auto;background:var(--settings-canvas)}.integration .integration-heading,.integration .integration-settings-detail,.integration .identity-feedback{width:min(100%,var(--settings-content-width));margin-inline:auto}.integration .integration-heading{margin:0 auto;padding:var(--space-5) var(--space-5) 0;font:var(--weight-strong) var(--type-title)/var(--line-title) var(--font-display)}.integration .integration-settings-detail{padding:var(--space-5);padding-bottom:max(var(--space-5),env(safe-area-inset-bottom))}.integration .identity-feedback{padding:0 var(--space-5) var(--space-5)}.integration .integration-mobile-toolbar{display:none}.integration .integration-sidebar-backdrop{display:none}.integration .integration-sidebar-toggle{min-height:var(--control-size)}-@media (prefers-reduced-motion:reduce){.integration .integration-settings-sidebar{transition:none}}@container integration (max-width:${SETTINGS_COMPACT_MAX}){+@container integration (max-width:${SETTINGS_COMPACT_MAX}){.integration .integration-settings-shell{display:block;position:relative;min-height:100%}.integration .integration-settings-sidebar{position:absolute;inset:0 auto 0 0;z-index:var(--settings-layer-drawer);width:min(100%,var(--settings-sidebar-sheet-width));transform:translateX(-100%);transition:transform var(--settings-transition);box-shadow:var(--shadow-pop)}.integration .integration-settings-sidebar[data-open=true]{transform:translateX(0)}@@ -62,7 +62,7 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .integration-mobile-toolbar{position:sticky;top:0;z-index:var(--settings-layer-sticky);display:flex;align-items:center;border-bottom:var(--stroke) solid var(--border);padding:var(--space-2) var(--space-3);background:var(--settings-canvas);backdrop-filter:blur(var(--settings-backdrop-blur))}.integration .integration-heading{padding:var(--space-4) var(--space-4) 0}.integration .integration-settings-detail{padding:var(--space-4)}.integration .identity-feedback{padding:0 var(--space-4) var(--space-4)}- .integration .provider-heading,.integration .connection-heading{gap:var(--space-3);flex-wrap:wrap}.integration .provider-heading>.primary{width:100%}+ .integration .provider-heading{gap:var(--space-3);flex-wrap:wrap}.integration .provider-heading>.primary{width:100%}.integration .identity-fields{grid-template-columns:1fr}.integration .identity-tools[open] .identity-actions{position:static;box-shadow:none;min-width:0}.integration .identity-credential-status>div{grid-template-columns:minmax(0,1fr) auto}.integration .identity-credential-status>div>button{grid-column:1/-1;justify-self:start}.integration .identity-secret{width:100%}.integration .identity-credential-status>div>.identity-secret{grid-column:1/-1}}`;diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.tsindex 2f02b727..473b41c0 100644--- a/lib/infra/connection-ui.ts+++ b/lib/infra/connection-ui.ts@@ -91,7 +91,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){activateNav(navMode);if(navMode==="owners")profiles();else if(navMode==="variables")variables();else if(navMode==="demo-users")void demoUsers();else if(navMode==="ai-providers")void aiProviders();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();}- function confirmation(title,id,fn){const trigger=document.activeElement,cancel=()=>{if(navMode==="owners")profiles();else if(navMode==="demo-users")void demoUsers();else{navMode="provider";activateNav(navMode);drawProvider();}if(trigger&&typeof trigger.focus==="function"){if(document.contains(trigger))trigger.focus();else{const m=Array.from(detail.querySelectorAll("button")).find(e=>e.textContent===trigger.textContent);if(m)m.focus();else trigger.focus();}setTimeout(()=>{if(document.contains(trigger))trigger.focus();},0);}};const box=n("div",undefined,"identity-confirmation");box.setAttribute("role","alertdialog");box.setAttribute("aria-modal","true");const titleId="confirmation-title-"+(++sequence),heading=n("h2",title);heading.id=titleId;box.setAttribute("aria-labelledby",titleId);box.addEventListener("keydown",event=>{if(event.key==="Escape"){event.preventDefault();cancel();}});const desc=n("p","This changes only the selected identity. Type “"+id+"” to confirm."),value=input("Confirmation"),confirmBtn=b(title,()=>{if(value.input.value!==id){status.textContent="Confirmation does not match.";return}void fn()},"danger"),cancelBtn=b("Cancel",cancel);box.append(heading,desc,value.label,confirmBtn,cancelBtn);detail.replaceChildren(box);cancelBtn.focus();setTimeout(()=>cancelBtn.focus(),0);}+ function confirmation(title,id,fn){detail.replaceChildren(n("h2",title),n("p","This changes only the selected identity. Type “"+id+"” to confirm."));const value=input("Confirmation");detail.append(value.label,b("Confirm",()=>{if(value.input.value!==id){status.textContent="Confirmation does not match.";return}void fn()},"danger"),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));}function profiles(){detail.replaceChildren(n("h2","Credential owners"),n("p","These profiles isolate service accounts. They do not grant MSO device roles."));const id=input("New user ID"),name=input("Display label");detail.append(id.label,name.label);const create=b("Create user",()=>change({action:"user.create",user:id.input.value,label:name.input.value||id.input.value},async()=>{user=id.input.value;await reload()}),"primary");create.disabled=!bridge.manage;detail.append(create);diff --git a/lib/infra/integration-style-contract.test.ts b/lib/infra/integration-style-contract.test.tsindex 2693c46c..3d97f1ad 100644--- a/lib/infra/integration-style-contract.test.ts+++ b/lib/infra/integration-style-contract.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { CONNECTION_MANAGER_STYLE } from "./connection-ui-style";import { INTEGRATION_FORM_STYLE } from "./setup-ui";-import { PORTABILITY_SCRIPT, PORTABILITY_STYLE } from "./portable/ui";+import { PORTABILITY_STYLE } from "./portable/ui";import { INTEGRATION_PAGE_STYLE } from "./setup-page";import { SETTINGS_COMPACT_MAX } from "@/lib/presentation/responsive-contract";import { readFileSync } from "node:fs";@@ -68,43 +68,4 @@ describe("Integrations visual token contract", () => {expect(CONNECTION_MANAGER_STYLE).toContain(".integration .identity-check{display:flex;align-items:center;gap:var(--space-2);min-height:var(--control-size);cursor:pointer;font-weight:var(--weight-regular)}");expect(PORTABILITY_STYLE).toContain(".portable-transfer .identity-check{display:flex;gap:var(--space-2);align-items:center;min-height:var(--control-size);cursor:pointer;font-weight:var(--weight-regular)}");});-- it("enforces WCAG AA compliant error styling and accessible role for transfer errors (R-27)", () => {- expect(PORTABILITY_STYLE).toContain(".transfer-error{");- expect(PORTABILITY_STYLE).toContain("color:var(--destructive-text)");- expect(PORTABILITY_STYLE).toContain("background:var(--settings-card)");- expect(PORTABILITY_STYLE).toContain("overflow-wrap:anywhere");- expect(PORTABILITY_SCRIPT).toContain("err.setAttribute('role','alert')");- });-- it("enforces safe text wrapping and explicit overflow handling without nowrap on connection badges (R-03)", () => {- // 1. .connection-state must not use white-space:nowrap, must allow wrap, and must handle overflow explicitly- expect(CONNECTION_MANAGER_STYLE).not.toMatch(/\.connection-state\{[^}]*white-space:nowrap/);- expect(CONNECTION_MANAGER_STYLE).toContain(".integration .connection-state{display:inline-block;max-width:100%");- expect(CONNECTION_MANAGER_STYLE).toMatch(/\.connection-state\{[^}]*overflow-wrap:anywhere/);- expect(CONNECTION_MANAGER_STYLE).toMatch(/\.connection-state\{[^}]*max-width:100%/);-- // 2. .identity-tags span must handle overflow and wrap cleanly- expect(CONNECTION_MANAGER_STYLE).toContain(".integration .identity-tags span{display:inline-block;max-width:100%");- expect(CONNECTION_MANAGER_STYLE).toMatch(/\.identity-tags span\{[^}]*overflow-wrap:anywhere/);-- // 3. .connection-heading and its contents must wrap and prevent flex blowouts- expect(CONNECTION_MANAGER_STYLE).toContain(".integration .provider-heading,.integration .connection-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--space-4);flex-wrap:wrap}");- expect(CONNECTION_MANAGER_STYLE).toContain(".integration .connection-heading small{display:block;margin-top:var(--space-1);color:var(--muted-foreground);overflow-wrap:anywhere}");- expect(CONNECTION_MANAGER_STYLE).toContain(".integration .connection-heading>div{min-width:0;max-width:100%}");- });-});--// iOS Safari zooms into any focused input whose font-size is below 16px, and the page does not-// zoom back out. --type-caption is 12px, so the sidebar search had this defect.-it("keeps every touch input at or above the 16px iOS auto-zoom threshold", () => {- expect(CONNECTION_MANAGER_STYLE).toMatch(/input\[type=search\]\{[^}]*font-size:var\(--type-body\)/);- // The general form control rule already uses the body size, which is 16px.- expect(INTEGRATION_FORM_STYLE).toMatch(/\.integration input,\.integration select\{[^}]*font:var\(--type-body\)/);-});--// The drawer slide is decorative; the state change is conveyed by position and aria-expanded.-it("stops the decorative drawer transition under reduced motion", () => {- expect(CONNECTION_MANAGER_STYLE).toContain("@media (prefers-reduced-motion:reduce)");- expect(CONNECTION_MANAGER_STYLE).toMatch(/prefers-reduced-motion:reduce\)\{[^}]*integration-settings-sidebar\{transition:none\}/);});diff --git a/lib/infra/portable/ui.ts b/lib/infra/portable/ui.tsindex b58d34ff..fb067c34 100644--- a/lib/infra/portable/ui.ts+++ b/lib/infra/portable/ui.ts@@ -58,7 +58,7 @@ function mountPortability(root,bridge){const apply=button('Apply import',async()=>{if(!preview||!reviewed.i.checked){status.textContent='Review the preview and confirm first.';return}apply.disabled=check.disabled=true;try{const result=await bridge.request({...input(),apply:true,confirm:preview.planId,acceptWarnings:reviewed.i.checked});previewBox.textContent=JSON.stringify(result,null,2);status.textContent='Import complete. Imported connections are not marked verified; external authorization must be completed again.';documentData=null;file.i.value='';decrypt.i.value='';preview=null}catch(e){status.textContent=e.message;apply.disabled=false}finally{check.disabled=false}},'primary');apply.disabled=true;card.append(file.l,decrypt.l,prefix.l,policyLabel,check,previewBox,reviewed.l,apply,status);body.append(card);}function render(){if(disposed)return;body.replaceChildren();exportTab.setAttribute('aria-selected',String(active==='export'));importTab.setAttribute('aria-selected',String(active==='import'));active==='export'?exportView():importView()}- render();bridge.request({action:'tree'}).then(data=>{if(disposed)return;tree=data;for(const owner of tree.users)for(const p of owner.providers)for(const c of p.connections)selected.add(owner.id+'|'+p.id+'|'+c.id);if(active==='export')render()}).catch(e=>{if(!disposed){tree={users:[]};const err=el('p',e.message,'transfer-error');err.setAttribute('role','alert');body.prepend(err)}});+ render();bridge.request({action:'tree'}).then(data=>{if(disposed)return;tree=data;for(const owner of tree.users)for(const p of owner.providers)for(const c of p.connections)selected.add(owner.id+'|'+p.id+'|'+c.id);if(active==='export')render()}).catch(e=>{if(!disposed){tree={users:[]};body.prepend(el('p',e.message,'transfer-error'))}});function cleanup(){disposed=true;documentData=null;preview=null;selected.clear();root.replaceChildren();root.classList.remove('portable-transfer','integration')}return cleanup;}@@ -71,6 +71,5 @@ export const PORTABILITY_STYLE=String.raw`.portable-transfer .identity-check{display:flex;gap:var(--space-2);align-items:center;min-height:var(--control-size);cursor:pointer;font-weight:var(--weight-regular)}.portable-transfer .identity-check input{width:var(--icon-size);height:var(--icon-size);margin:0;order:-1;flex:none;accent-color:var(--primary)}.portable-transfer .transfer-tree{max-height:var(--settings-scroll-max-height);overflow:auto;margin:var(--space-3) 0;padding:var(--space-3);border:var(--stroke) solid var(--border);border-radius:var(--radius-control);background:var(--background)}.portable-transfer .transfer-tree-user{padding:var(--space-2) 0;border-bottom:var(--stroke) solid var(--border)}.portable-transfer .transfer-tree-provider{padding-left:var(--space-6)}.portable-transfer .transfer-tree-provider>.identity-check~.identity-check{padding-left:var(--space-6);color:var(--muted-foreground)}.portable-transfer pre{max-height:var(--settings-code-max-height);overflow:auto;font:var(--type-caption)/var(--line-body) var(--font-mono);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--muted);border-radius:var(--radius-control);padding:var(--space-3)}.portable-transfer [role=status]{font-size:var(--type-small);overflow-wrap:anywhere}.portable-transfer .transfer-hint{font-size:var(--type-caption);color:var(--muted-foreground);margin-top:var(--space-3)}.portable-transfer button{min-height:var(--control-size);margin:var(--space-2) var(--space-2) var(--space-2) 0}-.portable-transfer .transfer-error{color:var(--destructive-text);background:var(--settings-card);border:var(--stroke) solid var(--settings-danger-border);border-radius:var(--radius-control);padding:var(--space-3);margin:var(--space-3) 0;overflow-wrap:anywhere}@container integration (max-width:${SETTINGS_COMPACT_MAX}){.portable-transfer .transfer-card{padding:var(--space-4)}.portable-transfer .transfer-tabs button{flex:1}.portable-transfer .transfer-tree-provider,.portable-transfer .transfer-tree-provider>.identity-check~.identity-check{padding-left:var(--space-3)}}`;diff --git a/lib/infra/setup-capability.test.ts b/lib/infra/setup-capability.test.tsindex e1324cce..26f4ced8 100644--- a/lib/infra/setup-capability.test.ts+++ b/lib/infra/setup-capability.test.ts@@ -78,9 +78,8 @@ describe("native integration setup capabilities", () => {it("standalone page contains no grant and its inline script parses", async () => {const { integrationSetupPage } = await import("./setup-page");const result = integrationSetupPage(); expect(result.csp).toContain("frame-ancestors 'none'");- const scripts = [...result.html.matchAll(/<script nonce="[^"]+">([\s\S]*?)<\/script>/g)].map(m => m[1]);- expect(scripts.length).toBeGreaterThan(0);- for (const script of scripts) expect(() => new Function(script)).not.toThrow();+ const script = result.html.match(/<script nonce="[^"]+">([\s\S]+)<\/script>/)?.[1];+ expect(script).toBeTruthy(); expect(() => new Function(script!)).not.toThrow();expect(result.html).not.toContain(KEY); expect(result.html).not.toContain("si-coder");});});diff --git a/lib/infra/setup-hub.test.ts b/lib/infra/setup-hub.test.tsindex 5897a049..84b8911f 100644--- a/lib/infra/setup-hub.test.ts+++ b/lib/infra/setup-hub.test.ts@@ -11,14 +11,7 @@ it("derives the complete native setup catalog from the same provider registry",});it("keeps guidance before login and preserves explicit role/expiry recovery", () => {const page = integrationSetupPage();- for (const script of inlineScripts(page.html)) expect(() => new Function(script)).not.toThrow();+ expect(() => new Function(inlineScripts(page.html)[0])).not.toThrow();for (const marker of ['"/api/auth/me"', 'owner=auth.role==="owner"', '"visibilitychange"', 'How to get this credential', 'mountConnectionManager', 'field-source', 'Array.isArray(f.links)']) expect(page.html).toContain(marker);expect(CONNECTION_MANAGER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");});-it("includes widget theme script in head before first paint to follow host theme", () => {- const page = integrationSetupPage();- const head = page.html.slice(0, page.html.indexOf("</head>"));- expect(head).toContain("applyHostTheme");- expect(head).toContain("window.openai");- expect(head).toMatch(/<script nonce="[^"]+">[\s\S]*applyHostTheme[\s\S]*<\/script>/);-});diff --git a/lib/infra/setup-page.ts b/lib/infra/setup-page.tsindex a9c9b0db..42d96a7f 100644--- a/lib/infra/setup-page.ts+++ b/lib/infra/setup-page.ts@@ -1,7 +1,7 @@import { MSO_LOGO_SVG } from "@/lib/presentation/logo";import {PORTABILITY_SCRIPT,PORTABILITY_STYLE} from "./portable/ui";import { randomBytes } from "node:crypto";-import { MSO_WIDGET_THEME_SCRIPT, MSO_WIDGET_TOKENS } from "@/lib/presentation/widget-tokens";+import { MSO_WIDGET_TOKENS } from "@/lib/presentation/widget-tokens";import { INTEGRATION_FORM_SCRIPT, INTEGRATION_FORM_STYLE } from "./setup-ui";import { CONNECTION_MANAGER_SCRIPT, CONNECTION_MANAGER_STYLE } from "./connection-ui";import { INTEGRATION_BROWSER_SCRIPT } from "./setup-browser";@@ -17,7 +17,7 @@ button{border:var(--stroke) solid var(--input);border-radius:var(--radius-controexport function integrationSetupPage(embedded = false) {const nonce = randomBytes(18).toString("base64");const catalog = JSON.stringify(connectionCatalog()).replace(/</g,"\\u003c");- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Integrations · MSO</title><style nonce="${nonce}">${MSO_WIDGET_TOKENS}${INTEGRATION_PAGE_STYLE}${INTEGRATION_FORM_STYLE}${CONNECTION_MANAGER_STYLE}${PORTABILITY_STYLE}${embedded ? "html,body{height:100%}body{padding:0;overflow:hidden}.site-bar{display:none}#setup{height:100%}" : ""}</style><script nonce="${nonce}">${MSO_WIDGET_THEME_SCRIPT}applyHostTheme();try{window.addEventListener("openai:set_globals",applyHostTheme,{passive:true});}catch(_){}</script></head><body><header class="site-bar"><strong>${MSO_LOGO_SVG} MSO</strong><span>Your service connections</span></header><main id="setup" class="integration"><h1>Integrations</h1><p>Preparing the native provider catalog…</p><noscript>Enable JavaScript to open the secure credential form. Credentials can also be entered through the MSO terminal.</noscript></main><script nonce="${nonce}">const INTEGRATIONS_CATALOG=${catalog};${INTEGRATION_FORM_SCRIPT}${CONNECTION_MANAGER_SCRIPT}${PORTABILITY_SCRIPT}${INTEGRATION_BROWSER_SCRIPT}</script></body></html>`;+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Integrations · MSO</title><style nonce="${nonce}">${MSO_WIDGET_TOKENS}${INTEGRATION_PAGE_STYLE}${INTEGRATION_FORM_STYLE}${CONNECTION_MANAGER_STYLE}${PORTABILITY_STYLE}${embedded ? "html,body{height:100%}body{padding:0;overflow:hidden}.site-bar{display:none}#setup{height:100%}" : ""}</style></head><body><header class="site-bar"><strong>${MSO_LOGO_SVG} MSO</strong><span>Your service connections</span></header><main id="setup" class="integration"><h1>Integrations</h1><p>Preparing the native provider catalog…</p><noscript>Enable JavaScript to open the secure credential form. Credentials can also be entered through the MSO terminal.</noscript></main><script nonce="${nonce}">const INTEGRATIONS_CATALOG=${catalog};${INTEGRATION_FORM_SCRIPT}${CONNECTION_MANAGER_SCRIPT}${PORTABILITY_SCRIPT}${INTEGRATION_BROWSER_SCRIPT}</script></body></html>`;return { html, csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors ${embedded ? "'self'" : "'none'"}` };}function integrationResponse(embedded: boolean) {diff --git a/scripts/mso-agent-chrome.mjs b/scripts/mso-agent-chrome.mjsindex 0c720e55..df0d1070 100644--- a/scripts/mso-agent-chrome.mjs+++ b/scripts/mso-agent-chrome.mjs@@ -1,7 +1,7 @@import { cellWidth, clean, fitCells } from "./tui/cells.mjs";import { composerFooter } from "./mso-agent-layout.mjs";-function candidateSplits(kept, total, activeIdx) {+export function candidateSplits(kept, total, activeIdx) {const splits = [];for (let l = 0; l <= kept; l++) {const r = kept - l;@@ -11,7 +11,7 @@ function candidateSplits(kept, total, activeIdx) {return all.sort((a, b) => Math.abs(a - kept / 2) - Math.abs(b - kept / 2));}-function makeSegments(itemsList, orientation = "horizontal", maxWidth = 80) {+export function makeSegments(itemsList, orientation = "horizontal", maxWidth = 80) {if (orientation === "vertical") {const contentWidth = Math.max(1, maxWidth - 1);return itemsList.map((it, row) => {@@ -22,7 +22,9 @@ function makeSegments(itemsList, orientation = "horizontal", maxWidth = 80) {row,start: 0,end: Math.min(it.width, contentWidth),- styled: fitCells(it.styled || it.plainText || "", contentWidth, { pad: false }),+ styled: cellWidth(it.styled || it.plainText || "") <= contentWidth+ ? (it.styled || it.plainText || "")+ : fitCells(it.styled || it.plainText || "", contentWidth, { pad: false }),plainText: it.plainText || it.text || "",text: it.text,isActive: Boolean(it.isActive),@@ -39,23 +41,37 @@ function makeSegments(itemsList, orientation = "horizontal", maxWidth = 80) {return segments;}+// The indicator reads ONLY explicit status or turnActive. Timestamps are deliberately ignored+// because updatedAt records turn completion, not progress (docs/AGENT-ACTIVITY-SIGNAL.md).+export function tabStatusGlyph(session) {+ if (!session || typeof session !== "object") return " ";+ const row = session.agentSession && typeof session.agentSession === "object" ? session.agentSession : session;+ if (row.error || session.error || ["error", "errored", "failed"].includes(String(row.status || session.status || ""))) return "!";+ if (row.turnActive === true || session.turnActive === true || ["working", "busy", "running"].includes(String(row.status || session.status || ""))) return "●";+ if (row.status === "idle" || session.status === "idle") return "○";+ return " ";+}+/** @param {Array<any>} sessions @param {string|number|null} [activeId] @param {any} [options] */-export function tabLayout(sessions, activeId = null, { colors = {}, width = 80, rows = null, orientation = "horizontal" } = {}) {+export function tabLayout(sessions, activeId = null, options = {}) {+ const opts = options || {};+ const width = opts.width, rows = opts.rows ?? null, orientation = opts.orientation || "horizontal", colors = opts.colors || {};if (!Array.isArray(sessions) || sessions.length === 0) {return { segments: [], maxWidth: Math.max(1, Number(width) || 80) };}const maxWidth = Math.max(1, Number(width) || 80);const sep = " ";const cBold = colors?.bold || "", cBlue = colors?.blue || "", cDim = colors?.dim || "", cReset = colors?.reset || "";+ const indicatorMode = (opts.indicators || opts.session?.tabsIndicators) === "status" ? "status" : "numbers";const items = sessions.map((s) => {const rawName = clean(s?.name || s?.agentSession?.name || "").replace(/^@/, "");const name = rawName || "agent";const id = String(s?.id || s?.agentSession?.id || "");const isActive = activeId != null && (String(activeId) === id || String(activeId).replace(/^@/, "") === name);- const marker = isActive ? "● " : "";+ const marker = indicatorMode === "status" ? `${tabStatusGlyph(s)} ` : (isActive ? "● " : "");const plainText = `${marker}@${name}`;- const styled = isActive ? `${cBold}${cBlue}${marker}@${name}${cReset}` : `${cDim}@${name}${cReset}`;+ const styled = isActive ? `${cBold}${cBlue}${marker}@${name}${cReset}` : `${cDim}${marker}@${name}${cReset}`;return { id, name, isActive, plainText, styled, width: cellWidth(plainText) };});@@ -131,7 +147,9 @@ export function tabRailLines(sessions, activeId = null, options = {}) {lines.push(" ".repeat(contentWidth) + borderChar);continue;}- const plain = fitCells(seg.plainText || "", contentWidth, { pad: false });+ const plain = cellWidth(seg.plainText || "") <= contentWidth+ ? (seg.plainText || "")+ : fitCells(seg.plainText || "", contentWidth, { pad: false });const pad = " ".repeat(Math.max(0, contentWidth - cellWidth(plain)));const styled = seg.isActive ? `${cBold}${cBlue}${plain}${cReset}` : (cDim ? `${cDim}${plain}${cReset}` : plain);lines.push(styled + pad + borderChar);@@ -165,18 +183,17 @@ export function chromeLines({width = 80,rows = null,footer = null,+ indicators = null,} = {}) {const termRows = rows != null ? Number(rows) : null;if (termRows !== null && termRows <= 6) return [];- const tab = tabRow(sessions, activeId, { colors, width });+ const ind = indicators ?? session?.tabsIndicators ?? session?.tabIndicators ?? null;+ const tab = tabRow(sessions, activeId, { colors, width, ...(ind ? { indicators: ind } : {}) });if (termRows !== null && termRows <= 8) return tab ? [tab] : [];- let foot = "";- if (footer != null) {- foot = typeof footer === "function" ? String(footer() || "") : String(footer || "");- } else if (session != null) {- foot = String(composerFooter(session, colors, width) || "");- }+ const foot = footer != null+ ? (typeof footer === "function" ? String(footer() || "") : String(footer || ""))+ : (session != null ? String(composerFooter(session, colors, width) || "") : "");return [tab, foot].filter((line) => typeof line === "string" && line.trim().length > 0).slice(0, 2);}@@ -192,12 +209,7 @@ export function tabsToSwitch(sessions, args) {const query = raw.toLowerCase().replace(/^@/, "");const getName = (s) => clean(s?.name || s?.agentSession?.name || "").toLowerCase().replace(/^@/, "");const getId = (s) => String(s?.id || s?.agentSession?.id || "").toLowerCase();- for (const match of [- (s) => getName(s) === query,- (s) => getId(s) === query,- (s) => getName(s).startsWith(query),- (s) => getId(s).startsWith(query),- ]) {+ for (const match of [(s) => getName(s) === query, (s) => getId(s) === query, (s) => getName(s).startsWith(query), (s) => getId(s).startsWith(query)]) {const hits = sessions.filter(match);if (hits.length === 1) return hits[0];if (hits.length > 1) return null;diff --git a/scripts/mso-agent-cmd-settings.mjs b/scripts/mso-agent-cmd-settings.mjsindex eac02b7e..672203ca 100644--- a/scripts/mso-agent-cmd-settings.mjs+++ b/scripts/mso-agent-cmd-settings.mjs@@ -26,8 +26,18 @@ export async function handleSettingsCommand(ctx, args = []) {// Propagate reset tab layout so the running screen loop repaints with defaultsconst tabsLayout = settings["tabs.layout"] ?? settings.layout;if (tabsLayout) session.tabsLayout = tabsLayout;+ const tabsIndicators = settings["tabs.indicators"] ?? settings.indicators;+ if (tabsIndicators) session.tabsIndicators = tabsIndicators;+ const tabsScope = settings["tabs.scope"] ?? settings.scope;+ if (tabsScope) session.tabsScope = tabsScope;if (settings.minwidth != null) session.paneMinColumns = Number(settings.minwidth);+ const scrollSpeed = settings["scroll.speed"] ?? settings.speed;+ if (scrollSpeed != null) session.scrollSpeed = Number(scrollSpeed);if (settings.grouping) session.grouping = settings.grouping;+ if (settings.mouse) {+ session.mouse = settings.mouse;+ session.screenLoop?.setMouse?.(settings.mouse);+ }session.screenLoop?.sync?.();// Propagate verbosity to session so status footer updates immediatelyif (settings.verbosity) session.verbosity = settings.verbosity;@@ -100,12 +110,24 @@ export async function handleSettingsCommand(ctx, args = []) {if (entry.key === "statusbar") session.statusBar = requestedValue === "on";// Sync tab rail orientation immediately so users see layout change without restartif (entry.key === "layout") session.tabsLayout = requestedValue;+ if (entry.key === "indicators") session.tabsIndicators = requestedValue;+ // Sync tab scope immediately so filtering updates on running screen loop+ if (entry.key === "scope") {+ session.tabsScope = requestedValue;+ session.screenLoop?.sync?.();+ }if (entry.key === "minwidth") session.paneMinColumns = valueToSave;+ if (entry.key === "speed") session.scrollSpeed = valueToSave;if (entry.key === "grouping") {session.grouping = requestedValue;// Repaint immediately so grouping change reflects on screen without restartsession.screenLoop?.sync?.();}+ // Mouse toggle updates reporting escape codes immediately so users regain native text selection+ if (entry.key === "mouse") {+ session.mouse = requestedValue;+ session.screenLoop?.setMouse?.(requestedValue);+ }// Propagate verbosity to session so status footer updates immediatelyif (entry.key === "verbosity") session.verbosity = requestedValue;}@@ -124,8 +146,16 @@ export function applySettings(session, settings = getSettings()) {// The screen loop reads session.tabsLayout to switch between horizontal row and vertical railconst tabsLayout = settings["tabs.layout"] ?? settings.layout;if (tabsLayout) session.tabsLayout = tabsLayout;+ const tabsIndicators = settings["tabs.indicators"] ?? settings.indicators;+ if (tabsIndicators) session.tabsIndicators = tabsIndicators;+ // Apply saved tabs scope preference so session starts with configured scope+ const tabsScope = settings["tabs.scope"] ?? settings.scope;+ if (tabsScope) session.tabsScope = tabsScope;if (settings.minwidth != null) session.paneMinColumns = Number(settings.minwidth);+ const scrollSpeed = settings["scroll.speed"] ?? settings.speed;+ if (scrollSpeed != null) session.scrollSpeed = Number(scrollSpeed);if (settings.grouping) session.grouping = settings.grouping;+ if (settings.mouse) session.mouse = settings.mouse;// Apply saved verbosity preference to session at startupif (settings.verbosity) session.verbosity = settings.verbosity;}diff --git a/scripts/mso-agent-diff-settings.test.ts b/scripts/mso-agent-diff-settings.test.tsnew file mode 100644index 00000000..429791f4--- /dev/null+++ b/scripts/mso-agent-diff-settings.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from "vitest";+import { formatEditDiff } from "./mso-agent-edit-diff.mjs";+import { paneLines } from "./mso-agent-pane.mjs";+import { SETTINGS, defaultSettings, resolveSetting } from "./mso-agent-settings.mjs";+import { handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";++describe("MSO Agent diff settings and honesty checks", () => {+ // Test 1: Defaults reproduce existing output byte for byte against recorded fixtures+ it("1. default output is byte-identical to recorded fixtures for formatEditDiff and paneLines", () => {+ const parsedStandard = {+ path: "src/sample.ts",+ written: true,+ diff: "--- a/src/sample.ts\n+++ b/src/sample.ts\n@@ -1,3 +1,3 @@\n-const oldVal = 1;\n+const newVal = 2;\n context line\n",+ };+ const expectedStandard =+ " edit sample.ts\n --- a/src/sample.ts\n +++ b/src/sample.ts\n @@ -1,3 +1,3 @@\n -const oldVal = 1;\n +const newVal = 2;\n context line";+ expect(formatEditDiff(parsedStandard)).toBe(expectedStandard);++ const parsedPreview = {+ path: "src/preview.ts",+ written: false,+ diff: "--- a/src/preview.ts\n+++ b/src/preview.ts\n@@ -1 +1 @@\n-old\n+new\n",+ };+ const expectedPreview =+ " edit preview.ts (preview, not written)\n --- a/src/preview.ts\n +++ b/src/preview.ts\n @@ -1 +1 @@\n -old\n +new";+ expect(formatEditDiff(parsedPreview)).toBe(expectedPreview);++ const parsedTrunc = {+ path: "src/sample.ts",+ written: true,+ diff: "@@ -1,5 +1,5 @@\n-line 1\n-line 2\n+line 3\n+line 4\n context\n",+ };+ const expectedTrunc =+ " edit sample.ts\n @@ -1,5 +1,5 @@\n -line 1\n -line 2\n … 3 more lines";+ expect(formatEditDiff(parsedTrunc, { cap: 3 })).toBe(expectedTrunc);++ // Diff pane empty state byte fixture+ const emptyPane = paneLines({ kind: "diff", lastDiff: null, width: 35, rows: 6 });+ expect(emptyPane).toEqual([+ "┌─────────────────────────────────┐",+ "│Last edit diff │",+ "├─────────────────────────────────┤",+ "│(no edits in this session) │",+ "│ │",+ "└─────────────────────────────────┘",+ ]);++ // Diff pane active state byte fixture+ const diffObj = {+ path: "src/sample.ts",+ diff: "--- a/src/sample.ts\n+++ b/src/sample.ts\n@@ -1,2 +1,2 @@\n-old line\n+new line\n",+ };+ const activePane = paneLines({ kind: "diff", lastDiff: diffObj, width: 35, rows: 8 });+ expect(activePane).toEqual([+ "┌─────────────────────────────────┐",+ "│Last edit diff │",+ "├─────────────────────────────────┤",+ "│edit sample.ts │",+ "│--- a/src/sample.ts │",+ "│+++ b/src/sample.ts │",+ "│@@ -1,2 +1,2 @@ │",+ "└─────────────────────────────────┘",+ ]);+ });++ // Test 2 & 3: Each refused candidate from opencode is absent from registry and documented+ it("2. candidate diff settings are absent from the registry to prevent phantom switches", () => {+ const keys = SETTINGS.map((s) => s.key);+ const paths = SETTINGS.map((s) => s.path);+ const defaults: Record<string, any> = defaultSettings();++ // diffs.wrap: refused because diff lines are clipped by fitCells to pane width, never wrapped+ expect(keys).not.toContain("diffs.wrap");+ expect(keys).not.toContain("wrap");+ expect(paths).not.toContain("diffs.wrap");+ expect(defaults["diffs.wrap"]).toBeUndefined();++ // diffs.view: refused because split side-by-side in 30-50 col pane leaves 13-23 cols per side+ expect(keys).not.toContain("diffs.view");+ expect(keys).not.toContain("view");+ expect(paths).not.toContain("diffs.view");+ expect(defaults["diffs.view"]).toBeUndefined();++ // diffs.tree: refused because the files pane kind already lists all changed files+ expect(keys).not.toContain("diffs.tree");+ expect(keys).not.toContain("tree");+ expect(paths).not.toContain("diffs.tree");+ expect(defaults["diffs.tree"]).toBeUndefined();++ // diffs.single: refused because diff pane only ever resolves the single latest edit diff+ expect(keys).not.toContain("diffs.single");+ expect(keys).not.toContain("single");+ expect(paths).not.toContain("diffs.single");+ expect(defaults["diffs.single"]).toBeUndefined();+ });++ it("3. resolveSetting returns null for refused diff settings and /settings reports unknown", async () => {+ // Setting resolution checks+ expect(resolveSetting(SETTINGS, "diffs.view")).toBeNull();+ expect(resolveSetting(SETTINGS, "diffs.wrap")).toBeNull();+ expect(resolveSetting(SETTINGS, "diffs.tree")).toBeNull();+ expect(resolveSetting(SETTINGS, "diffs.single")).toBeNull();++ // Running /settings command with refused diff settings reports unknown setting+ const printed: string[] = [];+ const ctx = {+ session: { paneKind: "off" },+ C: {},+ write: (line: string) => printed.push(line),+ };++ await handleSettingsCommand(ctx, ["diffs.view", "split"]);+ expect(printed.some((p) => p.includes('unknown setting "diffs.view"'))).toBe(true);++ printed.length = 0;+ await handleSettingsCommand(ctx, ["diffs.wrap", "word"]);+ expect(printed.some((p) => p.includes('unknown setting "diffs.wrap"'))).toBe(true);+ });++ // Test 4: An invalid value is refused with the valid list+ it("4. invalid values are refused with the valid list of options", async () => {+ const printed: string[] = [];+ const session: any = { paneKind: "off" };+ const ctx = {+ session,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Refuse invalid pane value while listing valid options including diff+ await handleSettingsCommand(ctx, ["pane", "invalid_pane_kind"]);+ expect(session.paneKind).toBe("off");+ const paneWarning = printed.find((p) => p.includes("invalid value"));+ expect(paneWarning).toBeDefined();+ expect(paneWarning).toContain("todos, diff, files, mcp, context, off");++ // Setting a valid pane kind works immediately+ printed.length = 0;+ await handleSettingsCommand(ctx, ["pane", "diff"]);+ expect(session.paneKind).toBe("diff");++ // Refuse invalid layout option with valid list+ printed.length = 0;+ await handleSettingsCommand(ctx, ["layout", "diagonal"]);+ const layoutWarning = printed.find((p) => p.includes("invalid value"));+ expect(layoutWarning).toBeDefined();+ expect(layoutWarning).toContain("horizontal, vertical");++ // Refuse invalid verbosity option with valid list+ printed.length = 0;+ await handleSettingsCommand(ctx, ["verbosity", "maximum"]);+ const verbosityWarning = printed.find((p) => p.includes("invalid value"));+ expect(verbosityWarning).toBeDefined();+ expect(verbosityWarning).toContain("low, medium, high");+ });+});diff --git a/scripts/mso-agent-mouse-setting.test.ts b/scripts/mso-agent-mouse-setting.test.tsnew file mode 100644index 00000000..8d58ff97--- /dev/null+++ b/scripts/mso-agent-mouse-setting.test.ts@@ -0,0 +1,163 @@+import { EventEmitter } from "node:events";+import { describe, expect, it, vi } from "vitest";+import { handleSettingsCommand, applySettings } from "./mso-agent-cmd-settings.mjs";+import { MOUSE_OFF, MOUSE_ON } from "./mso-agent-mouse.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";+import { SETTINGS } from "./mso-agent-settings-entries.mjs";++class FakeOutput extends EventEmitter {+ isTTY = true;+ columns = 80;+ rows = 24;+ chunks: string[] = [];+ write(str: string) {+ this.chunks.push(String(str));+ return true;+ }+}++describe("mouse setting gates terminal mouse reporting and dispatch", () => {+ it("entry matches expected schema in settings registry", () => {+ // Registry entry must define key, path, category and binary on/off options.+ const entry = SETTINGS.find((s) => s.key === "mouse");+ expect(entry).toBeDefined();+ expect(entry?.category).toBe("Input");+ expect(entry?.path).toBe("mouse");+ expect(entry?.default).toBe("on");+ expect(entry?.values).toEqual(["on", "off"]);+ });++ it("1. default on writes the on sequence at mount, asserted against today's behaviour", () => {+ // Preserves existing behavior: when no mouse setting is specified, mouse reporting turns on.+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session = { agentSession: { id: "s1", name: "test" }, history: [] };++ const loop = mountScreenLoop({ enabled: true, session, output, input });+ expect(output.chunks[0]).toBe(MOUSE_ON);++ loop.dispose();+ expect(output.chunks).toContain(MOUSE_OFF);+ });++ it("2. off writes nothing at mount and ignores wheel and click", () => {+ // With mouse disabled, terminal selection must remain unobstructed.+ const output = new FakeOutput();+ const input = new EventEmitter();+ const onTabClick = vi.fn();+ const session = {+ agentSession: { id: "s1", name: "test" },+ history: [],+ mouse: "off",+ };++ const loop = mountScreenLoop({+ enabled: true,+ session,+ output,+ input,+ onTabClick,+ getSessions: () => [{ id: "s1", name: "alpha" }, { id: "s2", name: "beta" }],+ });++ // Neither MOUSE_ON nor MOUSE_OFF should be emitted at mount when disabled.+ expect(output.chunks).not.toContain(MOUSE_ON);+ expect(output.chunks).not.toContain(MOUSE_OFF);++ const initialChunkCount = output.chunks.length;++ // Simulate mouse wheel sequence through input hook; must be ignored.+ input.emit("data", "\x1b[<64;20;15M");+ expect(output.chunks.length).toBe(initialChunkCount);++ // Simulate mouse click sequence on tab bar; callback must not be invoked.+ input.emit("data", "\x1b[<0;10;1M");+ expect(onTabClick).not.toHaveBeenCalled();++ loop.dispose();+ });++ it("3. toggling from on to off at runtime writes the off sequence immediately", async () => {+ // Turning mouse off at runtime releases terminal selection without restarting the agent.+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session: any = { agentSession: { id: "s1", name: "test" }, history: [] };++ const loop = mountScreenLoop({ enabled: true, session, output, input });+ expect(output.chunks[0]).toBe(MOUSE_ON);++ // Toggle off via settings command to simulate user typing /settings mouse off.+ const ctx = { session, print: () => {}, C: {} };+ await handleSettingsCommand(ctx, ["mouse", "off"]);++ expect(session.mouse).toBe("off");+ expect(output.chunks).toContain(MOUSE_OFF);++ // Toggling back on writes MOUSE_ON immediately.+ await handleSettingsCommand(ctx, ["mouse", "on"]);+ expect(session.mouse).toBe("on");+ const onCount = output.chunks.filter((c) => c === MOUSE_ON).length;+ expect(onCount).toBe(2);++ loop.dispose();+ });++ it("4. after a suspend and resume with the setting off, no mouse sequence is written", () => {+ // When mouse is off, entering and leaving prompts must not turn mouse capture back on.+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session = {+ agentSession: { id: "s1", name: "test" },+ history: [],+ mouse: "off",+ };++ const loop = mountScreenLoop({ enabled: true, session, output, input });+ const baselineChunks = [...output.chunks];++ loop.suspend();+ loop.resume();++ const postResumeChunks = output.chunks.slice(baselineChunks.length);+ const mouseSequences = postResumeChunks.filter((c) => c.includes(MOUSE_ON) || c.includes(MOUSE_OFF));+ expect(mouseSequences).toHaveLength(0);++ loop.dispose();+ });++ it("5. after a suspend and resume with the setting on, mouse is restored exactly once", () => {+ // Suspend must disable mouse capture, and resume must restore it once.+ const output = new FakeOutput();+ const input = new EventEmitter();+ const session = {+ agentSession: { id: "s1", name: "test" },+ history: [],+ mouse: "on",+ };++ const loop = mountScreenLoop({ enabled: true, session, output, input });+ expect(output.chunks[0]).toBe(MOUSE_ON);++ output.chunks = [];+ loop.suspend();+ expect(output.chunks).toContain(MOUSE_OFF);++ output.chunks = [];+ loop.resume();+ const onChunks = output.chunks.filter((c) => c === MOUSE_ON);+ expect(onChunks).toHaveLength(1);++ loop.dispose();+ });++ it("applySettings propagates mouse preference to session", () => {+ // Stored settings loaded at startup must configure session.mouse before mount.+ const sessionOff: any = {};+ applySettings(sessionOff, { mouse: "off" } as any);+ expect(sessionOff.mouse).toBe("off");++ const sessionOn: any = {};+ applySettings(sessionOn, { mouse: "on" } as any);+ expect(sessionOn.mouse).toBe("on");+ });+});diff --git a/scripts/mso-agent-mouse.mjs b/scripts/mso-agent-mouse.mjsindex 0f6527ef..b936b49a 100644--- a/scripts/mso-agent-mouse.mjs+++ b/scripts/mso-agent-mouse.mjs@@ -134,31 +134,62 @@ export function parseMouseChunk(chunk) {/*** Handles mouse wheel scrolling for the transcript viewport.- * Wheel up scrolls up by 3 lines; wheel down scrolls down by 3 lines.+ * Wheel step defaults to 3 lines, configurable via options or session scrollSpeed.* Returns true when the event was consumed.** @param {any} scroll* @param {any} event- * @param {{ rows?: number, onScroll?: (offset: number) => void }} [options]+ * @param {{ rows?: number, onScroll?: (offset: number) => void, step?: number, speed?: number, session?: any }} [options]* @returns {boolean}*/-export function handleMouse(scroll, event, { rows, onScroll } = {}) {+export function handleMouse(scroll, event, { rows, onScroll, step, speed, session } = {}) {if (!scroll || !event || event.kind !== "wheel") return false;+ // Viewport is line-based: fractional rows are impossible in a terminal cell grid.+ // We clamp step to integer range [1, 10] matching opencode bounds without pretending sub-line precision.+ const rawStep = step ?? speed ?? session?.scrollSpeed ?? scroll?.scrollSpeed ?? 3;+ const numStep = Number(rawStep);+ const resolvedStep = Number.isFinite(numStep) && numStep >= 1 ? Math.min(10, Math.floor(numStep)) : 3;+if (event.button === "up") {const maxOffset = Array.isArray(scroll?.lines) && scroll.lines.length > 0? Math.max(0, getAllLines(scroll).length - Math.max(1, Number(rows ?? scroll.rows) || 1)): Number.POSITIVE_INFINITY;- scroll.offset = Math.min(maxOffset, (scroll.offset || 0) + 3);+ scroll.offset = Math.min(maxOffset, (scroll.offset || 0) + resolvedStep);if (typeof onScroll === "function") onScroll(scroll.offset);return true;}if (event.button === "down") {- scroll.offset = Math.max(0, (scroll.offset || 0) - 3);+ scroll.offset = Math.max(0, (scroll.offset || 0) - resolvedStep);if (typeof onScroll === "function") onScroll(scroll.offset);return true;}return false;}++/**+ * Resolves whether mouse reporting is enabled given a setting/option and/or session.+ * Default is true ("on") to match existing behavior; only explicit "off" or false disables.+ *+ * @param {any} [setting]+ * @param {any} [session]+ * @returns {boolean}+ */+export function isMouseEnabled(setting, session) {+ const val = setting ?? session?.mouse;+ return val !== "off" && val !== false;+}++/**+ * Synchronizes mouse reporting state on an output stream.+ *+ * @param {any} output+ * @param {boolean} enabled+ * @returns {boolean}+ */+export function setMouseReporting(output, enabled) {+ return enabled ? enableMouse(output) : disableMouse(output);+}+diff --git a/scripts/mso-agent-panel-geometry.mjs b/scripts/mso-agent-panel-geometry.mjsnew file mode 100644index 00000000..6bdd7783--- /dev/null+++ b/scripts/mso-agent-panel-geometry.mjs@@ -0,0 +1,44 @@+// Panel geometry, kept out of the screen loop so three features can touch layout without pushing that+// file past the line ratchet. Every number here decides how much terminal a user sees, so the reasoning+// travels with the arithmetic.+import { chromeLines } from "./mso-agent-chrome.mjs";+import { composerSeparator } from "./mso-agent-layout.mjs";+import { paneWidth } from "./mso-agent-pane.mjs";+import { tabRailWidth } from "./mso-agent-chrome.mjs";+import { filterSessionsByScope } from "./mso-agent-session-list.mjs";++/**+ * @param {{+ * output: any, session: any, colors?: any, getSessions: () => Array<any>,+ * promptReservation: number, tabsLayout?: string|null, tabsScope?: string|null,+ * }} opts+ */+export function panelGeometry({ output, session, colors = {}, getSessions, promptReservation, tabsLayout = null, tabsScope = null }) {+ const cols = Math.max(20, Number(output.columns) || 80);+ const rows = Math.max(6, Number(output.rows) || 24);++ // Scope filters the session list, but never to a set the user cannot navigate back from.+ const list = getSessions();+ const scope = tabsScope || session?.tabsScope || session?.tabScope || "global";+ const targetCwd = session?.cwd || session?.agentSession?.cwd || (typeof process !== "undefined" ? process.cwd?.() : "");+ const scoped = scope !== "cwd" ? list : filterSessionsByScope(list, { scope, cwd: targetCwd, activeId: session?.agentSession?.id });++ // A vertical rail and a bottom row are the same list; the rail wins when it fits, and when it does+ // not the row takes over so session switching is never lost.+ const isVertical = (tabsLayout || session?.tabsLayout || session?.tabLayout) === "vertical";+ const railWidth = isVertical ? tabRailWidth(cols) : 0;+ const chrome = chromeLines({ session, sessions: railWidth > 0 ? [] : scoped, activeId: session.agentSession?.id, colors, width: cols, rows: null });++ const separator = composerSeparator(session, colors, cols);+ const hasSep = typeof separator === "string" && separator.length > 0;+ // The separator belongs to the panel in this mode; the composer is told to draw none.+ const panel = [hasSep ? separator : "", ...chrome].filter((line) => line.length > 0);+ const viewRows = Math.max(0, rows - panel.length - promptReservation);+ const tabRowY = railWidth > 0 ? -1 : viewRows + (hasSep ? 1 : 0);++ const kind = session?.paneKind && session.paneKind !== "off" ? session.paneKind : null;+ // The threshold is configurable so a narrow terminal can still have a 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: promptReservation, sessions: scoped };+}diff --git a/scripts/mso-agent-panel-suspend.mjs b/scripts/mso-agent-panel-suspend.mjsindex 2d42690f..3eb89c07 100644--- a/scripts/mso-agent-panel-suspend.mjs+++ b/scripts/mso-agent-panel-suspend.mjs@@ -1,4 +1,4 @@-import { disableMouse, enableMouse } from "./mso-agent-mouse.mjs";+import { disableMouse, enableMouse, isMouseEnabled } from "./mso-agent-mouse.mjs";import { enterScreen, leaveScreen } from "./mso-agent-altscreen.mjs";/**@@ -17,9 +17,10 @@ import { enterScreen, leaveScreen } from "./mso-agent-altscreen.mjs";* hook?: { setEnabled?: (on: boolean) => void } | null,* onRepaint: () => void,* onReset: () => void,+ * isMouseEnabled?: (() => boolean) | null,* }} options*/-export function createPanelSuspension({ session, output, hook = null, onRepaint, onReset }) {+export function createPanelSuspension({ session, output, hook = null, onRepaint, onReset, isMouseEnabled: mouseGate = null }) {let savedSink = null;let suspended = false;@@ -39,7 +40,10 @@ export function createPanelSuspension({ session, output, hook = null, onRepaint,if (!suspended) return;suspended = false;enterScreen(output);- enableMouse(output);+ // Mouse must be re-enabled only if the setting allows it, preventing+ // a suspend/resume cycle from resurrecting mouse capture when disabled.+ const mouseOn = typeof mouseGate === "function" ? mouseGate() : isMouseEnabled(null, session);+ if (mouseOn) enableMouse(output);hook?.setEnabled?.(true);if (savedSink) {session.streamSink = savedSink;diff --git a/scripts/mso-agent-screen-loop.mjs b/scripts/mso-agent-screen-loop.mjsindex 7c1751dd..e3f3fa22 100644--- a/scripts/mso-agent-screen-loop.mjs+++ b/scripts/mso-agent-screen-loop.mjs@@ -1,14 +1,14 @@import process from "node:process";-import { chromeLines, tabAtPoint, tabRailLines, tabRailWidth } from "./mso-agent-chrome.mjs";-import { composerSeparator } from "./mso-agent-layout.mjs";-import { disableMouse, enableMouse, handleMouse } from "./mso-agent-mouse.mjs";+import { tabAtPoint, tabRailLines, tabRailWidth } from "./mso-agent-chrome.mjs";+import { disableMouse, enableMouse, handleMouse, isMouseEnabled, setMouseReporting } from "./mso-agent-mouse.mjs";import { installInputHook } from "./mso-agent-input-hook.mjs";import { createPanelSuspension } from "./mso-agent-panel-suspend.mjs";+import { panelGeometry } from "./mso-agent-panel-geometry.mjs";import { writeFrame } from "./mso-agent-screen.mjs";import { transcriptLines } from "./mso-agent-transcript.mjs";import { appendStream, commitStream, createViewport, handleViewportKey, resetFollow, setLines } from "./mso-agent-viewport.mjs";import { renderViewport } from "./mso-agent-viewport-render.mjs";-import { paneLines, paneWidth } from "./mso-agent-pane.mjs";+import { paneLines } from "./mso-agent-pane.mjs";import { withPreamble } from "./mso-agent-banner-lines.mjs";import { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";export { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";@@ -29,6 +29,8 @@ export { clampPromptRows, PROMPT_ROWS } from "./mso-agent-composer-ui.mjs";* composer?: any,* preamble?: (() => Array<string> | null) | null,* tabsLayout?: string | null,+ * mouse?: string | boolean | null,+ * tabsScope?: string | null,* }} options*/export function mountScreenLoop({@@ -42,23 +44,20 @@ export function mountScreenLoop({composer = null,preamble = null,tabsLayout = null,+ mouse = null,+ tabsScope = null,} = {}) {if (!enabled || !session) {return {- active: false,- session: null,- paint() {},- sync() {},- suspend() {},- resume() {},- follow() {},+ active: false, session: null, paint() {}, sync() {}, suspend() {}, resume() {}, follow() {},geometry() { return { cols: 80, rows: 24, panel: [], viewRows: 0, tabRowY: 0, pWidth: 0, transWidth: 80, railWidth: 0, kind: null, promptRows: PROMPT_ROWS }; },- setPromptRows() {},- dispose() {},+ setPromptRows() {}, setMouse() {}, dispose() {},+ setPromptRows() {}, dispose() {},};}- enableMouse(output);+ let mouseEnabled = isMouseEnabled(mouse, session);+ if (mouseEnabled) enableMouse(output);const onTeardown = () => { disableMouse(output); };const detach = (target, event, listener) => {@@ -72,43 +71,24 @@ export function mountScreenLoop({let promptReservation = PROMPT_ROWS;const setPromptRows = (rows) => {- // When the composer reports its painted row count, clamp it so the panel never jumps on erase- // and never gets pushed off screen by a tall draft.- //- // Deliberately does NOT repaint here. The composer calls this WHILE it is painting its own draft- // and completion menu, so painting the panel from home would erase both: pressing "/" showed the- // draft and the whole command menu vanish. The reservation is still updated, and the next- // keypress or sync repaints with the new geometry.+ // Clamps reservation without repainting immediately; repainting while composer+ // is drawing its draft/menu would erase them before input is completed.const termRows = Math.max(6, Number(output.rows) || 24);const clamped = clampPromptRows(rows, termRows);if (clamped !== promptReservation) promptReservation = clamped;};if (composer) {- if (typeof composer.onRows === "function") composer.onRows(setPromptRows);- else composer.onRows = setPromptRows;+ typeof composer.onRows === "function" ? composer.onRows(setPromptRows) : (composer.onRows = setPromptRows);}session.onComposerRows = setPromptRows;- const geometry = (reservation = promptReservation) => {- const cols = Math.max(20, Number(output.columns) || 80);- const rows = Math.max(6, Number(output.rows) || 24);- const isVertical = (tabsLayout || session?.tabsLayout || session?.tabLayout) === "vertical";- const railWidth = isVertical ? tabRailWidth(cols) : 0;- const chromeSessions = railWidth > 0 ? [] : getSessions();- const chrome = chromeLines({ session, sessions: chromeSessions, activeId: session.agentSession?.id, colors, width: cols, rows: null });- const separator = composerSeparator(session, colors, cols);- const hasSep = typeof separator === "string" && separator.length > 0;- // The separator belongs to the panel in this mode; the composer is told to draw none.- const panel = [hasSep ? separator : "", ...chrome].filter((line) => line.length > 0);- 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;- // 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 };- };+ // Geometry lives in mso-agent-panel-geometry.mjs: three features touch layout and this file is at its+ // ceiling, but the arithmetic still has exactly one home.+ const geometry = (reservation = promptReservation) => panelGeometry({+ output, session, colors, getSessions, promptReservation: reservation, tabsLayout, tabsScope,+ });+ const currentSessions = () => geometry().sessions;// Repaints from the top of the screen and leaves the cursor where the composer expects to start,// because the composer paints relative to the cursor and cannot be told where to begin.@@ -117,7 +97,7 @@ export function mountScreenLoop({const { panel, viewRows, pWidth, transWidth, railWidth, kind } = geometry();const body = renderViewport(viewport, { colors, width: transWidth, rows: viewRows });const side = pWidth > 0 ? paneLines({ kind, session, colors, width: pWidth, rows: viewRows }) : [];- const rail = railWidth > 0 ? tabRailLines(getSessions(), session?.agentSession?.id, { colors, width: railWidth, rows: viewRows }) : [];+ const rail = railWidth > 0 ? tabRailLines(currentSessions(), session?.agentSession?.id, { colors, width: railWidth, rows: viewRows }) : [];const joined = body.map((line, i) => `${rail[i] || ""}${line}${side[i] || ""}`);const frame = [...joined, ...panel, ""];output.write("\x1b[H");@@ -144,9 +124,10 @@ export function mountScreenLoop({output.on?.("resize", onResize);const dispatchMouse = (event) => {- if (!event) return false;+ // When mouse setting is off, ignore wheel and click completely so terminal selection works.+ if (!event || !mouseEnabled) return false;if (event.kind === "wheel") {- if (handleMouse(viewport, event, { rows: geometry().viewRows })) { paint(); return true; }+ if (handleMouse(viewport, event, { rows: geometry().viewRows, step: session?.scrollSpeed })) { paint(); return true; }return false;}if (event.kind === "click") {@@ -154,7 +135,7 @@ export function mountScreenLoop({const hitOpts = railWidth > 0? { x: event.x, y: event.y, width: railWidth, rows: viewRows, orientation: "vertical" }: { x: event.x, y: event.y, width: cols, tabRow: tabRowY, orientation: "horizontal" };- const targetId = tabAtPoint(getSessions(), session?.agentSession?.id, hitOpts);+ const targetId = tabAtPoint(currentSessions(), session?.agentSession?.id, hitOpts);if (targetId && typeof onTabClick === "function") {Promise.resolve(onTabClick(targetId)).then(paint).catch(() => {});return true;@@ -176,9 +157,9 @@ export function mountScreenLoop({const panelSuspend = createPanelSuspension({session, output, hook, onRepaint: paint, onReset: () => { painted = []; },+ isMouseEnabled: () => mouseEnabled,});- const suspend = panelSuspend.suspend;- const resume = panelSuspend.resume;+ const { suspend, resume } = panelSuspend;setLines(viewport, withPreamble(preamble?.() ?? null, transcriptLines(session, { colors, width: geometry().transWidth, groupTools: session?.grouping === "auto" })));paint();@@ -193,15 +174,20 @@ export function mountScreenLoop({follow: () => resetFollow(viewport),geometry,setPromptRows,+ setMouse(val) {+ const next = isMouseEnabled(val);+ if (mouseEnabled === next) return;+ mouseEnabled = next;+ if (session) session.mouse = next ? "on" : "off";+ setMouseReporting(output, next);+ },dispose() {["exit", "SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => detach(process, sig, onTeardown));output.off?.("resize", onResize);hook.dispose();disableMouse(output);- if (session.streamSink) delete session.streamSink;- if (session.printSink) delete session.printSink;- if (session.onComposerRows) delete session.onComposerRows;- if (session.screenLoop) delete session.screenLoop;+ delete session.streamSink; delete session.printSink;+ delete session.onComposerRows; delete session.screenLoop;// The panel owns the whole screen, so the inline transcript is repainted once on the way out// instead of leaving the alternate buffer's last frame on screen.painted = [];diff --git a/scripts/mso-agent-scroll-speed.test.ts b/scripts/mso-agent-scroll-speed.test.tsnew file mode 100644index 00000000..88d42363--- /dev/null+++ b/scripts/mso-agent-scroll-speed.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from "vitest";+import { applySettings, handleSettingsCommand } from "./mso-agent-cmd-settings.mjs";+import { handleMouse } from "./mso-agent-mouse.mjs";+import { defaultSettings, loadSettings } from "./mso-agent-settings.mjs";+import { SETTINGS } from "./mso-agent-settings-entries.mjs";++describe("MSO Agent TUI scroll speed setting", () => {+ // Test 1: default 3 keeps today's behaviour, asserted against the current value.+ // We assert that the registered setting default is 3, defaultSettings returns 3,+ // and handleMouse without an explicit step still scrolls by exactly 3 lines.+ it("default 3 keeps today's behaviour, asserted against the current value", () => {+ const entry = SETTINGS.find((s) => s.key === "speed");+ expect(entry).toBeDefined();+ expect(entry?.default).toBe(3);+ expect(entry?.min).toBe(1);+ expect(entry?.max).toBe(10);+ expect(entry?.path).toBe("scroll.speed");++ const defaults: Record<string, any> = defaultSettings();+ expect(defaults.speed).toBe(3);++ // Assert handleMouse defaults to 3 lines per wheel event when no step option is supplied+ const scroll = { offset: 0 };+ const upConsumed = handleMouse(scroll, { kind: "wheel", button: "up" });+ expect(upConsumed).toBe(true);+ expect(scroll.offset).toBe(3);++ const downConsumed = handleMouse(scroll, { kind: "wheel", button: "down" });+ expect(downConsumed).toBe(true);+ expect(scroll.offset).toBe(0);+ });++ // Test 2: speed 1 moves one line and speed 10 moves ten.+ // Tests min and max bound velocities across both up and down directions.+ it("speed 1 moves one line and speed 10 moves ten", () => {+ const scroll = { offset: 0 };++ // Speed 1 moves by 1 line+ handleMouse(scroll, { kind: "wheel", button: "up" }, { step: 1 });+ expect(scroll.offset).toBe(1);+ handleMouse(scroll, { kind: "wheel", button: "down" }, { step: 1 });+ expect(scroll.offset).toBe(0);++ // Speed 10 moves by 10 lines+ handleMouse(scroll, { kind: "wheel", button: "up" }, { step: 10 });+ expect(scroll.offset).toBe(10);+ handleMouse(scroll, { kind: "wheel", button: "down" }, { step: 10 });+ expect(scroll.offset).toBe(0);++ // Also assert speed plumbed through session works identically+ const sessionFast = { scrollSpeed: 10 };+ handleMouse(scroll, { kind: "wheel", button: "up" }, { session: sessionFast });+ expect(scroll.offset).toBe(10);+ handleMouse(scroll, { kind: "wheel", button: "down" }, { session: sessionFast });+ expect(scroll.offset).toBe(0);+ });++ // Test 3: the setting is rejected below 1 and above 10 with a range message.+ // Rejects out-of-range values in CLI command and loader fallback.+ it("the setting is rejected below 1 and above 10 with a range message", async () => {+ const printed: string[] = [];+ const session: any = { scrollSpeed: 3 };+ const ctx = {+ session,+ C: {},+ write: (line: string) => printed.push(line),+ };++ // Below min (0) rejected with range message+ await handleSettingsCommand(ctx, ["speed", "0"]);+ expect(printed.some((msg) => msg.includes("accepted range is 1 to 10"))).toBe(true);+ expect(session.scrollSpeed).toBe(3);++ // Above max (11) rejected with range message+ printed.length = 0;+ await handleSettingsCommand(ctx, ["speed", "11"]);+ expect(printed.some((msg) => msg.includes("accepted range is 1 to 10"))).toBe(true);+ expect(session.scrollSpeed).toBe(3);++ // Negative numbers rejected+ printed.length = 0;+ await handleSettingsCommand(ctx, ["speed", "-5"]);+ expect(printed.some((msg) => msg.includes("accepted range is 1 to 10"))).toBe(true);+ expect(session.scrollSpeed).toBe(3);++ // loadSettings falls back to default 3 and records a warning for invalid values+ const loaded = loadSettings({+ path: "/mock/settings.json",+ readFile: () => JSON.stringify({ "scroll.speed": 0 }),+ });+ expect(loaded.speed).toBe(3);+ expect(loaded.warnings.some((w: string) => w.includes('invalid value "0" for speed'))).toBe(true);+ });++ // Test 4: a wheel event at any speed still never scrolls past the buffer bounds, asserted at both ends.+ // Viewport bounds clamp between offset 0 (bottom) and maxOffset (top).+ it("a wheel event at any speed still never scrolls past the buffer bounds, asserted at both ends", () => {+ // 30 lines with 10 visible rows yields maxOffset of 20+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);+ const scroll = { lines, offset: 0, rows: 10 };++ // Lower bound: scrolling down from 0 cannot go below 0 at any speed+ for (const speed of [1, 3, 5, 10]) {+ scroll.offset = 0;+ const consumed = handleMouse(scroll, { kind: "wheel", button: "down" }, { step: speed });+ expect(consumed).toBe(true);+ expect(scroll.offset).toBe(0);+ }++ // Upper bound: scrolling up near maxOffset cannot exceed maxOffset (20)+ for (const speed of [1, 3, 5, 10]) {+ // Starting at maxOffset (20), scrolling up remains clamped at 20+ scroll.offset = 20;+ const consumedAtMax = handleMouse(scroll, { kind: "wheel", button: "up" }, { step: speed });+ expect(consumedAtMax).toBe(true);+ expect(scroll.offset).toBe(20);++ // Starting at 18, scrolling up with step larger than remaining distance clamps at 20+ scroll.offset = 18;+ handleMouse(scroll, { kind: "wheel", button: "up" }, { step: 10 });+ expect(scroll.offset).toBe(20);+ }++ // Downward clamping from mid-position to 0 with large step+ scroll.offset = 4;+ handleMouse(scroll, { kind: "wheel", button: "down" }, { step: 10 });+ expect(scroll.offset).toBe(0);+ });++ // Test 5: the value reaches handleMouse from a saved settings file through applySettings.+ // Confirms the full path: file -> loadSettings -> applySettings -> session -> handleMouse.+ it("the value reaches handleMouse from a saved settings file through applySettings", () => {+ const rawConfig = JSON.stringify({ "scroll.speed": 7 });+ const settings = loadSettings({+ path: "/user/settings.json",+ readFile: () => rawConfig,+ });+ expect(settings.speed).toBe(7);++ const session: any = {};+ applySettings(session, settings);+ expect(session.scrollSpeed).toBe(7);++ // Now test that handleMouse uses the session's scrollSpeed value+ const scroll = { offset: 0 };+ handleMouse(scroll, { kind: "wheel", button: "up" }, { step: session.scrollSpeed });+ expect(scroll.offset).toBe(7);++ // Also test direct session option plumbing+ scroll.offset = 0;+ handleMouse(scroll, { kind: "wheel", button: "up" }, { session });+ expect(scroll.offset).toBe(7);+ });+});diff --git a/scripts/mso-agent-session-list.mjs b/scripts/mso-agent-session-list.mjsindex 68afbe6b..39e32bcd 100644--- a/scripts/mso-agent-session-list.mjs+++ b/scripts/mso-agent-session-list.mjs@@ -1,3 +1,5 @@+import path from "node:path";+import process from "node:process";import { cellWidth, clean } from "./tui/cells.mjs";import { formatSessionModified } from "./mso-agent-sessions.mjs";@@ -40,11 +42,8 @@ export function stateOf(row, now = Date.now()) {}function stateColor(state, colors = {}) {- if (state === "working") return colors.green || "";- if (state === "waiting") return colors.yellow || "";- if (state === "errored") return colors.red || colors.err || "";- if (state === "idle") return colors.dim || "";- return colors.dim || "";+ const map = { working: colors.green, waiting: colors.yellow, errored: colors.red || colors.err, idle: colors.dim };+ return map[state] || colors.dim || "";}function formatCell(text, width) {@@ -69,25 +68,41 @@ function formatCell(text, width) {return { visible: out, pad };}-function isSessionActive(row, activeId) {+export function isSessionActive(row, activeId) {if (activeId == null) return false;const id = String(row?.id || row?.agentSession?.id || "");const name = clean(row?.name || row?.agentSession?.name || "").replace(/^@/, "");return String(activeId) === id || String(activeId).replace(/^@/, "") === name;}+// Scopes session list to cwd or global. Active session is always kept so user never loses their tab.+// Non-active sessions missing a cwd are excluded in cwd mode, but retained in global mode./*** @param {Array<any>} rows- * @param {{- * colors?: Record<string, string>,- * width?: number,- * activeId?: string | number | null,- * now?: number,- * }} [options]+ * @param {{ scope?: string, cwd?: string, activeId?: string | number | null }} [options]+ * @returns {Array<any>}+ */+export function filterSessionsByScope(rows, { scope = "global", cwd = "", activeId = null } = {}) {+ if (!Array.isArray(rows)) return [];+ if (scope !== "cwd") return rows;+ const targetCwd = cwd || (typeof process !== "undefined" && process.cwd ? process.cwd() : "");+ let resolvedTarget = "";+ try { resolvedTarget = targetCwd ? path.resolve(targetCwd) : ""; } catch { resolvedTarget = ""; }+ return rows.filter((row) => {+ if (isSessionActive(row, activeId)) return true;+ if (!row?.cwd || !resolvedTarget) return false;+ try { return path.resolve(row.cwd) === resolvedTarget; } catch { return false; }+ });+}++/**+ * @param {Array<any>} rows+ * @param {{ colors?: Record<string, string>, width?: number, activeId?: string | number | null, now?: number, scope?: string, cwd?: string }} [options]* @returns {Array<string>}*/-export function sessionTable(rows, { colors = {}, width = 80, activeId = null, now = Date.now() } = {}) {- if (!Array.isArray(rows) || rows.length === 0) {+export function sessionTable(rows, { colors = {}, width = 80, activeId = null, now = Date.now(), scope = "global", cwd = "" } = {}) {+ const effectiveRows = scope === "cwd" ? filterSessionsByScope(rows, { scope, cwd, activeId }) : (Array.isArray(rows) ? rows : []);+ if (!effectiveRows.length) {return ["No active sessions."];}@@ -113,7 +128,7 @@ export function sessionTable(rows, { colors = {}, width = 80, activeId = null, nconst lines = [headerLine];- rows.forEach((row, idx) => {+ effectiveRows.forEach((row, idx) => {const isCurrent = isSessionActive(row, activeId);const mark = isCurrent ? "●" : " ";const rawName = clean(row?.name || "agent").replace(/^@/, "");@@ -141,43 +156,17 @@ export function sessionTable(rows, { colors = {}, width = 80, activeId = null, nreturn 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.+ // Trusts only explicit server status. Timestamp derivation is inverted because updatedAt+ // updates at turn completion, not during execution (docs/AGENT-ACTIVITY-SIGNAL.md).if (!row || typeof row !== "object") return false;const status = String(row.status || "");if (row.error || ["error", "errored", "failed"].includes(status)) return true;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.+ // Reports explicit server status without implying unverified timestamp freshness.if (!row || typeof row !== "object") return "unknown";if (row.error || ["error", "errored", "failed"].includes(String(row.status || ""))) {return `status: ${row.status || "errored"}`;diff --git a/scripts/mso-agent-settings-entries.mjs b/scripts/mso-agent-settings-entries.mjsindex d1c7a99f..de691c41 100644--- a/scripts/mso-agent-settings-entries.mjs+++ b/scripts/mso-agent-settings-entries.mjs@@ -1,6 +1,12 @@// 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.+//+// Evaluated and refused diff settings from opencode (diffs.*):+// - diffs.wrap: diff lines are clipped by fitCells to pane width, never wrapped; wrap: word has no consumer.+// - diffs.view: side pane is 30-50 cols; split side-by-side view leaves 13-23 cols per side, unreadable.+// - diffs.tree: redundant because the files pane kind (/pane files) already lists changed files.+// - diffs.single: pane only ever displays the latest edit diff; multiple files cannot appear at once.export const SETTINGS = [{@@ -20,6 +26,18 @@ export const SETTINGS = [values: ["horizontal", "vertical"],keywords: ["sidebar", "rail", "tabs", "tabLayout"],},+ {+ category: "Tabs", key: "indicators", path: "tabs.indicators",+ description: "Tab indicator style (numbers or status)", default: "numbers",+ values: ["status", "numbers"],+ keywords: ["tabs", "indicator", "indicators", "tabIndicators", "status icons"],+ },+ {+ category: "Tabs", key: "scope", path: "tabs.scope",+ description: "Tab bar session filtering scope (cwd or global)", default: "global",+ values: ["cwd", "global"],+ keywords: ["scope", "tabs", "directory", "cwd", "tabScope"],+ },{category: "Session", key: "minwidth", path: "session.pane_min_columns",description: "Minimum terminal width to show side pane", default: 100,@@ -36,4 +54,15 @@ export const SETTINGS = [description: "Status footer density (low, medium, high); does not affect transcript detail", default: "high",values: ["low", "medium", "high"], keywords: ["verbosity", "status", "footer", "density"],},+ {+ category: "Input", key: "speed", path: "scroll.speed",+ // Whole lines only: terminal row painting has no sub-line granularity+ description: "Lines to scroll per mouse wheel event", default: 3,+ min: 1, max: 10, keywords: ["scroll", "speed", "wheel"],+ },+ {+ category: "Input", key: "mouse", path: "mouse",+ description: "Terminal mouse reporting and interaction", default: "on",+ values: ["on", "off"], keywords: ["mouse", "click", "scroll"],+ },];diff --git a/scripts/mso-agent-status-indicator.test.ts b/scripts/mso-agent-status-indicator.test.tsnew file mode 100644index 00000000..584cbb10--- /dev/null+++ b/scripts/mso-agent-status-indicator.test.ts@@ -0,0 +1,161 @@+import { describe, expect, it } from "vitest";+import {+ tabAtPoint,+ tabLayout,+ tabRailLines,+ tabRow,+ tabStatusGlyph,+} from "./mso-agent-chrome.mjs";+import { SETTINGS } from "./mso-agent-settings-entries.mjs";+import { applySettings } from "./mso-agent-cmd-settings.mjs";++describe("MSO Agent TUI status indicators on tabs", () => {+ const sessions = [+ { id: "s1", name: "alpha", status: "working" },+ { id: "s2", name: "beta", status: "idle" },+ { id: "s3", name: "gamma", updatedAt: "2026-11-02T12:00:00.000Z" },+ ];++ // Requirement 1: Default numbers output is byte-identical to recorded fixture.+ it("default numbers output is byte-identical to a recorded fixture", () => {+ const fixtureHorizontal = "● @alpha @beta @gamma";+ const defaultRow = tabRow(sessions, "s1");+ const explicitNumbersRow = tabRow(sessions, "s1", { indicators: "numbers" });++ expect(defaultRow).toBe(fixtureHorizontal);+ expect(explicitNumbersRow).toBe(fixtureHorizontal);++ const fixtureVertical = [+ "● @alpha │",+ "@beta │",+ "@gamma │",+ ];+ const defaultRail = tabRailLines(sessions, "s1", { width: 20, rows: 3 });+ const explicitRail = tabRailLines(sessions, "s1", { width: 20, rows: 3, indicators: "numbers" });++ expect(defaultRail).toEqual(fixtureVertical);+ expect(explicitRail).toEqual(fixtureVertical);+ });++ // Requirement 2: status shows a glyph for an explicit working status.+ it("status shows a glyph for an explicit working status", () => {+ const workingList = [+ { id: "w1", name: "work-one", status: "working" },+ { id: "w2", name: "work-two", status: "busy" },+ { id: "w3", name: "work-three", status: "running" },+ ];+ for (const s of workingList) {+ expect(tabStatusGlyph(s)).toBe("●");+ const row = tabRow([s], s.id, { indicators: "status" });+ expect(row).toBe(`● @${s.name}`);+ }+ });++ // Requirement 3: status shows the unknown placeholder, not a guess, for a row with only updatedAt.+ it("status shows the unknown placeholder, not a guess, for a row with only updatedAt", () => {+ const timestampOnly = {+ id: "u1",+ name: "timestamped",+ updatedAt: "2026-11-02T12:00:00.000Z",+ };++ // The glyph must be a space character, never a guessed working or idle dot.+ expect(tabStatusGlyph(timestampOnly)).toBe(" ");++ const row = tabRow([timestampOnly], "u1", { indicators: "status" });+ // Stable column width: one space glyph placeholder followed by one delimiter space before @+ expect(row).toBe(" @timestamped");+ expect(row).not.toContain("●");+ expect(row).not.toContain("○");+ });++ // Requirement 4: a row with turnActive: true shows the working glyph.+ it("a row with turnActive: true shows the working glyph", () => {+ const activeTurn = {+ id: "t1",+ name: "turn-session",+ turnActive: true,+ updatedAt: "2026-10-01T00:00:00.000Z",+ };+ expect(tabStatusGlyph(activeTurn)).toBe("●");++ const row = tabRow([activeTurn], "t1", { indicators: "status" });+ expect(row).toBe("● @turn-session");+ });++ // Requirement 5: an error status shows the error glyph.+ it("an error status shows the error glyph", () => {+ const erroredSessions = [+ { id: "e1", name: "err-explicit", status: "error" },+ { id: "e2", name: "err-errored", status: "errored" },+ { id: "e3", name: "err-failed", status: "failed" },+ { id: "e4", name: "err-boolean", error: true },+ ];+ for (const s of erroredSessions) {+ expect(tabStatusGlyph(s)).toBe("!");+ const row = tabRow([s], s.id, { indicators: "status" });+ expect(row).toBe(`! @${s.name}`);+ }+ });++ // Requirement 6: tabAtPoint still resolves every visible cell correctly in both orientations with the indicator on.+ it("tabAtPoint still resolves every visible cell correctly in both orientations with the indicator on", () => {+ const testSessions = [+ { id: "s1", name: "alpha", status: "working" },+ { id: "s2", name: "beta", status: "idle" },+ { id: "s3", name: "gamma", updatedAt: "2026-11-02T12:00:00.000Z" },+ ];++ // Horizontal resolution test+ const horiz = tabLayout(testSessions, "s1", { indicators: "status", width: 80 });+ for (const seg of horiz.segments) {+ if (seg.type === "tab") {+ for (let x = seg.start; x < seg.end; x++) {+ const hit = tabAtPoint(testSessions, "s1", { x, y: 0, tabRow: 0, width: 80, indicators: "status" });+ expect(hit).toBe(seg.id);+ }+ }+ }++ // Vertical resolution test+ const vert = tabLayout(testSessions, "s1", { indicators: "status", orientation: "vertical", width: 20, rows: 5 });+ for (const seg of vert.segments) {+ if (seg.type === "tab") {+ for (let x = seg.start; x < seg.end; x++) {+ const hit = tabAtPoint(testSessions, "s1", { x, y: seg.row, orientation: "vertical", width: 20, rows: 5, indicators: "status" });+ expect(hit).toBe(seg.id);+ }+ }+ }+ });++ // Settings registry and propagation test+ it("declares tabs.indicators in SETTINGS and applies it via applySettings", () => {+ const entry = SETTINGS.find((s) => s.path === "tabs.indicators");+ expect(entry).toBeDefined();+ expect(entry?.default).toBe("numbers");+ expect(entry?.values).toEqual(["status", "numbers"]);++ const session: Record<string, any> = {};+ applySettings(session, { "tabs.indicators": "status" });+ expect(session.tabsIndicators).toBe("status");+ });++ // Renders working, idle, and unknown in row and rail+ it("renders status indicator for working, idle, and unknown session in row and rail", () => {+ const trio = [+ { id: "s1", name: "alpha", status: "working" },+ { id: "s2", name: "beta", status: "idle" },+ { id: "s3", name: "gamma", updatedAt: "2026-11-02T12:00:00.000Z" },+ ];+ const row = tabRow(trio, "s1", { indicators: "status" });+ expect(row).toBe("● @alpha ○ @beta @gamma");++ const rail = tabRailLines(trio, "s1", { indicators: "status", width: 20, rows: 3 });+ expect(rail).toEqual([+ "● @alpha │",+ "○ @beta │",+ " @gamma │",+ ]);+ });+});diff --git a/scripts/mso-agent-tabs-rail.mjs b/scripts/mso-agent-tabs-rail.mjsindex 16a7d01d..6dd950e6 100644--- a/scripts/mso-agent-tabs-rail.mjs+++ b/scripts/mso-agent-tabs-rail.mjs@@ -1,7 +1,8 @@// Vertical tab rail layout, kept out of mso-agent-chrome.mjs so that file stays under the line// ratchet. It is still the SAME layout source: the caller passes the same segment builder, so the// painted rail and its hit test cannot drift.-import { candidateSplits, makeSegments } from "./mso-agent-chrome.mjs";+import { candidateSplits, makeSegments, tabStatusGlyph } from "./mso-agent-chrome.mjs";+export { tabStatusGlyph };/*** Split items for a vertical rail of `maxRows` rows, dropping from the middle with a +N marker.diff --git a/scripts/mso-agent-tabs-scope.test.ts b/scripts/mso-agent-tabs-scope.test.tsnew file mode 100644index 00000000..574025dc--- /dev/null+++ b/scripts/mso-agent-tabs-scope.test.ts@@ -0,0 +1,116 @@+import { EventEmitter } from "node:events";+import { describe, expect, it } from "vitest";+import { SETTINGS } from "./mso-agent-settings-entries.mjs";+import { applySettings } from "./mso-agent-cmd-settings.mjs";+import { filterSessionsByScope, sessionTable } from "./mso-agent-session-list.mjs";+import { tabLayout } from "./mso-agent-chrome.mjs";+import { mountScreenLoop } from "./mso-agent-screen-loop.mjs";++class FakeOutput extends EventEmitter {+ isTTY = true;+ columns = 80;+ rows = 24;+ chunks: string[] = [];+ write(str: string) {+ this.chunks.push(String(str));+ return true;+ }+}++describe("tabs.scope settings and session filtering", () => {+ const fixtureSessions = [+ { id: "s1", name: "auth-worker", title: "OAuth setup", cwd: "/srv/project-a", updatedAt: "2026-11-02T10:00:00Z" },+ { id: "s2", name: "billing-fix", title: "Stripe webhook", cwd: "/srv/project-b", updatedAt: "2026-11-02T09:00:00Z" },+ { id: "s3", name: "db-migrate", title: "Migration run", cwd: "/srv/project-a", updatedAt: "2026-11-02T08:00:00Z" },+ { id: "s4", name: "docs-review", title: "Read docs", cwd: "/tmp/docs", updatedAt: "2026-11-02T07:00:00Z" },+ { id: "s5", name: "legacy-run", title: "Old task", cwd: undefined, updatedAt: "2026-11-02T06:00:00Z" },+ ];++ // Test 1: global shows every session+ it("global scope shows every session regardless of directory", () => {+ const result = filterSessionsByScope(fixtureSessions, { scope: "global", cwd: "/srv/project-a", activeId: "s1" });+ expect(result.map((s) => s.id)).toEqual(["s1", "s2", "s3", "s4", "s5"]);+ });++ // Test 2: cwd shows only sessions in the current directory PLUS the active one+ it("cwd scope shows only current directory sessions plus the active session", () => {+ // s4 is located in /tmp/docs but is the active session. s1 and s3 match /srv/project-a.+ // Inactive sessions from other dirs (s2) or lacking cwd (s5) are omitted.+ const result = filterSessionsByScope(fixtureSessions, { scope: "cwd", cwd: "/srv/project-a", activeId: "s4" });+ expect(result.map((s) => s.id)).toEqual(["s1", "s3", "s4"]);+ });++ // Test 3: default reproduces today's list exactly, asserted against a fixture+ it("default scope setting is global and reproduces today's full session list exactly", () => {+ const setting = SETTINGS.find((s) => s.key === "scope");+ expect(setting).toBeDefined();+ // Default must be global because today's MSO list is global across directories+ expect(setting?.default).toBe("global");+ expect(setting?.values).toEqual(["cwd", "global"]);++ // Calling filterSessionsByScope with no scope option uses global default+ const defaultResult = filterSessionsByScope(fixtureSessions);+ expect(defaultResult).toEqual(fixtureSessions);+ });++ // Test 4: tab row and /tabs table show the same ids for the same input+ it("tab row and /tabs table show the exact same session ids for identical input", () => {+ const opts = { scope: "cwd", cwd: "/srv/project-a", activeId: "s4" };+ const scoped = filterSessionsByScope(fixtureSessions, opts);+ const expectedIds = scoped.map((s) => s.id);++ // Tab row segments produce identical session IDs+ const { segments } = tabLayout(scoped, "s4");+ const tabIds = segments.filter((seg: any) => seg.type === "tab").map((seg: any) => seg.id);+ expect(tabIds).toEqual(expectedIds);++ // Session table lines display all scoped sessions and none of the omitted ones+ const tableLines = sessionTable(fixtureSessions, { ...opts, width: 80 });+ expect(tableLines).toHaveLength(expectedIds.length + 1);+ for (const session of scoped) {+ // Match on name prefix since formatCell truncates longer names to column bounds+ const prefix = `@${session.name.slice(0, 8)}`;+ const found = tableLines.some((line) => line.includes(prefix));+ expect(found).toBe(true);+ }+ expect(tableLines.some((line) => line.includes("@billing-fix"))).toBe(false);+ expect(tableLines.some((line) => line.includes("@legacy-run"))).toBe(false);+ });++ // Test 5: session with no cwd field is handled per a stated rule, not dropped silently+ it("session with no cwd is retained in global scope, omitted in cwd when inactive, and retained when active", () => {+ const noCwd = { id: "legacy-x", name: "legacy", title: "No CWD" };+ const list = [noCwd, { id: "dir-1", name: "app", cwd: "/app" }];++ // Rule: in global scope, missing cwd is never dropped+ const globalResult = filterSessionsByScope(list, { scope: "global" });+ expect(globalResult.map((s) => s.id)).toEqual(["legacy-x", "dir-1"]);++ // Rule: in cwd scope, inactive session with missing cwd is excluded because directory is unknown+ const cwdInactive = filterSessionsByScope(list, { scope: "cwd", cwd: "/app", activeId: "dir-1" });+ expect(cwdInactive.map((s) => s.id)).toEqual(["dir-1"]);++ // Rule: in cwd scope, active session with missing cwd is retained so user never loses active tab+ const cwdActive = filterSessionsByScope(list, { scope: "cwd", cwd: "/app", activeId: "legacy-x" });+ expect(cwdActive.map((s) => s.id)).toEqual(["legacy-x", "dir-1"]);+ });++ // Settings and screen loop integration+ it("applies scope setting to session and feeds scoped list into screen loop", () => {+ const session: any = { agentSession: { id: "s1", cwd: "/srv/project-a" } };+ applySettings(session, { "tabs.scope": "cwd" });+ expect(session.tabsScope).toBe("cwd");++ const out = new FakeOutput();+ const loop = mountScreenLoop({+ session,+ enabled: true,+ output: out as never,+ getSessions: () => fixtureSessions,+ tabsScope: "cwd",+ });+ const geom = loop.geometry();+ expect(geom.panel.length).toBeGreaterThan(0);+ loop.dispose();+ });+});diff --git a/scripts/mso-agent-turn.mjs b/scripts/mso-agent-turn.mjsindex 7f60b04d..8da9ab84 100644--- a/scripts/mso-agent-turn.mjs+++ b/scripts/mso-agent-turn.mjs@@ -10,7 +10,6 @@ import { approvesTool } from "./mso-agent-permissions.mjs";import { api, C, streamTurn } from "./mso-agent-runtime.mjs";import { completedReceipt } from "./mso-agent-ui.mjs";import { compactConsumedReadToolResults } from "./mso-agent-context.mjs";-import { persistSession } from "./mso-agent-session-ui.mjs";import { addUsage } from "./mso-agent-status.mjs";import { oneShotApproves } from "./mso-agent-oneshot.mjs";import { reasoningLine } from "./mso-agent-reasoning.mjs";@@ -51,18 +50,14 @@ export async function executeTool(rl, tool, call, agentSession, permission = "astry { approval = canonicalAgentApproval(tool.name, call.input || {}); }catch (error) { return { ok: false, result: `cannot safely approve tool call: ${error instanceof Error ? error.message : String(error)}` }; }}- let approved = options.approvalScope- ? oneShotApproves(options.approvalScope, tool.scope)- : approvesTool(permission, tool.scope);+ let approved = options.approvalScope ? oneShotApproves(options.approvalScope, tool.scope) : approvesTool(permission, tool.scope);if (!approved) {if (options.approvalScope) return { ok: false, result: "denied by user" };const approvalState = options.approvalState || null;if (approvalState) approvalState.pendingApproval = { tool: tool.name, scope: tool.scope, digest: approval?.digest || null, createdAt: new Date().toISOString() };try {const screenLoop = options.screenLoop || approvalState?.screenLoop;- approved = await requestExactToolApproval(rl, {- tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C, screenLoop,- });+ approved = await requestExactToolApproval(rl, { tool, input: call.input || {}, approval, onCancel: onInterrupt, signal, colors: C, screenLoop });if (approvalState) approvalState.pendingApproval = null;} catch (error) {if (signal?.aborted || isAbortError(error)) { if (approvalState) approvalState.pendingApproval = null; }@@ -129,8 +124,7 @@ export async function agentRound(rl, session, skillContext = null, signal = unde// Live row while the first token is in flight: a provider wait reads as work.activity?.waiting("thinking");const result = await turnStream(- session.history, session.state.tools, session.agentSession, skillContext, signal,- session.state.modelMeta?.context, lazyAssistantOutput(session, toolOptions),+ session.history, session.state.tools, session.agentSession, skillContext, signal, session.state.modelMeta?.context, lazyAssistantOutput(session, toolOptions),);// The current model round has consumed all prior read-tool payloads that were// still inside its projected context. Persist only bounded replay envelopes@@ -160,9 +154,7 @@ export async function agentRound(rl, session, skillContext = null, signal = undeconst results = [];for (const call of result.toolUses) {const tool = session.state.tools.find((row) => row.name === call.name);- const outcome = await toolExecutor(rl, tool, call, session.agentSession, session.permission, signal, onInterrupt, {- ...toolOptions, approvalState: options.approvalState || session,- });+ const outcome = await toolExecutor(rl, tool, call, session.agentSession, session.permission, signal, onInterrupt, { ...toolOptions, approvalState: options.approvalState || session });calls.push({ name: call.name, scope: tool?.scope || "unknown", ok: outcome.ok });results.push({ id: call.id, content: outcome.result, isError: !outcome.ok });}@@ -188,24 +180,38 @@ export function renderInteractionFailure(error, session, journal = {}, colors =return state;}+// Bookkeeping write persists turn lifecycle markers without failing the round if offline.+async function persistTurnActive(session, turnStartedAt) {+ if (!session?.agentSession?.id) return;+ if (turnStartedAt) session.agentSession.turnStartedAt = turnStartedAt;+ else delete session.agentSession.turnStartedAt;+ try {+ const body = { action: "update", id: session.agentSession.id, history: session.history, cwd: process.cwd(), turnStartedAt };+ if (session.titleOverride) body.title = session.titleOverride;+ const out = await api("/api/v1/agent-sessions", { method: "POST", body: JSON.stringify(body) });+ if (out?.session) session.agentSession = { ...session.agentSession, ...out.session };+ } catch { /* Bookkeeping write failure should never abort an interactive round. */ }+}+export async function runInteractiveRound(rl, session, skillContext, interrupts, localBridge = null) {const signal = interrupts.beginTurn();await localBridge?.setState("busy");let roundResult = null;const print = turnPrinter(session);+ // Persist turn start timestamp so session list reflects active work immediately.+ await persistTurnActive(session, new Date().toISOString());try {roundResult = await agentRound(rl, session, skillContext, signal, () => interrupts.interruptCurrent(), { print });- await persistSession(session);} catch (error) {- if (signal.aborted || isAbortError(error)) {- print(`${C.dim}turn interrupted.${C.reset}`);- } else {+ if (signal.aborted || isAbortError(error)) print(`${C.dim}turn interrupted.${C.reset}`);+ else {const journal = error?.turnJournal || { calls: roundResult?.calls || [] };const state = renderInteractionFailure(error, session, journal, C, print);if (isRecoverableInteractionError(error)) session.history.push(recoverableHistoryRow(state));}- await persistSession(session).catch(() => undefined);} finally {+ // Clear turn marker in finally block so aborted or crashed turns never stick in working state.+ await persistTurnActive(session, null);interrupts.endTurn(signal);await localBridge?.setState("idle");}