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(workflows): visualize agent sessions

Rahman97a51114b42e
diff --git a/app/api/v1/agent-sessions/monitor.test.ts b/app/api/v1/agent-sessions/monitor.test.ts
index 5059bd81..22c15be0 100644
--- a/app/api/v1/agent-sessions/monitor.test.ts
+++ b/app/api/v1/agent-sessions/monitor.test.ts
@@ -1,8 +1,8 @@
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() }));
+const mocks = vi.hoisted(() => ({ context: vi.fn(), page: vi.fn(), detail: vi.fn(), graph: vi.fn() }));
vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.context }));
-vi.mock("@/lib/agent/session-monitor", () => ({ ownerSessionPage: mocks.page, ownerSessionDetail: mocks.detail }));
+vi.mock("@/lib/agent/session-monitor", () => ({ ownerSessionPage: mocks.page, ownerSessionDetail: mocks.detail, ownerSessionGraph: mocks.graph }));
import { GET } from "./route";
beforeEach(() => { vi.clearAllMocks(); mocks.context.mockResolvedValue({ role: "owner", session: { device_id: "owner" } }); });
describe("session monitor route", () => {
@@ -17,6 +17,13 @@ describe("session monitor route", () => {
expect(mocks.page).toHaveBeenCalledWith(2, true, "fixture");
expect(response.headers.get("cache-control")).toBe("private, no-store");
});
+ it("serves the owner-only session graph projection with private no-store caching", async () => {
+ mocks.graph.mockResolvedValue({ session: { label: "fara-context" }, graph: { name: "fara-context" } });
+ const response = await GET(new NextRequest("http://localhost/api/v1/agent-sessions?view=graph&id=20260901_100000_aabbccdd"));
+ expect(response.status).toBe(200);
+ expect(mocks.graph).toHaveBeenCalledWith("20260901_100000_aabbccdd", 120);
+ 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);
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index be4e39bd..069f3903 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -1,4 +1,4 @@
-import { ownerSessionPage, ownerSessionDetail } from "@/lib/agent/session-monitor";
+import { ownerSessionPage, ownerSessionDetail, ownerSessionGraph } 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";
@@ -45,11 +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") {
+ const view = req.nextUrl.searchParams.get("view");
+ if (view === "monitor" || view === "graph") {
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", req.nextUrl.searchParams.get("q") || "");
+ const result = view === "graph"
+ ? (id ? await ownerSessionGraph(id, Number(req.nextUrl.searchParams.get("limit") || 120)) : null)
+ : (id ? await ownerSessionDetail(id, page) : await ownerSessionPage(page, req.nextUrl.searchParams.get("includeOffline") === "1", req.nextUrl.searchParams.get("q") || ""));
return NextResponse.json(result || { error: "session_not_found" }, { status: result ? 200 : 404, headers: { "Cache-Control": "private, no-store" } });
} catch (cause) {
const invalid = cause instanceof Error && ["invalid_session_id", "session search exceeds 200 characters"].includes(cause.message);
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index fdd6f7d2..675ad24e 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
import { roleAtLeast } from "@/lib/auth/roles";
import { createAgentSession, listAgentSessions } from "@/lib/agent/session-store";
+import { agentSessionLabel } from "@/lib/agent/session-name";
import { readSetupJson } from "@/lib/infra/setup-http";
import { rateLimited } from "@/lib/host/limits-api";
import { maxScope } from "@/lib/mcp/scope";
@@ -24,7 +25,7 @@ const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof
async function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}
function definition(graph:NonNullable<Awaited<ReturnType<typeof getWorkflowGraph>>>){const{revision:_r,createdAt:_c,updatedAt:_u,version:_v,...rest}=graph;return rest;}
export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=q.has("variables")?"operator":"viewer",session=await auth(minimum);if(!session)return fail("unauthorized",401);try{
- if(q.get("directory")==="1"){const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150),graphs=await listWorkflowGraphs(session.principal),sessions=await listAgentSessions(session.principal,50);return NextResponse.json({tools,workflows:graphs.filter((graph)=>!query||`${graph.name} ${graph.description} ${(graph.metadata.tags??[]).join(" ")}`.toLowerCase().includes(query)).map((graph)=>({id:graph.id,name:graph.name,status:graph.status,nodeCount:graph.nodes.length,updatedAt:graph.updatedAt})),sessions:sessions.filter((row)=>!query||`${row.title} ${row.name} ${row.cwd??""}`.toLowerCase().includes(query))},{headers});}
+ if(q.get("directory")==="1"){const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150),graphs=await listWorkflowGraphs(session.principal),sessions=await listAgentSessions(session.principal,50);return NextResponse.json({tools,workflows:graphs.filter((graph)=>!query||`${graph.name} ${graph.description} ${(graph.metadata.tags??[]).join(" ")}`.toLowerCase().includes(query)).map((graph)=>({id:graph.id,name:graph.name,status:graph.status,nodeCount:graph.nodes.length,updatedAt:graph.updatedAt})),sessions:sessions.filter((row)=>!query||`${agentSessionLabel(row.name,row.title,row.cwd)} ${row.title} ${row.name} ${row.cwd??""}`.toLowerCase().includes(query)).map((row)=>({...row,label:agentSessionLabel(row.name,row.title,row.cwd)}))},{headers});}
if(q.get("scripts")==="1"){const hint=q.get("project")?.trim();if(!hint)throw new Error("project is required");const project=await resolveProjectHint(hint);if(!project||project.matchedBy==="fuzzy")throw new Error("exact project not found");const query=(q.get("q")??"").toLowerCase().trim(),scripts=(await listAutomationScripts(project.path)).filter((script)=>!query||`${script.id} ${script.intent} ${script.status} ${script.steps.map((step)=>step.tool).join(" ")}`.toLowerCase().includes(query)).map((script)=>({id:script.id,intent:script.intent,status:script.status,stepCount:script.steps.length,updatedAt:script.updatedAt,project:script.project,tools:script.steps.map((step)=>step.tool)}));return NextResponse.json({project:project.id,scripts},{headers});}
if(q.get("catalog")==="1")return NextResponse.json({nodes:workflowNodeCatalog(q.get("q")??"")},{headers});
if(q.get("templates")==="1")return NextResponse.json({templates:workflowTemplates()},{headers});
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index bcc83bc9..625714fb 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**
+- `workflows` visualize agent sessions
- `ai` add dynamic free provider discovery
- `workflows` maximize script and search automation
diff --git a/frontend/slices/os-settings/components/mcp-session-detail.tsx b/frontend/slices/os-settings/components/mcp-session-detail.tsx
index 69663bdd..48c1ad27 100644
--- a/frontend/slices/os-settings/components/mcp-session-detail.tsx
+++ b/frontend/slices/os-settings/components/mcp-session-detail.tsx
@@ -1,9 +1,9 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
+import { openWindow } from "@/features/appshell";
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 }) {
@@ -14,22 +14,23 @@ export function McpSessionDetail({ id, onBack, onGuide }: { id: string; onBack:
{error && <SettingsBlock><p role="alert">{error}</p><Button onClick={reload}>Try again</Button></SettingsBlock>}
{!data ? !error && <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>
+ <h3 tabIndex={-1} className="break-words text-base font-semibold">{data.session.label}</h3>
+ <p className="text-sm">{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.title}</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} />}
+ {data.session.resumedFrom && <p className="text-xs text-muted-foreground">Resumed from another saved session.</p>}
+ {data.session.parentSessionId && <p className="text-xs text-muted-foreground">Created as a child of another saved session.</p>}
+ <Button variant="outline" onClick={() => openWindow("workflows", "Workflows", undefined, { view: "sessions", sessionId: id })}>Open execution graph</Button>
</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>
+ <p className="text-sm text-muted-foreground">Newest first. Recorded tool and workflow events only; raw arguments, outputs, private conversations, and internal session IDs 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 border-b border-border py-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>}
+ {event.workflowId && <p className="mt-1 text-xs text-muted-foreground">Linked workflow activity</p>}
</li>)}</ol> : <p className="text-sm">No recorded activity yet.</p>}
<SessionPaging {...data} label="Events" onPage={setPage} />
</section>
diff --git a/frontend/slices/os-settings/components/mcp-session-guide.tsx b/frontend/slices/os-settings/components/mcp-session-guide.tsx
index 5954aca4..a9711dc2 100644
--- a/frontend/slices/os-settings/components/mcp-session-guide.tsx
+++ b/frontend/slices/os-settings/components/mcp-session-guide.tsx
@@ -4,21 +4,21 @@ 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 }) {
+export function McpSessionGuide({ sessionRef, onBack }: { sessionRef?: string; onBack: () => void }) {
return <div className="min-w-0 space-y-4">
- <Button variant="ghost" onClick={onBack}>Back to {sessionId ? "session" : "sessions"}</Button>
+ <Button variant="ghost" onClick={onBack}>Back to {sessionRef ? "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>
+ <p className="text-sm">Call <code>local_agents_list</code> from the sending session, then target the returned <code>@name</code> or human session label. Internal durable IDs remain an implementation detail. 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 />
+ <p className="text-sm">This is the recommended JSON content for the message field, not a new protocol. Replace every placeholder and use the sending session’s human reference as <code>sourceSessionRef</code>. Keep the entire message below 16 KiB.</p>
+ <McpCopyField label="Handover payload" value={JSON.stringify(handoverExample(sessionRef), 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>
@@ -26,7 +26,7 @@ export function McpSessionGuide({ sessionId, onBack }: { sessionId?: string; onB
<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 />
+ <McpCopyField label="MCP task request" value={JSON.stringify(handoverRequestExample(sessionRef), 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 />
@@ -34,8 +34,8 @@ export function McpSessionGuide({ sessionId, onBack }: { sessionId?: string; onB
</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>
+ <McpCopyField label="CLI resume command" value={`mso agent --resume ${sessionRef || "agent-context-session"}`} />
+ <p className="text-sm">Owner-authorized CLI resume accepts the human session reference and 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>
@@ -44,7 +44,7 @@ export function McpSessionGuide({ sessionId, onBack }: { sessionId?: string; onB
<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>
+ <li>For another host, configure a remote A2A peer and send only explicit context. Human session references do not grant remote access.</li>
</ul>
<Button asChild variant="outline"><Link prefetch={false} href="/settings?section=a2a">Open A2A settings</Link></Button>
</SettingsBlock>
diff --git a/frontend/slices/os-settings/components/mcp-sessions.tsx b/frontend/slices/os-settings/components/mcp-sessions.tsx
index a844822c..d98a2004 100644
--- a/frontend/slices/os-settings/components/mcp-sessions.tsx
+++ b/frontend/slices/os-settings/components/mcp-sessions.tsx
@@ -2,9 +2,9 @@
import { useRef, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
+import { openWindow } from "@/features/appshell";
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";
@@ -13,19 +13,16 @@ export function McpSessions() {
const [query, setQuery] = useState("");
const [page, setPage] = useState(1);
const [includeOffline, setIncludeOffline] = useState(true);
- 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}&q=${encodeURIComponent(query)}`);
function focusTop() { requestAnimationFrame(() => { top.current?.focus(); top.current?.scrollIntoView({ block: "nearest" }); }); }
- function back() { setSelected(null); focusTop(); }
+ function openSession(id: string) { openWindow("workflows", "Workflows", undefined, { view: "sessions", sessionId: id }); }
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(); }} />
- : <>
+ {guide ? <McpSessionGuide onBack={() => { setGuide(false); 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">Saved conversations from MCP clients, MSO CLI, and Alfa. History stays available after disconnecting. Active shows recent presence; receiving messages requires a connected receiver.</p>
- <form className="flex gap-2" onSubmit={event => { event.preventDefault(); setQuery(search.trim()); setPage(1); }}><Input type="search" aria-label="Search saved sessions" placeholder="Search title, session, or project" maxLength={200} value={search} onChange={event => { setSearch(event.target.value); if (!event.target.value) { setQuery(""); setPage(1); } }} /><Button type="submit" variant="outline">Search</Button></form>
+ <p className="text-sm text-muted-foreground">Saved MCP, CLI, and Alfa sessions. Selecting one opens its read-only execution graph in Workflow; internal session IDs stay hidden from the interface.</p>
+ <form className="flex gap-2" onSubmit={event => { event.preventDefault(); setQuery(search.trim()); setPage(1); }}><Input type="search" aria-label="Search saved sessions" placeholder="Search agent-context or project" maxLength={200} value={search} onChange={event => { setSearch(event.target.value); if (!event.target.value) { setQuery(""); setPage(1); } }} /><Button type="submit" variant="outline">Search</Button></form>
<div className="flex flex-wrap gap-2" role="group" aria-label="Session filter">
{[true, false].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>)}
@@ -35,18 +32,18 @@ export function McpSessions() {
{!data ? !error && <p role="status">Loading sessions…</p> : <>
<p className="text-xs text-muted-foreground">{data.total} {includeOffline ? "stored" : "active"} · {data.activeCount} active · Checked {sessionTime(data.observedAt)}</p>
{data.sessions.length ? <div aria-label="Session cards" className="flex min-w-0 flex-col divide-y divide-border">
- {data.sessions.map(session => <Button key={session.id} id={`session-card-${session.id}`} variant="ghost"
- aria-label={`Open session ${session.name}: ${session.title}`} onClick={() => { setSelected(session.id); focusTop(); }}
+ {data.sessions.map(session => <Button key={session.id} variant="ghost"
+ aria-label={`Open session ${session.label}`} onClick={() => openSession(session.id)}
className="h-auto min-w-0 flex-col items-start justify-start gap-1 whitespace-normal rounded-none py-3 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="w-full truncate text-sm font-semibold">{session.label}</span>
+ <span className="line-clamp-2 w-full break-words text-xs font-normal text-muted-foreground [overflow-wrap:anywhere]">{session.title}</span>
+ <span className="text-xs font-normal text-muted-foreground">{session.eventCount} events · {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">{query ? "No sessions match this search. Try the session ID or a shorter title." : 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>}
+ </div> : <SettingsBlock><p className="text-sm">{query ? "No sessions match this search. Try the agent name, context, or project." : 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 all readable saved sessions; archived transcripts are separate. Plain terminal shells without an MSO agent session are not listed.</p>}
+ {includeOffline && <p className="text-xs text-muted-foreground">Shows readable saved sessions; archived transcripts remain separate. Plain terminal shells without an MSO agent session are not listed.</p>}
</>}
</>}
</div>;
diff --git a/frontend/slices/os-terminal/app.tsx b/frontend/slices/os-terminal/app.tsx
index 814c5c47..a21dcda2 100644
--- a/frontend/slices/os-terminal/app.tsx
+++ b/frontend/slices/os-terminal/app.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { AppProps } from "@/features/appshell";
import { TerminalSession, type TerminalSessionProps } from "./components/terminal-session";
import { TerminalTabs } from "./components/terminal-tabs";
@@ -15,6 +16,9 @@ export function Terminal({ initialCommand, initialCwd, tabbed = true }: Terminal
return <TerminalTabs initialCommand={initialCommand} initialCwd={initialCwd} />;
}
-export default function TerminalApp() {
- return <Terminal />;
+export default function TerminalApp({ payload }: AppProps) {
+ const row = payload && typeof payload === "object" ? payload as { initialCwd?: unknown; initialCommand?: unknown } : undefined;
+ const initialCwd = typeof row?.initialCwd === "string" && row.initialCwd ? row.initialCwd : undefined;
+ const initialCommand = typeof row?.initialCommand === "string" && row.initialCommand ? row.initialCommand : undefined;
+ return <Terminal initialCwd={initialCwd} initialCommand={initialCommand} />;
}
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index 6faaf373..e56d3cff 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -1,8 +1,9 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { Copy, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
+import { Activity, Copy, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
import type { AppProps, ToolbarItem } from "@/features/appshell";
+import type { SessionGraphView } from "@/lib/contracts/session-monitor";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
import { AppFrame, ResponsiveDialog, ResponsiveToolbar, openWindow, useContainer, useResponsive } from "@/features/appshell";
import { Badge } from "@/components/ui/badge";
@@ -13,20 +14,27 @@ import { WorkflowCreateDialog } from "./components/workflow-create-dialog";
import { WorkflowDetails, type WorkflowPanel } from "./components/workflow-details";
import { WorkflowLibrary } from "./components/workflow-library";
import { WorkflowNodePalette } from "./components/workflow-node-palette";
+import { WorkflowSessionDetails } from "./components/workflow-session-details";
+import { WorkflowSessionLibrary } from "./components/workflow-session-library";
import { tidyWorkflowNodes } from "./lib/canvas-layout";
-import { cloneGraph, createFromTemplate, createGraph, deleteGraph, getGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
+import { cloneGraph, createFromTemplate, createGraph, deleteGraph, getGraph, getSessionGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
type Definition = Omit<WorkflowGraph, "version" | "id" | "revision" | "createdAt" | "updatedAt">;
+type LibraryMode = "automations" | "sessions";
function starterGraph(): Definition { return { name: "New Workflow", description: "Private workflow graph.", status: "draft", inputs: {}, metadata: { provenance: "user" }, nodes: [{ id: "manual", name: "Manual Trigger", type: "manual", position: { x: 80, y: 160 }, config: {} }, { id: "output", name: "Output", type: "output", position: { x: 420, y: 160 }, config: {} }], edges: [{ id: "edge-start", source: "manual", target: "output" }] }; }
+function payloadSessionId(payload: unknown): string | undefined { if (!payload || typeof payload !== "object") return undefined; const row = payload as { view?: unknown; sessionId?: unknown }; return row.view === "sessions" && typeof row.sessionId === "string" ? row.sessionId : undefined; }
-export default function WorkflowsApp(_props: AppProps) {
+export default function WorkflowsApp(props: AppProps) {
const { isMobile } = useResponsive();
const [appRef, pane] = useContainer<HTMLDivElement>();
const overlayPane = isMobile || pane !== "lg";
const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null), [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
const [busy, setBusy] = useState(false), [dirty, setDirty] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<WorkflowPanel>("inspector"), [search, setSearch] = useState("");
const [libraryOpen, setLibraryOpen] = useState(false), [detailsOpen, setDetailsOpen] = useState(false), [showLibrary, setShowLibrary] = useState(true), [showDetails, setShowDetails] = useState(true);
+ const [libraryMode, setLibraryMode] = useState<LibraryMode>(() => payloadSessionId(props.payload) ? "sessions" : "automations");
+ const [sessionView, setSessionView] = useState<SessionGraphView | null>(null), [sessionSelected, setSessionSelected] = useState<string | null>(null);
const node = useMemo(() => graph?.nodes.find((item) => item.id === selected) ?? null, [graph, selected]);
+ const sessionNode = useMemo(() => sessionView?.graph.nodes.find((item) => item.id === sessionSelected) ?? null, [sessionSelected, sessionView]);
const runStates = useMemo(() => new Map(run?.nodes.map((item) => [item.id, item.state]) ?? []), [run]);
const runEdgeStates = useMemo(() => new Map(run?.edges?.map((item) => [item.id, item.state]) ?? []), [run]);
@@ -38,12 +46,23 @@ export default function WorkflowsApp(_props: AppProps) {
const frame = requestAnimationFrame(() => { setLibraryOpen(false); setDetailsOpen(false); });
return () => cancelAnimationFrame(frame);
}, [overlayPane]);
+ useEffect(() => {
+ const id = payloadSessionId(props.payload);
+ if (!id) return;
+ let alive = true;
+ setLibraryMode("sessions"); setMessage("");
+ void getSessionGraph(id).then((next) => { if (!alive) return; setSessionView(next); setSessionSelected("session-root"); }).catch((error: unknown) => { if (alive) setMessage(error instanceof Error ? error.message : "Could not load session"); });
+ return () => { alive = false; };
+ }, [props.payload]);
+
const wrap = async (fn: () => Promise<void>) => { setBusy(true); setMessage(""); try { await fn(); } catch (error) { setMessage(error instanceof Error ? error.message : "Action failed"); } finally { setBusy(false); } };
const mutate = (next: WorkflowGraph) => { setGraph(next); setDirty(true); };
- const selectGraph = async (id: string) => { setGraph(await getGraph(id)); setSelected(null); setRun(null); setDirty(false); setPanel("inspector"); setLibraryOpen(false); };
- const createBlank = () => wrap(async () => { const next = await createGraph(starterGraph()); await load(next.id); setSelected("manual"); setLibraryOpen(false); });
- const createTemplate = (id: string) => wrap(async () => { const next = await createFromTemplate(id); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
- const createAI = (definition: Definition) => wrap(async () => { const next = await createGraph(definition); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const selectGraph = async (id: string) => { setLibraryMode("automations"); setGraph(await getGraph(id)); setSelected(null); setRun(null); setDirty(false); setPanel("inspector"); setLibraryOpen(false); };
+ const selectSession = async (id: string) => { const next = await getSessionGraph(id); setLibraryMode("sessions"); setSessionView(next); setSessionSelected("session-root"); setLibraryOpen(false); setDetailsOpen(false); };
+ const refreshSession = async () => { if (!sessionView) return; const next = await getSessionGraph(sessionView.session.id); setSessionView(next); if (sessionSelected && !next.graph.nodes.some((item) => item.id === sessionSelected)) setSessionSelected("session-root"); };
+ const createBlank = () => wrap(async () => { const next = await createGraph(starterGraph()); setLibraryMode("automations"); await load(next.id); setSelected("manual"); setLibraryOpen(false); });
+ const createTemplate = (id: string) => wrap(async () => { const next = await createFromTemplate(id); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const createAI = (definition: Definition) => wrap(async () => { const next = await createGraph(definition); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
const saveCurrent = async () => { if (!graph) throw new Error("No workflow selected"); if (!dirty) return graph; const next = await updateGraph(graph); setGraph(next); setDirty(false); setGraphs(await listGraphs()); return next; };
const save = () => graph && wrap(async () => { await saveCurrent(); setMessage("Saved"); });
const duplicate = () => graph && wrap(async () => { const next = await cloneGraph(graph.id); await load(next.id); });
@@ -55,34 +74,42 @@ export default function WorkflowsApp(_props: AppProps) {
const addNode = (type: WorkflowGraphNodeType, defaults: Record<string, unknown>) => { if (!graph) return; const id = `${type}-${crypto.randomUUID().slice(0, 8)}`; const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (char) => char.toUpperCase()), type, position: { x: 220 + graph.nodes.length * 36, y: 240 + (graph.nodes.length % 4) * 110 }, config: structuredClone(defaults) }; mutate({ ...graph, nodes: [...graph.nodes, next] }); chooseNode(id); };
const connect = (source: string, target: string, sourceHandle?: string) => { if (!graph || graph.edges.some((edge) => edge.source === source && edge.target === target && edge.sourceHandle === sourceHandle)) return; mutate({ ...graph, edges: [...graph.edges, { id: `edge-${crypto.randomUUID().slice(0, 8)}`, source, target, ...(sourceHandle ? { sourceHandle } : {}) }] }); };
const openNode = async (id: string) => { if (!graph) return; const resolved = await resolveNode(graph.id, id); openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true }); };
+ const openSessionTerminal = () => { if (!sessionView) return; openWindow("os-terminal", "Terminal", undefined, { initialCwd: sessionView.session.cwd || "~" }, { multi: true }); };
const chooseNode = (id: string | null) => { setSelected(id); if (!id) return; setPanel("inspector"); if (overlayPane) setDetailsOpen(true); };
+ const chooseSessionNode = (id: string | null) => { setSessionSelected(id); if (!id) return; const target = sessionView?.graph.nodes.find((item) => item.id === id); if (target?.config.terminalContext === true) { setDetailsOpen(false); openSessionTerminal(); return; } if (overlayPane) setDetailsOpen(true); };
const tidy = () => graph && mutate({ ...graph, nodes: tidyWorkflowNodes(graph) });
const toggleLibrary = () => overlayPane ? setLibraryOpen(true) : setShowLibrary((value) => !value);
const toggleDetails = () => overlayPane ? setDetailsOpen(true) : setShowDetails((value) => !value);
- const library = <WorkflowLibrary graphs={graphs} activeId={graph?.id} search={search} onSearch={setSearch} onSelect={(id) => void wrap(() => selectGraph(id))} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/>;
- const details = graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={setPanel} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }}/> : null;
+ const automationLibrary = <WorkflowLibrary graphs={graphs} activeId={graph?.id} search={search} onSearch={setSearch} onSelect={(id) => void wrap(() => selectGraph(id))} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/>;
+ const library = <div className="flex h-full min-h-0 flex-col"><div className="grid grid-cols-2 gap-1 border-b p-2">{(["automations", "sessions"] as const).map((mode) => <button key={mode} type="button" className={`rounded-md px-2 py-1.5 text-xs capitalize ${libraryMode === mode ? "bg-accent font-semibold" : "text-muted-foreground hover:bg-accent/60"}`} onClick={() => setLibraryMode(mode)}>{mode}</button>)}</div><div className="min-h-0 flex-1">{libraryMode === "automations" ? automationLibrary : <WorkflowSessionLibrary activeId={sessionView?.session.id} onSelect={(id) => void wrap(() => selectSession(id))}/>}</div></div>;
+ const details = libraryMode === "sessions" && sessionView ? <WorkflowSessionDetails view={sessionView} node={sessionNode} onOpenTerminal={openSessionTerminal}/> : graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={setPanel} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }}/> : null;
const toolbarItems: ToolbarItem[] = [
{ id: "library", label: "Workflow library", icon: PanelLeft, onClick: toggleLibrary, primary: true },
- { id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void load(undefined, true), disabled: busy },
- ...(graph ? [
+ { id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void wrap(async () => { if (libraryMode === "sessions") await refreshSession(); else await load(undefined, true); }), disabled: busy },
+ ...(libraryMode === "automations" && graph ? [
{ id: "duplicate", label: "Duplicate", icon: Copy, onClick: () => void duplicate(), disabled: busy },
{ id: "save", label: "Save", icon: Save, onClick: () => void save(), disabled: busy || !dirty },
{ id: "run", label: "Run", icon: Play, onClick: () => void execute(), disabled: busy, primary: true },
{ id: "details", label: "Details", icon: PanelRight, onClick: toggleDetails },
{ id: "delete", label: "Delete", icon: Trash2, onClick: () => void remove(), disabled: busy },
- ] satisfies ToolbarItem[] : []),
+ ] satisfies ToolbarItem[] : libraryMode === "sessions" && sessionView ? [{ id: "details", label: "Session details", icon: PanelRight, onClick: toggleDetails }] satisfies ToolbarItem[] : []),
];
const showLibraryPanel = !overlayPane && showLibrary;
- const showDetailsPanel = !overlayPane && showDetails && Boolean(graph);
+ const showDetailsPanel = !overlayPane && showDetails && Boolean(libraryMode === "sessions" ? sessionView : graph);
+ const headerTitle = libraryMode === "sessions" ? sessionView?.session.label : graph?.name;
return <div ref={appRef} data-slot="workflows-feature" className="@container h-full min-h-0 min-w-0">
- <AppFrame safeArea={false} className="h-full min-w-0" toolbar={<div className="flex h-11 min-w-0 items-center gap-1 px-2 @min-[700px]:gap-2 @min-[700px]:px-3"><Workflow className="hidden size-4 shrink-0 @min-[700px]:block"/><span className="hidden shrink-0 text-sm font-semibold @min-[700px]:inline">Workflows</span>{dirty ? <Badge variant="outline" className="hidden shrink-0 @min-[520px]:inline-flex">Unsaved</Badge> : null}{graph ? <Input aria-label="Workflow name" className="h-8 min-w-[7rem] max-w-56 flex-1 @max-[600px]:max-w-none" value={graph.name} onChange={(event) => mutate({ ...graph, name: event.target.value })}/> : <div className="min-w-0 flex-1"/>}<WorkflowCreateDialog compact={overlayPane} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/><ResponsiveToolbar items={toolbarItems} compact={overlayPane} className="ml-auto shrink-0"/></div>}>
+ <AppFrame safeArea={false} className="h-full min-w-0" toolbar={<div className="flex h-11 min-w-0 items-center gap-1 px-2 @min-[700px]:gap-2 @min-[700px]:px-3"><Workflow className="hidden size-4 shrink-0 @min-[700px]:block"/><span className="hidden shrink-0 text-sm font-semibold @min-[700px]:inline">Workflows</span>{libraryMode === "sessions" ? <Badge variant="outline" className="shrink-0"><Activity className="mr-1 size-3"/>Session</Badge> : dirty ? <Badge variant="outline" className="hidden shrink-0 @min-[520px]:inline-flex">Unsaved</Badge> : null}{libraryMode === "automations" && graph ? <Input aria-label="Workflow name" className="h-8 min-w-[7rem] max-w-56 flex-1 @max-[600px]:max-w-none" value={graph.name} onChange={(event) => mutate({ ...graph, name: event.target.value })}/> : <div className="min-w-0 flex-1 truncate text-sm font-medium">{headerTitle || (libraryMode === "sessions" ? "Sessions" : "Workflows")}</div>}{libraryMode === "automations" ? <WorkflowCreateDialog compact={overlayPane} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/> : null}<ResponsiveToolbar items={toolbarItems} compact={overlayPane} className="ml-auto shrink-0"/></div>}>
<div className={`grid h-full min-h-0 min-w-0 ${showLibraryPanel ? "grid-cols-[220px_minmax(0,1fr)]" : "grid-cols-1"}`}>
{showLibraryPanel ? <aside className="min-h-0 min-w-0 border-r">{library}</aside> : null}
- <main className="flex min-h-0 min-w-0 overflow-hidden">{graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] font-medium"><Switch checked={graph.status === "active"} disabled={graph.status === "archived"} onCheckedChange={(checked) => mutate({ ...graph, status: checked ? "active" : "draft" })}/><span>Active</span></label><select aria-label="Workflow lifecycle" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="hidden min-w-0 truncate text-[10px] text-muted-foreground @min-[900px]:inline">Drag output → input. V Select · H Pan · +/- Zoom · F Fit · Space temporary pan.</span>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Create or select a workflow.</div>}{showDetailsPanel ? <aside className="w-[320px] shrink-0 border-l @min-[1200px]:w-[360px]">{details}</aside> : null}</main>
+ <main className="flex min-h-0 min-w-0 overflow-hidden">
+ {libraryMode === "automations" ? graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] font-medium"><Switch checked={graph.status === "active"} disabled={graph.status === "archived"} onCheckedChange={(checked) => mutate({ ...graph, status: checked ? "active" : "draft" })}/><span>Active</span></label><select aria-label="Workflow lifecycle" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="hidden min-w-0 truncate text-[10px] text-muted-foreground @min-[900px]:inline">Drag output → input. V Select · H Pan · +/- Zoom · F Fit · Space temporary pan.</span>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Create or select an automation.</div>
+ : sessionView ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 shrink-0 items-center gap-2 border-b px-3 text-[11px] text-muted-foreground"><span className="font-medium text-foreground">{sessionView.session.label}</span><span>read-only</span><span>·</span><span>{sessionView.shownEvents}/{sessionView.totalEvents} events</span>{message ? <span className="ml-auto truncate">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={sessionView.graph.revision} graph={sessionView.graph} selectedId={sessionSelected} onSelect={chooseSessionNode} onConnect={() => undefined} onMove={() => undefined} readOnly/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Select a session to inspect its execution graph.</div>}
+ {showDetailsPanel ? <aside className="w-[320px] shrink-0 border-l @min-[1200px]:w-[360px]">{details}</aside> : null}
+ </main>
</div>
- {overlayPane ? <><ResponsiveDialog open={libraryOpen} onOpenChange={setLibraryOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="left"><ResponsiveDialog.Header><ResponsiveDialog.Title>Workflows</ResponsiveDialog.Title><ResponsiveDialog.Description>Select or create a workflow without leaving the canvas.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{library}</ResponsiveDialog.Body></ResponsiveDialog><ResponsiveDialog open={detailsOpen && Boolean(graph)} onOpenChange={setDetailsOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="right"><ResponsiveDialog.Header><ResponsiveDialog.Title>{node?.name ?? graph?.name ?? "Workflow details"}</ResponsiveDialog.Title><ResponsiveDialog.Description>Inspect configuration, runs, versions, variables, and the directory without shrinking the canvas.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{details}</ResponsiveDialog.Body></ResponsiveDialog></> : null}
+ {overlayPane ? <><ResponsiveDialog open={libraryOpen} onOpenChange={setLibraryOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="left"><ResponsiveDialog.Header><ResponsiveDialog.Title>Workflows</ResponsiveDialog.Title><ResponsiveDialog.Description>Switch between reusable automations and recorded sessions.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{library}</ResponsiveDialog.Body></ResponsiveDialog><ResponsiveDialog open={detailsOpen && Boolean(libraryMode === "sessions" ? sessionView : graph)} onOpenChange={setDetailsOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="right"><ResponsiveDialog.Header><ResponsiveDialog.Title>{libraryMode === "sessions" ? sessionNode?.name ?? sessionView?.session.label ?? "Session details" : node?.name ?? graph?.name ?? "Workflow details"}</ResponsiveDialog.Title><ResponsiveDialog.Description>{libraryMode === "sessions" ? "Inspect recorded tool activity without exposing internal session IDs." : "Inspect configuration, runs, versions, variables, and the directory without shrinking the canvas."}</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{details}</ResponsiveDialog.Body></ResponsiveDialog></> : null}
</AppFrame>
</div>;
}
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
index 86eaa9cd..1154f2b5 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -39,10 +39,10 @@ function edgeVisual(edge:WorkflowGraph["edges"][number],state:WorkflowGraphRunEd
function toEdges(graph:WorkflowGraph,nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>,edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>):FlowEdge[]{return graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,sourceHandle:edge.sourceHandle??"output",targetHandle:"input",type:"smoothstep",...edgeVisual(edge,edgeStates?.get(edge.id),nodeStates)}));}
function minimapColor(node:FlowNode){const state=node.data.state;if(state==="running")return"var(--accent)";if(state==="failed")return"var(--destructive)";if(state==="completed")return"var(--success)";if(state==="skipped"||state==="blocked")return"var(--text-dim)";return"var(--info)";}
-export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeStates,edgeStates,onOpen,onDeleteNodes,onDeleteEdges,onTidy}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>;onOpen?:(id:string)=>void;onDeleteNodes?:(ids:string[])=>void;onDeleteEdges?:(ids:string[])=>void;onTidy?:()=>void;}){
+export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeStates,edgeStates,onOpen,onDeleteNodes,onDeleteEdges,onTidy,readOnly=false}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>;onOpen?:(id:string)=>void;onDeleteNodes?:(ids:string[])=>void;onDeleteEdges?:(ids:string[])=>void;onTidy?:()=>void;readOnly?:boolean;}){
const mappedNodes=useMemo(()=>toNodes(graph,selectedId,nodeStates),[graph,nodeStates,selectedId]),mappedEdges=useMemo(()=>toEdges(graph,nodeStates,edgeStates),[edgeStates,graph,nodeStates]);
- const compactFitNodeIds=useMemo(()=>{const triggers=graph.nodes.filter((node)=>["manual","schedule","webhook"].includes(node.type)).map((node)=>node.id);return (triggers.length?triggers:[graph.nodes[0]?.id]).filter((id):id is string=>Boolean(id)).slice(0,2);},[graph.nodes]);
+ const compactFitNodeIds=useMemo(()=>{if(readOnly)return graph.nodes.slice(0,2).map((node)=>node.id);const triggers=graph.nodes.filter((node)=>["manual","schedule","webhook"].includes(node.type)).map((node)=>node.id);return (triggers.length?triggers:[graph.nodes[0]?.id]).filter((id):id is string=>Boolean(id)).slice(0,2);},[graph.nodes,readOnly]);
const[nodes,setNodes,onNodesChange]=useNodesState<FlowNode>(mappedNodes),[edges,setEdges,onEdgesChange]=useEdgesState<FlowEdge>(mappedEdges);useEffect(()=>setNodes(mappedNodes),[mappedNodes,setNodes]);useEffect(()=>setEdges(mappedEdges),[mappedEdges,setEdges]);
const connect=(connection:Connection)=>{if(!connection.source||!connection.target||connection.source===connection.target)return;const handle=connection.sourceHandle&&connection.sourceHandle!=="output"?connection.sourceHandle:undefined;onConnect(connection.source,connection.target,handle);};
- return <GraphCanvas<FlowNode,FlowEdge> ariaLabel="Workflow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={connect} onPaneClick={()=>onSelect(null)} onNodeClick={(_,item)=>onSelect(item.id)} onNodeDoubleClick={(_,item)=>{const node=item.data.node;if((node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}} onNodeDragStop={(_,item)=>onMove(item.id,item.position)} onNodesDelete={(items)=>onDeleteNodes?.(items.map((item)=>item.id))} onEdgesDelete={(items)=>onDeleteEdges?.(items.map((item)=>item.id))} isValidConnection={(connection)=>Boolean(connection.source&&connection.target&&connection.source!==connection.target&&!graph.edges.some((edge)=>edge.source===connection.source&&edge.target===connection.target&&(edge.sourceHandle??undefined)===(connection.sourceHandle==="output"?undefined:connection.sourceHandle??undefined)))} nodesDraggable nodesConnectable edgesReconnectable={false} deleteKeyCode={["Backspace","Delete"]} onTidy={onTidy} snapToGrid snapGrid={[12,12]} defaultEdgeOptions={{type:"smoothstep",markerEnd:{type:MarkerType.ArrowClosed}}} miniMapNodeColor={(node)=>minimapColor(node as FlowNode)} miniMapNodeStrokeColor={(node)=>node.selected?"var(--accent)":"var(--border)"} compactFitNodeIds={compactFitNodeIds} compactFitMaxZoom={0.9}/>
+ return <GraphCanvas<FlowNode,FlowEdge> ariaLabel="Workflow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={readOnly?undefined:connect} onPaneClick={()=>onSelect(null)} onNodeClick={(_,item)=>onSelect(item.id)} onNodeDoubleClick={(_,item)=>{const node=item.data.node;if((readOnly||node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}} onNodeDragStop={(_,item)=>onMove(item.id,item.position)} onNodesDelete={readOnly?undefined:(items)=>onDeleteNodes?.(items.map((item)=>item.id))} onEdgesDelete={readOnly?undefined:(items)=>onDeleteEdges?.(items.map((item)=>item.id))} isValidConnection={(connection)=>Boolean(connection.source&&connection.target&&connection.source!==connection.target&&!graph.edges.some((edge)=>edge.source===connection.source&&edge.target===connection.target&&(edge.sourceHandle??undefined)===(connection.sourceHandle==="output"?undefined:connection.sourceHandle??undefined)))} nodesDraggable={!readOnly} nodesConnectable={!readOnly} edgesReconnectable={false} deleteKeyCode={readOnly?null:["Backspace","Delete"]} onTidy={onTidy} snapToGrid snapGrid={[12,12]} defaultEdgeOptions={{type:"smoothstep",markerEnd:{type:MarkerType.ArrowClosed}}} miniMapNodeColor={(node)=>minimapColor(node as FlowNode)} miniMapNodeStrokeColor={(node)=>node.selected?"var(--accent)":"var(--border)"} compactFitNodeIds={compactFitNodeIds} compactFitMaxZoom={readOnly?0.72:0.9}/>
}
diff --git a/frontend/slices/workflows/components/workflow-directory-panel.tsx b/frontend/slices/workflows/components/workflow-directory-panel.tsx
index fa3ae2dc..4f60eb20 100644
--- a/frontend/slices/workflows/components/workflow-directory-panel.tsx
+++ b/frontend/slices/workflows/components/workflow-directory-panel.tsx
@@ -6,10 +6,18 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { listWorkflowDirectory, type WorkflowDirectory } from "../lib/api";
type View = "tools" | "workflows" | "sessions";
+type DirectoryRow = WorkflowDirectory["tools"][number] | WorkflowDirectory["workflows"][number] | WorkflowDirectory["sessions"][number];
+function rowTitle(row: DirectoryRow): string {
+ if ("source" in row) return row.label || `${row.name}-${row.title}`;
+ return row.name;
+}
+function rowKey(row: DirectoryRow): string { return "id" in row ? row.id : row.name; }
+
export function WorkflowDirectoryPanel() {
const [view, setView] = useState<View>("tools"), [query, setQuery] = useState(""), [data, setData] = useState<WorkflowDirectory | null>(null), [error, setError] = useState("");
useEffect(() => { let alive = true; void listWorkflowDirectory().then((value)=>{if(alive)setData(value);}).catch((e)=>{if(alive)setError(e instanceof Error?e.message:"Directory unavailable");}); return()=>{alive=false;}; }, []);
- const q=query.toLowerCase().trim(), rows=useMemo(()=> view==="tools"?(data?.tools??[]).filter((r)=>!q||`${r.name} ${r.description} ${r.scope}`.toLowerCase().includes(q)):view==="workflows"?(data?.workflows??[]).filter((r)=>!q||`${r.name} ${r.status}`.toLowerCase().includes(q)):(data?.sessions??[]).filter((r)=>!q||`${r.title} ${r.name} ${r.cwd??""}`.toLowerCase().includes(q)),[data,q,view]);
+ const q=query.toLowerCase().trim();
+ const rows = useMemo<DirectoryRow[]>(()=> view==="tools"?(data?.tools??[]).filter((r)=>!q||`${r.name} ${r.description} ${r.scope}`.toLowerCase().includes(q)):view==="workflows"?(data?.workflows??[]).filter((r)=>!q||`${r.name} ${r.status}`.toLowerCase().includes(q)):(data?.sessions??[]).filter((r)=>!q||`${r.label??""} ${r.title} ${r.name} ${r.cwd??""}`.toLowerCase().includes(q)),[data,q,view]);
const icons={tools:Wrench,workflows:Workflow,sessions:Database}, Icon=icons[view];
- return <div className="flex h-full min-h-0 flex-col"><div className="space-y-2 border-b p-2"><div className="grid grid-cols-3 gap-1">{(["tools","workflows","sessions"] as const).map((item)=><button key={item} type="button" className={`rounded-md px-2 py-1.5 text-[10px] capitalize ${view===item?"bg-accent font-semibold":"text-muted-foreground hover:bg-accent/60"}`} onClick={()=>setView(item)}>{item}</button>)}</div><div className="relative"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="h-8 pl-7" placeholder={`Search ${view}…`} value={query} onChange={(e)=>setQuery(e.target.value)}/></div></div><ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">{error?<p className="p-2 text-xs text-destructive">{error}</p>:null}{rows.map((row)=><div key={(row as {id?:string;name?:string}).id??(row as {name:string}).name} className="rounded-lg border p-2"><div className="flex items-center gap-2"><Icon className="size-3.5 text-muted-foreground"/><div className="min-w-0 flex-1 truncate text-xs font-semibold">{"title" in row ? row.title : row.name}</div>{"scope" in row?<span className="text-[9px] uppercase text-muted-foreground">{row.scope}</span>:null}</div>{"description" in row?<p className="mt-1 line-clamp-2 text-[10px] text-muted-foreground">{row.description}</p>:null}{"status" in row?<p className="mt-1 text-[10px] text-muted-foreground">{row.status} · {row.nodeCount} nodes</p>:null}{"source" in row?<p className="mt-1 truncate text-[10px] text-muted-foreground">{row.source} · {row.id}</p>:null}</div>)}{rows.length===0&&!error?<p className="p-3 text-xs text-muted-foreground">No matching {view}.</p>:null}</div></ScrollArea></div>;
+ return <div className="flex h-full min-h-0 flex-col"><div className="space-y-2 border-b p-2"><div className="grid grid-cols-3 gap-1">{(["tools","workflows","sessions"] as const).map((item)=><button key={item} type="button" className={`rounded-md px-2 py-1.5 text-[10px] capitalize ${view===item?"bg-accent font-semibold":"text-muted-foreground hover:bg-accent/60"}`} onClick={()=>setView(item)}>{item}</button>)}</div><div className="relative"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="h-8 pl-7" placeholder={`Search ${view}…`} value={query} onChange={(e)=>setQuery(e.target.value)}/></div></div><ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">{error?<p className="p-2 text-xs text-destructive">{error}</p>:null}{rows.map((row)=><div key={rowKey(row)} className="rounded-lg border p-2"><div className="flex items-center gap-2"><Icon className="size-3.5 text-muted-foreground"/><div className="min-w-0 flex-1 truncate text-xs font-semibold">{rowTitle(row)}</div>{"inputSchema" in row?<span className="text-[9px] uppercase text-muted-foreground">{row.scope}</span>:null}</div>{"inputSchema" in row?<p className="mt-1 line-clamp-2 text-[10px] text-muted-foreground">{row.description}</p>:null}{"nodeCount" in row?<p className="mt-1 text-[10px] text-muted-foreground">{row.status} · {row.nodeCount} nodes</p>:null}{"source" in row?<p className="mt-1 truncate text-[10px] text-muted-foreground">{row.source} · {row.title}</p>:null}</div>)}{rows.length===0&&!error?<p className="p-3 text-xs text-muted-foreground">No matching {view}.</p>:null}</div></ScrollArea></div>;
}
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
index 1d6f46eb..dbdcfec3 100644
--- a/frontend/slices/workflows/components/workflow-inspector.tsx
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -44,7 +44,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
{node.type==="wait"&&<Field label="Delay ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field>}
{node.type==="cache"&&<><Field label="Cache mode"><select className={selectClass} value={String(node.config.mode??"get_or_set")} onChange={(e)=>setConfig("mode",e.target.value)}>{["get_or_set","get","set","delete"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field><Field label="Cache key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>{["get_or_set","set"].includes(String(node.config.mode??"get_or_set"))&&<><Field label="TTL seconds"><Input type="number" min={0} max={2592000} value={number(node.config.ttlSeconds,300)} onChange={(e)=>setConfig("ttlSeconds",Number(e.target.value))}/></Field><JsonField label="Value JSON / binding" value={node.config.value??{"$ref":"input"}} onChange={(value)=>setConfig("value",value)}/></>}</>}
{node.type==="memory"&&<><Field label="Memory scope"><select className={selectClass} value={String(node.config.scope??"agent")} onChange={(e)=>setConfig("scope",e.target.value)}><option value="agent">Agent memory</option><option value="project">Project memory</option></select></Field><Field label="Memory mode"><select className={selectClass} value={String(node.config.mode??"search")} onChange={(e)=>setConfig("mode",e.target.value)}>{(node.config.scope==="project"?["search","remember"]:["read","search","remember","forget"]).map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{String(node.config.mode??"search")==="search"&&<Field label="Query"><Input value={String(node.config.query??"")} onChange={(e)=>setConfig("query",e.target.value)}/></Field>}{node.config.scope!=="project"&&<Field label="Document"><select className={selectClass} value={String(node.config.document??"MEMORY.md")} onChange={(e)=>setConfig("document",e.target.value)}><option value="MEMORY.md">MEMORY.md</option><option value="USER.md">USER.md</option></select></Field>}{["remember","forget"].includes(String(node.config.mode))&&<Field label="Memory key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>}{String(node.config.mode)==="remember"&&<Field label={node.config.scope==="project"?"Summary":"Value"}><Textarea value={String(node.config.value??node.config.summary??"")} onChange={(e)=>setConfig(node.config.scope==="project"?"summary":"value",e.target.value)}/></Field>}</>}
- {node.type==="session"&&<><Field label="Session mode"><select className={selectClass} value={String(node.config.mode??"current")} onChange={(e)=>setConfig("mode",e.target.value)}>{["current","list","resume","note"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{node.config.mode==="resume"&&<Field label="Session ID"><Input value={String(node.config.sessionId??"")} onChange={(e)=>setConfig("sessionId",e.target.value)}/></Field>}{node.config.mode==="note"&&<Field label="Note"><Textarea value={String(node.config.note??"")} onChange={(e)=>setConfig("note",e.target.value)}/></Field>}</>}
+ {node.type==="session"&&<><Field label="Session mode"><select className={selectClass} value={String(node.config.mode??"current")} onChange={(e)=>setConfig("mode",e.target.value)}>{["current","list","resume","note"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{node.config.mode==="resume"&&<Field label="Session label"><Input placeholder="agent-context-session" value={String(node.config.sessionRef??"")} onChange={(e)=>setConfig("sessionRef",e.target.value)}/></Field>}{node.config.mode==="note"&&<Field label="Note"><Textarea value={String(node.config.note??"")} onChange={(e)=>setConfig("note",e.target.value)}/></Field>}</>}
{node.type==="directory"&&<><Field label="Directory source"><select className={selectClass} value={String(node.config.source??"tools")} onChange={(e)=>setConfig("source",e.target.value)}>{["tools","workflows","sessions","projects","skills"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field><Field label="Query"><Input value={String(node.config.query??"")} onChange={(e)=>setConfig("query",e.target.value)}/></Field><Field label="Limit"><Input type="number" min={1} max={100} value={number(node.config.limit,30)} onChange={(e)=>setConfig("limit",Number(e.target.value))}/></Field></>}
{node.type==="batch"&&<><Field label="Items path"><Input value={String(node.config.itemsPath??"input.items")} onChange={(e)=>setConfig("itemsPath",e.target.value)}/></Field><Field label="Batch size"><Input type="number" min={1} max={1000} value={number(node.config.size,10)} onChange={(e)=>setConfig("size",Number(e.target.value))}/></Field></>}
{node.type==="loop"&&<><Field label="Items path"><Input value={String(node.config.itemsPath??"input.items")} onChange={(e)=>setConfig("itemsPath",e.target.value)}/></Field><Field label="Tool per item"><Input value={String(node.config.tool??"")} onChange={(e)=>setConfig("tool",e.target.value)}/></Field><Field label="Concurrency"><Input type="number" min={1} max={4} value={number(node.config.concurrency,1)} onChange={(e)=>setConfig("concurrency",Number(e.target.value))}/></Field></>}
diff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsx
new file mode 100644
index 00000000..d1da5998
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-session-details.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { ExternalLink, TerminalSquare } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import type { SessionGraphView } from "@/lib/contracts/session-monitor";
+import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+
+function value(config: Record<string, unknown>, key: string): string | undefined {
+ const raw = config[key];
+ return typeof raw === "string" && raw ? raw : undefined;
+}
+
+export function WorkflowSessionDetails({ view, node, onOpenTerminal }: { view: SessionGraphView; node: WorkflowGraphNode | null; onOpenTerminal: () => void }) {
+ const config = node?.config ?? {};
+ const terminalContext = config.terminalContext === true;
+ return <div className="flex h-full min-h-0 flex-col bg-card/20">
+ <div className="border-b p-3">
+ <div className="truncate text-sm font-semibold">{view.session.label}</div>
+ <div className="mt-1 text-[10px] uppercase text-muted-foreground">{view.session.source} · {view.session.status}</div>
+ <p className="mt-2 text-xs text-muted-foreground">Read-only session projection. Tool payloads and raw transcripts are not duplicated into the graph.</p>
+ {view.omittedEvents ? <p className="mt-2 text-[10px] text-muted-foreground">Showing the latest {view.shownEvents} of {view.totalEvents} events for canvas performance.</p> : null}
+ </div>
+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-3 p-3">
+ {!node ? <p className="text-xs text-muted-foreground">Select a node to inspect its recorded activity.</p> : <>
+ <div><div className="text-[10px] uppercase text-muted-foreground">Node</div><div className="break-words text-sm font-semibold">{node.name}</div></div>
+ {value(config, "state") ? <div><div className="text-[10px] uppercase text-muted-foreground">State</div><div className="text-xs">{value(config, "state")}</div></div> : null}
+ {value(config, "at") ? <div><div className="text-[10px] uppercase text-muted-foreground">Time</div><time className="text-xs" dateTime={value(config, "at")}>{new Date(value(config, "at")!).toLocaleString()}</time></div> : null}
+ {value(config, "detail") ? <div><div className="text-[10px] uppercase text-muted-foreground">Detail</div><p className="whitespace-pre-wrap break-words text-xs [overflow-wrap:anywhere]">{value(config, "detail")}</p></div> : null}
+ {view.session.cwd ? <div><div className="text-[10px] uppercase text-muted-foreground">Context</div><p className="break-all text-xs text-muted-foreground">{view.session.cwd}</p></div> : null}
+ {terminalContext ? <Button className="w-full" variant="outline" onClick={onOpenTerminal}><TerminalSquare className="size-4"/>Open terminal here<ExternalLink className="ml-auto size-3.5"/></Button> : null}
+ </>}
+ </div></ScrollArea>
+ <div className="border-t p-3 text-[10px] text-muted-foreground">Successful MCP/Alfa workflows continue through MSO's existing learned-from-session automation pipeline; this view does not duplicate that state.</div>
+ </div>;
+}
diff --git a/frontend/slices/workflows/components/workflow-session-library.tsx b/frontend/slices/workflows/components/workflow-session-library.tsx
new file mode 100644
index 00000000..972c8e11
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-session-library.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Activity, ChevronLeft, ChevronRight, RefreshCw, Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import type { SessionPage } from "@/lib/contracts/session-monitor";
+import { listWorkflowSessions } from "../lib/api";
+
+export function WorkflowSessionLibrary({ activeId, onSelect }: { activeId?: string; onSelect: (id: string) => void }) {
+ const [search, setSearch] = useState(""), [query, setQuery] = useState(""), [page, setPage] = useState(1);
+ const [data, setData] = useState<SessionPage | null>(null), [error, setError] = useState(""), [nonce, setNonce] = useState(0);
+ useEffect(() => {
+ let alive = true;
+ setError("");
+ void listWorkflowSessions(page, query).then((value) => { if (alive) setData(value); }).catch((cause) => { if (alive) setError(cause instanceof Error ? cause.message : "Sessions unavailable"); });
+ return () => { alive = false; };
+ }, [page, query, nonce]);
+ return <div className="flex h-full min-h-0 flex-col bg-card/20">
+ <div className="space-y-2 border-b p-2">
+ <form className="flex gap-1" onSubmit={(event) => { event.preventDefault(); setPage(1); setQuery(search.trim()); }}>
+ <div className="relative min-w-0 flex-1"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="h-8 pl-7" aria-label="Search sessions" placeholder="agent-context" value={search} onChange={(event) => { setSearch(event.target.value); if (!event.target.value) { setPage(1); setQuery(""); } }}/></div>
+ <Button type="submit" variant="outline" size="icon" className="size-8" aria-label="Search sessions"><Search className="size-3.5"/></Button>
+ <Button type="button" variant="ghost" size="icon" className="size-8" aria-label="Refresh sessions" onClick={() => setNonce((value) => value + 1)}><RefreshCw className="size-3.5"/></Button>
+ </form>
+ <p className="text-[10px] text-muted-foreground">Read-only execution history. Labels use agent-context, while internal IDs stay hidden.</p>
+ </div>
+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">
+ {error ? <p className="p-2 text-xs text-destructive">{error}</p> : null}
+ {!data && !error ? <p className="p-3 text-xs text-muted-foreground">Loading sessions…</p> : null}
+ {data?.sessions.map((session) => <button key={session.id} type="button" onClick={() => onSelect(session.id)} aria-pressed={activeId === session.id} className={`w-full rounded-lg border p-2 text-left text-xs transition-colors hover:bg-accent/60 ${activeId === session.id ? "bg-accent" : "bg-card"}`}>
+ <div className="flex items-center gap-2"><Activity className="size-3.5 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1 truncate font-medium">{session.label}</div><span className="shrink-0 text-[9px] uppercase text-muted-foreground">{session.status}</span></div>
+ <p className="mt-1 line-clamp-2 break-words text-[10px] text-muted-foreground">{session.title}</p>
+ <p className="mt-1 text-[10px] text-muted-foreground">{session.source} · {session.eventCount} events</p>
+ </button>)}
+ {data && data.sessions.length === 0 && !error ? <p className="p-3 text-xs text-muted-foreground">No matching sessions.</p> : null}
+ </div></ScrollArea>
+ {data && data.pages > 1 ? <div className="flex items-center justify-between border-t p-2 text-[10px] text-muted-foreground"><Button size="icon" variant="ghost" className="size-7" disabled={data.page <= 1} onClick={() => setPage((value) => Math.max(1, value - 1))}><ChevronLeft className="size-3.5"/></Button><span>{data.page} / {data.pages}</span><Button size="icon" variant="ghost" className="size-7" disabled={data.page >= data.pages} onClick={() => setPage((value) => Math.min(data.pages, value + 1))}><ChevronRight className="size-3.5"/></Button></div> : null}
+ </div>;
+}
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index 55fa9b7d..54dfb068 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -1,3 +1,4 @@
+import type { SessionGraphView, SessionPage } from "@/lib/contracts/session-monitor";
import type { WorkflowGraph, WorkflowGraphRun, WorkflowGraphStatus } from "@/lib/contracts/workflow-graph";
import type { WorkflowNodeCatalogItem } from "@/lib/workflow/node-catalog";
import { cachedWorkflowResource, invalidateWorkflowResources, seedWorkflowResource } from "./resource-cache";
@@ -23,7 +24,10 @@ export async function deleteVariable(key:string){return post({action:"variable_d
export async function aiSuggest(prompt:string){return(await post<{definition:Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">}>({action:"ai_suggest",prompt})).definition;}
export async function resolveNode(graphId:string,nodeId:string){return json<{project:string;name:string;path:string;relativePath:string}>(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`);}
-export type WorkflowDirectory = {tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;sessions:Array<{id:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>};
+export async function listWorkflowSessions(page=1,query=""){const q=new URLSearchParams({view:"monitor",includeOffline:"1",page:String(page)});if(query.trim())q.set("q",query.trim());return json<SessionPage>(`/api/v1/agent-sessions?${q}`);}
+export async function getSessionGraph(id:string){return json<SessionGraphView>(`/api/v1/agent-sessions?view=graph&id=${encodeURIComponent(id)}&limit=120`);}
+
+export type WorkflowDirectory = {tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;sessions:Array<{id:string;label?:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>};
export async function listWorkflowDirectory(query=""){return cachedWorkflowResource(`directory:${query}`,15000,()=>json<WorkflowDirectory>(`/api/v1/workflows?directory=1&q=${encodeURIComponent(query)}`));}
export type WorkflowScriptSummary = { id:string; intent:string; status:"candidate"|"tested"; stepCount:number; updatedAt:string; project?:string; tools:string[] };
diff --git a/frontend/slices/workflows/session-graph-ui.test.ts b/frontend/slices/workflows/session-graph-ui.test.ts
new file mode 100644
index 00000000..b858f022
--- /dev/null
+++ b/frontend/slices/workflows/session-graph-ui.test.ts
@@ -0,0 +1,25 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const workflowApp = readFileSync(new URL("./app.tsx", import.meta.url), "utf8");
+const settingsSessions = readFileSync(new URL("../os-settings/components/mcp-sessions.tsx", import.meta.url), "utf8");
+const settingsDetail = readFileSync(new URL("../os-settings/components/mcp-session-detail.tsx", import.meta.url), "utf8");
+const sessionGuide = readFileSync(new URL("../os-settings/components/mcp-session-guide.tsx", import.meta.url), "utf8");
+const inspector = readFileSync(new URL("./components/workflow-inspector.tsx", import.meta.url), "utf8");
+
+describe("Workflow session graph UI contract", () => {
+ it("routes Settings sessions into the Workflow Sessions view and never renders the internal id", () => {
+ expect(settingsSessions).toContain('openWindow("workflows", "Workflows", undefined, { view: "sessions", sessionId: id })');
+ expect(settingsSessions).toContain("session.label");
+ for (const source of [settingsSessions, settingsDetail, sessionGuide, inspector]) {
+ expect(source).not.toContain('label="Session ID"');
+ expect(source).not.toContain("EXACT_SESSION_ID");
+ }
+ });
+
+ it("keeps session graphs read-only and opens terminal context in a fresh window", () => {
+ expect(workflowApp).toContain('type LibraryMode = "automations" | "sessions"');
+ expect(workflowApp).toContain("readOnly/>");
+ expect(workflowApp).toContain('openWindow("os-terminal", "Terminal", undefined, { initialCwd: sessionView.session.cwd || "~" }, { multi: true })');
+ });
+});
diff --git a/lib/agent/session-monitor.test.ts b/lib/agent/session-monitor.test.ts
index 2447786d..8aa4d856 100644
--- a/lib/agent/session-monitor.test.ts
+++ b/lib/agent/session-monitor.test.ts
@@ -8,7 +8,7 @@ vi.mock("./local-agent-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";
+import { ownerSessionDetail, ownerSessionGraph, 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),
@@ -58,6 +58,23 @@ describe("owner session monitor", () => {
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("projects a bounded read-only session graph using the human agent-context label", async () => {
+ const row = record(0);
+ row.events = [
+ { at: new Date(now).toISOString(), kind: "created", detail: "started" },
+ { at: new Date(now + 1).toISOString(), kind: "tool", tool: "exec_run", state: "completed", detail: "cwd=/project token=secret-value" },
+ { at: new Date(now + 2).toISOString(), kind: "tool", tool: "fs_read", state: "completed", detail: "package.json" },
+ ];
+ mocks.read.mockResolvedValue(row); mocks.presence.mockResolvedValue([]);
+ const view = await ownerSessionGraph(row.id, 2);
+ expect(view?.session.label).toBe("session-0-work-0");
+ expect(view?.graph.name).toBe("session-0-work-0");
+ expect(view?.graph.nodes[0]).toMatchObject({ id: "session-root", type: "session", name: "session-0-work-0" });
+ expect(view?.shownEvents).toBe(2); expect(view?.omittedEvents).toBe(1);
+ expect(view?.graph.nodes.some((node) => node.config.terminalContext === true)).toBe(true);
+ expect(JSON.stringify(view)).not.toContain("secret-value");
+ });
+
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();
diff --git a/lib/agent/session-monitor.ts b/lib/agent/session-monitor.ts
index 4cf0678c..bf6830a2 100644
--- a/lib/agent/session-monitor.ts
+++ b/lib/agent/session-monitor.ts
@@ -1,40 +1,202 @@
-import { SESSION_EVENT_PAGE_SIZE, SESSION_PAGE_SIZE } from "@/lib/contracts/session-monitor";
-import type { SessionCard, SessionDetail, SessionPage } from "@/lib/contracts/session-monitor";
+import {
+ SESSION_EVENT_PAGE_SIZE,
+ SESSION_GRAPH_EVENT_LIMIT,
+ SESSION_PAGE_SIZE,
+} from "@/lib/contracts/session-monitor";
+import type {
+ SessionCard,
+ SessionDetail,
+ SessionGraphView,
+ SessionPage,
+} from "@/lib/contracts/session-monitor";
+import type {
+ WorkflowGraph,
+ WorkflowGraphNode,
+} from "@/lib/contracts/workflow-graph";
import { redactText } from "@/lib/security/redact-text";
-import { listSessionRecords, readSessionFile, SESSION_ID } from "./session-files";
-import { listLocalAgentPresenceOwner, localAgentStatus } from "./local-agent-presence";
+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 { agentSessionLabel } from "./session-name";
+import type { AgentSession, AgentSessionEvent } 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;
+ return value
+ ? redactText(value, max).replace(/[\u0000-\u001f\u007f]/g, " ")
+ : undefined;
}
-function card(row: AgentSession, presence: LocalAgentPresenceRecord | undefined, now: number): SessionCard {
+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;
+ const entry =
+ presence?.principalHash === row.principalHash ? presence : undefined;
+ const name = text(row.name, 24) || "agent";
+ const title = text(row.title, 160) || "Untitled session";
+ const cwd = text(row.cwd);
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",
+ id: row.id,
+ name,
+ label: agentSessionLabel(name, title, cwd),
+ title,
+ 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,
+ lastSeenAt: entry?.lastSeenAt || row.updatedAt,
+ createdAt: row.createdAt,
+ 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));
+ const page = Math.min(
+ pages,
+ Math.max(1, Number.isFinite(requested) ? Math.trunc(requested) : 1),
+ );
return { total, page, pages, pageSize };
}
+function safeEvent(row: AgentSessionEvent) {
+ return {
+ 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),
+ };
+}
+function nodeName(event: ReturnType<typeof safeEvent>): string {
+ return (event.tool || event.kind || "event")
+ .replace(/[_.:-]+/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase())
+ .slice(0, 120);
+}
+function nodeType(
+ event: ReturnType<typeof safeEvent>,
+): WorkflowGraphNode["type"] {
+ if (event.kind === "workflow") return "subflow";
+ if (
+ event.kind === "note" ||
+ event.kind === "compacted" ||
+ event.kind === "archived"
+ )
+ return "memory";
+ return "tool";
+}
+function sessionGraph(
+ record: AgentSession,
+ session: SessionCard,
+ requestedLimit: number,
+): SessionGraphView {
+ const limit = Math.max(
+ 1,
+ Math.min(
+ SESSION_GRAPH_EVENT_LIMIT,
+ Math.trunc(requestedLimit) || SESSION_GRAPH_EVENT_LIMIT,
+ ),
+ );
+ const totalEvents = record.events.length;
+ const omittedEvents = Math.max(0, totalEvents - limit);
+ const events = record.events.slice(-limit).map(safeEvent);
+ const root: WorkflowGraphNode = {
+ id: "session-root",
+ name: session.label,
+ type: "session",
+ position: { x: 70, y: 100 },
+ config: {
+ label: session.label,
+ source: session.source,
+ status: session.status,
+ title: session.title,
+ ...(session.cwd ? { cwd: session.cwd } : {}),
+ },
+ };
+ const eventNodes: WorkflowGraphNode[] = events.map((event, index) => {
+ const row = Math.floor(index / 4),
+ column = index % 4,
+ displayColumn = row % 2 === 0 ? column : 3 - column;
+ return {
+ id: `event-${omittedEvents + index + 1}`,
+ name: nodeName(event),
+ type: nodeType(event),
+ position: { x: 340 + displayColumn * 250, y: 70 + row * 140 },
+ config: {
+ at: event.at,
+ kind: event.kind,
+ ...(event.tool ? { tool: event.tool } : {}),
+ ...(event.state ? { state: event.state } : {}),
+ ...(event.detail ? { detail: event.detail } : {}),
+ terminalContext: Boolean(
+ event.tool && /^(exec(?:_|\.)|terminal|shell)/i.test(event.tool),
+ ),
+ },
+ };
+ });
+ const nodes = [root, ...eventNodes];
+ const edges = eventNodes.map((node, index) => ({
+ id: `session-edge-${omittedEvents + index + 1}`,
+ source: index === 0 ? root.id : eventNodes[index - 1]!.id,
+ target: node.id,
+ }));
+ const graph: WorkflowGraph = {
+ version: 2,
+ id: `session:${record.id}`,
+ name: session.label,
+ description: session.title,
+ status: "archived",
+ inputs: {},
+ nodes,
+ edges,
+ metadata: {
+ provenance: "learned-from-session",
+ intent: session.title,
+ ...(session.cwd ? { project: session.cwd } : {}),
+ tags: ["session", session.source],
+ },
+ createdAt: record.createdAt,
+ updatedAt: record.updatedAt,
+ revision: `session-${Date.parse(record.updatedAt) || 0}`,
+ };
+ return {
+ session,
+ graph,
+ totalEvents,
+ shownEvents: events.length,
+ omittedEvents,
+ observedAt: new Date().toISOString(),
+ };
+}
+
/** Owner dashboard only. Model-facing directory remains strictly principal-scoped. */
-export async function ownerSessionPage(requested = 1, includeOffline = false, query = ""): Promise<SessionPage> {
- if (query.length > 200) throw new Error("session search exceeds 200 characters");
+export async function ownerSessionPage(
+ requested = 1,
+ includeOffline = false,
+ query = "",
+): Promise<SessionPage> {
+ if (query.length > 200)
+ throw new Error("session search exceeds 200 characters");
const search = query.trim().toLowerCase();
const presence = await listLocalAgentPresenceOwner();
- const now = Date.now(), byId = new Map(presence.map(row => [row.sessionId, row]));
+ const now = Date.now(),
+ byId = new Map(presence.map((row) => [row.sessionId, row]));
// Active refreshes must not load thousands of inactive transcripts from disk.
- const records: AgentSession[] = includeOffline ? await listSessionRecords() : [];
+ const records: AgentSession[] = includeOffline
+ ? await listSessionRecords()
+ : [];
if (!includeOffline) {
for (const entry of presence) {
if (["offline", "ended"].includes(localAgentStatus(entry, now))) continue;
@@ -42,21 +204,84 @@ export async function ownerSessionPage(requested = 1, includeOffline = false, qu
if (record) records.push(record);
}
}
- 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).filter(row => !search || [row.id, row.name, row.title, row.source, row.cwd].some(value => value?.toLowerCase().includes(search))).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt) || a.id.localeCompare(b.id));
+ 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)
+ .filter(
+ (row) =>
+ !search ||
+ [row.label, row.name, row.title, row.source, row.cwd].some((value) =>
+ value?.toLowerCase().includes(search),
+ ),
+ )
+ .sort(
+ (a, b) =>
+ b.lastSeenAt.localeCompare(a.lastSeenAt) ||
+ a.label.localeCompare(b.label),
+ );
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() };
+ 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(safeEvent);
+ return {
+ ...paging,
+ session: card(
+ record,
+ presence.find((row) => row.sessionId === id),
+ now,
+ ),
+ events,
+ observedAt: new Date(now).toISOString(),
+ };
}
-export async function ownerSessionDetail(id: string, requested = 1): Promise<SessionDetail | null> {
+export async function ownerSessionGraph(
+ id: string,
+ requestedLimit = SESSION_GRAPH_EVENT_LIMIT,
+): Promise<SessionGraphView | null> {
if (!SESSION_ID.test(id)) throw new Error("invalid_session_id");
- const [record, presence] = await Promise.all([readSessionFile(id), listLocalAgentPresenceOwner()]);
+ 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() };
+ const now = Date.now();
+ return sessionGraph(
+ record,
+ card(
+ record,
+ presence.find((row) => row.sessionId === id),
+ now,
+ ),
+ requestedLimit,
+ );
}
diff --git a/lib/agent/session-name.ts b/lib/agent/session-name.ts
index d6fbb5e6..f6472bcf 100644
--- a/lib/agent/session-name.ts
+++ b/lib/agent/session-name.ts
@@ -29,6 +29,27 @@ export function normalizeAgentSessionName(value: unknown): string {
return AGENT_SESSION_NAME_RE.test(raw) ? raw : "";
}
+function labelPart(value: unknown, max = 48): string {
+ return String(value ?? "")
+ .trim()
+ .normalize("NFKD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/-+/g, "-")
+ .replace(/^-|-$/g, "")
+ .slice(0, max)
+ .replace(/-$/g, "");
+}
+
+/** Human-facing session label. Durable session ids remain an internal lookup key. */
+export function agentSessionLabel(name: unknown, title: unknown, cwd?: unknown): string {
+ const agent = normalizeAgentSessionName(name) || labelPart(name, 24) || "agent";
+ const cwdLeaf = String(cwd ?? "").split(/[\\/]+/).filter(Boolean).pop();
+ const context = labelPart(title, 48) || labelPart(cwdLeaf, 48) || "session";
+ return `${agent}-${context}`.slice(0, 80).replace(/-$/g, "");
+}
+
export function requireAgentSessionName(value: unknown): string {
const name = normalizeAgentSessionName(value);
if (!name) throw new Error("session name must be 2-24 lowercase letters/numbers/hyphens, starting with a letter");
diff --git a/lib/agent/session-query.test.ts b/lib/agent/session-query.test.ts
index 81ffcc03..fd896c19 100644
--- a/lib/agent/session-query.test.ts
+++ b/lib/agent/session-query.test.ts
@@ -23,6 +23,11 @@ describe("full-store agent session resolver", () => {
expect(chooseAgentSessionRecord(rows, "2").title).toBe("Middle");
});
+ it("resolves the human agent-context label without requiring an internal id", () => {
+ const rows = [row(1, "Workflow Session Graph", "2026-09-01T12:00:00Z")];
+ expect(chooseAgentSessionRecord(rows, "test-1-workflow-session-graph").title).toBe("Workflow Session Graph");
+ });
+
it("can resolve a named session far beyond a 100-row client summary", () => {
const rows = Array.from({ length: 350 }, (_, i) => row(i + 1, `Session ${i + 1}`, new Date(1_788_000_000_000 - i * 1000).toISOString()));
rows[275]!.title = "Ancient Important Project";
@@ -33,6 +38,6 @@ describe("full-store agent session resolver", () => {
it("supports unique fuzzy titles but refuses ambiguous matches using human labels", () => {
const rows = [row(1, "Deploy Example Project", "2026-09-01T12:00:00Z"), row(2, "Audit Example Project", "2026-09-01T11:00:00Z")];
expect(chooseAgentSessionRecord(rows, "Deploy Example").title).toBe("Deploy Example Project");
- expect(() => chooseAgentSessionRecord(rows, "Example Project")).toThrow(/Deploy Example Project.*Audit Example Project|Audit Example Project.*Deploy Example Project/);
+ expect(() => chooseAgentSessionRecord(rows, "Example Project")).toThrow(/test-1-deploy-example-project.*test-2-audit-example-project|test-2-audit-example-project.*test-1-deploy-example-project/);
});
});
diff --git a/lib/agent/session-query.ts b/lib/agent/session-query.ts
index d25a9b68..2d0e7fae 100644
--- a/lib/agent/session-query.ts
+++ b/lib/agent/session-query.ts
@@ -6,6 +6,7 @@ import {
import { listSessionRecords, principalHash } from "./session-files";
import { redactText } from "@/lib/security/redact-text";
import type { AgentSession } from "./session-types";
+import { agentSessionLabel } from "./session-name";
import {
normalizeAgentSessionCwd,
sessionCwdRefMatch,
@@ -34,6 +35,9 @@ export function chooseAgentSessionRecord(
const ref = cleanRef(refValue),
q = ref.toLowerCase();
if (!ref || q === "latest" || q === "continue") return resumable[0]!;
+ const exactLabel = resumable.filter((row) => agentSessionLabel(row.name, row.title, row.cwd) === q);
+ if (exactLabel.length === 1) return exactLabel[0]!;
+ if (exactLabel.length > 1) throw new Error("session label is ambiguous");
const exactId = resumable.find((row) => row.id === ref);
if (exactId) return exactId;
const wantedName = q.replace(/^@/, "");
@@ -79,7 +83,7 @@ export function chooseAgentSessionRecord(
if (unique.length > 1) {
const labels = unique
.slice(0, 6)
- .map((row) => row.title.replace(/[\r\n\t]+/g, " ").slice(0, 72));
+ .map((row) => agentSessionLabel(row.name, row.title, row.cwd));
throw new Error(`session reference is ambiguous: ${labels.join(" | ")}`);
}
throw new Error("session_not_found");
diff --git a/lib/agent/session-record.ts b/lib/agent/session-record.ts
index c7f2748d..eaba785d 100644
--- a/lib/agent/session-record.ts
+++ b/lib/agent/session-record.ts
@@ -3,12 +3,14 @@ import { archiveAgentSession, pruneAgentSessionArchives } from "./session-archiv
import { principalHash, readSessionFile } from "./session-files";
import { compactSessionContext, MAX_EVENTS, sessionContextTokens } from "./session-policy";
import type { AgentSession, AgentSessionEvent, AgentSessionSummary } from "./session-types";
+import { agentSessionLabel } from "./session-name";
export function summary(record: AgentSession): AgentSessionSummary {
return {
id: record.id,
source: record.source,
name: record.name,
+ label: agentSessionLabel(record.name, record.title, record.cwd),
title: record.title,
titleSource: record.titleSource,
createdAt: record.createdAt,
diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.ts
index f0829267..f106f84c 100644
--- a/lib/agent/session-types.ts
+++ b/lib/agent/session-types.ts
@@ -51,6 +51,7 @@ export interface AgentSessionSummary {
id: string;
source: AgentSessionSource;
name: string;
+ label: string;
title: string;
titleSource: AgentSessionTitleSource;
createdAt: string;
diff --git a/lib/contracts/session-handover.ts b/lib/contracts/session-handover.ts
index f05f194a..391003e4 100644
--- a/lib/contracts/session-handover.ts
+++ b/lib/contracts/session-handover.ts
@@ -1,11 +1,11 @@
/** 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"],
+ required: ["version", "objective", "sourceSessionRef", "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}$" },
+ sourceSessionRef: { type: "string", minLength: 2, maxLength: 96, description: "Human session reference, preferably agent-context label or @agent-name." },
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 } },
@@ -15,14 +15,14 @@ export const SESSION_HANDOVER_SCHEMA = {
constraints: { type: "array", maxItems: 20, items: { type: "string", maxLength: 500 } },
},
} as const;
-export function handoverExample(sourceSessionId = "20260909_120000_1234abcd") {
+export function handoverExample(sourceSessionRef = "@source-agent") {
return { version: 1, objective: "Continue the reviewed task",
- sourceSessionId, project: { path: "/path/to/project", branch: "feat/task" },
+ sourceSessionRef, 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)) };
+export function handoverRequestExample(sourceSessionRef?: string) {
+ return { target: "@target-agent", kind: "task", intent: "request", requires_user_relay: true,
+ message: JSON.stringify(handoverExample(sourceSessionRef)) };
}
diff --git a/lib/contracts/session-monitor.ts b/lib/contracts/session-monitor.ts
index 8960c8bc..b4e6baed 100644
--- a/lib/contracts/session-monitor.ts
+++ b/lib/contracts/session-monitor.ts
@@ -1,9 +1,13 @@
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+
export const SESSION_PAGE_SIZE = 6;
export const SESSION_EVENT_PAGE_SIZE = 20;
+export const SESSION_GRAPH_EVENT_LIMIT = 120;
export type SessionStatus = "ready" | "idle" | "busy" | "ended" | "offline";
export interface SessionCard {
id: string;
name: string;
+ label: string;
title: string;
source: "mcp" | "cli" | "alfa";
status: SessionStatus;
@@ -42,3 +46,11 @@ export interface SessionDetail {
pageSize: number;
observedAt: string;
}
+export interface SessionGraphView {
+ session: SessionCard;
+ graph: WorkflowGraph;
+ totalEvents: number;
+ shownEvents: number;
+ omittedEvents: number;
+ observedAt: string;
+}
diff --git a/lib/mcp/tools-agent.ts b/lib/mcp/tools-agent.ts
index 9169b6dd..e6497695 100644
--- a/lib/mcp/tools-agent.ts
+++ b/lib/mcp/tools-agent.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { forgetAgentMemory, queryAgentMemory, readAgentMemory, rememberAgentMemory, type AgentMemoryDocument, type AgentMemoryKind, type AgentMemorySensitivity } from "@/lib/agent/memory-store";
import { agentSessionSummary, appendAgentSessionEvent, getAgentSession, listAgentSessions, renameAgentSession, resumeAgentSession } from "@/lib/agent/session-store";
import { type McpTool, S, str } from "./tool-kit";
+import { resolveAgentSessionRef } from "@/lib/agent/session-query";
function principal(context: { principal?: string }): string {
if (!context.principal) throw new Error("agent session principal is unavailable");
@@ -47,8 +48,13 @@ export const AGENT_TOOLS: McpTool[] = [
name: "agent_session_resume",
description: "Read the safe resume packet for one prior MSO session owned by this client. It returns summary/recent context, never ChatGPT hidden transcript.",
scope: "read", annotations: { readOnlyHint: true, idempotentHint: true },
- inputSchema: S({ session_id: { type: "string", description: "Exact MSO session id from agent_session_current/list." } }, ["session_id"]),
- run: (a, context) => resumeAgentSession(principal(context), str(a, "session_id"), context.sessionId),
+ inputSchema: S({ session_ref: { type: "string", description: "Human session label (agent-context), @name, title, or legacy exact id." }, session_id: { type: "string", description: "Legacy exact MSO session id; prefer session_ref." } }),
+ run: async (a, context) => {
+ const owner = principal(context), ref = optionalString(a, "session_ref") || optionalString(a, "session_id");
+ if (!ref) throw new Error("session_ref is required");
+ const target = await resolveAgentSessionRef(owner, ref);
+ return resumeAgentSession(owner, target.id, context.sessionId);
+ },
},
{
name: "agent_session_rename",
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index 2f518e78..98a228e5 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -101,7 +101,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
const mode = typeof config.mode === "string" ? config.mode : "current";
if (mode === "current") return { output: await callTool("agent_session_current", {}, context, resolve), log: "Current durable session resolved." };
if (mode === "list") return { output: await callTool("agent_sessions_list", { limit: Number(config.limit) || 20 }, context, resolve), log: "Durable sessions listed." };
- if (mode === "resume") return { output: await callTool("agent_session_resume", { session_id: String(config.sessionId ?? "") }, context, resolve), log: "Session resume packet loaded." };
+ if (mode === "resume") return { output: await callTool("agent_session_resume", { session_ref: String(config.sessionRef ?? config.sessionId ?? "") }, context, resolve), log: "Session resume packet loaded." };
if (mode === "note") return { output: await callTool("agent_session_note", { note: String(config.note ?? "") }, context, resolve), log: "Session note saved." };
throw new Error("session node mode must be current, list, resume, or note");
}
diff --git a/scripts/e2e/mcp-sessions.mjs b/scripts/e2e/mcp-sessions.mjs
index 62d81c18..98684bdf 100644
--- a/scripts/e2e/mcp-sessions.mjs
+++ b/scripts/e2e/mcp-sessions.mjs
@@ -16,23 +16,21 @@ export async function mcpSessionsJourney(page, fixture) {
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(3);
- 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();
+ const monitor = JSON.parse(raw);
+ const graphResponse = await page.request.get(fixture.base + `/api/v1/agent-sessions?view=graph&id=${encodeURIComponent(monitor.sessions[0].id)}`);
+ const graphRaw = await graphResponse.text();
+ expect(graphResponse.status()).toBe(200); expect(graphRaw).not.toMatch(/PRIVATE_TRANSCRIPT|PRIVATE_CONTEXT|FIXTURE_SECRET_MUST_NOT_LEAK|principalHash/);
+
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.locator('[data-slot="mcp-page"]').innerText()).not.toMatch(/\b\d{8}_\d{6}_[a-f0-9]{8}\b/);
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: "Active", exact: true }).click();
await expect(page.getByText("Page 1 of 2 · 8 sessions", { exact: true })).toBeVisible();
audit = await new AxeBuilder({ page }).include('[data-slot="mcp-page"]').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();
@@ -54,6 +52,19 @@ export async function mcpSessionsJourney(page, fixture) {
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");
+
+ // Session selection now hands off to Workflow instead of expanding private detail inside Settings.
+ await page.getByRole("button", { name: "Next sessions page", exact: true }).click();
+ await expect(cards).toHaveCount(3);
+ const openLabel = (await cards.first().getAttribute("aria-label"))?.replace(/^Open session /, "") || "";
+ expect(openLabel).toMatch(/^[a-z][a-z0-9-]+-[a-z0-9-]+$/);
+ await cards.first().click();
+ await expect(page.getByRole("application", { name: "Workflow canvas" })).toBeVisible();
+ await expect(page.getByText(openLabel, { exact: true }).last()).toBeVisible();
+ const terminalToolNode = page.locator(".react-flow__node").filter({ hasText: "Exec Run" }).first();
+ await expect(terminalToolNode).toBeVisible();
+ expect(await page.locator('[data-slot="workflows-feature"]').innerText()).not.toMatch(/\b\d{8}_\d{6}_[a-f0-9]{8}\b/);
+ await terminalToolNode.click();
+ await expect(page.getByRole("tablist", { name: "Terminal sessions" }).last()).toBeVisible();
+ console.log("PASS session labels, Workflow graph handoff, terminal context, redaction, handover, keyboard and accessibility");
}