Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(mcp): add session cards, readable logs and handover guide

Rahmane668f3f5e4d9
diff --git a/app/api/v1/agent-sessions/monitor.test.ts b/app/api/v1/agent-sessions/monitor.test.ts
new file mode 100644
index 00000000..54703cce
--- /dev/null
+++ b/app/api/v1/agent-sessions/monitor.test.ts
@@ -0,0 +1,27 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+const mocks = vi.hoisted(() => ({ context: vi.fn(), page: vi.fn(), detail: vi.fn() }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.context }));
+vi.mock("@/lib/agent/session-monitor", () => ({ ownerSessionPage: mocks.page, ownerSessionDetail: mocks.detail }));
+import { GET } from "./route";
+beforeEach(() => { vi.clearAllMocks(); mocks.context.mockResolvedValue({ role: "owner", session: { device_id: "owner" } }); });
+describe("session monitor route", () => {
+ it.each([null, { role: "viewer" }, { role: "operator" }])("denies non-owner access before reading records: %j", async context => {
+ mocks.context.mockResolvedValue(context);
+ const response = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=monitor"));
+ expect(response.status).toBe(403); expect(mocks.page).not.toHaveBeenCalled(); expect(mocks.detail).not.toHaveBeenCalled();
+ });
+ it("uses explicit monitor pagination with private no-store responses", async () => {
+ mocks.page.mockResolvedValue({ sessions: [], total: 0 });
+ const response = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=monitor&page=2&includeOffline=1"));
+ expect(mocks.page).toHaveBeenCalledWith(2, true);
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ });
+ it("returns 404 for a missing exact session and does not expose store error details", async () => {
+ mocks.detail.mockResolvedValue(null);
+ expect((await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=monitor&id=missing"))).status).toBe(404);
+ mocks.detail.mockRejectedValue(new Error("private/path/token=hidden"));
+ const response = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=monitor&id=bad"));
+ expect(JSON.stringify(await response.json())).not.toContain("hidden");
+ });
+});
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index 5d31e35e..6dcbd645 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -1,3 +1,4 @@
+import { ownerSessionPage, ownerSessionDetail } from "@/lib/agent/session-monitor";
import type { AgentSession } from "@/lib/agent/session-types";
import { artifactLocation } from "@/lib/agent/artifact-paths";
import { NextRequest, NextResponse } from "next/server";
@@ -44,6 +45,14 @@ export async function GET(req: NextRequest) {
const principal = await ownerPrincipal();
if (!principal)
return NextResponse.json({ error: "owner_role_required" }, { status: 403 });
+ if (req.nextUrl.searchParams.get("view") === "monitor") {
+ try {
+ const id = req.nextUrl.searchParams.get("id");
+ const page = Number(req.nextUrl.searchParams.get("page") || 1);
+ const result = id ? await ownerSessionDetail(id, page) : await ownerSessionPage(page, req.nextUrl.searchParams.get("includeOffline") === "1");
+ return NextResponse.json(result || { error: "session_not_found" }, { status: result ? 200 : 404, headers: { "Cache-Control": "private, no-store" } });
+ } catch { return NextResponse.json({ error: "session_monitor_unavailable" }, { status: 400 }); }
+ }
const ref = (
req.nextUrl.searchParams.get("ref") ||
req.nextUrl.searchParams.get("id") ||
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7cdfb61a..03d2c268 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `mcp` add session cards, readable logs and handover guide
- split MCP access and add plugin registry
**Fixed**
diff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.md
index f7476982..152951b4 100644
--- a/docs/LOCAL-AGENTS.md
+++ b/docs/LOCAL-AGENTS.md
@@ -197,3 +197,39 @@ No external broker, database, daemon, or framework is required.
Older `mso a2a local ...` one-shot delegation/virtual-loopback-card helpers remain for backward compatibility and protocol testing. They are **not** the transport used by `/agents`, `/message`, local `/delegate`, the Local Agents MCP tools, or live inbox delivery in MSO 1.11+ / current MSO.
New same-host communication should use Local Agents. Public/remote interoperability should use A2A v1.
+
+## Sessions dashboard and explicit handover
+
+Settings → MCP → **Sessions** is an Owner-only observation surface for durable external MCP,
+MSO CLI and recorded Alfa sessions. The default filter shows valid presence leases, six cards
+per page. All stored includes offline/ended records from the existing bounded session store
+(up to 5,000 entries, with unreadable records isolated). A plain terminal without an MSO agent
+session is not a durable agent session. A lease does not prove a subscribed receiver.
+
+Click a card for metadata and newest-first tool/workflow events (20 per page). The monitor
+returns allowlisted, redacted fields; no raw transcript, memory snapshot, principal hash,
+arguments, or tool output. Existing event compaction/archival retention still applies. The
+owner browser polls every 15 seconds while visible and displays the observation time.
+`GET /api/v1/agent-sessions?view=monitor&page=1` is the same Owner-only API, with
+`includeOffline=1` for retained records; `id=<exact-session-id>&page=1` returns event pages.
+Responses are private/no-store. Observation does not broaden model-facing messaging rights.
+
+The in-app **Handover guide** includes copyable examples and the recommended JSON Schema
+from `lib/contracts/session-handover.ts`. It is explicit message content, not a new MCP/A2A
+transport: version, objective, sourceSessionId, project path/branch, completed, nextSteps,
+evidence, blockers and constraints. Keep the entire serialized message under 16 KiB even
+when individual fields meet the schema bounds. Replace example values before sending.
+
+1. Discover recipients with `local_agents_list` from the actual sending session. Dashboard
+ visibility across principals does not make those sessions eligible message recipients.
+2. Call `local_agent_message_send` with the exact target, `kind: task`, `intent: request`,
+ `requires_user_relay: true`, and the serialized brief as the string `message`.
+3. Keep the returned request message ID. The recipient answers with `local_agent_reply`
+ using `reply_to_message_id`; the sender checks with `local_agent_request_wait` using
+ `request_message_id`. Queued/delivered are transport states, not verified completion.
+4. For owner-authorized terminal continuation, use `mso agent --resume <exact-session-id>`.
+ External sessions become a CLI continuation referencing the source, not control over
+ the external client's process. Remote hosts use the separately authorized A2A peer flow.
+
+Never copy credentials or hidden context into a brief. Preserve scope, identify exact worktree
+and branch, include verification evidence and blockers, and do not resend blindly on timeout.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 9fa8e6ce..832d15cb 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,5 +1,18 @@
## 2026-09-09 — Complete Semgrep parser coverage
+## 2026-09-09 — MCP Sessions dashboard and handover reference
+
+Added the third MCP tab for six-card session pagination, exact-session readable event logs,
+active versus stored filters, receiver observability, and a copyable structured handover guide.
+The Owner dashboard reuses durable session/presence records; model-facing same-principal
+messaging remains unchanged. Only allowlisted redacted metadata/events leave the monitor.
+Keyboard tabs, mobile reflow, pagination, error recovery, scope refusal and redaction receive
+regression coverage. The handover format is documented message content with existing request/
+reply correlation and CLI resume, not an implicit transfer of hidden context or permissions.
+Validation: 2,701 tests and four production smoke tests passed without skips; required browser
+journeys cover desktop, portrait, and landscape, including the session dashboard and handover guide.
+
+
The remaining forty parser diagnostics are resolved through explicit multiline Bash case arms, quoted parameter-error words, parser-compatible arithmetic and non-truncating append-open lock descriptors. Permission masks retain octal interpretation through validated conversion; process stat parsing retains its last-closing-parenthesis boundary. TypeScript import types are named aliases, JSX ampersands are entities and embedded-script regexes use equivalent escaped less-than literals. Two CLI responsibilities move into focused sourced modules with fixture inventories updated. No Semgrep rules or source files are excluded; both CI and the full security entrypoint now use `--strict --error` so parser diagnostics block completion. This supersedes the earlier documented scanner limitation.
## 2026-09-09 — Gateway release handshake under CI scheduling
diff --git a/frontend/slices/os-settings/components/mcp-direction-tabs.tsx b/frontend/slices/os-settings/components/mcp-direction-tabs.tsx
new file mode 100644
index 00000000..a891f5a9
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-direction-tabs.tsx
@@ -0,0 +1,29 @@
+"use client";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+export const MCP_TABS = [
+ { id: "inbound", title: "Access MSO", description: "External clients → MSO" },
+ { id: "outbound", title: "MSO Access", description: "MSO → external services" },
+ { id: "sessions", title: "Sessions", description: "Activity & handover" },
+] as const;
+export type McpTab = (typeof MCP_TABS)[number]["id"];
+export function McpDirectionTabs({ value, onChange }: { value: McpTab; onChange: (value: McpTab) => void }) {
+ return <div role="tablist" aria-label="MCP direction" className="grid grid-cols-3 gap-1 rounded-lg bg-secondary p-1">
+ {MCP_TABS.map((item, index) => <Button key={item.id} id={`mcp-${item.id}-tab`} type="button" variant="ghost"
+ role="tab" aria-selected={value === item.id} aria-controls="mcp-direction-panel"
+ tabIndex={value === item.id ? 0 : -1} onClick={() => onChange(item.id)}
+ onKeyDown={event => {
+ const next = event.key === "Home" ? 0 : event.key === "End" ? MCP_TABS.length - 1
+ : event.key === "ArrowRight" ? (index + 1) % MCP_TABS.length
+ : event.key === "ArrowLeft" ? (index + MCP_TABS.length - 1) % MCP_TABS.length : -1;
+ if (next < 0) return;
+ event.preventDefault(); onChange(MCP_TABS[next].id);
+ document.getElementById(`mcp-${MCP_TABS[next].id}-tab`)?.focus();
+ }}
+ className={cn("h-auto min-h-11 min-w-0 flex-col items-start whitespace-normal px-2 py-2 text-left",
+ value === item.id ? "bg-card shadow-sm" : "text-muted-foreground")}>
+ <span className="text-sm font-medium">{item.title}</span>
+ <span className="hidden text-xs font-normal leading-relaxed sm:block">{item.description}</span>
+ </Button>)}
+ </div>;
+}
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
index f6154448..80310e57 100644
--- a/frontend/slices/os-settings/components/mcp-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -7,7 +7,8 @@ import { SettingsBlock, SettingsSection } from "@/features/shell-settings";
import { IS_DEMO } from "@/lib/demo";
import { Lock, Plug } from "lucide-react";
import { useRef, useState } from "react";
-import { cn } from "@/lib/utils";
+import { McpDirectionTabs, type McpTab } from "./mcp-direction-tabs";
+import { McpSessions } from "./mcp-sessions";
import { McpActivity } from "./mcp-activity";
import { McpConnectionSection } from "./mcp-connection-section";
import { McpCopyField } from "./mcp-copy-field";
@@ -36,9 +37,9 @@ export function McpSection() {
function OwnerMcpSection() {
const { state, error, reload } = useMcpState();
const [page, setPage] = useState<McpPage>("overview");
- const [direction, setDirection] = useState<"inbound" | "outbound">("inbound");
+ const [direction, setDirection] = useState<McpTab>("inbound");
const top = useRef<HTMLDivElement>(null);
- function selectDirection(next: "inbound" | "outbound") { setDirection(next); setPage("overview"); }
+ function selectDirection(next: McpTab) { setDirection(next); setPage("overview"); }
function navigate(next: McpPage) {
setPage(next);
requestAnimationFrame(() => { top.current?.focus(); top.current?.scrollIntoView({ block: "nearest" }); });
@@ -56,12 +57,10 @@ function OwnerMcpSection() {
);
return (
<div ref={top} tabIndex={-1} data-slot="mcp-page" className="space-y-4 outline-none">
- <div className="space-y-3">
- <div role="tablist" aria-label="MCP direction" className="grid grid-cols-2 gap-2 rounded-lg bg-secondary p-1">
- {[{ id: "inbound", title: "Access MSO", copy: "External clients and agents → MSO" }, { id: "outbound", title: "MSO Access", copy: "MSO → external MCPs, services, and projects" }].map(item => <button key={item.id} id={`mcp-${item.id}-tab`} type="button" role="tab" aria-selected={direction === item.id} aria-controls="mcp-direction-panel" tabIndex={direction === item.id ? 0 : -1} onClick={() => selectDirection(item.id as "inbound" | "outbound")} onKeyDown={event => { if (event.key === "ArrowLeft" || event.key === "ArrowRight") { event.preventDefault(); selectDirection(direction === "inbound" ? "outbound" : "inbound"); } }} className={cn("min-h-11 rounded-md px-3 py-2 text-left text-sm", direction === item.id ? "bg-card shadow-sm" : "text-muted-foreground")}><span className="block font-medium">{item.title}</span><span className="block text-xs leading-relaxed">{item.copy}</span></button>)}
- </div>
- <p id="mcp-direction-panel" role="tabpanel" aria-labelledby={`mcp-${direction}-tab`} className="text-sm leading-relaxed text-muted-foreground">{direction === "inbound" ? "Inbound: approve how external clients and agents access this MSO host." : "Outbound: choose how this MSO host reaches external MCPs, services, and project capabilities."}</p>
- </div>
+ <McpDirectionTabs value={direction} onChange={selectDirection} />
+ <div id="mcp-direction-panel" role="tabpanel" aria-labelledby={`mcp-${direction}-tab`} className="@container min-w-0 space-y-4">
+ {direction === "sessions" ? <McpSessions /> : <>
+ <p className="text-sm text-muted-foreground">{direction === "inbound" ? "Approve how external clients and agents access this MSO host." : "Choose how MSO reaches external services and projects."}</p>
{page === "overview" && direction === "outbound" && <SettingsBlock className="space-y-2 py-4"><p className="text-sm font-medium">External connections</p><p className="text-sm text-muted-foreground">Manage external MCP and service credentials through Integrations. Registry entries remain descriptive until a separate approved connection or activation is completed.</p><Button asChild variant="secondary"><Link href="/integrations">Open Integrations</Link></Button></SettingsBlock>}
<McpNavigation active={page} onSelect={navigate} activeCount={state.tokens.filter(token => token.status === "active").length} direction={direction} />
{page === "connect" && <McpSetupGuide origin={state.origin} maxScope={state.maxScope} />}
@@ -70,6 +69,8 @@ function OwnerMcpSection() {
{page === "activity" && <McpActivity />}
{page === "tools" && <McpToolsetCard info={state.toolset} />}
{page === "registry" && <McpPluginRegistry />}
+ </>}
+ </div>
</div>
);
}
diff --git a/frontend/slices/os-settings/components/mcp-session-detail.tsx b/frontend/slices/os-settings/components/mcp-session-detail.tsx
new file mode 100644
index 00000000..71b34083
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-session-detail.tsx
@@ -0,0 +1,38 @@
+"use client";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { SettingsBlock } from "@/features/shell-settings";
+import type { SessionDetail } from "@/lib/contracts/session-monitor";
+import { McpCopyField } from "./mcp-copy-field";
+import { SessionPaging, sessionTime } from "./mcp-session-paging";
+import { useSessionMonitor } from "./use-session-monitor";
+export function McpSessionDetail({ id, onBack, onGuide }: { id: string; onBack: () => void; onGuide: () => void }) {
+ const [page, setPage] = useState(1);
+ const { data, error, reload } = useSessionMonitor<SessionDetail>(`id=${encodeURIComponent(id)}&page=${page}`);
+ return <div className="min-w-0 space-y-4">
+ <div className="flex flex-wrap gap-2"><Button variant="ghost" onClick={onBack}>Back to sessions</Button><Button variant="outline" onClick={onGuide}>Handover guide</Button></div>
+ {error ? <SettingsBlock><p role="alert">{error}</p><Button onClick={reload}>Try again</Button></SettingsBlock>
+ : !data ? <p role="status">Loading session…</p> : <>
+ <SettingsBlock className="min-w-0 space-y-3">
+ <h3 tabIndex={-1} className="break-words text-base font-semibold">{data.session.title}</h3>
+ <p className="text-sm">@{data.session.name} · {data.session.source === "mcp" ? "External MCP" : data.session.source === "cli" ? "MSO CLI" : "Alfa"} · {data.session.status}</p>
+ <p className="text-sm text-muted-foreground">{data.session.receiverConnected ? "Receiver connected" : "No receiver connected"} · Last seen {sessionTime(data.session.lastSeenAt)}</p>
+ <McpCopyField label="Session ID" value={id} />
+ {data.session.cwd && <p className="break-all text-sm">Project directory: {data.session.cwd}</p>}
+ {data.session.resumedFrom && <McpCopyField label="Resumed from" value={data.session.resumedFrom} />}
+ {data.session.parentSessionId && <McpCopyField label="Parent session" value={data.session.parentSessionId} />}
+ </SettingsBlock>
+ <section aria-label="Session activity log" className="min-w-0 space-y-3">
+ <h3 className="text-sm font-semibold">Activity log</h3>
+ <p className="text-sm text-muted-foreground">Newest first. Recorded tool and workflow events only; raw arguments, outputs, and private conversations are not shown. Older events may have been compacted ({data.session.archiveCount} archives).</p>
+ {data.events.length ? <ol className="space-y-2">{data.events.map((event, index) => <li key={event.at + ":" + index} className="min-w-0 rounded-lg border border-border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2"><span className="break-all text-sm font-medium">{(event.tool || event.kind).replaceAll("_", " ")}</span><span className="text-xs">{event.state || event.kind}</span></div>
+ <time dateTime={event.at} className="text-xs text-muted-foreground">{sessionTime(event.at)}</time>
+ {event.detail && <p className="mt-2 whitespace-pre-wrap break-words text-sm [overflow-wrap:anywhere]">{event.detail}</p>}
+ {event.workflowId && <p className="mt-1 break-all text-xs text-muted-foreground">Workflow: {event.workflowId}</p>}
+ </li>)}</ol> : <p className="text-sm">No recorded activity yet.</p>}
+ <SessionPaging {...data} label="Events" onPage={setPage} />
+ </section>
+ </>}
+ </div>;
+}
diff --git a/frontend/slices/os-settings/components/mcp-session-guide.tsx b/frontend/slices/os-settings/components/mcp-session-guide.tsx
new file mode 100644
index 00000000..5954aca4
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-session-guide.tsx
@@ -0,0 +1,52 @@
+"use client";
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { SettingsBlock } from "@/features/shell-settings";
+import { handoverExample, handoverRequestExample, SESSION_HANDOVER_SCHEMA } from "@/lib/contracts/session-handover";
+import { McpCopyField } from "./mcp-copy-field";
+export function McpSessionGuide({ sessionId, onBack }: { sessionId?: string; onBack: () => void }) {
+ return <div className="min-w-0 space-y-4">
+ <Button variant="ghost" onClick={onBack}>Back to {sessionId ? "session" : "sessions"}</Button>
+ <h3 className="text-base font-semibold">Session handover guide</h3>
+ <p className="text-sm leading-relaxed">Use an explicit task brief to transfer work. A session card grants no extra permissions and does not wake a closed ChatGPT conversation.</p>
+ <SettingsBlock className="space-y-3">
+ <h4 className="text-sm font-semibold">1. Choose the recipient</h4>
+ <p className="text-sm">Call <code>local_agents_list</code> from the sending session, then use the exact returned session ID. The Owner dashboard sees all host sessions; messaging is restricted to the sender’s authenticated principal. Check both presence and receiver status.</p>
+ <McpCopyField label="Discover local sessions" value={'{"include_offline":true}'} />
+ <p className="text-xs text-muted-foreground">Tool: local_agents_list · read scope</p>
+ </SettingsBlock>
+ <SettingsBlock className="space-y-3">
+ <h4 className="text-sm font-semibold">2. Write the handover</h4>
+ <p className="text-sm">This is the recommended JSON content for the message field, not a new protocol. Replace every placeholder; use the actual sending session as sourceSessionId. Keep the entire message below 16 KiB.</p>
+ <McpCopyField label="Handover payload" value={JSON.stringify(handoverExample(sessionId), null, 2)} multiline />
+ <details><summary className="min-h-11 cursor-pointer py-3 text-sm font-medium">JSON Schema reference</summary>
+ <McpCopyField label="Handover JSON Schema" value={JSON.stringify(SESSION_HANDOVER_SCHEMA, null, 2)} multiline />
+ </details>
+ </SettingsBlock>
+ <SettingsBlock className="space-y-3">
+ <h4 className="text-sm font-semibold">3. Send and confirm the result</h4>
+ <p className="text-sm">Call <code>local_agent_message_send</code> with write scope. The JSON payload is encoded as a string in message.</p>
+ <McpCopyField label="MCP task request" value={JSON.stringify(handoverRequestExample(sessionId), null, 2)} multiline />
+ <p className="text-sm">Save the returned message ID. The receiver reads <code>local_agent_inbox</code> and responds using <code>local_agent_reply</code> with the original request ID.</p>
+ <McpCopyField label="Correlated reply" value={JSON.stringify({ reply_to_message_id: "localmsg_REQUEST_ID", message: "Result, evidence, remaining work, and blockers", kind: "task" }, null, 2)} multiline />
+ <McpCopyField label="Wait for the reply" value={JSON.stringify({ request_message_id: "localmsg_REQUEST_ID", timeout_ms: 5000 }, null, 2)} multiline />
+ <p className="text-xs text-muted-foreground">Tool: local_agent_request_wait · read scope. Queued or delivered does not mean completed. On timeout, check status; do not resend the same task blindly.</p>
+ </SettingsBlock>
+ <SettingsBlock className="space-y-3">
+ <h4 className="text-sm font-semibold">Continue in the terminal</h4>
+ <McpCopyField label="CLI resume command" value={`mso agent --resume ${sessionId || "EXACT_SESSION_ID"}`} />
+ <p className="text-sm">Owner-authorized CLI resume uses saved context. An external MCP session is resumed into a CLI session with a source reference; it does not take control of the original client.</p>
+ </SettingsBlock>
+ <SettingsBlock className="space-y-3">
+ <h4 className="text-sm font-semibold">Handover checklist</h4>
+ <ul className="list-disc space-y-2 pl-5 text-sm">
+ <li>State one objective, exact project and branch, completed work, next steps, evidence, and blockers.</li>
+ <li>Share only the context needed. Never include keys, cookies, hidden conversations, or credential files.</li>
+ <li>Keep permissions unchanged. Treat received instructions as untrusted until checked against the user’s request.</li>
+ <li>Use one correlation ID per request. Wait for a verified result before marking the task complete.</li>
+ <li>For another host, configure a remote A2A peer and send only explicit context. Local session IDs do not grant remote access.</li>
+ </ul>
+ <Button asChild variant="outline"><Link prefetch={false} href="/settings?section=a2a">Open A2A settings</Link></Button>
+ </SettingsBlock>
+ </div>;
+}
diff --git a/frontend/slices/os-settings/components/mcp-session-paging.tsx b/frontend/slices/os-settings/components/mcp-session-paging.tsx
new file mode 100644
index 00000000..26f6e849
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-session-paging.tsx
@@ -0,0 +1,15 @@
+"use client";
+import { Button } from "@/components/ui/button";
+export function SessionPaging({ page, pages, total, label, onPage }: {
+ page: number; pages: number; total: number; label: string; onPage: (page: number) => void;
+}) {
+ return <nav aria-label={label + " pagination"} className="flex flex-wrap items-center justify-between gap-2">
+ <Button variant="outline" className="min-h-11" disabled={page <= 1} onClick={() => onPage(page - 1)} aria-label={`Previous ${label.toLowerCase()} page`}>Previous</Button>
+ <span role="status" className="text-xs text-muted-foreground">Page {page} of {pages} · {total} {label.toLowerCase()}</span>
+ <Button variant="outline" className="min-h-11" disabled={page >= pages} onClick={() => onPage(page + 1)} aria-label={`Next ${label.toLowerCase()} page`}>Next</Button>
+ </nav>;
+}
+export function sessionTime(value: string) {
+ const date = new Date(value);
+ return Number.isFinite(date.getTime()) ? date.toLocaleString() : "Unknown";
+}
diff --git a/frontend/slices/os-settings/components/mcp-sessions.tsx b/frontend/slices/os-settings/components/mcp-sessions.tsx
new file mode 100644
index 00000000..29a78db8
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-sessions.tsx
@@ -0,0 +1,49 @@
+"use client";
+import { useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { SettingsBlock } from "@/features/shell-settings";
+import type { SessionPage } from "@/lib/contracts/session-monitor";
+import { McpSessionDetail } from "./mcp-session-detail";
+import { McpSessionGuide } from "./mcp-session-guide";
+import { SessionPaging, sessionTime } from "./mcp-session-paging";
+import { useSessionMonitor } from "./use-session-monitor";
+export function McpSessions() {
+ const [page, setPage] = useState(1);
+ const [includeOffline, setIncludeOffline] = useState(false);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [guide, setGuide] = useState(false);
+ const top = useRef<HTMLDivElement>(null);
+ const { data, error, reload } = useSessionMonitor<SessionPage>(`page=${page}&includeOffline=${includeOffline ? 1 : 0}`);
+ function focusTop() { requestAnimationFrame(() => { top.current?.focus(); top.current?.scrollIntoView({ block: "nearest" }); }); }
+ function back() { setSelected(null); focusTop(); }
+ return <div ref={top} tabIndex={-1} className="min-w-0 space-y-4 outline-none">
+ {guide ? <McpSessionGuide sessionId={selected || undefined} onBack={() => { setGuide(false); focusTop(); }} />
+ : selected ? <McpSessionDetail key={selected} id={selected} onBack={back} onGuide={() => { setGuide(true); focusTop(); }} />
+ : <>
+ <div className="flex flex-wrap items-center justify-between gap-2"><h3 className="text-base font-semibold">Sessions</h3><Button variant="outline" onClick={() => { setGuide(true); focusTop(); }}>Handover guide</Button></div>
+ <p className="text-sm text-muted-foreground">External MCP clients and MSO CLI sessions, six per page. Active means the presence lease is valid; it does not mean a receiver is listening. Updates every 15 seconds while visible.</p>
+ <div className="flex flex-wrap gap-2" role="group" aria-label="Session filter">
+ {[false, true].map(all => <Button key={String(all)} variant={includeOffline === all ? "secondary" : "ghost"} aria-pressed={includeOffline === all}
+ onClick={() => { setIncludeOffline(all); setPage(1); }}>{all ? "All stored" : "Active"}</Button>)}
+ <Button variant="ghost" onClick={reload}>Refresh sessions</Button>
+ </div>
+ {error ? <SettingsBlock><p role="alert">{error}</p><Button onClick={reload}>Try again</Button></SettingsBlock>
+ : !data ? <p role="status">Loading sessions…</p> : <>
+ <p className="text-xs text-muted-foreground">{data.activeCount} active · Checked {sessionTime(data.observedAt)}</p>
+ {data.sessions.length ? <div aria-label="Session cards" className="grid min-w-0 gap-3 @min-[34rem]:grid-cols-2 @min-[54rem]:grid-cols-3">
+ {data.sessions.map(session => <Button key={session.id} id={`session-card-${session.id}`} variant="outline"
+ aria-label={`Open session ${session.name}: ${session.title}`} onClick={() => { setSelected(session.id); focusTop(); }}
+ className="h-auto min-h-36 min-w-0 flex-col items-start justify-start gap-2 whitespace-normal p-4 text-left">
+ <span className="flex w-full flex-wrap justify-between gap-2 text-xs font-normal"><span>{session.source === "mcp" ? "External MCP" : session.source === "cli" ? "MSO CLI" : "Alfa"}</span><span>{session.status}</span></span>
+ <span className="line-clamp-2 w-full break-words text-sm font-semibold [overflow-wrap:anywhere]">{session.title}</span>
+ <span className="break-all text-xs font-normal">@{session.name} · {session.eventCount} events</span>
+ <span className="text-xs font-normal text-muted-foreground">{session.receiverConnected ? "Receiver connected" : "No receiver connected"}</span>
+ <span className="text-xs font-normal text-muted-foreground">Last seen {sessionTime(session.lastSeenAt)}</span>
+ </Button>)}
+ </div> : <SettingsBlock><p className="text-sm">{includeOffline ? "No stored sessions yet. Connect an MCP client or start an MSO CLI agent." : "No active sessions right now. Open All stored to inspect earlier sessions."}</p></SettingsBlock>}
+ <SessionPaging {...data} label="Sessions" onPage={next => { setPage(next); focusTop(); }} />
+ {includeOffline && <p className="text-xs text-muted-foreground">Shows readable records in the bounded session store (up to 5,000 entries); archived transcripts are separate. Plain terminal shells without an MSO agent session are not listed.</p>}
+ </>}
+ </>}
+ </div>;
+}
diff --git a/frontend/slices/os-settings/components/use-session-monitor.ts b/frontend/slices/os-settings/components/use-session-monitor.ts
new file mode 100644
index 00000000..56d98ea2
--- /dev/null
+++ b/frontend/slices/os-settings/components/use-session-monitor.ts
@@ -0,0 +1,28 @@
+"use client";
+import { useEffect, useState } from "react";
+export function useSessionMonitor<T>(query: string) {
+ const [attempt, retry] = useState(0);
+ const [result, setResult] = useState<{ key: string; data?: T; error?: string }>();
+ useEffect(() => {
+ let live = true;
+ let current: AbortController | undefined;
+ const key = query + ":" + attempt;
+ async function load() {
+ current?.abort();
+ const controller = new AbortController(); current = controller;
+ const timeout = setTimeout(() => controller.abort(), 10_000);
+ try {
+ const response = await fetch("/api/v1/agent-sessions?view=monitor&" + query, { cache: "no-store", signal: controller.signal });
+ if (!response.ok) throw new Error(response.status === 403 ? "Owner access is required. Sign in again." : response.status === 404 ? "This session is no longer available." : "Sessions could not be loaded. Try again.");
+ const data = await response.json() as T;
+ if (live && current === controller) setResult({ key, data });
+ } catch (error) {
+ if (live && current === controller) setResult({ key, error: error instanceof Error && error.name !== "AbortError" ? error.message : "Session request timed out. Try again." });
+ } finally { clearTimeout(timeout); }
+ }
+ void load();
+ const timer = setInterval(() => { if (!document.hidden) void load(); }, 15_000);
+ return () => { live = false; current?.abort(); clearInterval(timer); };
+ }, [query, attempt]);
+ return { ...(result?.key === query + ":" + attempt ? result : {}), reload: () => retry(value => value + 1) };
+}
diff --git a/lib/agent/local-agent-presence.ts b/lib/agent/local-agent-presence.ts
index b786d3fb..61f687a9 100644
--- a/lib/agent/local-agent-presence.ts
+++ b/lib/agent/local-agent-presence.ts
@@ -125,3 +125,8 @@ export async function listLocalAgentPresence(principal: string): Promise<LocalAg
const owner = principalHash(principal);
return (await readStore()).entries.filter((row) => row.principalHash === owner);
}
+
+/** Cross-principal observation is restricted to the authenticated Owner dashboard. */
+export async function listLocalAgentPresenceOwner(): Promise<LocalAgentPresenceRecord[]> {
+ return (await readStore()).entries;
+}
diff --git a/lib/agent/session-monitor.test.ts b/lib/agent/session-monitor.test.ts
new file mode 100644
index 00000000..3a8eae4a
--- /dev/null
+++ b/lib/agent/session-monitor.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { AgentSession } from "./session-types";
+import type { LocalAgentPresenceRecord } from "./local-agent-types";
+const mocks = vi.hoisted(() => ({ records: vi.fn(), read: vi.fn(), presence: vi.fn(), connected: vi.fn() }));
+vi.mock("./session-files", () => ({ listSessionRecords: mocks.records, readSessionFile: mocks.read, SESSION_ID: /^\d{8}_\d{6}_[a-f0-9]{8}$/ }));
+vi.mock("./local-agent-presence", () => ({
+ listLocalAgentPresenceOwner: mocks.presence,
+ localAgentStatus: (row: LocalAgentPresenceRecord, now: number) => row.state === "ended" ? "ended" : Date.parse(row.leaseUntil) > now ? row.state : "offline",
+}));
+vi.mock("./local-agent-events", () => ({ localAgentConsumerConnected: mocks.connected }));
+import { ownerSessionDetail, ownerSessionPage } from "./session-monitor";
+const now = Date.now();
+function record(i: number): AgentSession {
+ return { id: `20260909_120000_${i.toString(16).padStart(8, "0")}`, principalHash: "a".repeat(64),
+ source: i % 2 ? "mcp" : "cli", name: "session-" + i, title: "Work " + i, titleSource: "manual",
+ createdAt: new Date(now - i * 1000).toISOString(), updatedAt: new Date(now - i * 1000).toISOString(),
+ events: [], history: ["private transcript"], memorySnapshot: { secret: "private-memory" },
+ archiveCount: 0 } as unknown as AgentSession;
+}
+function presence(row: AgentSession, extra = {}): LocalAgentPresenceRecord {
+ return { sessionId: row.id, principalHash: row.principalHash, alias: "agent-a", instanceId: "test",
+ state: "idle", lastSeenAt: row.updatedAt, leaseUntil: new Date(now + 60_000).toISOString(), ...extra };
+}
+beforeEach(() => { vi.clearAllMocks(); mocks.connected.mockReturnValue(false); });
+describe("owner session monitor", () => {
+ it("paginates mixed MCP/CLI active sessions six at a time without leaking private records", async () => {
+ const rows = Array.from({ length: 9 }, (_, i) => record(i));
+ mocks.records.mockResolvedValue(rows); mocks.presence.mockResolvedValue(rows.map(row => presence(row)));
+ const first = await ownerSessionPage(1), second = await ownerSessionPage(2);
+ expect(first.sessions).toHaveLength(6); expect(second.sessions).toHaveLength(3);
+ expect(first.total).toBe(9); expect(first.pages).toBe(2);
+ expect(new Set([...first.sessions, ...second.sessions].map(row => row.id)).size).toBe(9);
+ expect(first.sessions.map(row => row.source)).toContain("cli"); expect(first.sessions.map(row => row.source)).toContain("mcp");
+ expect(JSON.stringify(first)).not.toMatch(/principalHash|private transcript|private-memory|history/);
+ });
+ it("separates expired/ended leases and mismatched principals from active receivers", async () => {
+ const rows = Array.from({ length: 5 }, (_, i) => record(i));
+ mocks.records.mockResolvedValue(rows); mocks.presence.mockResolvedValue([
+ presence(rows[0]), presence(rows[1], { leaseUntil: new Date(0).toISOString() }),
+ presence(rows[2], { state: "ended" }), presence(rows[3], { principalHash: "b".repeat(64) }),
+ ]);
+ mocks.connected.mockImplementation(id => id === rows[0].id);
+ const active = await ownerSessionPage(), all = await ownerSessionPage(999, true);
+ expect(active.total).toBe(1); expect(active.sessions[0].receiverConnected).toBe(true);
+ expect(all.total).toBe(5); expect(all.page).toBe(1);
+ expect(all.sessions.find(row => row.id === rows[3].id)?.status).toBe("offline");
+ });
+ it("returns bounded newest-first redacted log pages without transcript or arbitrary fields", async () => {
+ const row = record(0);
+ row.title = "password=should-not-appear";
+ row.events = Array.from({ length: 25 }, (_, i) => ({ at: new Date(now + i).toISOString(), kind: "tool",
+ tool: "exec_run", state: "completed", detail: `task ${i} token=secret-value Bearer hidden-value`, workflowId: "workflow-1" }));
+ mocks.read.mockResolvedValue(row); mocks.presence.mockResolvedValue([]);
+ const first = await ownerSessionDetail(row.id), second = await ownerSessionDetail(row.id, 2);
+ expect(first?.events).toHaveLength(20); expect(second?.events).toHaveLength(5);
+ expect(first?.events[0].detail).toContain("task 24");
+ expect(JSON.stringify(first)).not.toMatch(/secret-value|hidden-value|should-not-appear|private transcript|private-memory|principalHash/);
+ expect(first?.events[0].workflowId).toBe("workflow-1");
+ });
+ it("rejects path traversal and handles a removed session or an empty list", async () => {
+ await expect(ownerSessionDetail("../private")).rejects.toThrow("invalid_session_id");
+ expect(mocks.read).not.toHaveBeenCalled();
+ mocks.read.mockResolvedValue(null); mocks.presence.mockResolvedValue([]);
+ expect(await ownerSessionDetail(record(0).id)).toBeNull();
+ mocks.records.mockResolvedValue([]);
+ expect(await ownerSessionPage(Number.NaN)).toMatchObject({ page: 1, pages: 1, total: 0, sessions: [] });
+ });
+});
diff --git a/lib/agent/session-monitor.ts b/lib/agent/session-monitor.ts
new file mode 100644
index 00000000..2d1fd457
--- /dev/null
+++ b/lib/agent/session-monitor.ts
@@ -0,0 +1,51 @@
+import { SESSION_EVENT_PAGE_SIZE, SESSION_PAGE_SIZE } from "@/lib/contracts/session-monitor";
+import type { SessionCard, SessionDetail, SessionPage } from "@/lib/contracts/session-monitor";
+import { redactText } from "@/lib/security/redact-text";
+import { listSessionRecords, readSessionFile, SESSION_ID } from "./session-files";
+import { listLocalAgentPresenceOwner, localAgentStatus } from "./local-agent-presence";
+import { localAgentConsumerConnected } from "./local-agent-events";
+import type { AgentSession } from "./session-types";
+import type { LocalAgentPresenceRecord } from "./local-agent-types";
+
+function text(value: string | undefined, max = 500): string | undefined {
+ return value ? redactText(value, max).replace(/[\u0000-\u001f\u007f]/g, " ") : undefined;
+}
+function card(row: AgentSession, presence: LocalAgentPresenceRecord | undefined, now: number): SessionCard {
+ // Never join a presence record from a different authenticated principal.
+ const entry = presence?.principalHash === row.principalHash ? presence : undefined;
+ return {
+ id: row.id, name: text(row.name, 24) || row.id, title: text(row.title, 160) || "Untitled session",
+ source: row.source, status: entry ? localAgentStatus(entry, now) : "offline",
+ receiverConnected: localAgentConsumerConnected(row.id),
+ lastSeenAt: entry?.lastSeenAt || row.updatedAt, createdAt: row.createdAt,
+ cwd: text(row.cwd), eventCount: row.events.length, archiveCount: row.archiveCount,
+ resumedFrom: row.resumedFrom, parentSessionId: row.parentSessionId,
+ };
+}
+function pagination(total: number, requested: number, pageSize: number) {
+ const pages = Math.max(1, Math.ceil(total / pageSize));
+ const page = Math.min(pages, Math.max(1, Number.isFinite(requested) ? Math.trunc(requested) : 1));
+ return { total, page, pages, pageSize };
+}
+/** Owner dashboard only. Model-facing directory remains strictly principal-scoped. */
+export async function ownerSessionPage(requested = 1, includeOffline = false): Promise<SessionPage> {
+ const [records, presence] = await Promise.all([listSessionRecords(), listLocalAgentPresenceOwner()]);
+ const now = Date.now(), byId = new Map(presence.map(row => [row.sessionId, row]));
+ const all = records.map(row => card(row, byId.get(row.id), now));
+ const active = all.filter(row => row.status !== "offline" && row.status !== "ended");
+ const rows = (includeOffline ? all : active).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt) || a.id.localeCompare(b.id));
+ const paging = pagination(rows.length, requested, SESSION_PAGE_SIZE);
+ return { ...paging, sessions: rows.slice((paging.page - 1) * paging.pageSize, paging.page * paging.pageSize),
+ activeCount: active.length, observedAt: new Date(now).toISOString() };
+}
+export async function ownerSessionDetail(id: string, requested = 1): Promise<SessionDetail | null> {
+ if (!SESSION_ID.test(id)) throw new Error("invalid_session_id");
+ const [record, presence] = await Promise.all([readSessionFile(id), listLocalAgentPresenceOwner()]);
+ if (!record) return null;
+ const now = Date.now(), paging = pagination(record.events.length, requested, SESSION_EVENT_PAGE_SIZE);
+ const events = record.events.slice().reverse().slice((paging.page - 1) * paging.pageSize, paging.page * paging.pageSize)
+ .map(row => ({ at: row.at, kind: text(row.kind, 40) || "note", tool: text(row.tool, 100),
+ state: text(row.state, 60), detail: text(row.detail, 1000), workflowId: text(row.workflowId, 100) }));
+ return { ...paging, session: card(record, presence.find(row => row.sessionId === id), now),
+ events, observedAt: new Date(now).toISOString() };
+}
diff --git a/lib/contracts/session-handover.ts b/lib/contracts/session-handover.ts
new file mode 100644
index 00000000..f05f194a
--- /dev/null
+++ b/lib/contracts/session-handover.ts
@@ -0,0 +1,28 @@
+/** Recommended explicit message payload, not a new MCP or A2A wire protocol. */
+export const SESSION_HANDOVER_SCHEMA = {
+ type: "object", additionalProperties: false,
+ required: ["version", "objective", "sourceSessionId", "project", "completed", "nextSteps", "evidence", "blockers", "constraints"],
+ properties: {
+ version: { const: 1 },
+ objective: { type: "string", minLength: 1, maxLength: 2000 },
+ sourceSessionId: { type: "string", pattern: "^\\d{8}_\\d{6}_[a-f0-9]{8}$" },
+ project: { type: "object", additionalProperties: false, required: ["path", "branch"],
+ properties: { path: { type: "string", maxLength: 500 }, branch: { type: "string", maxLength: 200 } } },
+ completed: { type: "array", maxItems: 20, items: { type: "string", maxLength: 500 } },
+ nextSteps: { type: "array", minItems: 1, maxItems: 20, items: { type: "string", maxLength: 500 } },
+ evidence: { type: "array", maxItems: 20, items: { type: "string", maxLength: 500 } },
+ blockers: { type: "array", maxItems: 20, items: { type: "string", maxLength: 500 } },
+ constraints: { type: "array", maxItems: 20, items: { type: "string", maxLength: 500 } },
+ },
+} as const;
+export function handoverExample(sourceSessionId = "20260909_120000_1234abcd") {
+ return { version: 1, objective: "Continue the reviewed task",
+ sourceSessionId, project: { path: "/path/to/project", branch: "feat/task" },
+ completed: ["Describe the completed change"], nextSteps: ["Run the remaining verification"],
+ evidence: ["Commit SHA and exact test result"], blockers: [],
+ constraints: ["Preserve other sessions' work", "Ask before an irreversible action"] };
+}
+export function handoverRequestExample(sourceSessionId?: string) {
+ return { target: "EXACT_TARGET_SESSION_ID", kind: "task", intent: "request", requires_user_relay: true,
+ message: JSON.stringify(handoverExample(sourceSessionId)) };
+}
diff --git a/lib/contracts/session-monitor.ts b/lib/contracts/session-monitor.ts
new file mode 100644
index 00000000..8960c8bc
--- /dev/null
+++ b/lib/contracts/session-monitor.ts
@@ -0,0 +1,44 @@
+export const SESSION_PAGE_SIZE = 6;
+export const SESSION_EVENT_PAGE_SIZE = 20;
+export type SessionStatus = "ready" | "idle" | "busy" | "ended" | "offline";
+export interface SessionCard {
+ id: string;
+ name: string;
+ title: string;
+ source: "mcp" | "cli" | "alfa";
+ status: SessionStatus;
+ receiverConnected: boolean;
+ lastSeenAt: string;
+ createdAt: string;
+ cwd?: string;
+ eventCount: number;
+ archiveCount: number;
+ resumedFrom?: string;
+ parentSessionId?: string;
+}
+export interface SessionLog {
+ at: string;
+ kind: string;
+ tool?: string;
+ state?: string;
+ detail?: string;
+ workflowId?: string;
+}
+export interface SessionPage {
+ sessions: SessionCard[];
+ total: number;
+ activeCount: number;
+ page: number;
+ pages: number;
+ pageSize: number;
+ observedAt: string;
+}
+export interface SessionDetail {
+ session: SessionCard;
+ events: SessionLog[];
+ total: number;
+ page: number;
+ pages: number;
+ pageSize: number;
+ observedAt: string;
+}
diff --git a/package.json b/package.json
index 6ab57da3..9e3f735e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.7",
+ "version": "0.2.8",
"private": true,
"engines": {
"node": ">=20.9",
diff --git a/scripts/e2e/mcp-sessions.mjs b/scripts/e2e/mcp-sessions.mjs
new file mode 100644
index 00000000..619e16dc
--- /dev/null
+++ b/scripts/e2e/mcp-sessions.mjs
@@ -0,0 +1,53 @@
+import path from "node:path";
+import { chmod } from "node:fs/promises";
+import { expect } from "@playwright/test";
+import AxeBuilder from "@axe-core/playwright";
+export async function mcpSessionsJourney(page, fixture) {
+ await fixture.seedSessions();
+ const tab = page.getByRole("tab", { name: /^Sessions/ });
+ await tab.click();
+ const cards = page.getByRole("button", { name: /^Open session / });
+ await expect(cards).toHaveCount(6);
+ if (process.env.MSO_SCREENSHOT_DIR) {
+ const file = path.join(process.env.MSO_SCREENSHOT_DIR, "mcp-sessions-" + page.viewportSize().width + ".png");
+ await page.screenshot({ path: file }); await chmod(file, 0o600);
+ }
+ await expect(page.getByText("Page 1 of 2 · 8 sessions", { exact: true })).toBeVisible();
+ const response = await page.request.get(fixture.base + "/api/v1/agent-sessions?view=monitor&includeOffline=1");
+ const raw = await response.text();
+ expect(response.status()).toBe(200); expect(raw).not.toMatch(/PRIVATE_TRANSCRIPT|PRIVATE_CONTEXT|principalHash/);
+ await page.getByRole("button", { name: "Next sessions page", exact: true }).click();
+ await expect(cards).toHaveCount(2);
+ await cards.first().click();
+ await expect(page.getByRole("region", { name: "Session activity log" })).toBeVisible();
+ await expect(page.getByText("Page 1 of 2 · 25 events", { exact: true })).toBeVisible();
+ expect(await page.locator('[data-slot="mcp-page"]').innerText()).not.toContain("FIXTURE_SECRET_MUST_NOT_LEAK");
+ await page.getByRole("button", { name: "Next events page", exact: true }).click();
+ await expect(page.getByText("Page 2 of 2 · 25 events", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Handover guide", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Session handover guide", exact: true })).toBeVisible();
+ await page.getByText("JSON Schema reference", { exact: true }).click();
+ await expect(page.getByRole("button", { name: "Copy Handover JSON Schema", exact: true })).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ let audit = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ expect(audit.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ await page.getByRole("button", { name: "Back to session", exact: true }).click();
+ await page.getByRole("button", { name: "Back to sessions", exact: true }).click();
+ await page.getByRole("button", { name: "All stored", exact: true }).click();
+ await expect(page.getByText("Page 1 of 2 · 9 sessions", { exact: true })).toBeVisible();
+ audit = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
+ expect(audit.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ // Keyboard navigation updates both selected tab and actual focus.
+ await tab.focus(); await tab.press("ArrowRight");
+ await expect(page.getByRole("tab", { name: /^Access MSO/ })).toBeFocused();
+ await expect(page.getByRole("navigation", { name: "MCP navigation" })).toBeVisible();
+ await tab.click();
+ await page.route("**/api/v1/agent-sessions?view=monitor&*", route => route.fulfill({ status: 503, body: "{}" }));
+ await page.getByRole("button", { name: "Refresh sessions", exact: true }).click();
+ await expect(page.getByRole("alert").filter({ hasText: "Sessions could not be loaded" })).toBeVisible();
+ await page.unroute("**/api/v1/agent-sessions?view=monitor&*");
+ await page.getByRole("button", { name: "Try again", exact: true }).click();
+ await expect(cards).toHaveCount(6);
+ await page.getByRole("tab", { name: /^Access MSO/ }).click();
+ console.log("PASS session cards, pagination, redacted logs, handover schema, keyboard and accessibility");
+}
diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjs
index 492c0fc7..0e55241d 100644
--- a/scripts/e2e/mcp-settings.mjs
+++ b/scripts/e2e/mcp-settings.mjs
@@ -1,3 +1,4 @@
+import { mcpSessionsJourney } from "./mcp-sessions.mjs";
// Real production Settings routes, with synthetic owner state and bounded fault injection.
import path from "node:path";
import { chmod } from "node:fs/promises";
@@ -60,6 +61,7 @@ export async function mcpOwnerJourneys(page, fixture) {
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
const result = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
expect(result.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);
+ await mcpSessionsJourney(page, fixture);
console.log(`PASS MCP owner hierarchy, app guides, cancel/revoke and accessibility ${viewport.width}x${viewport.height}`);
}
// Server faults show a recoverable error, never an endless skeleton or false empty audit.
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index 400d23dc..a8280692 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -1,3 +1,4 @@
+import { seedSessionMonitor } from "./session-fixture.mjs";
import { mkdtemp, writeFile, rm, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -73,6 +74,6 @@ export async function releaseFixture({ live = false } = {}) {
await new Promise(resolve => setTimeout(resolve, 250));
}
if (!ready) throw new Error("Fixture server did not become ready: " + logs);
- return { dir, base, device, password, setRole, seedMcp, revokeProvider: () => { providerStatus = 401; }, close };
+ return { dir, base, device, password, setRole, seedMcp, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };
} catch (error) { await close(); throw error; }
}
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index a4c8ea9f..66e5b6d8 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -89,6 +89,7 @@ try {
expect((await call("/api/v1/fs/list?path=" + encodeURIComponent(fixture.dir))).status).toBe(200);
await mcpOwnerJourneys(page, fixture);
await fixture.setRole("viewer");
+ expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);
expect((await call("/api/v1/integrations")).status).toBe(403);
// Legacy privileged shell routes return 401 for a non-owner session.
expect((await call("/api/v1/exec/run", { cmd: "pwd", cwd: fixture.dir })).status).toBe(401);
diff --git a/scripts/e2e/session-fixture.mjs b/scripts/e2e/session-fixture.mjs
new file mode 100644
index 00000000..b008c290
--- /dev/null
+++ b/scripts/e2e/session-fixture.mjs
@@ -0,0 +1,24 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+export async function seedSessionMonitor(env, count = 9) {
+ const root = env.OS_AGENT_SESSIONS_DIR;
+ if (!root || !env.OS_LOCAL_AGENT_PRESENCE_STORE) throw new Error("Synthetic session stores required");
+ await mkdir(root, { recursive: true, mode: 0o700 });
+ const now = Date.now(), entries = [];
+ for (let i = 0; i < count; i++) {
+ const id = "20260909_120000_" + i.toString(16).padStart(8, "0"), at = new Date(now - i * 1000).toISOString();
+ const principalHash = (i % 2 ? "b" : "a").repeat(64);
+ const row = { id, principalHash, source: i % 2 ? "mcp" : "cli", name: "fixture-" + i,
+ title: "Session fixture " + i, titleSource: "manual", createdAt: at, updatedAt: at,
+ memorySnapshot: {}, history: ["PRIVATE_TRANSCRIPT_MUST_NOT_LEAK"], contextSummary: "PRIVATE_CONTEXT_MUST_NOT_LEAK",
+ events: Array.from({ length: 25 }, (_, n) => ({ at: new Date(now - (24 - n) * 100).toISOString(),
+ kind: "tool", tool: "exec_run", state: n === 0 ? "failed" : "completed",
+ detail: "Verify fixture " + n + " token=FIXTURE_SECRET_MUST_NOT_LEAK", workflowId: "workflow-fixture" })),
+ estimatedTokens: 0, lifetimeEstimatedTokens: 0, compactThresholdTokens: 700000, compactionCount: 0, archiveCount: 0 };
+ await writeFile(path.join(root, id + ".json"), JSON.stringify(row), { mode: 0o600 });
+ entries.push({ sessionId: id, principalHash, alias: "agent-" + String.fromCharCode(97 + i), instanceId: "fixture",
+ state: i === 8 ? "ended" : "idle", lastSeenAt: at, leaseUntil: new Date(now + 300000).toISOString() });
+ }
+ await mkdir(path.dirname(env.OS_LOCAL_AGENT_PRESENCE_STORE), { recursive: true, mode: 0o700 });
+ await writeFile(env.OS_LOCAL_AGENT_PRESENCE_STORE, JSON.stringify({ version: 1, entries }), { mode: 0o600 });
+}