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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(threads): show, count and open a thread's sub-agents
rubenluetke10-beepd04e80d3adf9
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.tsindex f579fd036b..200637a7e7 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts@@ -129,6 +129,41 @@ export interface ToolBlock {question?: QuestionState;/** When the call was made; a result without its own duration is timed from here. */startedMs: number;+ /** The sub-agent this call spawned, when the runner reported one (`subagent_*` events). */+ subagent?: SubagentState;+}++/** How a sub-agent stands: still working, or how it ended. */+export type SubagentStatus = "running" | "done" | "failed" | "stopped";++/**+ * A sub-agent a coding agent spawned, filed on the call that spawned it. Its+ * own conversation — text, thoughts, calls, its own sub-agents — folds into+ * `blocks` from the events that name it (`agent_id`), never into the turn.+ */+export interface SubagentState {+ /** The short task title ("Explore the auth code"). */+ description: string;+ /** The vendor's agent kind ("general-purpose", "Explore"); "" when it names none. */+ agentType: string;+ /** The whole task the main agent gave it. */+ prompt: string;+ /** It runs beside the main agent; the spawn call's own result is only a receipt. */+ background: boolean;+ /** The vendor's thread id for the agent, when it has one (Codex). */+ threadId: string;+ status: SubagentStatus;+ /** Its answer, as the vendor reported it at the end. */+ summary: string;+ /** What it is doing now ("Running the tests"). */+ activity: string;+ lastTool: string;+ tokens: number | null;+ toolUses: number | null;+ durationMs: number | null;+ startedMs: number;+ finishedMs: number | null;+ blocks: TurnBlock[];}export type TurnBlock = TextBlock | ReasoningBlock | ToolBlock;@@ -450,6 +485,130 @@ function upsertBlock<B extends TurnBlock>(return { ...turn, blocks: replaceAt(turn.blocks, i, next) };}+function emptySubagent(startedMs: number): SubagentState {+ return {+ description: "",+ agentType: "",+ prompt: "",+ background: false,+ threadId: "",+ status: "running",+ summary: "",+ activity: "",+ lastTool: "",+ tokens: null,+ toolUses: null,+ durationMs: null,+ startedMs,+ finishedMs: null,+ blocks: [],+ };+}++/**+ * `blocks` with the first tool block `match` picks — at the top or inside+ * any sub-agent's conversation — replaced by `fn(block)`. Null when none matches.+ */+function mapToolDeep(+ blocks: TurnBlock[],+ match: (b: ToolBlock) => boolean,+ fn: (b: ToolBlock) => ToolBlock,+): TurnBlock[] | null {+ for (let i = 0; i < blocks.length; i += 1) {+ const b = blocks[i];+ if (b.kind !== "tool") continue;+ if (match(b)) {+ const next = fn(b);+ return next === b ? blocks : replaceAt(blocks, i, next);+ }+ if (b.subagent) {+ const inner = mapToolDeep(b.subagent.blocks, match, fn);+ if (inner) {+ return inner === b.subagent.blocks ? blocks : replaceAt(blocks, i, { ...b, subagent: { ...b.subagent, blocks: inner } });+ }+ }+ }+ return null;+}++/** Update the sub-agent `agentId` spawned; a spawn call the stream never announced gets a row of its own. */+function updateSubagent(+ turn: TurnItem,+ agentId: string,+ tsMs: number,+ fn: (sub: SubagentState) => SubagentState,+): TurnItem {+ const apply = (b: ToolBlock): ToolBlock => {+ const sub = b.subagent ?? emptySubagent(b.startedMs);+ const next = fn(sub);+ return next === sub && b.subagent ? b : { ...b, subagent: next };+ };+ const blocks = mapToolDeep(turn.blocks, (b) => b.callId === agentId, apply);+ if (blocks) return blocks === turn.blocks ? turn : { ...turn, blocks };+ const spawn: ToolBlock = {+ kind: "tool", callId: agentId, name: "Agent", input: null, output: null,+ isError: false, durationMs: null, approval: null, startedMs: tsMs,+ };+ return { ...turn, blocks: [...turn.blocks, apply(spawn)] };+}++/**+ * Fold a block-level step into a sub-agent's own conversation: the same step+ * the turn would take, taken on the sub-agent's blocks.+ */+function updateHost(tl: Timeline, turnId: string, agentId: string, tsMs: number, fn: (turn: TurnItem) => TurnItem): Timeline {+ if (!agentId) return updateTurn(tl, turnId, fn);+ return updateTurn(tl, turnId, (turn) =>+ updateSubagent(turn, agentId, tsMs, (sub) => {+ const host: TurnItem = { ...turn, blocks: sub.blocks };+ const next = fn(host);+ return next === host || next.blocks === sub.blocks ? sub : { ...sub, blocks: next.blocks };+ }),+ );+}++function closeLiveBlocks(blocks: TurnBlock[], nowMs: number): TurnBlock[] {+ return blocks.some((b) => b.kind === "reasoning" && b.live)+ ? blocks.map((b) => b.kind === "reasoning" && b.live ? { ...b, live: false, durationMs: b.durationMs ?? Math.max(0, nowMs - b.startedMs) } : b)+ : blocks;+}++function finishSubagent(sub: SubagentState, status: SubagentStatus, nowMs: number, summary = ""): SubagentState {+ return {+ ...sub,+ status,+ summary: summary || sub.summary,+ activity: "",+ finishedMs: sub.finishedMs ?? nowMs,+ durationMs: sub.durationMs ?? Math.max(0, nowMs - sub.startedMs),+ blocks: closeLiveBlocks(sub.blocks, nowMs),+ };+}++/**+ * A turn's end settles every sub-agent still marked working, however deep: a+ * foreground one by its call's result, a background one that never reported+ * its end as stopped — its process is gone.+ */+function settleSubagents(blocks: TurnBlock[], nowMs: number): TurnBlock[] {+ let changed = false;+ const next = blocks.map((b) => {+ if (b.kind !== "tool" || !b.subagent) return b;+ const inner = settleSubagents(b.subagent.blocks, nowMs);+ let sub = inner === b.subagent.blocks ? b.subagent : { ...b.subagent, blocks: inner };+ if (sub.status === "running") {+ const answered = !sub.background && b.output !== null;+ sub = finishSubagent(sub, answered ? (b.isError ? "failed" : "done") : "stopped", nowMs, answered ? b.output ?? "" : "");+ }+ if (sub === b.subagent) return b;+ changed = true;+ return { ...b, subagent: sub };+ });+ return changed ? next : blocks;+}++const SUBAGENT_STATUSES: readonly SubagentStatus[] = ["running", "done", "failed", "stopped"];+/** Fold one event. Pure; returns `tl` itself when nothing changed. */export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const p = ev.payload ?? {};@@ -457,6 +616,8 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const base: Timeline =seq > tl.lastSeq ? { ...tl, lastSeq: seq, sessionPatch: null } : tl.sessionPatch ? { ...tl, sessionPatch: null } : tl;const turnId = str(p.turn_id);+ // A sub-agent's own step names the agent; it folds into that agent's conversation.+ const agentId = str(p.agent_id);switch (ev.kind) {case "agent_message": {@@ -530,7 +691,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const id = str(p.message_id, "live");const delta = str(p.text);if (!delta) return base;- return updateTurn(base, turnId, (turn) =>+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) =>upsertBlock<TextBlock>(closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,@@ -542,7 +703,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {case "assistant_text": {const id = str(p.message_id, "live");const text = str(p.text);- return updateTurn(base, turnId, (turn) =>+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) =>upsertBlock<TextBlock>(closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "text" && b.id === id,@@ -555,7 +716,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {// The model began to think. Its thinking may never stream (Claude Code// redacts it), so this is what the person sees meanwhile: one live// row, "Thinking…", counting the seconds until the finished block.- return updateTurn(base, turnId, (turn) => {+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) => {const last = turn.blocks[turn.blocks.length - 1];if (last && last.kind === "reasoning" && last.live) return turn;return {@@ -577,7 +738,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {case "reasoning_delta": {const delta = str(p.text);if (!delta) return base;- return updateTurn(base, turnId, (turn) => {+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) => {// Deltas grow the newest live reasoning block; a finished one starts a new block.const last = turn.blocks[turn.blocks.length - 1];if (last && last.kind === "reasoning" && last.live) {@@ -610,7 +771,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const text = str(p.text);const durationMs = num(p.duration_ms);const messageId = str(p.message_id) || undefined;- return updateTurn(base, turnId, (turn) => {+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) => {const last = turn.blocks[turn.blocks.length - 1];if (last && last.kind === "reasoning" && last.live) {return {@@ -660,7 +821,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {case "tool_call": {const callId = str(p.call_id);- return updateTurn(base, turnId, (turn) =>+ return updateHost(base, turnId, agentId, ev.ts_ms, (turn) =>upsertBlock<ToolBlock>(closeLiveReasoning(turn, ev.ts_ms),(b) => b.kind === "tool" && b.callId === callId,@@ -682,12 +843,13 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {case "tool_result": {const callId = str(p.call_id);- return updateTurn(base, turnId, (turn) =>+ const answered = updateHost(base, turnId, agentId, ev.ts_ms, (turn) =>upsertBlock<ToolBlock>(turn,(b) => b.kind === "tool" && b.callId === callId,(ex) => ({...(ex?.question ? { question: ex.question } : {}),+ ...(ex?.subagent ? { subagent: ex.subagent } : {}),kind: "tool",callId,name: ex?.name ?? str(p.name),@@ -703,6 +865,61 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {}),),);+ // A foreground sub-agent's answer IS its spawn call's result.+ return updateTurn(answered, turnId, (turn) => {+ const blocks = mapToolDeep(+ turn.blocks,+ (b) => b.callId === callId && b.subagent?.status === "running" && !b.subagent.background,+ (b) => ({ ...b, subagent: finishSubagent(b.subagent!, b.isError ? "failed" : "done", ev.ts_ms, b.output ?? "") }),+ );+ return blocks && blocks !== turn.blocks ? { ...turn, blocks } : turn;+ });+ }++ case "subagent_started": {+ if (!agentId) return base;+ return updateTurn(base, turnId, (turn) =>+ updateSubagent(turn, agentId, ev.ts_ms, (sub) => ({+ ...sub,+ description: str(p.description) || sub.description,+ agentType: str(p.agent_type) || sub.agentType,+ prompt: str(p.prompt) || sub.prompt,+ background: Boolean(p.background),+ threadId: str(p.thread_id) || sub.threadId,+ })),+ );+ }++ case "subagent_progress": {+ if (!agentId) return base;+ return updateTurn(base, turnId, (turn) =>+ updateSubagent(turn, agentId, ev.ts_ms, (sub) => sub.status !== "running" ? sub : {+ ...sub,+ activity: str(p.activity) || sub.activity,+ lastTool: str(p.last_tool) || sub.lastTool,+ tokens: num(p.tokens) ?? sub.tokens,+ toolUses: num(p.tool_uses) ?? sub.toolUses,+ durationMs: num(p.duration_ms) ?? sub.durationMs,+ }),+ );+ }++ case "subagent_finished": {+ if (!agentId) return base;+ const raw = str(p.status, "done") as SubagentStatus;+ const status = SUBAGENT_STATUSES.includes(raw) && raw !== "running" ? raw : "done";+ return updateTurn(base, turnId, (turn) =>+ updateSubagent(turn, agentId, ev.ts_ms, (sub) => {+ const ended = finishSubagent({ ...sub, durationMs: num(p.duration_ms) ?? sub.durationMs }, status, ev.ts_ms, str(p.summary));+ return {+ ...ended,+ // A later report (the notification after a status patch) may only add to the first.+ status: sub.status === "running" ? status : sub.status,+ tokens: num(p.tokens) ?? sub.tokens,+ toolUses: num(p.tool_uses) ?? sub.toolUses,+ };+ }),+ );}case "usage_delta": {@@ -731,8 +948,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {input: p.input,summary: str(p.summary),};- const withTurn = updateTurn(base, turnId, (turn) =>- upsertBlock<ToolBlock>(+ const withTurn = updateTurn(base, turnId, (turn) => {+ const approval = { approvalId, summary: pending.summary, decision: null };+ const nested = mapToolDeep(turn.blocks, (b) => b.callId === callId, (b) => ({ ...b, approval }));+ if (nested) return nested === turn.blocks ? turn : { ...turn, blocks: nested };+ return upsertBlock<ToolBlock>(turn,(b) => b.kind === "tool" && b.callId === callId,(ex) => ({@@ -743,11 +963,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {output: ex?.output ?? null,isError: ex?.isError ?? false,durationMs: ex?.durationMs ?? null,- approval: { approvalId, summary: pending.summary, decision: null },+ approval,startedMs: ex?.startedMs ?? ev.ts_ms,}),- ),- );+ );+ });return {...withTurn,pendingApprovals: [@@ -761,18 +981,12 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {const approvalId = str(p.approval_id);const decision = str(p.decision);const withTurn = updateTurn(base, turnId, (turn) => {- const i = turn.blocks.findIndex(- (b) => b.kind === "tool" && b.approval?.approvalId === approvalId,+ const blocks = mapToolDeep(+ turn.blocks,+ (b) => b.approval?.approvalId === approvalId,+ (b) => ({ ...b, approval: b.approval ? { ...b.approval, decision } : null }),);- if (i < 0) return turn;- const block = turn.blocks[i] as ToolBlock;- return {- ...turn,- blocks: replaceAt(turn.blocks, i, {- ...block,- approval: block.approval ? { ...block.approval, decision } : null,- }),- };+ return blocks && blocks !== turn.blocks ? { ...turn, blocks } : turn;});return {...withTurn,@@ -828,7 +1042,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {status: status === "running" ? "done" : status,// A turn that ended mid-stream closes its live reasoning block, and// a question nobody can answer any more stops asking.- blocks: turn.blocks.map((b) =>+ blocks: settleSubagents(turn.blocks, ev.ts_ms).map((b) =>b.kind === "reasoning" && b.live? {...b,diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.test.tsxnew file mode 100644index 0000000000..50b50f4f40--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.test.tsx@@ -0,0 +1,84 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { SubagentState, ToolBlock, TurnBlock, TurnItem, TurnStatus } from "@/components/agentchat/reduce";+import { ThreadTimeline } from "./ThreadTimeline";+import { OpenSubagent, SubagentHeader, SubagentSwitcher } from "./ThreadSubagents";+import { listSubagents } from "./subagents";++const sub = (over: Partial<SubagentState> = {}): SubagentState => ({+ description: "Explore the auth code", agentType: "Explore", prompt: "Find where tokens are checked.", background: true,+ threadId: "", status: "running", summary: "", activity: "Reading auth.py", lastTool: "Read", tokens: 12400,+ toolUses: 3, durationMs: null, startedMs: Date.now(), finishedMs: null, blocks: [], ...over,+});++const spawn = (id: string, over: Partial<SubagentState> = {}): ToolBlock => ({+ kind: "tool", callId: id, name: "Agent", input: { description: "x" }, output: "Async agent launched successfully.",+ isError: false, durationMs: 10, approval: null, startedMs: 1, subagent: sub(over),+});++function turn(blocks: TurnBlock[], status: TurnStatus = "running"): TurnItem {+ return {+ type: "turn", id: "t1", provider: "claude-cli", model: "", effort: "", runner: "", status, blocks,+ startedMs: Date.now(), durationMs: status === "running" ? null : 5000, usage: null, liveUsage: null, costUsd: null, error: null,+ };+}++afterEach(cleanup);++describe("thread sub-agents", () => {+ it("shows a spawned sub-agent as a card that opens its conversation", () => {+ const open = vi.fn();+ render(<OpenSubagent.Provider value={open}>+ <ThreadTimeline items={[turn([spawn("a1")])]} sessionId="s1" bottomInset={0} />+ </OpenSubagent.Provider>);+ const card = screen.getByTestId("thread-subagent-card");+ expect(card.textContent).toContain("Explore the auth code");+ expect(card.textContent).toContain("Reading auth.py");+ expect(card.textContent).toContain("3 tools");+ expect(card.textContent).toContain("12.4k tokens");+ expect(screen.getByTestId("thread-working").textContent).toContain("1 sub-agent working");+ fireEvent.click(card);+ expect(open).toHaveBeenCalledWith("a1");+ });++ it("keeps a finished turn's sub-agents in view under its folded work", () => {+ render(<ThreadTimeline items={[turn([+ { kind: "tool", callId: "c0", name: "Bash", input: { command: "ls" }, output: "ok", isError: false, durationMs: 5, approval: null, startedMs: 1 },+ spawn("a1", { status: "done", summary: "Tokens are checked in auth.py." }),+ { kind: "text", id: "m1", text: "Done." },+ ], "done")]} sessionId="s1" bottomInset={0} />);+ expect(screen.getByTestId("thread-worked-for")).toBeTruthy();+ const card = screen.getByTestId("thread-subagent-card");+ expect(card.getAttribute("data-status")).toBe("done");+ expect(card.textContent).toContain("Tokens are checked in auth.py.");+ });++ it("counts the sub-agents and switches between them and the main thread", () => {+ const entries = listSubagents([turn([spawn("a1"), spawn("a2", { description: "Write tests", status: "done" })])]);+ const onOpen = vi.fn();+ render(<SubagentSwitcher entries={entries} openId="a2" onOpen={onOpen} />);+ expect(screen.getByTestId("thread-subagent-count").textContent).toBe("2 sub-agents · 1 working");+ const tabs = screen.getAllByTestId("thread-subagent-tab");+ expect(tabs.map((tab) => tab.getAttribute("aria-current"))).toEqual(["false", "true"]);+ fireEvent.click(tabs[0]);+ expect(onOpen).toHaveBeenCalledWith("a1");+ fireEvent.click(screen.getByTestId("thread-subagent-main"));+ expect(onOpen).toHaveBeenCalledWith(null);+ });++ it("opens with the task it was given and a way back", () => {+ const [entry] = listSubagents([turn([spawn("a1")])]);+ const onOpen = vi.fn();+ render(<SubagentHeader entry={entry} path={[entry]} onOpen={onOpen} />);+ expect(screen.getByRole("region", { name: "Task" }).textContent).toContain("Find where tokens are checked.");+ fireEvent.click(screen.getByTestId("thread-subagent-back"));+ expect(onOpen).toHaveBeenCalledWith(null);+ });++ it("says so when the CLI reports only the task and the answer", () => {+ const block: ToolBlock = { kind: "tool", callId: "c1", name: "task", input: { description: "Review", prompt: "Review it" }, output: "Fine.", isError: false, durationMs: 5, approval: null, startedMs: 1 };+ const [entry] = listSubagents([turn([block], "done")]);+ render(<SubagentHeader entry={entry} path={[entry]} onOpen={() => {}} />);+ expect(screen.getByTestId("thread-subagent-unstreamed")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.tsxnew file mode 100644index 0000000000..b411b573f7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadSubagents.tsx@@ -0,0 +1,221 @@+import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";+import { ArrowLeft, Bot, Check, ChevronRight, CircleSlash, Loader2, MessageSquare, ShieldAlert, X } from "lucide-react";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import type { SubagentStatus, ToolBlock, TurnItem } from "@/components/agentchat/reduce";+import { traceDuration } from "@/components/agentchat/traceEntries";+import { cn } from "@/lib/utils";+import { shortCount, subagentCounts, subagentEntry, type SubagentEntry } from "./subagents";++/**+ * A thread's sub-agents on screen: a card where the main agent spawned one,+ * a switcher above the conversation that counts them and opens any of them,+ * and the header of an opened sub-agent's own conversation.+ */++/** Opens a sub-agent's conversation by the id of the call that spawned it. */+export const OpenSubagent = createContext<(id: string) => void>(() => {});++const STATUS_WORD: Record<SubagentStatus, string> = {+ running: "Working",+ done: "Done",+ failed: "Failed",+ stopped: "Stopped",+};++/** A sub-agent's state at a glance: working, waiting for the person, or how it ended. */+export function SubagentMark({ status, waiting = false, className }: { status: SubagentStatus; waiting?: boolean; className?: string }) {+ const box = cn("h-3.5 w-3.5 shrink-0", className);+ if (waiting && status === "running") return <ShieldAlert aria-hidden className={cn(box, "text-warning")} />;+ if (status === "running") return <Loader2 aria-hidden className={cn(box, "animate-spin text-muted-foreground")} />;+ if (status === "done") return <Check aria-hidden className={cn(box, "text-success")} />;+ if (status === "failed") return <X aria-hidden className={cn(box, "text-destructive")} />;+ return <CircleSlash aria-hidden className={cn(box, "text-muted-foreground")} />;+}++/** A clock that writes its own text once a second, so nothing around it re-renders to tick. */+function LiveClock({ since }: { since: number }) {+ const ref = useRef<HTMLSpanElement | null>(null);+ useEffect(() => {+ const tick = () => { if (ref.current) ref.current.textContent = traceDuration(Math.max(0, Date.now() - since)); };+ tick();+ const timer = window.setInterval(tick, 1000);+ return () => window.clearInterval(timer);+ }, [since]);+ return <span ref={ref} className="tabular-nums">{traceDuration(Math.max(0, Date.now() - since))}</span>;+}++function firstLine(text: string): string {+ return text.split(/\r?\n/).map((line) => line.replace(/^[#>*\-\s]+/, "").trim()).find(Boolean) ?? "";+}++/** "4 tools · 23.4k tokens · 12s" — what the sub-agent spent so far. */+function SubagentMeta({ entry }: { entry: SubagentEntry }) {+ const parts: string[] = [];+ if (entry.toolUses) parts.push(`${entry.toolUses} ${entry.toolUses === 1 ? "tool" : "tools"}`);+ if (entry.tokens) parts.push(`${shortCount(entry.tokens)} tokens`);+ const running = entry.status === "running";+ const duration = !running && entry.durationMs ? traceDuration(entry.durationMs) : "";+ if (duration) parts.push(duration);+ if (!parts.length && !running) return null;+ return <span className="shrink-0 tabular-nums">+ {parts.join(" · ")}+ {running && <>{parts.length ? " · " : ""}<LiveClock since={entry.startedMs} /></>}+ </span>;+}++/** The line under a card's title: what it does now, else how it ended. */+function statusLine(entry: SubagentEntry): string {+ if (entry.status === "running") {+ if (entry.waiting) return "Waiting for your approval";+ return entry.activity || (entry.block.subagent?.lastTool ? `Using ${entry.block.subagent.lastTool}` : "Working");+ }+ if (entry.status === "failed") return firstLine(entry.summary) || "Failed";+ if (entry.status === "stopped") return "Stopped before it answered";+ return firstLine(entry.summary) || "Finished";+}++/**+ * Where the main agent spawned a sub-agent: one card with its task, what it+ * is doing or how it ended, and what it spent. A click opens its conversation.+ */+export function SubagentCard({ block, turn }: { block: ToolBlock; turn: TurnItem }) {+ const open = useContext(OpenSubagent);+ const entry = useMemo(() => subagentEntry(block, turn), [block, turn]);+ const running = entry.status === "running";+ return <button type="button" onClick={() => open(entry.id)} data-testid="thread-subagent-card" data-status={entry.status}+ aria-label={`Open sub-agent ${entry.title}, ${STATUS_WORD[entry.status].toLowerCase()}`}+ className="group/agent flex w-full min-w-0 items-center gap-3 rounded-xl border border-border bg-card px-3 py-2.5 text-left transition-colors hover:border-border-strong hover:bg-secondary/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span aria-hidden className="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-secondary text-foreground-secondary">+ <Bot className="h-4 w-4" strokeWidth={1.75} />+ <span className="absolute -bottom-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full border border-border bg-card">+ <SubagentMark status={entry.status} waiting={entry.waiting} className="h-2.5 w-2.5" />+ </span>+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-medium text-foreground-strong">{entry.title}</span>+ {entry.agentType && <span className="shrink-0 rounded-md border border-border px-1.5 text-[11px] leading-4 text-muted-foreground">{entry.agentType}</span>}+ </span>+ <span className="mt-0.5 flex min-w-0 items-center gap-2 text-xs text-muted-foreground">+ <span className={cn("min-w-0 truncate", running && !entry.waiting && "live-tool-shine", entry.waiting && "text-warning", entry.status === "failed" && "text-destructive")}>{statusLine(entry)}</span>+ <span aria-hidden className="text-muted-foreground/50">·</span>+ <SubagentMeta entry={entry} />+ </span>+ </span>+ <span className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground transition-colors group-hover/agent:text-foreground">+ <MessageSquare aria-hidden className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Open</span>+ <ChevronRight aria-hidden className="h-3.5 w-3.5" />+ </span>+ </button>;+}++/** "3 sub-agents · 2 working · 1 waiting" — the switcher's own count. */+export function subagentSummary(entries: readonly SubagentEntry[]): string {+ const counts = subagentCounts(entries);+ const parts = [`${counts.total} ${counts.total === 1 ? "sub-agent" : "sub-agents"}`];+ if (counts.running) parts.push(`${counts.running} working`);+ if (counts.waiting) parts.push(`${counts.waiting} waiting`);+ if (counts.failed) parts.push(`${counts.failed} failed`);+ return parts.join(" · ");+}++/**+ * The switcher above the conversation: the main thread first, then every+ * sub-agent the thread spawned — nested ones after their parent — each with+ * its state. The open one is marked; a click switches the conversation.+ */+export function SubagentSwitcher({ entries, openId, onOpen }: {+ entries: readonly SubagentEntry[];+ openId: string | null;+ onOpen: (id: string | null) => void;+}) {+ const strip = useRef<HTMLDivElement | null>(null);+ // The open tab stays in view when the list is wider than the column.+ useEffect(() => {+ const active = strip.current?.querySelector<HTMLElement>("[aria-current=true]");+ active?.scrollIntoView?.({ block: "nearest", inline: "nearest" });+ }, [openId]);+ if (entries.length === 0) return null;+ const tab = (active: boolean) => cn(+ "flex h-7 max-w-[15rem] shrink-0 items-center gap-1.5 rounded-lg px-2.5 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ active ? "bg-secondary text-foreground-strong" : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",+ );+ return <nav aria-label="Sub-agents" data-testid="thread-subagent-switcher"+ className="flex min-w-0 items-center gap-2 border-b border-border/70 bg-background px-3 py-1.5">+ <div ref={strip} className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ <button type="button" aria-current={openId === null} onClick={() => onOpen(null)} className={tab(openId === null)} data-testid="thread-subagent-main">+ <MessageSquare aria-hidden className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">Main thread</span>+ </button>+ <span aria-hidden className="mx-1 h-4 w-px shrink-0 bg-border" />+ {entries.map((entry) => <button key={entry.id} type="button" aria-current={openId === entry.id} onClick={() => onOpen(entry.id)}+ title={entry.prompt || entry.title} className={tab(openId === entry.id)} data-testid="thread-subagent-tab" data-status={entry.status}>+ {entry.depth > 0 && <span aria-hidden className="shrink-0 text-muted-foreground/60">{"›".repeat(entry.depth)}</span>}+ <SubagentMark status={entry.status} waiting={entry.waiting} />+ <span className="truncate">{entry.title}</span>+ </button>)}+ </div>+ <span className="hidden shrink-0 text-xs tabular-nums text-muted-foreground md:inline" data-testid="thread-subagent-count">{subagentSummary(entries)}</span>+ </nav>;+}++/**+ * The top of an opened sub-agent's conversation: the way back, who it is,+ * where it sits (a sub-agent's own sub-agents name their parents), how it+ * stands, and the task the main agent gave it.+ */+export function SubagentHeader({ entry, path, onOpen }: {+ entry: SubagentEntry;+ path: readonly SubagentEntry[];+ onOpen: (id: string | null) => void;+}) {+ const [taskOpen, setTaskOpen] = useState(false);+ const long = entry.prompt.length > 280 || entry.prompt.split("\n").length > 5;+ const parent = path.length > 1 ? path[path.length - 2] : null;+ return <div className="space-y-3" data-testid="thread-subagent-header">+ <div className="flex min-w-0 items-center gap-2 text-sm">+ <button type="button" onClick={() => onOpen(parent ? parent.id : null)} data-testid="thread-subagent-back"+ className="flex h-7 shrink-0 items-center gap-1.5 rounded-md px-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ArrowLeft aria-hidden className="h-4 w-4" />+ <span>{parent ? parent.title : "Main thread"}</span>+ </button>+ </div>+ <div className="flex min-w-0 items-start gap-3">+ <span aria-hidden className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-secondary text-foreground-secondary">+ <Bot className="h-5 w-5" strokeWidth={1.75} />+ </span>+ <div className="min-w-0 flex-1">+ <h2 className="flex min-w-0 items-center gap-2 text-base font-semibold text-foreground-strong">+ <span className="truncate">{entry.title}</span>+ {entry.agentType && <span className="shrink-0 rounded-md border border-border px-1.5 text-[11px] font-normal leading-4 text-muted-foreground">{entry.agentType}</span>}+ </h2>+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">+ <span className="flex items-center gap-1">+ <SubagentMark status={entry.status} waiting={entry.waiting} />+ {entry.waiting && entry.status === "running" ? "Waiting for your approval" : STATUS_WORD[entry.status]}+ </span>+ {entry.background && <><span aria-hidden>·</span><span>In the background</span></>}+ <span aria-hidden>·</span>+ <SubagentMeta entry={entry} />+ </div>+ </div>+ </div>+ {entry.prompt && <section aria-label="Task" className="rounded-xl border border-border bg-card px-3 py-2.5">+ <div className="mb-1 text-xs font-medium text-muted-foreground">Task from {parent ? parent.title : "the main agent"}</div>+ <div className={cn("relative text-sm leading-6 text-foreground-secondary [overflow-wrap:anywhere]", long && !taskOpen && "max-h-32 overflow-hidden")}>+ <div className="prose prose-neutral max-w-none text-sm dark:prose-invert prose-p:my-1 prose-p:text-foreground-secondary prose-li:text-foreground-secondary"><ChatMarkdown text={entry.prompt} /></div>+ {long && !taskOpen && <div aria-hidden className="pointer-events-none absolute inset-x-0 bottom-0 h-10 bg-gradient-to-t from-card to-transparent" />}+ </div>+ {long && <button type="button" aria-expanded={taskOpen} onClick={() => setTaskOpen(!taskOpen)}+ className="mt-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {taskOpen ? "Show less" : "Show the whole task"}+ </button>}+ </section>}+ {!entry.streamed && <p className="text-xs text-muted-foreground" data-testid="thread-subagent-unstreamed">+ {entry.status === "running"+ ? "This agent's CLI does not stream a sub-agent's steps. Its answer shows here when it finishes."+ : "This agent's CLI reported only the task and the answer, not the sub-agent's steps."}+ </p>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsxindex 54b342a9dd..4c65b5ab55 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx@@ -9,6 +9,8 @@ import { useT } from "@/i18n";import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { buildThreadRows, isFailed, thoughtGist, type ThreadRow, type WorkGroup, type WorkItem } from "./threadWork";+import { SubagentCard } from "./ThreadSubagents";+import { listSubagents } from "./subagents";/*** A thread's conversation: the person's messages on the right, the agent's@@ -558,6 +560,9 @@ const TurnView = memo(function TurnView({ turn }: { turn: TurnItem }) {const [workOpen, setWorkOpen] = useState(false);// Finished: every step and thought folds behind one "Worked for …" line; the answer stays.const { work, answer: tail } = useMemo(() => (running ? { work: rows, answer: [] } : foldFinished(rows)), [rows, running]);+ // The sub-agents it spawned stay in view under the fold: each opens its own conversation.+ const agents = useMemo(() => work.filter((row) => row.kind === "agent"), [work]);+ const agentsWorking = useMemo(() => running ? listSubagents([turn]).filter((entry) => entry.status === "running").length : 0, [turn, running]);const folded = !running && work.length > 0;const duration = turn.durationMs != null ? traceDuration(turn.durationMs) : "";const foldLabel = turn.status === "cancelled" ? `Stopped${duration ? ` after ${duration}` : ""}`@@ -567,6 +572,7 @@ const TurnView = memo(function TurnView({ turn }: { turn: TurnItem }) {if (row.kind === "work") return <WorkGroupView key={row.id} group={row} running={running} />;if (row.kind === "thought") return <ThoughtView key={row.id} text={row.text} />;if (row.kind === "text") return <div key={row.id} className={cn(PROSE, THREAD_MEDIA)}><ChatMarkdown text={row.text} /></div>;+ if (row.kind === "agent") return <SubagentCard key={row.id} block={row.block} turn={turn} />;const pending = pendingLabel(row.block);return pending ? <WorkRow key={row.id} icon={pending.icon} label={pending.text} live /> : null;};@@ -577,13 +583,15 @@ const TurnView = memo(function TurnView({ turn }: { turn: TurnItem }) {<span className="tabular-nums">{foldLabel}</span><ChevronRight aria-hidden className={cn("h-3.5 w-3.5 transition-transform duration-150", workOpen && "rotate-90")} /></button>- {workOpen && <div className="space-y-1.5 pb-2 pt-1" data-testid="thread-worked-steps">{work.map(renderRow)}</div>}+ {workOpen && <div className="space-y-1.5 pb-2 pt-1" data-testid="thread-worked-steps">{work.filter((row) => row.kind !== "agent").map(renderRow)}</div>}<div aria-hidden className="mt-1 border-b border-border/70" /></div>}+ {folded && agents.length > 0 && <div className="space-y-1.5 pt-1" data-testid="thread-turn-subagents">{agents.map(renderRow)}</div>}{(folded ? tail : rows).map(renderRow)}{running? <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">- <span className="whitespace-nowrap">Working for <Elapsed since={turn.startedMs} /></span>+ <span className="whitespace-nowrap">Working for <Elapsed since={turn.startedMs} />+ {agentsWorking > 0 && <> · {agentsWorking} {agentsWorking === 1 ? "sub-agent" : "sub-agents"} working</>}</span></div>: <>{turn.status === "error" && turn.error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{turn.error}</p>}@@ -623,10 +631,12 @@ function ItemView({ item }: { item: TimelineItem }) {* the bottom and stays put once they scroll up to read; a button brings them* back down.*/-export function ThreadTimeline({ items, sessionId, bottomInset, folder = "" }: {+export function ThreadTimeline({ items, sessionId, bottomInset, folder = "", lead }: {items: TimelineItem[]; sessionId: string | null; bottomInset: number;/** The thread's project folder; changed files list relative to it. */folder?: string;+ /** What reads above the conversation — an opened sub-agent's header and task. */+ lead?: ReactNode;}) {const scroller = useRef<HTMLDivElement | null>(null);const pinned = useRef(true);@@ -665,6 +675,7 @@ export function ThreadTimeline({ items, sessionId, bottomInset, folder = "" }: {}}className="h-full overflow-y-auto scrollbar-jarvis"><div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-5 pt-6" style={{ paddingBottom: bottomInset + 24 }}>+ {lead}{items.map((item) => <ItemView key={item.id} item={item} />)}</div></div>diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsxindex 4130a07627..0af2d75986 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx@@ -8,7 +8,9 @@ import { ThreadBranchBar, type ThreadCheckout } from "./ThreadBranchBar";import { ThreadComposer } from "./ThreadComposer";import { ThreadMenuItem, ThreadPopover } from "./ThreadPopover";import { ThreadTimeline } from "./ThreadTimeline";+import { OpenSubagent, SubagentHeader, SubagentSwitcher } from "./ThreadSubagents";import { useRecalledMessages, withoutRecalled } from "./recalledMessages";+import { fetchDiscoveredAgents, listSubagents, mergeDiscovered, subagentPath, subagentTurn, type DiscoveredAgent } from "./subagents";import { projectIdFor, rememberedSeat, useThreadChatStore } from "./threadModel";/**@@ -40,6 +42,10 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {const [projectMenu, setProjectMenu] = useState(false);const [composerHeight, setComposerHeight] = useState(160);const composerBox = useRef<HTMLDivElement | null>(null);+ // The sub-agent whose conversation shows instead of the main thread's, by its spawn call.+ const [openAgent, setOpenAgent] = useState<string | null>(null);+ // Sub-agents the CLI filed on its own (Codex), read for the open thread.+ const [discovered, setDiscovered] = useState<{ sessionId: string; agents: DiscoveredAgent[] } | null>(null);const projectAnchor = useRef<HTMLButtonElement | null>(null);// The draft whose first message is on its way: its session belongs to this project.const startingIn = useRef<string | null>(null);@@ -150,6 +156,58 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {}, [isDraft, activeSessionId, lastError]);const running = timeline.items.some((item) => item.type === "turn" && item.status === "running");+ // Codex streams the main agent only; its sub-agents' steps come from its own files.+ const codexThread = Boolean(session && catalog?.providers.find((row) => row.id === session.provider)?.runner === "codex-cli");+ useEffect(() => {+ const id = selection.sessionId;+ if (!codexThread || !id || !onScreen) return;+ let stopped = false;+ const load = () => {+ fetchDiscoveredAgents(id)+ .then((agents) => { if (!stopped) setDiscovered({ sessionId: id, agents }); })+ // A failed read leaves the cards the stream reported; the next poll or visit tries again.+ .catch((error: unknown) => console.debug("thread sub-agents unavailable", error));+ };+ load();+ const timer = running ? window.setInterval(load, 4000) : undefined;+ return () => {+ stopped = true;+ if (timer !== undefined) window.clearInterval(timer);+ };+ }, [codexThread, selection.sessionId, running, onScreen]);+ const items = useMemo(() => {+ const shown = withoutRecalled(timeline.items, recalled);+ return discovered && discovered.sessionId === selection.sessionId+ ? mergeDiscovered(shown, discovered.agents, session?.vendor_session ?? "")+ : shown;+ }, [timeline.items, recalled, discovered, selection.sessionId, session?.vendor_session]);+ const agents = useMemo(() => listSubagents(items), [items]);+ const agentPath = useMemo(() => (openAgent ? subagentPath(agents, openAgent) : []), [agents, openAgent]);+ const agent = agentPath.length ? agentPath[agentPath.length - 1] : null;+ const agentItems = useMemo(() => (agent ? [subagentTurn(agent)] : []), [agent]);+ const userCount = timeline.items.filter((item) => item.type === "user").length;++ // Another thread, or a new message to the main agent, brings the main conversation back.+ useEffect(() => { setOpenAgent(null); }, [selection.sessionId]);+ const sentCount = useRef(userCount);+ useEffect(() => {+ if (userCount > sentCount.current) setOpenAgent(null);+ sentCount.current = userCount;+ }, [userCount]);++ // Escape leaves a sub-agent's conversation for the one it came from.+ useEffect(() => {+ if (!openAgent || !onScreen) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ const target = event.target as HTMLElement | null;+ if (target?.closest("textarea, input, [contenteditable=true], [role=dialog], [role=menu]")) return;+ const parent = agentPath.length > 1 ? agentPath[agentPath.length - 2].id : null;+ setOpenAgent(parent);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [openAgent, onScreen, agentPath]);if (!project) {return <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center" data-testid="thread-view-empty">@@ -189,13 +247,17 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {<ThreadComposer threadKey={threadKey} prepareDraft={prepareDraft} autoFocusNonce={focusNonce + (onScreen ? 1 : 0)} strip={strip} onScreen={onScreen} /></div></div>- : <>- <ThreadTimeline items={withoutRecalled(timeline.items, recalled)} sessionId={selection.sessionId} bottomInset={composerHeight} folder={folder} />+ : <OpenSubagent.Provider value={setOpenAgent}>+ <SubagentSwitcher entries={agents} openId={agent ? agent.id : null} onOpen={setOpenAgent} />+ {agent+ ? <ThreadTimeline items={agentItems} sessionId={`agent:${agent.id}`} bottomInset={composerHeight} folder={folder}+ lead={<SubagentHeader entry={agent} path={agentPath} onOpen={setOpenAgent} />} />+ : <ThreadTimeline items={items} sessionId={selection.sessionId} bottomInset={composerHeight} folder={folder} />}<div ref={composerBox} className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-background from-70% to-transparent px-5 pb-4 pt-6"><div className="pointer-events-auto"><ThreadComposer threadKey={threadKey} prepareDraft={prepareDraft} autoFocusNonce={focusNonce} strip={strip} onScreen={onScreen} /></div></div>- </>}+ </OpenSubagent.Provider>}</div>;}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.test.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.test.tsnew file mode 100644index 0000000000..4f1ebcec6c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from "vitest";+import { EMPTY_TIMELINE, reduceEvents, type TextBlock, type ToolBlock, type TurnItem } from "@/components/agentchat/reduce";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { isSpawnTool, listSubagents, mergeDiscovered, subagentCounts, subagentPath, subagentTurn, type DiscoveredAgent } from "./subagents";++let seq = 0;+const ev = (kind: string, payload: Record<string, unknown>, ts = 1000 + seq): AgentChatEvent =>+ ({ seq: ++seq, ts_ms: ts, kind, payload } as AgentChatEvent);++/** The events the backend sends for one Claude Code turn that ran a background agent. */+function claudeRun(): AgentChatEvent[] {+ return [+ ev("turn_started", { turn_id: "t1", provider: "claude-cli" }),+ ev("tool_call", { turn_id: "t1", call_id: "spawn", name: "Agent", input: { description: "Count files", prompt: "Run echo" } }),+ ev("subagent_started", { turn_id: "t1", agent_id: "spawn", description: "Count files", agent_type: "general-purpose", prompt: "Run echo", background: true }),+ ev("tool_result", { turn_id: "t1", call_id: "spawn", output: "Async agent launched successfully.", is_error: false }),+ ev("tool_call", { turn_id: "t1", agent_id: "spawn", call_id: "bash", name: "Bash", input: { command: "echo hi" } }),+ ev("subagent_progress", { turn_id: "t1", agent_id: "spawn", activity: "Running echo", last_tool: "Bash", tokens: 23416, tool_uses: 1 }),+ ev("tool_result", { turn_id: "t1", agent_id: "spawn", call_id: "bash", output: "hi", is_error: false }),+ ev("assistant_text", { turn_id: "t1", agent_id: "spawn", message_id: "sub2", text: "hi" }),+ ];+}++const finished = (status = "completed") => [+ ev("subagent_finished", { turn_id: "t1", agent_id: "spawn", status: status === "completed" ? "done" : status, summary: "hi", tokens: 25617, tool_uses: 1, duration_ms: 5509 }),+ ev("assistant_text", { turn_id: "t1", message_id: "m2", text: "The agent said hi." }),+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 9000 }),+];++const turnOf = (events: AgentChatEvent[]) => reduceEvents(EMPTY_TIMELINE, events).items.find((item) => item.type === "turn") as TurnItem;++describe("sub-agents in the timeline", () => {+ it("files a sub-agent's steps and words under its spawn call, never the main answer", () => {+ const turn = turnOf([...claudeRun(), ...finished()]);+ const texts = turn.blocks.filter((b): b is TextBlock => b.kind === "text").map((b) => b.text);+ expect(texts).toEqual(["The agent said hi."]);+ const spawn = turn.blocks.find((b) => b.kind === "tool" && b.callId === "spawn") as ToolBlock;+ expect(spawn.subagent?.status).toBe("done");+ expect(spawn.subagent?.summary).toBe("hi");+ expect(spawn.subagent?.tokens).toBe(25617);+ expect(spawn.subagent?.blocks.map((b) => b.kind)).toEqual(["tool", "text"]);+ expect(turn.blocks.some((b) => b.kind === "tool" && b.callId === "bash")).toBe(false);+ });++ it("keeps a background agent working past its launch receipt, with what it does now", () => {+ const [entry] = listSubagents(reduceEvents(EMPTY_TIMELINE, claudeRun()).items);+ expect(entry.status).toBe("running");+ expect(entry.activity).toBe("Running echo");+ expect(entry.tokens).toBe(23416);+ expect(entry.title).toBe("Count files");+ expect(entry.agentType).toBe("general-purpose");+ expect(entry.streamed).toBe(true);+ });++ it("stops a background agent that never reported its end once the turn is over", () => {+ const turn = turnOf([...claudeRun(), ev("turn_finished", { turn_id: "t1", status: "cancelled" })]);+ const [entry] = listSubagents([turn]);+ expect(entry.status).toBe("stopped");+ });++ it("finishes a foreground agent by its spawn call's result", () => {+ const turn = turnOf([+ ev("turn_started", { turn_id: "t1" }),+ ev("tool_call", { turn_id: "t1", call_id: "spawn", name: "Agent", input: { description: "Look", prompt: "Look around" } }),+ ev("subagent_started", { turn_id: "t1", agent_id: "spawn", description: "Look", prompt: "Look around", background: false }),+ ev("tool_result", { turn_id: "t1", call_id: "spawn", output: "Found three files.", is_error: false }),+ ]);+ const [entry] = listSubagents([turn]);+ expect(entry.status).toBe("done");+ expect(entry.summary).toBe("Found three files.");+ });++ it("nests a sub-agent's own sub-agent and finds the way back to it", () => {+ const items = reduceEvents(EMPTY_TIMELINE, [+ ...claudeRun(),+ ev("tool_call", { turn_id: "t1", agent_id: "spawn", call_id: "inner", name: "Agent", input: { description: "Dig deeper" } }),+ ev("subagent_started", { turn_id: "t1", agent_id: "inner", description: "Dig deeper", prompt: "Dig", background: false }),+ ev("assistant_text", { turn_id: "t1", agent_id: "inner", message_id: "i1", text: "Dug." }),+ ]).items;+ const entries = listSubagents(items);+ expect(entries.map((entry) => [entry.id, entry.depth, entry.parentId])).toEqual([["spawn", 0, null], ["inner", 1, "spawn"]]);+ expect(subagentPath(entries, "inner").map((entry) => entry.id)).toEqual(["spawn", "inner"]);+ expect(entries[1].blocks).toHaveLength(1);+ expect(subagentCounts(entries)).toEqual({ total: 2, running: 2, failed: 0, waiting: 0 });+ });++ it("puts an approval a sub-agent asks for on its own call and marks the agent waiting", () => {+ const items = reduceEvents(EMPTY_TIMELINE, [+ ...claudeRun(),+ ev("tool_call", { turn_id: "t1", agent_id: "spawn", call_id: "rm", name: "Bash", input: { command: "rm -rf build" } }),+ ev("approval_required", { turn_id: "t1", approval_id: "a1", call_id: "rm", name: "Bash", input: {}, summary: "rm -rf build" }),+ ]).items;+ const [entry] = listSubagents(items);+ expect(entry.waiting).toBe(true);+ const turn = items.find((item) => item.type === "turn") as TurnItem;+ expect(turn.blocks.some((b) => b.kind === "tool" && b.callId === "rm")).toBe(false);+ const resolved = listSubagents(reduceEvents({ ...EMPTY_TIMELINE, items }, [ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow" })]).items);+ expect(resolved[0].waiting).toBe(false);+ });++ it("reads any CLI's spawn call as a sub-agent with its task and answer", () => {+ expect(isSpawnTool("task")).toBe(true);+ expect(isSpawnTool("Task")).toBe(true);+ expect(isSpawnTool("spawn_agent")).toBe(true);+ expect(isSpawnTool("TaskCreate")).toBe(false);+ expect(isSpawnTool("Bash")).toBe(false);+ const turn = turnOf([+ ev("turn_started", { turn_id: "t1", provider: "opencode-cli" }),+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "task", input: { description: "Review", prompt: "Review the diff", subagent_type: "reviewer" } }),+ ev("tool_result", { turn_id: "t1", call_id: "c1", output: "Two issues.", is_error: false }),+ ]);+ const [entry] = listSubagents([turn]);+ expect(entry).toMatchObject({ title: "Review", agentType: "reviewer", prompt: "Review the diff", status: "done", summary: "Two issues.", streamed: false });+ // Its conversation is its answer.+ expect(subagentTurn(entry).blocks).toEqual([{ kind: "text", id: "answer:c1", text: "Two issues." }]);+ });++ it("reads a Codex agent's answer from its finished report", () => {+ const turn = turnOf([+ ev("turn_started", { turn_id: "t1", provider: "codex-cli" }),+ ev("tool_call", { turn_id: "t1", call_id: "item_3", name: "spawn_agent", input: { prompt: "Reply with PONG" } }),+ ev("tool_result", { turn_id: "t1", call_id: "item_3", output: "child-1", is_error: false }),+ ev("subagent_started", { turn_id: "t1", agent_id: "item_3", thread_id: "child-1", description: "Reply with PONG", prompt: "Reply with PONG", background: true }),+ ]);+ expect(listSubagents([turn])[0].status).toBe("running");+ const done = turnOf([+ ...[+ ev("turn_started", { turn_id: "t1", provider: "codex-cli" }),+ ev("tool_call", { turn_id: "t1", call_id: "item_3", name: "spawn_agent", input: { prompt: "Reply with PONG" } }),+ ev("subagent_started", { turn_id: "t1", agent_id: "item_3", thread_id: "child-1", prompt: "Reply with PONG", background: true }),+ ev("tool_result", { turn_id: "t1", call_id: "item_3", output: "child-1", is_error: false }),+ ],+ ev("subagent_finished", { turn_id: "t1", agent_id: "item_3", status: "done", summary: "PONG" }),+ ]);+ const [entry] = listSubagents([done]);+ expect(entry.status).toBe("done");+ expect(subagentTurn(entry).blocks).toEqual([{ kind: "text", id: "answer:item_3", text: "PONG" }]);+ });+});++describe("sub-agents the CLI filed on its own", () => {+ const discovered = (over: Partial<DiscoveredAgent> = {}): DiscoveredAgent => ({+ thread_id: "child-1", parent_thread_id: "root", nickname: "Heisenberg", role: "default", path: "/root/grok_research",+ started_ms: 2000, updated_ms: 5000, status: "done", summary: "Found it.",+ events: [+ { seq: 0, ts_ms: 2100, kind: "tool_call", payload: { call_id: "c1", name: "RunCommand", input: { command: "ls" } } } as AgentChatEvent,+ { seq: 0, ts_ms: 2200, kind: "tool_result", payload: { call_id: "c1", output: "a.txt", is_error: false } } as AgentChatEvent,+ { seq: 0, ts_ms: 2300, kind: "assistant_text", payload: { message_id: "m1", text: "Found it." } } as AgentChatEvent,+ ],+ ...over,+ });+ const codexTurn = (status: "running" | "done"): TurnItem => turnOf([+ ev("turn_started", { turn_id: "t1", provider: "openai-codex" }, 1000),+ ev("tool_call", { turn_id: "t1", call_id: "c0", name: "RunCommand", input: { command: "git status" } }, 1500),+ ev("assistant_text", { turn_id: "t1", message_id: "m0", text: "All done." }, 6000),+ ...(status === "done" ? [ev("turn_finished", { turn_id: "t1", status: "done" }, 7000)] : []),+ ]);++ it("gives an unannounced Codex agent a card with its own steps in the turn it ran in", () => {+ const merged = mergeDiscovered([codexTurn("done")], [discovered()], "root");+ const [entry] = listSubagents(merged);+ expect(entry).toMatchObject({ title: "grok research", agentType: "Heisenberg", status: "done", summary: "Found it.", streamed: true });+ expect(entry.blocks.map((b) => b.kind)).toEqual(["tool", "text"]);+ // The card sits before the closing answer.+ const turn = merged[0] as TurnItem;+ expect(turn.blocks.map((b) => (b.kind === "tool" ? b.callId : b.kind))).toEqual(["c0", "codex:child-1", "text"]);+ });++ it("fills a spawn the stream announced instead of adding a second card", () => {+ const turn = turnOf([+ ev("turn_started", { turn_id: "t1", provider: "openai-codex" }, 1000),+ ev("tool_call", { turn_id: "t1", call_id: "item_3", name: "spawn_agent", input: { prompt: "Research" } }, 1500),+ ev("subagent_started", { turn_id: "t1", agent_id: "item_3", thread_id: "child-1", prompt: "Research", background: true }, 1500),+ ]);+ const entries = listSubagents(mergeDiscovered([turn], [discovered({ status: "running", summary: "" })], "root"));+ expect(entries).toHaveLength(1);+ expect(entries[0].id).toBe("item_3");+ expect(entries[0].streamed).toBe(true);+ expect(entries[0].status).toBe("running");+ });++ it("nests a sub-agent's own sub-agent and stops what a finished turn left running", () => {+ const merged = mergeDiscovered([codexTurn("done")], [+ discovered(),+ discovered({ thread_id: "grand-1", parent_thread_id: "child-1", path: "/root/grok_research/tests", status: "running", events: [] }),+ ], "root");+ const entries = listSubagents(merged);+ expect(entries.map((entry) => [entry.id, entry.depth, entry.parentId])).toEqual([["codex:child-1", 0, null], ["codex:grand-1", 1, "codex:child-1"]]);+ const lone = listSubagents(mergeDiscovered([codexTurn("done")], [discovered({ status: "running" })], "root"));+ expect(lone[0].status).toBe("stopped");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.tsnew file mode 100644index 0000000000..e68e5007c5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/subagents.ts@@ -0,0 +1,357 @@+import { EMPTY_TIMELINE, reduceEvents, type SubagentState, type SubagentStatus, type TextBlock, type TimelineItem, type ToolBlock, type TurnBlock, type TurnItem, type TurnStatus } from "@/components/agentchat/reduce";+import type { AgentChatEvent } from "@/lib/agentChatApi";++/**+ * The sub-agents of a thread, read the same way for every coding agent.+ *+ * Claude Code and Codex report their sub-agents (`subagent_*` events): those+ * carry a life — started, working, finished — and, for Claude Code, the+ * sub-agent's whole conversation. Every other CLI is read from its spawn+ * call alone: the task it was given (the call's input) and its answer (the+ * call's result). Either way a sub-agent is one entry here, keyed by the call+ * that spawned it, so the thread can count, list and open them.+ */++/** Tool names that spawn a sub-agent, across CLIs: Claude Code, Codex, OpenCode, Kimi and kin. */+const SPAWN_TOOLS = new Set([+ "task", "agent", "spawn_agent", "spawnagent", "subagent", "sub_agent", "spawn_subagent",+ "launch_agent", "dispatch_agent", "run_agent", "delegate_task",+]);++export function isSpawnTool(name: string): boolean {+ const bare = name.split("__").pop() ?? name;+ return SPAWN_TOOLS.has(bare.toLowerCase());+}++/** True when this call spawned a sub-agent — reported, or read off its tool name. */+export function isSubagentCall(block: ToolBlock): boolean {+ return Boolean(block.subagent) || isSpawnTool(block.name);+}++/** One sub-agent as the thread shows it. */+export interface SubagentEntry {+ /** The spawning call's id — the key everything opens a sub-agent by. */+ id: string;+ turnId: string;+ /** 0 for the main agent's own sub-agents, 1 for theirs, … */+ depth: number;+ /** The sub-agent that spawned this one; null for the main agent's. */+ parentId: string | null;+ title: string;+ agentType: string;+ prompt: string;+ status: SubagentStatus;+ summary: string;+ activity: string;+ tokens: number | null;+ toolUses: number | null;+ durationMs: number | null;+ startedMs: number;+ finishedMs: number | null;+ background: boolean;+ /** An approval or a question inside it waits for the person. */+ waiting: boolean;+ /** Its conversation; empty when the CLI only reported its task and answer. */+ blocks: TurnBlock[];+ /** The CLI streamed its conversation (not only its task and answer). */+ streamed: boolean;+ block: ToolBlock;+}++function text(value: unknown): string {+ return typeof value === "string" ? value.trim() : "";+}++function record(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};+}++/** The receipt a background spawn returns at once — never the agent's answer. */+export function isLaunchReceipt(output: string | null): boolean {+ return Boolean(output && /^(Async agent launched|agentId:)/i.test(output.trim()));+}++function firstLine(value: string, max = 80): string {+ const line = value.split(/\r?\n/).find((part) => part.trim())?.trim() ?? "";+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;+}++function waitsForPerson(blocks: TurnBlock[]): boolean {+ return blocks.some((b) => b.kind === "tool" && (+ (b.approval !== null && b.approval.decision === null)+ || (b.question !== undefined && !b.question.closed)+ ));+}++/** A sub-agent read from a spawn call the CLI did not report on. */+function derived(block: ToolBlock, turnStatus: TurnStatus): SubagentState {+ const input = record(block.input);+ const prompt = text(input.prompt) || text(input.message) || text(input.task) || text(input.instructions);+ const output = block.output;+ const status: SubagentStatus = output !== null && !isLaunchReceipt(output)+ ? block.isError ? "failed" : "done"+ : turnStatus === "running" ? "running" : "stopped";+ return {+ description: text(input.description) || text(input.title) || text(input.name),+ agentType: text(input.subagent_type) || text(input.agent_type) || text(input.agent) || text(input.role),+ prompt,+ background: Boolean(input.run_in_background),+ threadId: "",+ status,+ summary: status === "running" || isLaunchReceipt(output) ? "" : output ?? "",+ activity: "",+ lastTool: "",+ tokens: null,+ toolUses: null,+ durationMs: block.durationMs,+ startedMs: block.startedMs,+ finishedMs: block.durationMs !== null ? block.startedMs + block.durationMs : null,+ blocks: [],+ };+}++function entryOf(block: ToolBlock, turn: TurnItem, depth: number, parentId: string | null): SubagentEntry {+ const sub = block.subagent ?? derived(block, turn.status);+ const input = record(block.input);+ const title = sub.description || text(input.description) || firstLine(sub.prompt) || sub.agentType || "Sub-agent";+ return {+ id: block.callId,+ turnId: turn.id,+ depth,+ parentId,+ title,+ agentType: sub.agentType || text(input.subagent_type),+ prompt: sub.prompt || text(input.prompt),+ status: sub.status,+ summary: sub.summary,+ activity: sub.activity,+ tokens: sub.tokens,+ toolUses: sub.toolUses ?? (sub.blocks.length ? sub.blocks.filter((b) => b.kind === "tool").length : null),+ durationMs: sub.durationMs,+ startedMs: sub.startedMs,+ finishedMs: sub.finishedMs,+ background: sub.background,+ waiting: block.approval?.decision === null || waitsForPerson(sub.blocks),+ blocks: sub.blocks,+ streamed: sub.blocks.length > 0,+ block,+ };+}++function walk(blocks: TurnBlock[], turn: TurnItem, depth: number, parentId: string | null, out: SubagentEntry[]): void {+ for (const block of blocks) {+ if (block.kind !== "tool" || !isSubagentCall(block)) continue;+ const entry = entryOf(block, turn, depth, parentId);+ out.push(entry);+ walk(entry.blocks, turn, depth + 1, entry.id, out);+ }+}++/** Every sub-agent of a thread, in the order they were spawned, nested ones after their parent. */+export function listSubagents(items: readonly TimelineItem[]): SubagentEntry[] {+ const out: SubagentEntry[] = [];+ for (const item of items) if (item.type === "turn") walk(item.blocks, item, 0, null, out);+ return out;+}++/** The sub-agent a call spawned, read for the turn it ran in. */+export function subagentEntry(block: ToolBlock, turn: TurnItem): SubagentEntry {+ return entryOf(block, turn, 0, null);+}++/** The chain from the main agent's sub-agent down to `id`; empty when it is unknown. */+export function subagentPath(entries: readonly SubagentEntry[], id: string): SubagentEntry[] {+ const byId = new Map(entries.map((entry) => [entry.id, entry]));+ const path: SubagentEntry[] = [];+ let at = byId.get(id);+ while (at) {+ path.unshift(at);+ at = at.parentId ? byId.get(at.parentId) : undefined;+ }+ return path;+}++/** How many are still working, and how many in all. */+export function subagentCounts(entries: readonly SubagentEntry[]): { total: number; running: number; failed: number; waiting: number } {+ return {+ total: entries.length,+ running: entries.filter((entry) => entry.status === "running").length,+ failed: entries.filter((entry) => entry.status === "failed").length,+ waiting: entries.filter((entry) => entry.waiting).length,+ };+}++const TURN_STATUS: Record<SubagentStatus, TurnStatus> = { running: "running", done: "done", failed: "error", stopped: "cancelled" };++/**+ * A sub-agent's conversation as a turn, so the thread draws it exactly like+ * the main agent's work: its steps, thoughts and answer. A CLI that only+ * reported the answer shows that answer as the text.+ */+export function subagentTurn(entry: SubagentEntry): TurnItem {+ const answer: TextBlock[] = !entry.streamed && entry.summary.trim()+ ? [{ kind: "text", id: `answer:${entry.id}`, text: entry.summary }]+ : [];+ const running = entry.status === "running";+ return {+ type: "turn",+ id: `agent:${entry.id}`,+ provider: "",+ model: "",+ effort: "",+ runner: "",+ status: TURN_STATUS[entry.status],+ blocks: [...entry.blocks, ...answer],+ startedMs: entry.startedMs,+ durationMs: running ? null : entry.durationMs ?? (entry.finishedMs !== null ? Math.max(0, entry.finishedMs - entry.startedMs) : null),+ usage: null,+ liveUsage: null,+ costUsd: null,+ error: entry.status === "failed" ? firstLine(entry.summary, 300) || null : null,+ };+}++/** "23.4k tokens" — a count the way a dense line says it. */+export function shortCount(value: number): string {+ if (value < 1000) return String(value);+ if (value < 100_000) return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`;+ if (value < 1_000_000) return `${Math.round(value / 1000)}k`;+ return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;+}++/** A sub-agent the CLI filed on its own (a Codex rollout), as `/sessions/{id}/subagents` returns it. */+export interface DiscoveredAgent {+ thread_id: string;+ parent_thread_id: string;+ nickname: string;+ role: string;+ path: string;+ started_ms: number;+ updated_ms: number;+ status: string;+ summary: string;+ events: AgentChatEvent[];+}++/** The sub-agents a thread's CLI filed on its own; empty for a CLI that streams them. */+export async function fetchDiscoveredAgents(sessionId: string): Promise<DiscoveredAgent[]> {+ const res = await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/subagents`);+ if (!res.ok) throw new Error(`sub-agents unavailable (${res.status})`);+ const body = (await res.json()) as { agents?: DiscoveredAgent[] };+ return Array.isArray(body.agents) ? body.agents : [];+}++function discoveredStatus(raw: string): SubagentStatus {+ return raw === "done" || raw === "failed" || raw === "stopped" ? raw : "running";+}++/** "/root/grok_research" → "grok research": the task name Codex gave the agent. */+function pathTitle(path: string): string {+ const tail = path.split("/").filter(Boolean).pop() ?? "";+ return tail.replace(/[_-]+/g, " ").trim();+}++/** A discovered agent's own steps, folded by the same reducer as the thread. */+function discoveredBlocks(agent: DiscoveredAgent): TurnBlock[] {+ const scratch = "discovered";+ const events: AgentChatEvent[] = [+ { seq: 0, ts_ms: agent.started_ms, kind: "turn_started", payload: { turn_id: scratch } } as AgentChatEvent,+ ...agent.events.map((event) => ({ ...event, seq: 0, payload: { ...event.payload, turn_id: scratch } })),+ ];+ const turn = reduceEvents(EMPTY_TIMELINE, events).items.find((item): item is TurnItem => item.type === "turn");+ return turn?.blocks ?? [];+}++function findThread(blocks: TurnBlock[], threadId: string): boolean {+ return blocks.some((b) => b.kind === "tool" && (b.subagent?.threadId === threadId || (b.subagent ? findThread(b.subagent.blocks, threadId) : false)));+}++/** `blocks` with `fn` applied to the spawn block of `threadId`, wherever it sits. */+function patchThread(blocks: TurnBlock[], threadId: string, fn: (b: ToolBlock) => ToolBlock): TurnBlock[] {+ let changed = false;+ const next = blocks.map((b) => {+ if (b.kind !== "tool" || !b.subagent) return b;+ if (b.subagent.threadId === threadId) { changed = true; return fn(b); }+ const inner = patchThread(b.subagent.blocks, threadId, fn);+ if (inner === b.subagent.blocks) return b;+ changed = true;+ return { ...b, subagent: { ...b.subagent, blocks: inner } };+ });+ return changed ? next : blocks;+}++/** Where a new card goes: before the first call made after it started, else before the closing answer. */+function insertAt(blocks: TurnBlock[], startedMs: number, finished: boolean): number {+ const later = blocks.findIndex((b) => b.kind === "tool" && b.startedMs > startedMs);+ if (later >= 0) return later;+ if (!finished) return blocks.length;+ let at = blocks.length;+ while (at > 0 && blocks[at - 1].kind === "text") at -= 1;+ return at;+}++/**+ * The thread with the sub-agents its CLI filed on its own folded in: a known+ * one (its spawn call named its thread) gains its steps and its end; an+ * unknown one gets a card of its own in the turn it ran in, or inside the+ * sub-agent that spawned it.+ */+export function mergeDiscovered(items: TimelineItem[], agents: readonly DiscoveredAgent[], rootThread: string): TimelineItem[] {+ if (!agents.length) return items;+ let next = items;+ for (const agent of agents) {+ const blocks = discoveredBlocks(agent);+ const status = discoveredStatus(agent.status);+ const turnIndex = next.findIndex((item) => item.type === "turn" && findThread(item.blocks, agent.thread_id));+ if (turnIndex >= 0) {+ const turn = next[turnIndex] as TurnItem;+ const patched = patchThread(turn.blocks, agent.thread_id, (b) => {+ const sub = b.subagent!;+ return {+ ...b,+ subagent: {+ ...sub,+ blocks: sub.blocks.length ? sub.blocks : blocks,+ summary: sub.summary || agent.summary,+ status: sub.status === "running" && status !== "running" ? status : sub.status,+ },+ };+ });+ next = next.map((item, index) => (index === turnIndex ? { ...turn, blocks: patched } : item));+ continue;+ }+ const spawn: ToolBlock = {+ kind: "tool", callId: `codex:${agent.thread_id}`, name: "spawn_agent", input: null, output: null,+ isError: false, durationMs: null, approval: null, startedMs: agent.started_ms,+ subagent: {+ description: pathTitle(agent.path) || agent.nickname, agentType: agent.nickname || (agent.role !== "default" ? agent.role : ""),+ prompt: "", background: true, threadId: agent.thread_id, status, summary: agent.summary,+ activity: "", lastTool: "", tokens: null, toolUses: null, durationMs: null,+ startedMs: agent.started_ms, finishedMs: status === "running" ? null : agent.updated_ms || null, blocks,+ },+ };+ if (agent.parent_thread_id && agent.parent_thread_id !== rootThread) {+ const parentIndex = next.findIndex((item) => item.type === "turn" && findThread(item.blocks, agent.parent_thread_id));+ if (parentIndex < 0) continue;+ const turn = next[parentIndex] as TurnItem;+ const patched = patchThread(turn.blocks, agent.parent_thread_id, (b) => ({+ ...b,+ subagent: { ...b.subagent!, blocks: [...b.subagent!.blocks, spawn] },+ }));+ next = next.map((item, index) => (index === parentIndex ? { ...turn, blocks: patched } : item));+ continue;+ }+ let turnAt = -1;+ next.forEach((item, index) => { if (item.type === "turn" && item.startedMs <= agent.started_ms) turnAt = index; });+ if (turnAt < 0) continue;+ const turn = next[turnAt] as TurnItem;+ const running = turn.status === "running";+ // A turn that ended took its sub-agents with it.+ const placed = !running && status === "running"+ ? { ...spawn, subagent: { ...spawn.subagent!, status: "stopped" as const, finishedMs: agent.updated_ms || agent.started_ms } }+ : spawn;+ const at = insertAt(turn.blocks, agent.started_ms, !running);+ next = next.map((item, index) => (index === turnAt ? { ...turn, blocks: [...turn.blocks.slice(0, at), placed, ...turn.blocks.slice(at)] } : item));+ }+ return next;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/threadWork.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/threadWork.tsindex 770b3b67dd..3ee9679b44 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/threadWork.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/threadWork.ts@@ -16,6 +16,7 @@import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnStatus } from "@/components/agentchat/reduce";import { buildTimeline, summarize, type Call, type CallKind, type Translate } from "@/components/agentchat/traceEntries";+import { isSubagentCall } from "./subagents";/** One step of a group: a tool call, or the wordless thought a running turn is having. */export type WorkItem =@@ -43,7 +44,9 @@ export type ThreadRow =/** A thought in the agent's own words, read as a paragraph between its work. */| { kind: "thought"; id: string; text: string; block: ReasoningBlock; live: boolean }/** A call that waits for the person: an approval or a question card. */- | { kind: "pending"; id: string; block: ToolBlock };+ | { kind: "pending"; id: string; block: ToolBlock }+ /** A sub-agent the turn spawned: a card of its own that opens its conversation. */+ | { kind: "agent"; id: string; block: ToolBlock };export function isFailed(call: Call): boolean {return call.status === "failed" || call.status === "blocked" || call.status === "declined";@@ -113,7 +116,14 @@ export function buildThreadRows(blocks: TurnBlock[], options: { t: Translate; lafor (const entry of timeline.entries) {if (entry.kind === "activity") {- for (const call of entry.calls) items.push({ kind: "call", id: call.id, call, startedMs: started.get(call.id) ?? 0 });+ for (const call of entry.calls) {+ if (isSubagentCall(call.block)) {+ flush();+ rows.push({ kind: "agent", id: `agent:${call.id}`, block: call.block });+ } else {+ items.push({ kind: "call", id: call.id, call, startedMs: started.get(call.id) ?? 0 });+ }+ }continue;}const block = entry.block;@@ -130,6 +140,8 @@ export function buildThreadRows(blocks: TurnBlock[], options: { t: Translate; la}flush();if (block.kind === "text") rows.push({ kind: "text", id: entry.id, text: block.text, block });+ // A sub-agent waiting on an approval keeps its card; the card says it waits.+ else if (isSubagentCall(block)) rows.push({ kind: "agent", id: `agent:${block.callId}`, block });else rows.push({ kind: "pending", id: entry.id, block });}flush();