Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agents): every agent row opens its own insight page — what happened, step by step

rubenluetke10-beep84af6604e006
diff --git a/jarvis/ui/web/frontend/src/components/missions/api.ts b/jarvis/ui/web/frontend/src/components/missions/api.ts
index 2d8c134fa6..3640bec03b 100644
--- a/jarvis/ui/web/frontend/src/components/missions/api.ts
+++ b/jarvis/ui/web/frontend/src/components/missions/api.ts
@@ -7,6 +7,7 @@ import type {
CriticVerdictReady,
EventEnvelope,
MissionDetail,
+ MissionResult,
MissionSummary,
MissionToolApprovalDecision,
MissionToolApprovalsResponse,
@@ -46,6 +47,11 @@ export async function fetchMissionDetail(id: string): Promise<MissionDetail> {
return { mission: data.mission, events, verdicts, worker_snapshots };
}
+/** The signed outcome plus the deliverables' bounded contents. */
+export async function fetchMissionResult(id: string): Promise<MissionResult> {
+ return requestJson(`${API_BASE}/${encodeURIComponent(id)}/result`);
+}
+
export function missionToolApprovalsQueryKey(missionId: string | null) {
return ["missions", "tool-approvals", missionId] as const;
}
diff --git a/jarvis/ui/web/frontend/src/store/jarvisAgents.ts b/jarvis/ui/web/frontend/src/store/jarvisAgents.ts
index d5683ab16d..4ffe1b3318 100644
--- a/jarvis/ui/web/frontend/src/store/jarvisAgents.ts
+++ b/jarvis/ui/web/frontend/src/store/jarvisAgents.ts
@@ -48,6 +48,15 @@ export interface SubAgentNode {
depth: number;
ui_appeared_at: number;
ui_fade_at?: number;
+ /**
+ * The dashed mission id the REST detail endpoints want. The registry keys
+ * its nodes by the dash-stripped form, so the board carries both.
+ */
+ mission_id?: string | null;
+ /** The archived output directory (its slug) while it still exists on disk. */
+ output_slug?: string | null;
+ /** The mission's terminal reason (`task_error`, `ui_cancel`, …), when known. */
+ outcome_reason?: string | null;
}
const FADE_OUT_MS = 60_000;
diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.ts
index e514345386..877cd11d4f 100644
--- a/jarvis/ui/web/frontend/src/types/missions.ts
+++ b/jarvis/ui/web/frontend/src/types/missions.ts
@@ -266,6 +266,33 @@ export interface MissionDetail {
worker_snapshots: JarvisAgentWorkerSnapshot[];
}
+/** One deliverable file as `GET /api/missions/{id}/result` lists it. */
+export interface MissionArtifact {
+ path: string;
+ deliverable_path: string;
+ size: number;
+ is_text: boolean;
+ /** Bounded text contents; null for binary files or past the total cap. */
+ content: string | null;
+ truncated: boolean;
+}
+
+/** Mirror of `get_mission_result` in jarvis/ui/web/missions_routes.py. */
+export interface MissionResult {
+ mission_id: string;
+ state: MissionState;
+ language: string;
+ /** The request with the worker quality directive stripped, bounded. */
+ prompt: string;
+ terminal_event: EventType | null;
+ summary: string | null;
+ result_uri: string | null;
+ reason: string | null;
+ artifacts: MissionArtifact[];
+ artifact_count: number;
+ truncated: boolean;
+}
+
/** Secret-free projection of one paused supervisor tool call. */
export interface PendingMissionToolApproval {
trace_id: string;
diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
index ae82770d4e..2f33a018d7 100644
--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
@@ -1,7 +1,7 @@
/**
* JarvisAgentsView — board of every Jarvis-Agent, live and past.
*
- * This file is the data half. It reads TWO sources and merges them:
+ * This file is the data half. It reads THREE sources and merges them:
*
* - `/api/sub-agents/tree` — the live registry. Carries tool calls and a
* running clock, but it is an in-memory bus subscriber that drops a finished
@@ -9,35 +9,51 @@
* - `/api/missions` — the durable record of the same runs. No tool calls, but
* it survives, so the board is not blank whenever nothing happens to be
* running in this exact minute.
+ * - `/api/outputs` — the archive of output directories. It knows a run's
+ * terminal reason, one-line summary and the slug its deliverables live
+ * under, which is what turns "Failed" into "provider quota exhausted" on the
+ * board and what the insight page opens the Artifacts section with.
*
* Before the merge the board was live-only, which meant every number read 0
* and the table read "no agents are running right now" even with hundreds of
* finished runs on disk. See `missionRows.ts` for the mapping and why a run
* present in both wins as its live node.
*
- * All of the presentation — header, headline numbers, table and per-row
- * drilldown — lives in `DepartureBoard`, which renders it with the shared
- * `components/extensions/primitives` so this section looks like Spend, Skills,
- * Plugins, MCPs and CLIs rather than like a screen of its own.
+ * Presentation lives in two siblings: `DepartureBoard` (header, headline
+ * numbers, table) and `AgentInsight` (one run in full — outcome, story,
+ * transcript, review, output). Clicking a row swaps the board for the insight
+ * page inside this section; "← Back" swaps it back. Both render with the
+ * shared `components/extensions/primitives` so this section looks like Spend,
+ * Skills, Plugins, MCPs and CLIs rather than like a screen of its own.
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { useSubAgentStore, type SubAgentTreeSnapshot } from "@/store/jarvisAgents";
+import { useSubAgentStore, type SubAgentNode, type SubAgentTreeSnapshot } from "@/store/jarvisAgents";
+import { useEventStore } from "@/store/events";
import { DepartureBoard } from "./sub-agents/DepartureBoard";
+import { AgentInsight } from "./sub-agents/AgentInsight";
import { selectTaskRows } from "./sub-agents/rows";
-import { mergeBoardRows } from "./sub-agents/missionRows";
+import { mergeBoardRows, HISTORY_LIMIT, normalizeTraceId } from "./sub-agents/missionRows";
import { fetchMissions } from "@/components/missions/api";
import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";
import { useMissionsStore } from "@/components/missions/store";
+import { useOutputsList } from "@/hooks/useOutputs";
import { useSectionHealth } from "@/hooks/useProviders";
+/** The query parameter the Artifacts section reads to pre-select a run. */
+const RUN_PARAM = "run";
+
export function JarvisAgentsView() {
const { health } = useSectionHealth();
const subAgents = useSubAgentStore((s) => s.subAgents);
const sweepExpired = useSubAgentStore((s) => s.sweepExpired);
const hydrateSnapshot = useSubAgentStore((s) => s.hydrateSnapshot);
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
const [snapshotError, setSnapshotError] = useState<string | null>(null);
+ // The run whose insight page is open, by dash-stripped id. Kept as an id
+ // rather than a node so the page follows the row through live updates.
+ const [openTraceId, setOpenTraceId] = useState<string | null>(null);
// One row per task: collapse each worker into its mission row so a single
// dispatched task shows once (the mission "Sub-Agent" carrying the task
@@ -57,9 +73,27 @@ export function JarvisAgentsView() {
refetchInterval: 30_000,
});
+ // The archive half — optional enrichment, never a blocker: a row whose
+ // directory is gone keeps what the mission record says about it.
+ const outputsQuery = useOutputsList();
+
const nodesList = useMemo(
- () => mergeBoardRows(liveRows, historyQuery.data?.missions ?? []),
- [liveRows, historyQuery.data],
+ () =>
+ mergeBoardRows(
+ liveRows,
+ historyQuery.data?.missions ?? [],
+ HISTORY_LIMIT,
+ outputsQuery.data ?? [],
+ ),
+ [liveRows, historyQuery.data, outputsQuery.data],
+ );
+
+ const openAgent = useMemo(
+ () =>
+ openTraceId
+ ? nodesList.find((n) => normalizeTraceId(n.trace_id) === openTraceId) ?? null
+ : null,
+ [nodesList, openTraceId],
);
const loadSnapshot = useCallback(async (signal?: AbortSignal) => {
@@ -112,12 +146,45 @@ export function JarvisAgentsView() {
return () => window.clearTimeout(id);
}, [missionLastSeq, loadSnapshot]);
+ // Hand a run to the Artifacts section. That view reads `?run=<slug>` once at
+ // mount (VisualizationView), so the address is written first and the section
+ // switched second; `useSectionUrlMemory` carries the parameter along.
+ const openOutput = useCallback(
+ (slug: string) => {
+ try {
+ const url = new URL(window.location.href);
+ url.searchParams.set(RUN_PARAM, slug);
+ window.history.replaceState(window.history.state, "", `${url.pathname}${url.search}${url.hash}`);
+ } catch {
+ /* a WebView that refuses the write still switches sections; the
+ Artifacts view then opens on its newest run instead of this one */
+ }
+ setActiveSection("visualization");
+ },
+ [setActiveSection],
+ );
+
+ const onOpen = useCallback((agent: SubAgentNode) => {
+ setOpenTraceId(normalizeTraceId(agent.trace_id));
+ }, []);
+
+ if (openAgent) {
+ return (
+ <AgentInsight
+ agent={openAgent}
+ onBack={() => setOpenTraceId(null)}
+ onOpenOutput={openOutput}
+ />
+ );
+ }
+
return (
<DepartureBoard
agents={nodesList}
snapshotError={snapshotError}
health={health["subagents"] ?? null}
historyError={historyQuery.isError}
+ onOpen={onOpen}
/>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.test.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.test.tsx
new file mode 100644
index 0000000000..94a5219140
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.test.tsx
@@ -0,0 +1,238 @@
+import type { ReactElement } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { SubAgentNode } from "@/store/jarvisAgents";
+import { AgentInsight, outcomeLines, reasonLabel, requestTitle } from "./AgentInsight";
+import { deriveOutcome } from "./outcome";
+
+const MISSION_ID = "019fecaa-5a92-7360-a784-829281639cf6";
+const WID = "019fecaa-5a92::019fecaa-5aa5::iter0";
+
+function envelope(payload: Record<string, unknown>, n: number, workerId: string | null = null) {
+ return {
+ event_id: `e${n}`,
+ seq: n,
+ mission_id: MISSION_ID,
+ parent_event_id: null,
+ worker_id: workerId,
+ source_actor: "kontrollierer",
+ ts_ms: 1_786_382_015_000 + n * 1_000,
+ schema_version: 1,
+ payload,
+ };
+}
+
+const DETAIL = {
+ mission: {
+ id: MISSION_ID,
+ prompt: "creates me an HTML file about the newest model releases",
+ state: "FAILED",
+ language: "en",
+ iteration: 0,
+ cost_usd: 0,
+ created_ms: 1_786_382_015_000,
+ updated_ms: 1_786_382_027_000,
+ },
+ events: [
+ envelope({ event_type: "MissionDispatched", prompt: "x", parent_mission_id: null, priority: 0, language: "en" }, 1),
+ envelope({ event_type: "MissionPlanReady", plan: [{}], n_workers: 1, expected_output: "Single-step plan" }, 2),
+ envelope(
+ { event_type: "WorkerSpawned", worker_id: WID, step: {}, pid: 0, cli: "claude", model: "", worktree: "C:/wt", session_id: "s1" },
+ 3,
+ WID,
+ ),
+ envelope(
+ { event_type: "WorkerProgress", worker_id: WID, pct: null, note: "Grep: jarvis/ui", stalled: false, tokens_so_far: 0, cost_so_far: 0 },
+ 4,
+ WID,
+ ),
+ envelope(
+ { event_type: "WorkerKilled", worker_id: WID, reason: "budget", error_class: "provider_quota", error_detail: "You've reached your limit." },
+ 5,
+ WID,
+ ),
+ envelope(
+ {
+ event_type: "MissionFailed",
+ reason: "task_error",
+ error_class: "provider_quota",
+ last_state: "CRITIQUING",
+ partial_artifacts: [],
+ error_detail: "You've reached your limit.",
+ failed_provider: "claude",
+ },
+ 6,
+ ),
+ ],
+ verdicts: [],
+ worker_snapshots: [],
+};
+
+const RESULT = {
+ mission_id: MISSION_ID,
+ state: "FAILED",
+ language: "en",
+ prompt: "creates me an HTML file about the newest model releases\n\nSupporting context: none",
+ terminal_event: "MissionFailed",
+ summary: null,
+ result_uri: null,
+ reason: "task_error",
+ artifacts: [],
+ artifact_count: 0,
+ truncated: false,
+};
+
+const OUTPUTS = {
+ sessions: [{ slug: "mission_019fecaa-5a92", status: "error", mission_id: MISSION_ID, terminal_reason: "task_error" }],
+};
+
+const PLAN = {
+ plan: { plan_id: "mission_019fecaa-5a92", vision: "", status: "failed", total_steps: 2 },
+ steps: [
+ { step_id: "t:0", name: "I will look at the workspace first.", kind: "reasoning", status: "done", output: "I will look at the workspace first.", task_key: "t" },
+ { step_id: "t:1", name: "jarvis/ui", tool_name: "Grep", kind: "tool", status: "failed", error: "quota", task_key: "t" },
+ ],
+ final_answer: null,
+ truncated: false,
+ dropped_steps: 0,
+};
+
+function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
+}
+
+function agentNode(over: Partial<SubAgentNode> = {}): SubAgentNode {
+ return {
+ trace_id: MISSION_ID.replace(/-/g, ""),
+ mission_id: MISSION_ID,
+ kind: "jarvis_agent",
+ name: "",
+ status: "failed",
+ parent_trace_id: null,
+ started_ns: 1_786_382_015_000 * 1_000_000,
+ completed_ns: null,
+ duration_ms: 12_000,
+ cost_usd: 0,
+ tokens_in: 0,
+ tokens_out: 0,
+ utterance: "creates me an HTML file about the newest model releases",
+ context_hints: [],
+ prompts: [],
+ tool_calls: [],
+ children_trace_ids: [],
+ error: null,
+ error_class: null,
+ review_iterations: 0,
+ depth: 0,
+ ui_appeared_at: 1,
+ ...over,
+ };
+}
+
+function renderWithQuery(ui: ReactElement) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
+}
+
+const identity = (key: string) => key;
+
+describe("AgentInsight", () => {
+ beforeEach(() => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.endsWith(`/api/missions/${MISSION_ID}/result`)) return jsonResponse(RESULT);
+ if (url.endsWith(`/api/missions/${MISSION_ID}`)) return jsonResponse(DETAIL);
+ if (url.endsWith("/api/outputs")) return jsonResponse(OUTPUTS);
+ if (url.endsWith("/api/outputs/mission_019fecaa-5a92/plan")) return jsonResponse(PLAN);
+ return new Response("not found", { status: 404 });
+ }),
+ );
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("explains a quota failure in plain words, with the provider's own text", async () => {
+ renderWithQuery(<AgentInsight agent={agentNode()} onBack={() => {}} onOpenOutput={() => {}} />);
+
+ // "Did not deliver" shows from the row's own status before the record
+ // arrives; the reason line is the first thing that needs the fetch.
+ expect(await screen.findByText("Did not deliver")).toBeTruthy();
+ expect(await screen.findByText("The worker's task failed")).toBeTruthy();
+ // The classified cause and the raw upstream message.
+ expect(screen.getByText(/Provider quota exhausted/)).toBeTruthy();
+ // Quoted in the verdict AND in the story's kill entry — both on purpose.
+ expect(screen.getAllByText("You've reached your limit.").length).toBeGreaterThanOrEqual(2);
+ // The kill and where in the pipeline it broke.
+ expect(screen.getByText("Worker (round 0) stopped")).toBeTruthy();
+ expect(screen.getByText("budget or provider quota")).toBeTruthy();
+ // The story timeline lands on the failure by default for a failed run.
+ expect(await screen.findByText("Worker started · claude · round 1")).toBeTruthy();
+ expect(screen.getByText("Grep")).toBeTruthy();
+ });
+
+ it("hands the archived output slug to the Artifacts section", async () => {
+ const opened: string[] = [];
+ renderWithQuery(<AgentInsight agent={agentNode()} onBack={() => {}} onOpenOutput={(s) => opened.push(s)} />);
+
+ const button = await screen.findByRole("button", { name: /open output/i });
+ await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(button);
+ expect(opened).toEqual(["mission_019fecaa-5a92"]);
+ });
+
+ it("shows the reconstructed transcript with reasoning and a failed tool step", async () => {
+ renderWithQuery(<AgentInsight agent={agentNode()} onBack={() => {}} onOpenOutput={() => {}} />);
+ await screen.findByText("Did not deliver");
+
+ fireEvent.click(await screen.findByRole("tab", { name: /transcript/i }));
+ expect(await screen.findByText("I will look at the workspace first.")).toBeTruthy();
+ expect(screen.getByText("quota")).toBeTruthy();
+ // The header's status dot says "Failed" too; the step adds a second one.
+ expect(screen.getAllByText("Failed", { selector: "span" }).length).toBeGreaterThanOrEqual(2);
+ });
+
+ it("goes back to the board", async () => {
+ let back = 0;
+ renderWithQuery(<AgentInsight agent={agentNode()} onBack={() => { back += 1; }} onOpenOutput={() => {}} />);
+ fireEvent.click(await screen.findByRole("button", { name: /Agents/ }));
+ expect(back).toBe(1);
+ });
+});
+
+describe("outcomeLines", () => {
+ it("lists nothing beyond progress for a run still working", () => {
+ const outcome = deriveOutcome(DETAIL.events.slice(0, 4) as never, "en");
+ const lines = outcomeLines(agentNode({ status: "running" }), outcome, identity);
+ expect(lines.map((l) => l.id)).toEqual(["notes"]);
+ });
+
+ it("orders a failure as reason → cause → provider text → kills → state", () => {
+ const outcome = deriveOutcome(DETAIL.events as never, "en");
+ const lines = outcomeLines(agentNode(), outcome, identity);
+ expect(lines.map((l) => l.id)).toEqual(["reason", "class", "detail", "provider", `kill-${WID}`, "state"]);
+ expect(lines.find((l) => l.id === "detail")?.mono).toBe(true);
+ });
+});
+
+describe("requestTitle / reasonLabel", () => {
+ it("takes the first paragraph and clamps it", () => {
+ expect(requestTitle("Do this\n\nSupporting context: …", "none")).toBe("Do this");
+ expect(requestTitle(" ", "none")).toBe("none");
+ expect(requestTitle("x".repeat(300), "none")).toHaveLength(178);
+ });
+
+ it("falls back to the raw token for an unknown reason and keeps the tail", () => {
+ expect(reasonLabel("decompose_failed: no brain", identity)).toBe(
+ "subagents_view.reason.decompose_failed (no brain)",
+ );
+ expect(reasonLabel("something_new", identity)).toBe("something_new");
+ expect(reasonLabel(null, identity)).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.tsx
new file mode 100644
index 0000000000..3b69749859
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/AgentInsight.tsx
@@ -0,0 +1,1020 @@
+/**
+ * AgentInsight — one agent run, in full.
+ *
+ * The board row answers "did it land?" in one word. This page answers the
+ * questions that word raises: what exactly went wrong, what the agent did
+ * step by step, what the reviewer said, and what it left behind. It replaces
+ * the board inside the section (a "← Back" link at the top, the same quiet
+ * primitives) rather than opening a dialog, because a run's story is a page,
+ * not a tooltip.
+ *
+ * Four sources, all of which already exist — nothing here is a second store:
+ *
+ * - `GET /api/missions/{id}` — the durable event stream (dispatch, spawns,
+ * the worker's own progress notes, verdicts, kills, the terminal event).
+ * `outcome.ts` turns it into the verdict paragraph and the story timeline.
+ * - `GET /api/missions/{id}/result` — the signed summary and the deliverable
+ * files with bounded contents.
+ * - `GET /api/outputs` + `GET /api/outputs/{slug}/plan` — the archived worker
+ * transcript, reconstructed into reasoning / tool / spawn steps and the final
+ * answer. Only while the output directory still exists; a cleaned-up run
+ * says so instead of pretending the agent did nothing.
+ * - The live registry node the board already holds — tool calls with real
+ * status and a running clock for an agent that is still working.
+ *
+ * Every visible string goes through i18n; the brand is the wake-word-derived
+ * assistant name (lib/agentBrand.ts), never a product name.
+ */
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ AlertTriangle,
+ ArrowUpRight,
+ Bot,
+ Brain,
+ CheckCircle2,
+ CircleAlert,
+ FileText,
+ Gavel,
+ ListChecks,
+ Map as MapIcon,
+ Rocket,
+ ScrollText,
+ StopCircle,
+ TerminalSquare,
+ Timer,
+ Wrench,
+ XCircle,
+} from "lucide-react";
+
+import type { SubAgentNode, ToolCallEntry } from "@/store/jarvisAgents";
+import type { CriticAxisResult, CriticVerdictReady, MissionArtifact } from "@/types/missions";
+import { fetchMissionDetail, fetchMissionResult } from "@/components/missions/api";
+import { useOutputsList, usePlanForOutput, type PlanStep } from "@/hooks/useOutputs";
+import { missionMapUrl } from "@/hooks/useVisualArtifacts";
+import { openExternalUrl } from "@/lib/openExternal";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import {
+ BackLink,
+ DetailHeader,
+ FactRows,
+ Panel,
+ SegmentedFilter,
+ SoftButton,
+ StatusDot,
+ StatTile,
+} from "@/components/extensions/primitives";
+import { agentBrand, agentsBrand } from "@/lib/agentBrand";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+import { fill, useT, useUiLanguage } from "@/i18n";
+import { failureLabel } from "./failureLabel";
+import {
+ buildStory,
+ deriveOutcome,
+ KILL_REASON_LABEL_KEYS,
+ missionIdFromTraceId,
+ REASON_LABEL_KEYS,
+ splitReason,
+ type AgentOutcome,
+ type StoryEntry,
+ type StoryTone,
+} from "./outcome";
+import { formatBytes, formatClock, formatDuration, formatOffset, formatUsd } from "./format";
+
+type Tab = "story" | "transcript" | "review" | "output";
+type T = (key: string) => string;
+
+const STATUS_TONE: Record<SubAgentNode["status"], "busy" | "ok" | "error" | "warn"> = {
+ running: "busy",
+ completed: "ok",
+ failed: "error",
+ cancelled: "warn",
+};
+
+const TONE_TEXT: Record<StoryTone, string> = {
+ neutral: "text-muted-foreground",
+ busy: "text-primary",
+ ok: "text-emerald-600 dark:text-emerald-400",
+ warn: "text-amber-600 dark:text-amber-400",
+ error: "text-destructive",
+};
+
+const TONE_RING: Record<StoryTone, string> = {
+ neutral: "border-border bg-card",
+ busy: "border-primary/50 bg-primary/10",
+ ok: "border-emerald-500/50 bg-emerald-500/10",
+ warn: "border-amber-500/50 bg-amber-500/10",
+ error: "border-destructive/50 bg-destructive/10",
+};
+
+/** The first paragraph of the request — the part the user actually said. */
+export function requestTitle(text: string | null | undefined, fallback: string): string {
+ const raw = (text ?? "").trim();
+ if (!raw) return fallback;
+ const first = raw.split(/\n\s*\n/)[0].replace(/\s+/g, " ").trim();
+ return first.length > 180 ? `${first.slice(0, 177).trimEnd()}…` : first || fallback;
+}
+
+/** Plain-language label for a mission-level reason, else the raw token. */
+export function reasonLabel(reason: string | null | undefined, t: T): string | null {
+ const { head, tail } = splitReason(reason);
+ if (!head) return null;
+ const key = REASON_LABEL_KEYS[head];
+ const label = key ? t(key) : head;
+ return tail ? `${label} (${tail})` : label;
+}
+
+function killLabel(reason: string, t: T): string {
+ const key = KILL_REASON_LABEL_KEYS[reason];
+ return key ? t(key) : reason;
+}
+
+function axisPassed(axis: CriticAxisResult): boolean | null {
+ if (axis.pass === true || axis.status === "pass") return true;
+ if (axis.pass === false || axis.status === "fail") return false;
+ return null;
+}
+
+interface Props {
+ agent: SubAgentNode;
+ onBack: () => void;
+ onOpenOutput: (slug: string) => void;
+}
+
+export function AgentInsight({ agent, onBack, onOpenOutput }: Props) {
+ const t = useT();
+ const locale = useUiLanguage();
+ const assistantName = useEventStore((s) => s.assistantName);
+ const missionId = agent.mission_id ?? missionIdFromTraceId(agent.trace_id);
+ const running = agent.status === "running";
+
+ const detail = useQuery({
+ queryKey: ["missions", "detail", missionId],
+ queryFn: () => fetchMissionDetail(missionId),
+ refetchInterval: running ? 3_000 : false,
+ });
+ const result = useQuery({
+ queryKey: ["missions", "result", missionId],
+ queryFn: () => fetchMissionResult(missionId),
+ refetchInterval: running ? 10_000 : false,
+ });
+ const outputs = useOutputsList();
+ const slug = useMemo(() => {
+ const match = outputs.data?.find((o) => o.mission_id === missionId);
+ return match?.slug ?? agent.output_slug ?? null;
+ }, [outputs.data, missionId, agent.output_slug]);
+ const plan = usePlanForOutput(slug);
+
+ const events = detail.data?.events ?? [];
+ const language = detail.data?.mission.language ?? "en";
+ const outcome = useMemo(() => deriveOutcome(events, language), [events, language]);
+ const story = useMemo(() => buildStory(events), [events]);
+ const steps: PlanStep[] = plan.data?.steps ?? [];
+ const artifacts: MissionArtifact[] = result.data?.artifacts ?? [];
+ const finalAnswer = plan.data?.final_answer ?? null;
+
+ const hasOutput = artifacts.length > 0 || !!finalAnswer || !!outcome.summary;
+ const [tab, setTab] = useState<Tab | null>(null);
+ // Land where the answer is: a delivered run opens on its output, everything
+ // else opens on the story of how it got where it got.
+ const activeTab: Tab = tab ?? (outcome.terminal === "approved" && hasOutput ? "output" : "story");
+
+ const title = requestTitle(result.data?.prompt ?? agent.utterance, t("subagents_view.task_none"));
+ const startedMs = events[0]?.ts_ms ?? Math.floor(agent.started_ns / 1_000_000);
+ const endedMs = detail.data?.mission.updated_ms ?? null;
+ const runtimeMs =
+ agent.duration_ms ??
+ (outcome.terminal && endedMs ? endedMs - startedMs : running ? Date.now() - startedMs : null);
+
+ const tabOptions: { id: Tab; label: string; count?: number }[] = [
+ { id: "story", label: t("subagents_view.tab_story"), count: story.length },
+ { id: "transcript", label: t("subagents_view.tab_transcript"), count: steps.length },
+ { id: "review", label: t("subagents_view.tab_review"), count: outcome.verdicts.length },
+ { id: "output", label: t("subagents_view.tab_output"), count: artifacts.length },
+ ];
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <ScrollArea className="flex-1">
+ <div className="mx-auto flex w-full max-w-[1180px] flex-col gap-4 px-6 py-6">
+ <BackLink label={agentsBrand(assistantName)} onClick={onBack} />
+
+ <DetailHeader
+ leading={
+ <span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl border border-border bg-card/60 text-primary">
+ <Bot className="h-5 w-5" />
+ </span>
+ }
+ title={title}
+ titleAccessory={
+ <StatusDot
+ tone={STATUS_TONE[agent.status]}
+ pulse={running}
+ label={t(`subagents_view.status.${agent.status}`)}
+ />
+ }
+ byline={fill(t("subagents_view.insight_byline"), {
+ agent: agentBrand(assistantName),
+ started: formatClock(startedMs, locale),
+ runtime: runtimeMs != null ? formatDuration(runtimeMs) : "—",
+ })}
+ actions={
+ <>
+ {slug && (
+ <SoftButton
+ onClick={() => void openExternalUrl(`${window.location.origin}${missionMapUrl(slug)}`)}
+ >
+ <MapIcon className="h-3.5 w-3.5" />
+ {t("subagents_view.action_map")}
+ </SoftButton>
+ )}
+ <SoftButton primary disabled={!slug} onClick={() => slug && onOpenOutput(slug)}>
+ <ArrowUpRight className="h-3.5 w-3.5" />
+ {t("subagents_view.action_open_output")}
+ </SoftButton>
+ </>
+ }
+ />
+
+ {detail.isError && (
+ <Notice tone="error">
+ {fill(t("subagents_view.insight_load_error"), {
+ detail: detail.error instanceof Error ? detail.error.message : "",
+ })}
+ </Notice>
+ )}
+
+ {/* The verdict — what happened, in words ------------------------ */}
+ <OutcomePanel
+ agent={agent}
+ outcome={outcome}
+ loading={detail.isPending}
+ artifactCount={result.data?.artifact_count ?? artifacts.length}
+ t={t}
+ />
+
+ {/* The numbers ------------------------------------------------- */}
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
+ <StatTile
+ icon={<Timer className="h-4 w-4" />}
+ label={t("subagents_view.col_runtime")}
+ value={runtimeMs != null ? formatDuration(runtimeMs) : "—"}
+ hint={endedMs && outcome.terminal ? formatClock(endedMs, locale) : t("subagents_view.stat_active_hint_idle")}
+ />
+ <StatTile
+ icon={<Bot className="h-4 w-4" />}
+ label={t("subagents_view.stat_workers_label")}
+ value={String(outcome.workers.length)}
+ hint={
+ outcome.workers.length > 0
+ ? outcome.workers.map((w) => w.cli).filter(Boolean).join(", ") || "—"
+ : t("subagents_view.stat_workers_hint_none")
+ }
+ />
+ <StatTile
+ icon={<Wrench className="h-4 w-4" />}
+ label={t("subagents_view.stat_tools_label")}
+ value={String(
+ Math.max(
+ agent.tool_calls.length,
+ steps.filter((s) => s.kind !== "reasoning").length,
+ outcome.workers.reduce((sum, w) => sum + w.tool_notes, 0),
+ ),
+ )}
+ hint={t("subagents_view.stat_tools_hint_run")}
+ />
+ <StatTile
+ icon={<Gavel className="h-4 w-4" />}
+ label={t("subagents_view.stat_reviews_label")}
+ value={String(outcome.verdicts.length)}
+ tone={outcome.revisions > 0 ? "warn" : "ok"}
+ hint={
+ outcome.revisions > 0
+ ? fill(t("subagents_view.stat_reviews_hint_revisions"), { n: outcome.revisions })
+ : t("subagents_view.stat_reviews_hint_none")
+ }
+ />
+ <StatTile
+ icon={<ScrollText className="h-4 w-4" />}
+ label={t("subagents_view.stat_cost_label")}
+ value={formatUsd(Math.max(outcome.cost_usd, agent.cost_usd))}
+ hint={
+ outcome.tokens_used > 0
+ ? fill(t("subagents_view.stat_cost_hint_tokens"), { n: outcome.tokens_used.toLocaleString() })
+ : t("subagents_view.stat_cost_hint_none")
+ }
+ />
+ </div>
+
+ {/* Live tool calls from the registry, while it still holds them --- */}
+ {agent.tool_calls.length > 0 && (
+ <Panel>
+ <div className="flex items-center gap-2 border-b border-border px-4 py-2.5 text-xs font-medium text-muted-foreground">
+ <TerminalSquare className="h-3.5 w-3.5 text-primary" />
+ {t("subagents_view.drill_tools")}
+ </div>
+ <div className="divide-y divide-border/70">
+ {agent.tool_calls.map((call, idx) => (
+ <LiveToolCall key={`${agent.trace_id}-${idx}`} call={call} t={t} />
+ ))}
+ </div>
+ </Panel>
+ )}
+
+ {/* The record ---------------------------------------------------- */}
+ <Panel>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3">
+ <SegmentedFilter
+ value={activeTab}
+ onChange={setTab}
+ options={tabOptions}
+ label={t("subagents_view.tabs_label")}
+ />
+ {slug ? (
+ <span className="font-mono text-[11px] text-muted-foreground/70">{slug}</span>
+ ) : (
+ <span className="text-[11px] text-muted-foreground/70">
+ {t("subagents_view.no_output_dir")}
+ </span>
+ )}
+ </div>
+
+ {activeTab === "story" && (
+ <StoryList story={story} startedMs={startedMs} loading={detail.isPending} assistantName={assistantName} t={t} />
+ )}
+ {activeTab === "transcript" && (
+ <Transcript
+ steps={steps}
+ finalAnswer={finalAnswer}
+ truncated={!!plan.data?.truncated}
+ dropped={plan.data?.dropped_steps ?? 0}
+ hasSlug={!!slug}
+ loading={!!slug && plan.isPending}
+ t={t}
+ />
+ )}
+ {activeTab === "review" && <Review outcome={outcome} t={t} />}
+ {activeTab === "output" && (
+ <Output
+ outcome={outcome}
+ finalAnswer={finalAnswer}
+ artifacts={artifacts}
+ truncated={!!result.data?.truncated}
+ slug={slug}
+ onOpenOutput={onOpenOutput}
+ t={t}
+ />
+ )}
+ </Panel>
+
+ <FactRows
+ className="px-1"
+ rows={[
+ { label: t("subagents_view.fact_mission_id"), value: <span className="font-mono text-sm">{missionId}</span> },
+ {
+ label: t("subagents_view.fact_request"),
+ value: <ClampedBlock text={result.data?.prompt ?? agent.utterance ?? ""} t={t} lines={3} />,
+ },
+ ...(outcome.result_uri
+ ? [{ label: t("subagents_view.fact_result_uri"), value: <span className="break-all font-mono text-xs">{outcome.result_uri}</span> }]
+ : []),
+ ]}
+ />
+ </div>
+ </ScrollArea>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Outcome — the verdict paragraph
+// ---------------------------------------------------------------------------
+
+interface OutcomeLine {
+ id: string;
+ tone: StoryTone;
+ label: string;
+ text: string;
+ mono?: boolean;
+}
+
+export function outcomeLines(agent: SubAgentNode, outcome: AgentOutcome, t: T): OutcomeLine[] {
+ const lines: OutcomeLine[] = [];
+ const reason = reasonLabel(outcome.reason, t);
+
+ if (outcome.terminal === "failed" || outcome.terminal === "timed_out") {
+ if (reason) lines.push({ id: "reason", tone: "error", label: t("subagents_view.line_reason"), text: reason });
+ const cls = failureLabel({ error: null, error_class: outcome.error_class }, t);
+ if (cls) lines.push({ id: "class", tone: "error", label: t("subagents_view.line_error_class"), text: cls });
+ if (outcome.error_detail) {
+ lines.push({ id: "detail", tone: "neutral", label: t("subagents_view.line_provider_said"), text: outcome.error_detail, mono: true });
+ }
+ if (outcome.failed_provider) {
+ lines.push({ id: "provider", tone: "neutral", label: t("subagents_view.line_provider"), text: outcome.failed_provider });
+ }
+ for (const kill of outcome.kills) {
+ const iter = /::iter(\d+)$/.exec(kill.worker_id)?.[1];
+ lines.push({
+ id: `kill-${kill.worker_id}`,
+ tone: kill.reason === "user" ? "warn" : "error",
+ label: iter != null
+ ? fill(t("subagents_view.line_worker_stopped_iter"), { n: iter })
+ : t("subagents_view.line_worker_stopped"),
+ text: kill.error_detail && kill.error_detail !== outcome.error_detail
+ ? `${killLabel(kill.reason, t)} — ${kill.error_detail}`
+ : killLabel(kill.reason, t),
+ });
+ }
+ if (outcome.lastVerdict && outcome.lastVerdict.verdict !== "approve") {
+ lines.push({
+ id: "verdict",
+ tone: "warn",
+ label: fill(t("subagents_view.line_reviewer"), { verdict: t(`subagents_view.verdict.${outcome.lastVerdict.verdict}`) }),
+ text: outcome.lastVerdict.summary,
+ });
+ }
+ if (outcome.lastCorrection) {
+ lines.push({ id: "correction", tone: "warn", label: t("subagents_view.line_correction"), text: outcome.lastCorrection.correction_instruction });
+ }
+ if (outcome.last_state) {
+ lines.push({ id: "state", tone: "neutral", label: t("subagents_view.line_last_state"), text: t(`mission_state.${outcome.last_state.toLowerCase()}`) });
+ }
+ if (outcome.partial_artifacts.length > 0) {
+ lines.push({
+ id: "partial",
+ tone: "neutral",
+ label: t("subagents_view.line_partial"),
+ text: fill(t("subagents_view.line_partial_text"), { n: outcome.partial_artifacts.length }),
+ });
+ }
+ if (outcome.terminal === "timed_out" && outcome.deadline_ms) {
+ lines.push({ id: "deadline", tone: "neutral", label: t("subagents_view.line_deadline"), text: formatDuration(outcome.deadline_ms) });
+ }
+ } else if (outcome.terminal === "cancelled") {
+ if (reason) lines.push({ id: "reason", tone: "warn", label: t("subagents_view.line_reason"), text: reason });
+ if (outcome.cascade) lines.push({ id: "cascade", tone: "neutral", label: t("subagents_view.line_cascade"), text: t("subagents_view.line_cascade_text") });
+ for (const kill of outcome.kills) {
+ lines.push({ id: `kill-${kill.worker_id}`, tone: "warn", label: t("subagents_view.line_worker_stopped"), text: killLabel(kill.reason, t) });
+ }
+ } else if (outcome.terminal === "approved") {
+ if (outcome.summary) lines.push({ id: "summary", tone: "ok", label: t("subagents_view.line_summary"), text: outcome.summary });
+ if (outcome.lastVerdict) {
+ lines.push({
+ id: "verdict",
+ tone: "ok",
+ label: fill(t("subagents_view.line_reviewer"), { verdict: t(`subagents_view.verdict.${outcome.lastVerdict.verdict}`) }),
+ text: outcome.lastVerdict.summary,
+ });
+ }
+ if (outcome.revisions > 0) {
+ lines.push({ id: "revisions", tone: "warn", label: t("subagents_view.line_revisions"), text: fill(t("subagents_view.line_revisions_text"), { n: outcome.revisions }) });
+ }
+ } else {
+ // Still running, or no terminal event recorded yet.
+ const live = failureLabel(agent, t);
+ if (live) lines.push({ id: "live-error", tone: "error", label: t("subagents_view.line_reason"), text: live });
+ const notes = outcome.workers.reduce((sum, w) => sum + w.notes, 0);
+ if (notes > 0) lines.push({ id: "notes", tone: "busy", label: t("subagents_view.line_progress"), text: fill(t("subagents_view.line_progress_text"), { n: notes }) });
+ if (outcome.lastCorrection) {
+ lines.push({ id: "correction", tone: "warn", label: t("subagents_view.line_correction"), text: outcome.lastCorrection.correction_instruction });
+ }
+ }
+ return lines;
+}
+
+function OutcomePanel({
+ agent,
+ outcome,
+ loading,
+ artifactCount,
+ t,
+}: {
+ agent: SubAgentNode;
+ outcome: AgentOutcome;
+ loading: boolean;
+ artifactCount: number;
+ t: T;
+}) {
+ const state: "running" | "approved" | "failed" | "cancelled" | "timed_out" =
+ outcome.terminal ?? (agent.status === "running" ? "running" : agent.status === "failed" ? "failed" : agent.status === "cancelled" ? "cancelled" : "approved");
+ const tone: StoryTone =
+ state === "approved" ? "ok" : state === "running" ? "busy" : state === "cancelled" ? "warn" : "error";
+ const Icon =
+ state === "approved" ? CheckCircle2 : state === "running" ? Rocket : state === "cancelled" ? StopCircle : XCircle;
+ const lines = outcomeLines(agent, outcome, t);
+
+ return (
+ <Panel>
+ <div className="flex items-start gap-3 px-4 py-4">
+ <span className={cn("grid h-9 w-9 shrink-0 place-items-center rounded-full border", TONE_RING[tone], TONE_TEXT[tone])}>
+ <Icon className="h-[18px] w-[18px]" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="font-display text-[15px] font-semibold text-foreground">
+ {t(`subagents_view.outcome.${state}`)}
+ </div>
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ {loading
+ ? t("subagents_view.insight_loading")
+ : state === "approved"
+ ? fill(t("subagents_view.outcome_approved_hint"), { n: artifactCount })
+ : t(`subagents_view.outcome_hint.${state}`)}
+ </p>
+ </div>
+ </div>
+ {lines.length > 0 && (
+ <dl className="grid grid-cols-[max-content_minmax(0,1fr)] gap-x-6 gap-y-2 border-t border-border px-4 py-3 text-sm">
+ {lines.map((line) => (
+ <div key={line.id} className="contents">
+ <dt className={cn("text-xs leading-6", TONE_TEXT[line.tone])}>{line.label}</dt>
+ <dd className={cn("min-w-0 leading-6 text-foreground/90", line.mono && "whitespace-pre-wrap break-words font-mono text-[12.5px]")}>
+ {line.text}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ </Panel>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Story — the run as it unfolded
+// ---------------------------------------------------------------------------
+
+const STORY_ICON: Record<StoryEntry["kind"], typeof Bot> = {
+ dispatched: Rocket,
+ plan: ListChecks,
+ spawn: Bot,
+ narration: Brain,
+ tool: Wrench,
+ draft: FileText,
+ verdict: Gavel,
+ correction: AlertTriangle,
+ killed: StopCircle,
+ budget: AlertTriangle,
+ approved: CheckCircle2,
+ failed: XCircle,
+ cancelled: StopCircle,
+ timed_out: Timer,
+};
+
+function storyTitle(entry: StoryEntry, assistantName: string, t: T): string {
+ const agent = agentBrand(assistantName);
+ const m = entry.meta;
+ switch (entry.kind) {
+ case "dispatched":
+ return fill(t("subagents_view.story.dispatched"), { agent });
+ case "plan":
+ return fill(t("subagents_view.story.plan"), { n: m.workers ?? "1" });
+ case "spawn":
+ return fill(t("subagents_view.story.spawn"), {
+ cli: m.cli || "—",
+ iter: String((entry.iteration ?? 0) + 1),
+ }) + (m.model ? ` · ${m.model}` : "");
+ case "narration":
+ return fill(t("subagents_view.story.narration"), { agent });
+ case "tool":
+ return entry.tool ?? t("subagents_view.tool_unnamed");
+ case "draft":
+ return fill(t("subagents_view.story.draft"), { n: m.diff_lines ?? "0" });
+ case "verdict":
+ return fill(t("subagents_view.story.verdict"), {
+ verdict: t(`subagents_view.verdict.${m.verdict}`),
+ confidence: m.confidence ?? "",
+ });
+ case "correction":
+ return m.next_model
+ ? fill(t("subagents_view.story.correction_model"), { model: m.next_model })
+ : t("subagents_view.story.correction");
+ case "killed":
+ return fill(t("subagents_view.story.killed"), { reason: killLabel(m.reason ?? "", t) });
+ case "budget":
+ return fill(t("subagents_view.story.budget"), { pct: m.pct ?? "", limit: m.limit ?? "" });
+ case "approved":
+ return t("subagents_view.story.approved");
+ case "failed":
+ return fill(t("subagents_view.story.failed"), { reason: reasonLabel(m.reason, t) ?? "" });
+ case "cancelled":
+ return fill(t("subagents_view.story.cancelled"), { reason: reasonLabel(m.reason, t) ?? "" });
+ case "timed_out":
+ return t("subagents_view.story.timed_out");
+ default:
+ return entry.kind;
+ }
+}
+
+function StoryList({
+ story,
+ startedMs,
+ loading,
+ assistantName,
+ t,
+}: {
+ story: StoryEntry[];
+ startedMs: number;
+ loading: boolean;
+ assistantName: string;
+ t: T;
+}) {
+ if (story.length === 0) {
+ return <EmptyNote>{loading ? t("subagents_view.insight_loading") : t("subagents_view.story_empty")}</EmptyNote>;
+ }
+ return (
+ <ol className="divide-y divide-border/60">
+ {story.map((entry) => {
+ const Icon = STORY_ICON[entry.kind];
+ const title = storyTitle(entry, assistantName, t);
+ return (
+ <li key={entry.id} className="grid grid-cols-[64px_28px_minmax(0,1fr)] items-start gap-x-3 px-4 py-2.5">
+ <span className="pt-0.5 text-right font-mono text-[11px] tabular-nums text-muted-foreground/70">
+ {formatOffset(entry.ts_ms - startedMs)}
+ </span>
+ <span className={cn("grid h-6 w-6 place-items-center rounded-full border", TONE_RING[entry.tone], TONE_TEXT[entry.tone])}>
+ <Icon className="h-3.5 w-3.5" />
+ </span>
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
+ <span className={cn("text-sm font-medium", entry.kind === "tool" ? "font-mono text-[13px] text-foreground" : "text-foreground")}>
+ {title}
+ </span>
+ {entry.iteration != null && entry.kind !== "spawn" && entry.kind !== "verdict" && entry.kind !== "correction" && (
+ <span className="text-[11px] text-muted-foreground/70">
+ {fill(t("subagents_view.iteration_short"), { n: entry.iteration + 1 })}
+ </span>
+ )}
+ {entry.meta.pct && <span className="text-[11px] text-muted-foreground/70">{entry.meta.pct}</span>}
+ </div>
+ {entry.text && (
+ <ClampedBlock
+ text={entry.text}
+ t={t}
+ lines={entry.kind === "tool" ? 2 : 3}
+ className={cn("mt-0.5 text-sm", entry.kind === "tool" ? "font-mono text-[12.5px] text-muted-foreground" : "text-foreground/85")}
+ />
+ )}
+ {entry.verdict && <AxisChips verdict={entry.verdict} />}
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+function AxisChips({ verdict }: { verdict: CriticVerdictReady }) {
+ const entries = Object.entries(verdict.axes ?? {});
+ if (entries.length === 0) return null;
+ return (
+ <div className="mt-1.5 flex flex-wrap gap-1.5">
+ {entries.map(([name, axis]) => {
+ const passed = axisPassed(axis);
+ return (
+ <span
+ key={name}
+ className={cn(
+ "inline-flex h-5 items-center gap-1 rounded-md border px-1.5 font-mono text-[10.5px]",
+ passed === true && "border-emerald-500/40 text-emerald-600 dark:text-emerald-400",
+ passed === false && "border-destructive/40 text-destructive",
+ passed === null && "border-border text-muted-foreground",
+ )}
+ >
+ {passed === true ? <CheckCircle2 className="h-3 w-3" /> : passed === false ? <XCircle className="h-3 w-3" /> : null}
+ {name}
+ </span>
+ );
+ })}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Transcript — reasoning / tool / spawn steps from the archived stream
+// ---------------------------------------------------------------------------
+
+const STEP_TONE: Record<string, "busy" | "ok" | "error" | "warn" | "off"> = {
+ pending: "off",
+ running: "busy",
+ done: "ok",
+ failed: "error",
+ skipped: "warn",
+};
+
+function Transcript({
+ steps,
+ finalAnswer,
+ truncated,
+ dropped,
+ hasSlug,
+ loading,
+ t,
+}: {
+ steps: PlanStep[];
+ finalAnswer: string | null;
+ truncated: boolean;
+ dropped: number;
+ hasSlug: boolean;
+ loading: boolean;
+ t: T;
+}) {
+ const lanes = useMemo(() => {
+ const map = new Map<string, PlanStep[]>();
+ for (const step of steps) {
+ const key = step.task_key ?? "";
+ if (!map.has(key)) map.set(key, []);
+ map.get(key)!.push(step);
+ }
+ return [...map.entries()];
+ }, [steps]);
+
+ if (!hasSlug) return <EmptyNote>{t("subagents_view.transcript_no_dir")}</EmptyNote>;
+ if (loading) return <EmptyNote>{t("subagents_view.insight_loading")}</EmptyNote>;
+ if (steps.length === 0 && !finalAnswer) return <EmptyNote>{t("subagents_view.transcript_empty")}</EmptyNote>;
+
+ return (
+ <div>
+ {(truncated || dropped > 0) && (
+ <div className="border-b border-border px-4 py-2 text-[11px] text-amber-600 dark:text-amber-400">
+ {dropped > 0
+ ? fill(t("subagents_view.transcript_dropped"), { n: dropped })
+ : t("subagents_view.transcript_truncated")}
+ </div>
+ )}
+ {lanes.map(([key, laneSteps], laneIdx) => (
+ <div key={key || laneIdx}>
+ {lanes.length > 1 && (
+ <div className="border-b border-border bg-sheen/[0.03] px-4 py-1.5 text-[11px] font-medium text-muted-foreground">
+ {fill(t("subagents_view.transcript_lane"), { n: laneIdx + 1 })}
+ <span className="ml-2 font-mono text-muted-foreground/60">{key}</span>
+ </div>
+ )}
+ <ol className="divide-y divide-border/60">
+ {laneSteps.map((step, idx) => (
+ <TranscriptStep key={step.step_id} step={step} index={idx + 1} t={t} />
+ ))}
+ </ol>
+ </div>
+ ))}
+ {finalAnswer && (
+ <div className="border-t border-border px-4 py-3">
+ <div className="mb-1.5 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <CheckCircle2 className="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />
+ {t("subagents_view.final_answer")}
+ </div>
+ <ClampedBlock text={finalAnswer} t={t} lines={8} className="whitespace-pre-wrap text-sm text-foreground/90" />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function TranscriptStep({ step, index, t }: { step: PlanStep; index: number; t: T }) {
+ const kind = step.kind ?? "tool";
+ const Icon = kind === "reasoning" ? Brain : kind === "spawn" ? Bot : Wrench;
+ const body = step.error ?? step.output ?? null;
+ return (
+ <li className="grid grid-cols-[36px_28px_minmax(0,1fr)_110px] items-start gap-x-3 px-4 py-2.5">
+ <span className="pt-0.5 text-right font-mono text-[11px] tabular-nums text-muted-foreground/60">{index}</span>
+ <span className={cn("grid h-6 w-6 place-items-center rounded-full border border-border bg-card", kind === "reasoning" ? "text-primary" : "text-muted-foreground")}>
+ <Icon className="h-3.5 w-3.5" />
+ </span>
+ <div className="min-w-0">
+ <div className={cn("text-sm", kind === "reasoning" ? "text-foreground/85" : "font-mono text-[13px] text-foreground")}>
+ {kind === "reasoning" ? (
+ <ClampedBlock text={step.output ?? step.name} t={t} lines={3} />
+ ) : (
+ <>
+ {step.tool_name && <span className="mr-2 text-muted-foreground">{step.tool_name}</span>}
+ <span className="break-all">{step.name}</span>
+ </>
+ )}
+ </div>
+ {kind !== "reasoning" && body && (
+ <ClampedBlock
+ text={body}
+ t={t}
+ lines={2}
+ className={cn("mt-0.5 whitespace-pre-wrap font-mono text-[12px]", step.error ? "text-destructive" : "text-muted-foreground")}
+ />
+ )}
+ {step.writes && step.writes.length > 0 && (
+ <div className="mt-0.5 font-mono text-[11px] text-muted-foreground/70">
+ {fill(t("subagents_view.step_writes"), { path: step.writes.join(", ") })}
+ </div>
+ )}
+ </div>
+ <div className="flex justify-end">
+ {kind !== "reasoning" && (
+ <StatusDot tone={STEP_TONE[step.status] ?? "off"} pulse={step.status === "running"} label={t(`subagents_view.step_status.${step.status}`)} />
+ )}
+ </div>
+ </li>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Review — the critic's verdicts and the corrections it demanded
+// ---------------------------------------------------------------------------
+
+function Review({ outcome, t }: { outcome: AgentOutcome; t: T }) {
+ if (outcome.verdicts.length === 0 && !outcome.lastCorrection) {
+ return <EmptyNote>{t("subagents_view.review_empty")}</EmptyNote>;
+ }
+ return (
+ <div className="divide-y divide-border/60">
+ {outcome.verdicts.map((v, idx) => {
+ const tone: StoryTone = v.verdict === "approve" ? "ok" : v.verdict === "revise" ? "warn" : "error";
+ return (
+ <div key={`${v.worker_id}-${v.iteration}-${idx}`} className="px-4 py-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={cn("rounded-md border px-1.5 py-0.5 font-mono text-[10.5px] uppercase tracking-wider", TONE_RING[tone], TONE_TEXT[tone])}>
+ {t(`subagents_view.verdict.${v.verdict}`)}
+ </span>
+ <span className="text-[11px] text-muted-foreground">
+ {fill(t("subagents_view.iteration_short"), { n: v.iteration + 1 })} · {Math.round(v.confidence * 100)}%
+ </span>
+ </div>
+ <p className="mt-1.5 text-sm text-foreground/90">{v.summary}</p>
+ <ul className="mt-2 space-y-1">
+ {Object.entries(v.axes ?? {}).map(([name, axis]) => {
+ const passed = axisPassed(axis);
+ const evidence = (axis.evidence ?? []).filter((e): e is string => typeof e === "string");
+ return (
+ <li key={name} className="text-xs">
+ <span className={cn("mr-2 inline-flex items-center gap-1 font-mono", passed === true ? TONE_TEXT.ok : passed === false ? TONE_TEXT.error : "text-muted-foreground")}>
+ {passed === true ? <CheckCircle2 className="h-3 w-3" /> : passed === false ? <XCircle className="h-3 w-3" /> : <CircleAlert className="h-3 w-3" />}
+ {name}
+ </span>
+ {evidence.length > 0 && (
+ <span className="text-muted-foreground">{evidence.join(" · ")}</span>
+ )}
+ {axis.notes && <span className="ml-1 italic text-muted-foreground">{String(axis.notes)}</span>}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+ })}
+ {outcome.lastCorrection && (
+ <div className="px-4 py-3">
+ <div className="flex items-center gap-2 text-xs font-medium text-amber-600 dark:text-amber-400">
+ <AlertTriangle className="h-3.5 w-3.5" />
+ {outcome.lastCorrection.next_model
+ ? fill(t("subagents_view.story.correction_model"), { model: outcome.lastCorrection.next_model })
+ : t("subagents_view.story.correction")}
+ </div>
+ <p className="mt-1 whitespace-pre-wrap text-sm text-foreground/90">{outcome.lastCorrection.correction_instruction}</p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Output — summary, final answer, deliverables
+// ---------------------------------------------------------------------------
+
+function Output({
+ outcome,
+ finalAnswer,
+ artifacts,
+ truncated,
+ slug,
+ onOpenOutput,
+ t,
+}: {
+ outcome: AgentOutcome;
+ finalAnswer: string | null;
+ artifacts: MissionArtifact[];
+ truncated: boolean;
+ slug: string | null;
+ onOpenOutput: (slug: string) => void;
+ t: T;
+}) {
+ if (!outcome.summary && !finalAnswer && artifacts.length === 0) {
+ return <EmptyNote>{t("subagents_view.output_empty")}</EmptyNote>;
+ }
+ return (
+ <div className="divide-y divide-border/60">
+ {outcome.summary && (
+ <div className="px-4 py-3">
+ <div className="mb-1 text-xs font-medium text-muted-foreground">{t("subagents_view.line_summary")}</div>
+ <p className="text-sm text-foreground/90">{outcome.summary}</p>
+ </div>
+ )}
+ {finalAnswer && (
+ <div className="px-4 py-3">
+ <div className="mb-1 text-xs font-medium text-muted-foreground">{t("subagents_view.final_answer")}</div>
+ <ClampedBlock text={finalAnswer} t={t} lines={10} className="whitespace-pre-wrap text-sm text-foreground/90" />
+ </div>
+ )}
+ {artifacts.length > 0 && (
+ <div>
+ <div className="flex items-center justify-between gap-3 px-4 py-2.5">
+ <div className="text-xs font-medium text-muted-foreground">
+ {fill(t("subagents_view.deliverables"), { n: artifacts.length })}
+ {truncated && <span className="ml-2 text-amber-600 dark:text-amber-400">{t("subagents_view.deliverables_truncated")}</span>}
+ </div>
+ {slug && (
+ <SoftButton onClick={() => onOpenOutput(slug)}>
+ <ArrowUpRight className="h-3.5 w-3.5" />
+ {t("subagents_view.action_open_output")}
+ </SoftButton>
+ )}
+ </div>
+ <ul className="divide-y divide-border/60 border-t border-border/60">
+ {artifacts.map((a) => (
+ <li key={a.path} className="px-4 py-2.5">
+ <div className="flex items-center gap-2 text-sm">
+ <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate font-mono text-[13px]" title={a.deliverable_path}>{a.deliverable_path}</span>
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{formatBytes(a.size)}</span>
+ </div>
+ {a.content && (
+ <ClampedBlock
+ text={a.content}
+ t={t}
+ lines={4}
+ className="mt-1 whitespace-pre-wrap rounded-md bg-sheen/[0.04] px-2.5 py-1.5 font-mono text-[12px] text-muted-foreground"
+ />
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Small shared pieces
+// ---------------------------------------------------------------------------
+
+function LiveToolCall({ call, t }: { call: ToolCallEntry; t: T }) {
+ const tone: Record<ToolCallEntry["status"], "busy" | "ok" | "error"> = { running: "busy", completed: "ok", failed: "error" };
+ return (
+ <div className="grid grid-cols-[minmax(0,1fr)_64px_96px] items-center gap-3 px-4 py-2.5 text-sm">
+ <div className="min-w-0">
+ <div className="truncate font-medium text-foreground">{call.tool_name || t("subagents_view.tool_unnamed")}</div>
+ <div className="truncate text-xs text-muted-foreground" title={call.args_preview}>
+ {call.error || call.args_preview || call.output_preview || "—"}
+ </div>
+ </div>
+ <div className="text-right text-xs tabular-nums text-muted-foreground">
+ {call.duration_ms != null ? formatDuration(call.duration_ms) : "—"}
+ </div>
+ <div className="flex justify-end">
+ <StatusDot tone={tone[call.status]} pulse={call.status === "running"} label={t(`subagents_view.tool_status.${call.status}`)} />
+ </div>
+ </div>
+ );
+}
+
+const CLAMP_CLASS: Record<number, string> = {
+ 2: "line-clamp-2",
+ 3: "line-clamp-3",
+ 4: "line-clamp-4",
+ 8: "line-clamp-[8]",
+ 10: "line-clamp-[10]",
+};
+
+/** Text that clamps to `lines` and expands on a click — the page's own "more". */
+function ClampedBlock({ text, t, lines, className }: { text: string; t: T; lines: 2 | 3 | 4 | 8 | 10; className?: string }) {
+ const [open, setOpen] = useState(false);
+ // Roughly: a text that cannot overflow needs no toggle. Measured by length
+ // and line breaks rather than layout so the list never re-flows on mount.
+ const long = text.length > lines * 90 || text.split("\n").length > lines;
+ return (
+ <div className={cn("min-w-0", className)}>
+ <div className={cn("break-words", !open && long && CLAMP_CLASS[lines])}>{text}</div>
+ {long && (
+ <button type="button" onClick={() => setOpen((v) => !v)} className="mt-0.5 text-xs text-primary hover:underline">
+ {open ? t("subagents_view.see_less") : t("subagents_view.see_more")}
+ </button>
+ )}
+ </div>
+ );
+}
+
+function EmptyNote({ children }: { children: React.ReactNode }) {
+ return <div className="px-4 py-8 text-center text-sm text-muted-foreground">{children}</div>;
+}
+
+function Notice({ tone, children }: { tone: "warn" | "error"; children: React.ReactNode }) {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 rounded-xl border px-3.5 py-2.5 text-sm",
+ tone === "error"
+ ? "border-destructive/30 bg-destructive/10 text-destructive"
+ : "border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",
+ )}
+ >
+ <CircleAlert className="h-4 w-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">{children}</span>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx
index decdb85cb3..af681ad2d0 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx
@@ -1,5 +1,5 @@
import type { ComponentProps } from "react";
-import { cleanup, render, screen, within } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { DepartureBoard } from "./DepartureBoard";
@@ -75,6 +75,53 @@ describe("DepartureBoard cancellation status", () => {
});
});
+describe("DepartureBoard row click", () => {
+ it("opens the run's insight page from the row and keeps the chevron for the inline peek", () => {
+ const opened: string[] = [];
+ // A finished run with tool calls: it has a drilldown but is not
+ // auto-expanded (only running rows are), so the chevron's effect is visible.
+ const agent = node({
+ trace_id: "m-live",
+ status: "completed",
+ utterance: "Live mission",
+ tool_calls: [
+ { tool_name: "Read", args_preview: "x.py", started_ns: 1, status: "completed" },
+ ],
+ });
+ render(<DepartureBoard agents={[agent]} onOpen={(a) => opened.push(a.trace_id)} />);
+
+ const row = screen.getByRole("row", { name: "Live mission" });
+ expect(screen.queryByText("x.py")).toBeNull();
+ fireEvent.click(row);
+ expect(opened).toEqual(["m-live"]);
+ expect(screen.queryByText("x.py")).toBeNull();
+
+ // The chevron is its own control: it expands the row in place and does
+ // NOT navigate — clicking it must not add a second "opened" entry.
+ fireEvent.click(within(row).getByRole("button", { name: /expand row/i }));
+ expect(opened).toEqual(["m-live"]);
+ expect(screen.getByText("x.py")).toBeTruthy();
+ });
+
+ it("shows the archived terminal reason in the result column of a failed row", () => {
+ render(
+ <DepartureBoard
+ agents={[
+ node({
+ trace_id: "m-quota",
+ status: "failed",
+ utterance: "Quota mission",
+ error: null,
+ outcome_reason: "review_time_budget_exhausted",
+ }),
+ ]}
+ />,
+ );
+ const row = screen.getByRole("row", { name: /quota mission/i });
+ expect(within(row).getByText("The review ran out of time")).toBeTruthy();
+ });
+});
+
describe("DepartureBoard empty state", () => {
it("says nothing is running rather than showing an empty table", () => {
render(<DepartureBoard agents={[]} />);
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
index 42f0347d0f..b5038b7aab 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
@@ -52,6 +52,8 @@ import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
import { fill, useT } from "@/i18n";
import { failureLabel } from "./failureLabel";
+import { formatDuration } from "./format";
+import { REASON_LABEL_KEYS, splitReason } from "./outcome";
// The four run states map onto the shared StatusDot tones: a running agent is
// the app's own "busy" (brand primary), a finished one is the token set's
@@ -70,13 +72,7 @@ const TOOL_STATUS_TONE: Record<ToolCallEntry["status"], "busy" | "ok" | "error">
failed: "error",
};
-function formatRelative(ms: number): string {
- if (!Number.isFinite(ms) || ms < 0) return "—";
- if (ms < 1000) return `${Math.floor(ms)}ms`;
- if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;
- if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;
- return `${Math.floor(ms / 3_600_000)}h`;
-}
+const formatRelative = formatDuration;
function startedMs(node: SubAgentNode): number {
return node.started_ns > 1_000_000_000_000_000
@@ -105,6 +101,15 @@ function taskLabel(node: SubAgentNode, t: (key: string) => string): string {
return node.utterance || node.context_hints.at(0) || node.prompts.at(0) || t("subagents_view.task_none");
}
+/** Plain-language label for a mission-level terminal reason, else the raw token. */
+function outcomeReasonLabel(node: SubAgentNode, t: (key: string) => string): string | null {
+ const { head, tail } = splitReason(node.outcome_reason);
+ if (!head) return null;
+ const key = REASON_LABEL_KEYS[head];
+ const label = key ? t(key) : head;
+ return tail ? `${label} (${tail})` : label;
+}
+
function resultLabel(node: SubAgentNode, t: (key: string) => string): string {
const failure = failureLabel(node, t);
if (failure) return failure;
@@ -112,6 +117,10 @@ function resultLabel(node: SubAgentNode, t: (key: string) => string): string {
if (summary) return summary.replace("[summary] ", "");
if (node.status === "completed") return t("subagents_view.result_done");
if (node.status === "running") return t("subagents_view.result_running");
+ // The outputs archive knows WHY a past run ended ("provider quota", "the
+ // reviewer ran out of time") where the mission list only knows THAT it did.
+ const reason = outcomeReasonLabel(node, t);
+ if (reason) return reason;
// A row from the durable record carries no error text, so without these two
// a failed or cancelled past run showed an em dash next to a red status —
// as if the outcome were unknown rather than stated one column to the left.
@@ -126,6 +135,8 @@ interface Props {
health?: SectionHealth | null;
/** The durable half could not be loaded; the live half still renders. */
historyError?: boolean;
+ /** A row was clicked: open that run's insight page. */
+ onOpen?: (agent: SubAgentNode) => void;
}
export function DepartureBoard({
@@ -133,6 +144,7 @@ export function DepartureBoard({
snapshotError = null,
health = null,
historyError = false,
+ onOpen,
}: Props) {
const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
@@ -326,6 +338,7 @@ export function DepartureBoard({
nowMs={nowMs}
expanded={expanded.has(agent.trace_id)}
onToggle={() => toggle(agent.trace_id)}
+ onOpen={onOpen ? () => onOpen(agent) : undefined}
t={t}
/>
))
@@ -378,6 +391,7 @@ function AgentRow({
nowMs,
expanded,
onToggle,
+ onOpen,
t,
}: {
agent: SubAgentNode;
@@ -385,6 +399,7 @@ function AgentRow({
nowMs: number;
expanded: boolean;
onToggle: () => void;
+ onOpen?: () => void;
t: (key: string) => string;
}) {
const assistantName = useEventStore((s) => s.assistantName);
@@ -392,21 +407,36 @@ function AgentRow({
const task = taskLabel(agent, t);
const result = resultLabel(agent, t);
+ // The row itself opens the run's insight page; the chevron keeps the quick
+ // inline peek at live tool calls for a run that is still working. Without an
+ // `onOpen` (the board rendered on its own) the row falls back to the peek.
+ const rowClick = onOpen ?? (hasDrilldown ? onToggle : undefined);
+
return (
<Fragment>
<TableRow
columns={columns}
- onClick={hasDrilldown ? onToggle : undefined}
+ onClick={rowClick}
selected={expanded}
ariaLabel={task}
>
- <Cell className="text-muted-foreground">
+ <Cell className="text-muted-foreground" stop={hasDrilldown && !!onOpen}>
{hasDrilldown ? (
- expanded ? (
- <ChevronDown className="h-4 w-4" />
- ) : (
- <ChevronRight className="h-4 w-4" />
- )
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={expanded}
+ aria-label={t("subagents_view.col_expand")}
+ className="grid h-6 w-6 place-items-center rounded-md hover:bg-accent hover:text-foreground"
+ >
+ {expanded ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </button>
+ ) : onOpen ? (
+ <ChevronRight className="h-4 w-4 opacity-0 transition-opacity group-hover:opacity-60" />
) : null}
</Cell>
<Cell>
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/format.ts b/jarvis/ui/web/frontend/src/views/sub-agents/format.ts
new file mode 100644
index 0000000000..741d3edf04
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/format.ts
@@ -0,0 +1,54 @@
+/** Small number/time formatters the agent board and the insight page share. */
+
+/** `850ms`, `12s`, `5m`, `2h` — the board's compact duration. */
+export function formatDuration(ms: number): string {
+ if (!Number.isFinite(ms) || ms < 0) return "—";
+ if (ms < 1000) return `${Math.floor(ms)}ms`;
+ if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;
+ if (ms < 3_600_000) {
+ const m = Math.floor(ms / 60_000);
+ const s = Math.floor((ms % 60_000) / 1000);
+ return s > 0 && m < 10 ? `${m}m ${s}s` : `${m}m`;
+ }
+ const h = Math.floor(ms / 3_600_000);
+ const m = Math.floor((ms % 3_600_000) / 60_000);
+ return m > 0 ? `${h}h ${m}m` : `${h}h`;
+}
+
+/** `+0.0s`, `+12s`, `+3m 05s` — an offset from the run's start. */
+export function formatOffset(ms: number): string {
+ if (!Number.isFinite(ms) || ms < 0) return "+0s";
+ if (ms < 60_000) return `+${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
+ const m = Math.floor(ms / 60_000);
+ const s = Math.floor((ms % 60_000) / 1000);
+ return `+${m}m ${String(s).padStart(2, "0")}s`;
+}
+
+/** Date + time in the viewer's locale — "24 Aug, 19:13". */
+export function formatClock(ms: number | null | undefined, locale?: string): string {
+ if (!ms || !Number.isFinite(ms)) return "—";
+ try {
+ return new Intl.DateTimeFormat(locale, {
+ day: "numeric",
+ month: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(ms));
+ } catch {
+ return new Date(ms).toISOString().slice(0, 16).replace("T", " ");
+ }
+}
+
+/** `1.2 KB`, `26 KB`, `3.1 MB`. */
+export function formatBytes(size: number): string {
+ if (!Number.isFinite(size) || size < 0) return "—";
+ if (size < 1024) return `${size} B`;
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(size < 10 * 1024 ? 1 : 0)} KB`;
+ return `${(size / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+/** `$0.0123` — costs stay in dollars because that is what providers bill in. */
+export function formatUsd(value: number): string {
+ if (!Number.isFinite(value) || value <= 0) return "—";
+ return `$${value < 0.01 ? value.toFixed(4) : value.toFixed(2)}`;
+}
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts b/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts
index 8f7778e368..fdeaf3df88 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts
@@ -17,9 +17,17 @@
*
* A run present in both wins as its LIVE node, because only that one has the
* tool calls and the running clock.
+ *
+ * A third, optional source is the outputs archive (`/api/outputs`): it knows
+ * the run's terminal reason, its one-line summary and — most usefully — the
+ * slug of the directory the deliverables live in. Where a row's mission is in
+ * that list, the row learns its reason, summary and output slug; where it is
+ * not (the directory was cleaned up), the row keeps what it had.
*/
import type { MissionSummary } from "@/types/missions";
import type { SubAgentNode } from "@/store/jarvisAgents";
+import type { OutputSummary } from "@/hooks/useOutputs";
+import { missionIdFromTraceId } from "./outcome";
/** How many past runs the board carries. The table is a board, not an archive. */
export const HISTORY_LIMIT = 50;
@@ -67,6 +75,7 @@ export function missionToNode(mission: MissionSummary): SubAgentNode {
return {
trace_id: normalizeTraceId(mission.id),
+ mission_id: mission.id,
kind: "jarvis_agent",
name: "",
status,
@@ -95,6 +104,33 @@ export function missionToNode(mission: MissionSummary): SubAgentNode {
};
}
+/**
+ * What the outputs archive knows about a row, keyed by the dash-stripped id.
+ * Only the fields the board and the insight page read are copied over.
+ */
+function outputsByTrace(outputs: OutputSummary[]): Map<string, OutputSummary> {
+ const map = new Map<string, OutputSummary>();
+ for (const o of outputs) {
+ if (o.mission_id) map.set(normalizeTraceId(o.mission_id), o);
+ }
+ return map;
+}
+
+function enrich(node: SubAgentNode, output: OutputSummary | undefined): SubAgentNode {
+ const next: SubAgentNode = {
+ ...node,
+ mission_id: node.mission_id ?? missionIdFromTraceId(node.trace_id),
+ };
+ if (!output) return next;
+ next.output_slug = output.slug;
+ next.outcome_reason = output.terminal_reason ?? output.error ?? null;
+ const hasSummary = node.prompts.some((p) => p.startsWith("[summary] "));
+ if (output.summary && !hasSummary) {
+ next.prompts = [...node.prompts, `[summary] ${output.summary}`];
+ }
+ return next;
+}
+
/**
* Live nodes first, then any past run the registry no longer holds.
*
@@ -105,6 +141,7 @@ export function mergeBoardRows(
live: SubAgentNode[],
missions: MissionSummary[],
limit: number = HISTORY_LIMIT,
+ outputs: OutputSummary[] = [],
): SubAgentNode[] {
const seen = new Set(live.map((n) => normalizeTraceId(n.trace_id)));
const history: SubAgentNode[] = [];
@@ -116,5 +153,8 @@ export function mergeBoardRows(
history.push(missionToNode(mission));
}
- return [...live, ...history].sort((a, b) => b.started_ns - a.started_ns);
+ const byTrace = outputsByTrace(outputs);
+ return [...live, ...history]
+ .map((n) => enrich(n, byTrace.get(normalizeTraceId(n.trace_id))))
+ .sort((a, b) => b.started_ns - a.started_ns);
}
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/outcome.test.ts b/jarvis/ui/web/frontend/src/views/sub-agents/outcome.test.ts
new file mode 100644
index 0000000000..79a35a5f83
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/outcome.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, it } from "vitest";
+
+import type { AnyPayload, EventEnvelope } from "@/types/missions";
+import {
+ buildStory,
+ classifyNote,
+ deriveOutcome,
+ missionIdFromTraceId,
+ splitReason,
+} from "./outcome";
+
+let seq = 0;
+function env(
+ payload: AnyPayload,
+ over: Partial<Omit<EventEnvelope, "payload">> = {},
+): EventEnvelope {
+ seq += 1;
+ return {
+ event_id: `e${seq}`,
+ seq,
+ mission_id: "m1",
+ parent_event_id: null,
+ worker_id: null,
+ source_actor: "kontrollierer",
+ ts_ms: 1_000 + seq * 1_000,
+ schema_version: 1,
+ ...over,
+ payload,
+ };
+}
+
+/** The event stream of a real quota failure (2026-08-10, mission 019fecaa). */
+function quotaFailure(): EventEnvelope[] {
+ const wid = "019fecaa-5a92::019fecaa-5aa5::iter0";
+ return [
+ env({ event_type: "MissionDispatched", prompt: "Build the page", parent_mission_id: null, priority: 0, language: "en" }),
+ env({ event_type: "MissionStateChanged", from_state: "PENDING", to_state: "RUNNING", reason: "kontrollierer-start" }),
+ env({ event_type: "MissionPlanReady", plan: [{}], n_workers: 1, expected_output: "Single-step plan" }),
+ env(
+ { event_type: "WorkerSpawned", worker_id: wid, step: {}, pid: 0, cli: "claude", model: "", worktree: "C:/wt", session_id: "s1" },
+ { worker_id: wid },
+ ),
+ env(
+ { event_type: "WorkerProgress", worker_id: wid, pct: null, note: "You've reached your limit.", stalled: false, tokens_so_far: 0, cost_so_far: 0 },
+ { worker_id: wid, source_actor: "worker" },
+ ),
+ env(
+ { event_type: "WorkerKilled", worker_id: wid, reason: "budget", error_class: "provider_quota", error_detail: "You've reached your limit." },
+ { worker_id: wid },
+ ),
+ env({
+ event_type: "MissionFailed",
+ reason: "task_error",
+ error_class: "provider_quota",
+ last_state: "CRITIQUING",
+ partial_artifacts: [],
+ error_detail: "You've reached your limit.",
+ failed_provider: "claude",
+ }),
+ ];
+}
+
+describe("deriveOutcome", () => {
+ it("reads a provider-quota failure into reason, class, detail and the kill", () => {
+ const out = deriveOutcome(quotaFailure(), "en");
+ expect(out.terminal).toBe("failed");
+ expect(out.reason).toBe("task_error");
+ expect(out.error_class).toBe("provider_quota");
+ expect(out.error_detail).toBe("You've reached your limit.");
+ expect(out.failed_provider).toBe("claude");
+ expect(out.last_state).toBe("CRITIQUING");
+ expect(out.kills).toHaveLength(1);
+ expect(out.kills[0].reason).toBe("budget");
+ expect(out.workers).toHaveLength(1);
+ expect(out.workers[0].cli).toBe("claude");
+ expect(out.workers[0].ended_reason).toBe("budget");
+ expect(out.planWorkers).toBe(1);
+ });
+
+ it("keeps the reviewer's last verdict and correction on a review failure", () => {
+ const wid = "m::t::iter1";
+ const events = [
+ env({ event_type: "MissionDispatched", prompt: "x", parent_mission_id: null, priority: 0, language: "de" }),
+ env(
+ {
+ event_type: "CriticVerdictReady",
+ worker_id: wid,
+ verdict: "revise",
+ summary: "The review document is missing.",
+ confidence: 0.8,
+ axes: { correctness: { status: "fail", evidence: ["log:no file"] } },
+ iteration: 1,
+ },
+ { source_actor: "critic", worker_id: wid },
+ ),
+ env(
+ { event_type: "WorkerCorrectionRequired", worker_id: wid, correction_instruction: "Write the document.", iteration: 1, next_model: "opus" },
+ { source_actor: "critic", worker_id: wid },
+ ),
+ env({
+ event_type: "MissionFailed",
+ reason: "review_time_budget_exhausted",
+ error_class: null,
+ last_state: "CRITIQUING",
+ partial_artifacts: ["C:/out/diff.iter1.patch"],
+ }),
+ ];
+ const out = deriveOutcome(events, "de");
+ expect(out.reason).toBe("review_time_budget_exhausted");
+ expect(out.lastVerdict?.verdict).toBe("revise");
+ expect(out.lastCorrection?.next_model).toBe("opus");
+ expect(out.revisions).toBe(1);
+ expect(out.partial_artifacts).toEqual(["C:/out/diff.iter1.patch"]);
+ });
+
+ it("picks the summary in the mission's language on approval", () => {
+ const events = [
+ env({
+ event_type: "MissionApproved",
+ result_uri: "file:///out",
+ tokens_used: 10,
+ cost_usd: 0.02,
+ wall_ms: 5000,
+ summary_de: "Fertig.", // i18n-allow: German runtime-output fixture
+ summary_en: "Done.",
+ }),
+ ];
+ expect(deriveOutcome(events, "de").summary).toBe("Fertig."); // i18n-allow
+ expect(deriveOutcome(events, "en").summary).toBe("Done.");
+ expect(deriveOutcome(events, "en").cost_usd).toBe(0.02);
+ });
+
+ it("has no terminal for a run still in flight", () => {
+ const out = deriveOutcome(quotaFailure().slice(0, 4), "en");
+ expect(out.terminal).toBeNull();
+ expect(out.workers[0].ended_ms).toBeNull();
+ });
+});
+
+describe("buildStory", () => {
+ it("drops state-machine chatter and keeps the narrative in order", () => {
+ const story = buildStory(quotaFailure());
+ expect(story.map((s) => s.kind)).toEqual([
+ "dispatched",
+ "plan",
+ "spawn",
+ "narration",
+ "killed",
+ "failed",
+ ]);
+ const killed = story.find((s) => s.kind === "killed")!;
+ expect(killed.meta.reason).toBe("budget");
+ expect(killed.tone).toBe("error");
+ expect(story.at(-1)!.meta.provider).toBe("claude");
+ });
+
+ it("tells a tool note apart from the worker's own commentary", () => {
+ const wid = "m::t::iter0";
+ const note = (text: string) =>
+ env(
+ { event_type: "WorkerProgress", worker_id: wid, pct: null, note: text, stalled: false, tokens_so_far: 0, cost_so_far: 0 },
+ { worker_id: wid, source_actor: "worker" },
+ );
+ const story = buildStory([
+ note("Grep: jarvis/ui/web/frontend/src"),
+ note("Ich schaue mir zuerst den Arbeitsbereich an."), // i18n-allow: worker narration fixture
+ note("PowerShell: git diff AGENTS.md"),
+ ]);
+ expect(story.map((s) => [s.kind, s.tool])).toEqual([
+ ["tool", "Grep"],
+ ["narration", null],
+ ["tool", "PowerShell"],
+ ]);
+ expect(story[0].text).toBe("jarvis/ui/web/frontend/src");
+ expect(story[0].iteration).toBe(0);
+ });
+});
+
+describe("classifyNote", () => {
+ it("does not mistake a sentence with a colon for a tool", () => {
+ expect(classifyNote("Note: the build passed").kind).toBe("narration");
+ expect(classifyNote("Read: C:/x.py").kind).toBe("tool");
+ expect(classifyNote("WebFetch: https://example.org").tool).toBe("WebFetch");
+ });
+});
+
+describe("splitReason / missionIdFromTraceId", () => {
+ it("splits a reason with a detail tail", () => {
+ expect(splitReason("decompose_failed: no brain")).toEqual({ head: "decompose_failed", tail: "no brain" });
+ expect(splitReason("task_error")).toEqual({ head: "task_error", tail: null });
+ expect(splitReason(null)).toEqual({ head: null, tail: null });
+ });
+
+ it("re-dashes a stripped uuid and leaves anything else alone", () => {
+ expect(missionIdFromTraceId("019fecaa5a927360a784829281639cf6")).toBe(
+ "019fecaa-5a92-7360-a784-829281639cf6",
+ );
+ expect(missionIdFromTraceId("019fecaa-5a92-7360-a784-829281639cf6")).toBe(
+ "019fecaa-5a92-7360-a784-829281639cf6",
+ );
+ expect(missionIdFromTraceId("abc")).toBe("abc");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/outcome.ts b/jarvis/ui/web/frontend/src/views/sub-agents/outcome.ts
new file mode 100644
index 0000000000..0186700712
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/outcome.ts
@@ -0,0 +1,516 @@
+/**
+ * What happened to one agent run — derived from its mission event stream.
+ *
+ * The board row can only say "Failed". The durable event stream behind it
+ * says WHY: which worker was killed and for what reason, what the provider
+ * answered, what the reviewer objected to, how many revision rounds ran, and
+ * what was left behind. This module reads that stream ONCE into two plain
+ * shapes the insight page renders:
+ *
+ * - `deriveOutcome` — the verdict: terminal event, reason, error class, the
+ * upstream error text, kills, the last review verdict and correction, the
+ * workers that ran. Everything a "what went wrong" paragraph needs.
+ * - `buildStory` — the run as it unfolded: dispatch → plan → worker spawn →
+ * the worker's own narration and tool calls (from `WorkerProgress` notes)
+ * → draft → review → correction → kill → terminal. State-machine chatter
+ * (PENDING→RUNNING, RUNNING→CRITIQUING) is dropped: the entries around it
+ * already tell that part of the story.
+ *
+ * Pure functions over the typed envelopes in `types/missions.ts`; no fetch,
+ * no store, so every branch is unit-testable with hand-built events.
+ */
+import type {
+ CriticVerdictReady,
+ EventEnvelope,
+ MissionFailed,
+ WorkerCorrectionRequired,
+ WorkerKilled,
+} from "@/types/missions";
+
+export type Terminal = "approved" | "failed" | "cancelled" | "timed_out";
+
+export interface WorkerLane {
+ worker_id: string;
+ iteration: number;
+ cli: string;
+ model: string;
+ session_id: string | null;
+ spawned_ms: number;
+ ended_ms: number | null;
+ /** The `WorkerKilled.reason` when the worker was killed, else null. */
+ ended_reason: string | null;
+ /** Narration + tool notes this worker reported. */
+ notes: number;
+ tool_notes: number;
+}
+
+export interface AgentOutcome {
+ terminal: Terminal | null;
+ /** Raw mission-level reason (`task_error`, `critic_loop_exhausted`, …). */
+ reason: string | null;
+ error_class: string | null;
+ error_detail: string | null;
+ failed_provider: string | null;
+ last_state: string | null;
+ partial_artifacts: string[];
+ /** The approved run's summary in the mission's own language. */
+ summary: string | null;
+ result_uri: string | null;
+ cascade: boolean;
+ deadline_ms: number | null;
+ last_progress_ms: number | null;
+ wall_ms: number | null;
+ tokens_used: number;
+ cost_usd: number;
+ kills: WorkerKilled[];
+ verdicts: CriticVerdictReady[];
+ lastVerdict: CriticVerdictReady | null;
+ lastCorrection: WorkerCorrectionRequired | null;
+ workers: WorkerLane[];
+ revisions: number;
+ planWorkers: number | null;
+ expectedOutput: string | null;
+}
+
+export type StoryKind =
+ | "dispatched"
+ | "plan"
+ | "spawn"
+ | "narration"
+ | "tool"
+ | "draft"
+ | "verdict"
+ | "correction"
+ | "killed"
+ | "budget"
+ | "approved"
+ | "failed"
+ | "cancelled"
+ | "timed_out";
+
+export type StoryTone = "neutral" | "busy" | "ok" | "warn" | "error";
+
+export interface StoryEntry {
+ id: string;
+ ts_ms: number;
+ kind: StoryKind;
+ tone: StoryTone;
+ /** The raw text the entry carries: a note, a summary, an instruction, an error. */
+ text: string;
+ worker_id: string | null;
+ iteration: number | null;
+ /** Tool name for `tool` entries (`Read`, `Grep`, `PowerShell` …). */
+ tool: string | null;
+ /** Extra facts to print as small labels (cli, model, reason, …). */
+ meta: Record<string, string>;
+ verdict: CriticVerdictReady | null;
+}
+
+/** Mission-level failure reasons the orchestrator emits → i18n key. */
+export const REASON_LABEL_KEYS: Readonly<Record<string, string>> = {
+ task_error: "subagents_view.reason.task_error",
+ attempts_timed_out: "subagents_view.reason.attempts_timed_out",
+ budget_exceeded: "subagents_view.reason.budget_exceeded",
+ worktree_setup_failed: "subagents_view.reason.worktree_setup_failed",
+ critic_unavailable: "subagents_view.reason.critic_unavailable",
+ critic_rejected: "subagents_view.reason.critic_rejected",
+ review_time_budget_exhausted: "subagents_view.reason.review_time_budget_exhausted",
+ critic_loop_exhausted: "subagents_view.reason.critic_loop_exhausted",
+ decompose_failed: "subagents_view.reason.decompose_failed",
+ interrupted: "subagents_view.reason.interrupted",
+ mission_timed_out: "subagents_view.reason.mission_timed_out",
+ ui_cancel: "subagents_view.reason.ui_cancel",
+ user_cancelled: "subagents_view.reason.ui_cancel",
+ parent_cancelled: "subagents_view.reason.parent_cancelled",
+};
+
+/** `WorkerKilled.reason` vocabulary → i18n key. */
+export const KILL_REASON_LABEL_KEYS: Readonly<Record<string, string>> = {
+ timeout: "subagents_view.kill.timeout",
+ user: "subagents_view.kill.user",
+ budget: "subagents_view.kill.budget",
+ parent_cancelled: "subagents_view.kill.parent_cancelled",
+ injection_detected: "subagents_view.kill.injection_detected",
+ path_guard: "subagents_view.kill.path_guard",
+ worker_error: "subagents_view.kill.worker_error",
+};
+
+/**
+ * A mission reason may carry a detail after a colon (`decompose_failed: …`).
+ * The label is looked up on the head; the tail is returned for display.
+ */
+export function splitReason(reason: string | null | undefined): {
+ head: string | null;
+ tail: string | null;
+} {
+ const raw = (reason ?? "").trim();
+ if (!raw) return { head: null, tail: null };
+ const idx = raw.indexOf(":");
+ if (idx === -1) return { head: raw, tail: null };
+ return { head: raw.slice(0, idx).trim(), tail: raw.slice(idx + 1).trim() || null };
+}
+
+/**
+ * Registry trace ids are the mission UUID with its dashes stripped. The REST
+ * detail endpoints want the dashed form, so put them back for a 32-hex id and
+ * pass anything else through untouched.
+ */
+export function missionIdFromTraceId(traceId: string): string {
+ const compact = traceId.replace(/-/g, "");
+ if (!/^[0-9a-f]{32}$/i.test(compact)) return traceId;
+ return [
+ compact.slice(0, 8),
+ compact.slice(8, 12),
+ compact.slice(12, 16),
+ compact.slice(16, 20),
+ compact.slice(20),
+ ].join("-");
+}
+
+// A worker progress note is either the worker's own commentary ("Ich schaue
+// mir zuerst den Arbeitsbereich an …") or a tool call the runtime rendered
+// as "Tool: argument". The known tool families are matched by name; any other
+// single PascalCase word before a colon is treated as a tool too, so a new
+// runtime tool still reads as an action rather than as prose.
+const KNOWN_TOOLS = new Set(
+ [
+ "read", "write", "edit", "multiedit", "glob", "grep", "bash", "powershell",
+ "shell", "exec", "task", "agent", "webfetch", "websearch", "notebookedit",
+ "todowrite", "apply_patch", "list", "ls", "search", "fetch", "run",
+ ].map((s) => s.toLowerCase()),
+);
+const TOOL_NOTE_RE = /^([A-Z][A-Za-z_]{1,24}):\s+(.+)$/s;
+
+export function classifyNote(note: string): {
+ kind: "tool" | "narration";
+ tool: string | null;
+ text: string;
+} {
+ const trimmed = note.trim();
+ const m = TOOL_NOTE_RE.exec(trimmed);
+ if (m) {
+ const name = m[1];
+ const known = KNOWN_TOOLS.has(name.toLowerCase());
+ // A PascalCase single word before a colon reads as a tool call; a plain
+ // sentence-initial capitalised word ("Note: …", "Hinweis: …") would too,
+ // so only the known families and CamelCase compounds count.
+ const camel = /^[A-Z][a-z]+[A-Z]/.test(name);
+ if (known || camel) return { kind: "tool", tool: name, text: m[2].trim() };
+ }
+ return { kind: "narration", tool: null, text: trimmed };
+}
+
+function iterationOf(workerId: string | null | undefined): number | null {
+ if (!workerId) return null;
+ const m = /::iter(\d+)$/.exec(workerId);
+ return m ? Number(m[1]) : null;
+}
+
+function str(v: unknown): string {
+ return typeof v === "string" ? v : v == null ? "" : String(v);
+}
+
+export function deriveOutcome(
+ events: EventEnvelope[],
+ language: string,
+): AgentOutcome {
+ const out: AgentOutcome = {
+ terminal: null,
+ reason: null,
+ error_class: null,
+ error_detail: null,
+ failed_provider: null,
+ last_state: null,
+ partial_artifacts: [],
+ summary: null,
+ result_uri: null,
+ cascade: false,
+ deadline_ms: null,
+ last_progress_ms: null,
+ wall_ms: null,
+ tokens_used: 0,
+ cost_usd: 0,
+ kills: [],
+ verdicts: [],
+ lastVerdict: null,
+ lastCorrection: null,
+ workers: [],
+ revisions: 0,
+ planWorkers: null,
+ expectedOutput: null,
+ };
+ const lanes = new Map<string, WorkerLane>();
+
+ for (const env of events) {
+ const p = env.payload;
+ switch (p.event_type) {
+ case "MissionPlanReady":
+ out.planWorkers = p.n_workers;
+ out.expectedOutput = p.expected_output || null;
+ break;
+ case "WorkerSpawned": {
+ if (!lanes.has(p.worker_id)) {
+ lanes.set(p.worker_id, {
+ worker_id: p.worker_id,
+ iteration: iterationOf(p.worker_id) ?? 0,
+ cli: str(p.cli),
+ model: str(p.model),
+ session_id: p.session_id ?? null,
+ spawned_ms: env.ts_ms,
+ ended_ms: null,
+ ended_reason: null,
+ notes: 0,
+ tool_notes: 0,
+ });
+ }
+ break;
+ }
+ case "WorkerProgress": {
+ const lane = lanes.get(p.worker_id);
+ if (lane && p.note) {
+ lane.notes += 1;
+ if (classifyNote(p.note).kind === "tool") lane.tool_notes += 1;
+ }
+ if (p.tokens_so_far) out.tokens_used = Math.max(out.tokens_used, p.tokens_so_far);
+ if (p.cost_so_far) out.cost_usd = Math.max(out.cost_usd, p.cost_so_far);
+ break;
+ }
+ case "WorkerDraftReady": {
+ if (p.tokens_used) out.tokens_used = Math.max(out.tokens_used, p.tokens_used);
+ if (p.cost_usd) out.cost_usd = Math.max(out.cost_usd, p.cost_usd);
+ break;
+ }
+ case "CriticVerdictReady":
+ out.verdicts.push(p);
+ out.lastVerdict = p;
+ break;
+ case "WorkerCorrectionRequired":
+ out.lastCorrection = p;
+ out.revisions = Math.max(out.revisions, p.iteration);
+ break;
+ case "WorkerKilled": {
+ out.kills.push(p);
+ const lane = lanes.get(p.worker_id);
+ if (lane) {
+ lane.ended_ms = env.ts_ms;
+ lane.ended_reason = p.reason;
+ }
+ if (!out.error_class && p.error_class) out.error_class = p.error_class;
+ if (!out.error_detail && p.error_detail) out.error_detail = p.error_detail;
+ break;
+ }
+ case "MissionApproved":
+ out.terminal = "approved";
+ out.summary = (language === "de" ? p.summary_de : p.summary_en) || p.summary_en || p.summary_de || null;
+ out.result_uri = p.result_uri || null;
+ out.wall_ms = p.wall_ms || null;
+ if (p.tokens_used) out.tokens_used = Math.max(out.tokens_used, p.tokens_used);
+ if (p.cost_usd) out.cost_usd = Math.max(out.cost_usd, p.cost_usd);
+ break;
+ case "MissionFailed": {
+ const f: MissionFailed = p;
+ out.terminal = "failed";
+ out.reason = f.reason || null;
+ out.error_class = f.error_class ?? out.error_class;
+ out.error_detail = f.error_detail ?? out.error_detail;
+ out.failed_provider = f.failed_provider ?? null;
+ out.last_state = f.last_state || null;
+ out.partial_artifacts = Array.isArray(f.partial_artifacts) ? f.partial_artifacts : [];
+ break;
+ }
+ case "MissionCancelled":
+ out.terminal = "cancelled";
+ out.reason = p.reason || null;
+ out.cascade = Boolean(p.cascade);
+ break;
+ case "MissionTimedOut":
+ out.terminal = "timed_out";
+ out.reason = "mission_timed_out";
+ out.deadline_ms = p.deadline_ms || null;
+ out.last_progress_ms = p.last_progress_ms || null;
+ break;
+ default:
+ break;
+ }
+ }
+
+ // A worker that never got an explicit kill still ended when the mission
+ // did; without this a finished run listed every worker as still live.
+ if (out.terminal) {
+ const endTs = events.length ? events[events.length - 1].ts_ms : null;
+ for (const lane of lanes.values()) {
+ if (lane.ended_ms == null) lane.ended_ms = endTs;
+ }
+ }
+ out.workers = [...lanes.values()].sort((a, b) => a.spawned_ms - b.spawned_ms);
+ return out;
+}
+
+const TERMINAL_TONE: Record<Terminal, StoryTone> = {
+ approved: "ok",
+ failed: "error",
+ cancelled: "warn",
+ timed_out: "error",
+};
+
+export function buildStory(events: EventEnvelope[]): StoryEntry[] {
+ const story: StoryEntry[] = [];
+ const push = (env: EventEnvelope, entry: Omit<StoryEntry, "id" | "ts_ms">) => {
+ story.push({ id: `${env.event_id}-${story.length}`, ts_ms: env.ts_ms, ...entry });
+ };
+ const base = (env: EventEnvelope) => ({
+ worker_id: env.worker_id ?? null,
+ iteration: iterationOf(env.worker_id),
+ tool: null as string | null,
+ meta: {} as Record<string, string>,
+ verdict: null as CriticVerdictReady | null,
+ });
+
+ for (const env of events) {
+ const p = env.payload;
+ switch (p.event_type) {
+ case "MissionDispatched":
+ push(env, { ...base(env), kind: "dispatched", tone: "neutral", text: "", meta: { language: p.language } });
+ break;
+ case "MissionPlanReady":
+ push(env, {
+ ...base(env),
+ kind: "plan",
+ tone: "neutral",
+ text: p.expected_output || "",
+ meta: { workers: String(p.n_workers) },
+ });
+ break;
+ case "WorkerSpawned":
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: iterationOf(p.worker_id),
+ kind: "spawn",
+ tone: "busy",
+ text: "",
+ meta: {
+ cli: str(p.cli),
+ ...(p.model ? { model: str(p.model) } : {}),
+ },
+ });
+ break;
+ case "WorkerProgress": {
+ if (!p.note) break;
+ const c = classifyNote(p.note);
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: iterationOf(p.worker_id),
+ kind: c.kind,
+ tone: p.stalled ? "warn" : "neutral",
+ text: c.text,
+ tool: c.tool,
+ meta: p.pct != null ? { pct: `${Math.round(p.pct)}%` } : {},
+ });
+ break;
+ }
+ case "WorkerDraftReady":
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: iterationOf(p.worker_id),
+ kind: "draft",
+ tone: "neutral",
+ text: "",
+ meta: { diff_lines: String(p.diff ? p.diff.split("\n").length : 0) },
+ });
+ break;
+ case "CriticVerdictReady":
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: p.iteration,
+ kind: "verdict",
+ tone: p.verdict === "approve" ? "ok" : p.verdict === "revise" ? "warn" : "error",
+ text: p.summary,
+ meta: { verdict: p.verdict, confidence: `${Math.round(p.confidence * 100)}%` },
+ verdict: p,
+ });
+ break;
+ case "WorkerCorrectionRequired":
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: p.iteration,
+ kind: "correction",
+ tone: "warn",
+ text: p.correction_instruction,
+ meta: p.next_model ? { next_model: p.next_model } : {},
+ });
+ break;
+ case "WorkerKilled":
+ push(env, {
+ ...base(env),
+ worker_id: p.worker_id,
+ iteration: iterationOf(p.worker_id),
+ kind: "killed",
+ tone: p.reason === "user" || p.reason === "parent_cancelled" ? "warn" : "error",
+ text: p.error_detail ?? "",
+ meta: {
+ reason: p.reason,
+ ...(p.error_class ? { error_class: p.error_class } : {}),
+ },
+ });
+ break;
+ case "MissionBudgetWarning":
+ push(env, {
+ ...base(env),
+ kind: "budget",
+ tone: "warn",
+ text: "",
+ meta: { pct: `${Math.round(p.pct_used)}%`, limit: `$${p.limit_usd}` },
+ });
+ break;
+ case "MissionApproved":
+ push(env, {
+ ...base(env),
+ kind: "approved",
+ tone: TERMINAL_TONE.approved,
+ text: p.summary_en || p.summary_de || "",
+ meta: {},
+ });
+ break;
+ case "MissionFailed":
+ push(env, {
+ ...base(env),
+ kind: "failed",
+ tone: TERMINAL_TONE.failed,
+ text: p.error_detail ?? "",
+ meta: {
+ reason: p.reason,
+ ...(p.error_class ? { error_class: p.error_class } : {}),
+ ...(p.failed_provider ? { provider: p.failed_provider } : {}),
+ },
+ });
+ break;
+ case "MissionCancelled":
+ push(env, {
+ ...base(env),
+ kind: "cancelled",
+ tone: TERMINAL_TONE.cancelled,
+ text: "",
+ meta: { reason: p.reason, ...(p.cascade ? { cascade: "yes" } : {}) },
+ });
+ break;
+ case "MissionTimedOut":
+ push(env, {
+ ...base(env),
+ kind: "timed_out",
+ tone: TERMINAL_TONE.timed_out,
+ text: "",
+ meta: {},
+ });
+ break;
+ default:
+ // MissionStateChanged / BusStats: bookkeeping, not story.
+ break;
+ }
+ }
+ return story;
+}