From b0839e45b995b7ed5407b442c74db2ef9711c15d Mon Sep 17 00:00:00 2001 From: T3 Code Test Date: Thu, 13 Aug 2026 05:47:16 +0530 Subject: [PATCH] feat(web): show v2 subagents through the Agents CTA --- apps/web/src/components/ChatView.tsx | 2 + .../chat/MessagesTimeline.logic.test.ts | 146 ++++++++++ .../components/chat/MessagesTimeline.logic.ts | 63 +++++ .../components/chat/MessagesTimeline.test.tsx | 46 +-- .../src/components/chat/MessagesTimeline.tsx | 261 +++++++++++++++--- .../src/state/subagentRuntime.test.ts | 152 +++++++++- .../src/state/subagentRuntime.ts | 104 ++++--- 7 files changed, 672 insertions(+), 102 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1b0f72654f..f215894b79 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -6419,6 +6419,8 @@ function ChatViewContent(props: ChatViewProps) {
{/* Messages — LegendList handles virtualization and scrolling internally */} = {}): RuntimeSubagent { + return { + id, + kind: "subagent", + title: id, + role: null, + model: null, + effort: null, + status: "running", + activationCount: 1, + usage: null, + progress: null, + lastToolName: null, + result: null, + error: null, + outputFile: null, + parentAgentId: null, + agentIndex: null, + phaseIndex: null, + phaseTitle: null, + attempt: null, + workflowName: null, + phases: [], + runHandles: null, + recentActivity: [], + firstSeenAt: "2026-08-13T10:00:00.000Z", + startedAt: "2026-08-13T10:00:00.000Z", + completedAt: null, + updatedAt: "2026-08-13T10:00:00.000Z", + ...overrides, + }; +} + +function subagentTimelineEntry(id: string, runId: string | null): TimelineEntry { + return { + id: `entry:${id}`, + kind: "event", + createdAt: "2026-08-13T10:00:00.000Z", + projectedItem: { + item: { id: `item:${id}`, type: "subagent", subagentId: id, runId }, + } as never, + }; +} + +describe("collapseSubagentTimelineEntries", () => { + it("keeps one CTA anchor per workflow and per-run direct-spawn batch", () => { + const coordinator = runtimeAgent("workflow-1", { + kind: "workflow", + phases: [{ index: 0, title: "Inspect" }], + }); + const memberOne = runtimeAgent("member-1", { + kind: "workflow_agent", + parentAgentId: coordinator.id, + phaseIndex: 0, + }); + const memberTwo = runtimeAgent("member-2", { + kind: "workflow_agent", + parentAgentId: coordinator.id, + phaseIndex: 0, + }); + const directOne = runtimeAgent("direct-1"); + const directTwo = runtimeAgent("direct-2"); + const agentPanelModel = { + workflows: [ + { + workflow: coordinator, + phases: [ + { + index: 0, + title: "Inspect", + members: [memberOne, memberTwo], + state: "running", + activeCount: 2, + settledCount: 0, + }, + ], + unphasedMembers: [], + }, + ], + directAgents: [directOne, directTwo], + runningCount: 5, + waitingCount: 0, + idleCount: 0, + settledCount: 0, + totalTokens: 0, + hasAgents: true, + liveCount: 5, + } satisfies AgentPanelModel; + const result = collapseSubagentTimelineEntries({ + timelineEntries: [ + subagentTimelineEntry(memberOne.id, "run-1"), + subagentTimelineEntry(coordinator.id, "run-1"), + subagentTimelineEntry(memberTwo.id, "run-1"), + subagentTimelineEntry(directOne.id, "run-1"), + subagentTimelineEntry(directTwo.id, "run-1"), + ], + agentPanelModel, + }); + + expect(result.timelineEntries.map((entry) => entry.id)).toEqual([ + "entry:member-1", + "entry:direct-1", + ]); + expect(result.ctaByItemId.get("item:member-1")).toEqual({ + workflowId: "workflow-1", + agentIds: ["member-1", "workflow-1", "member-2"], + }); + expect(result.ctaByItemId.get("item:direct-1")).toEqual({ + workflowId: null, + agentIds: ["direct-1", "direct-2"], + }); + }); + + it("does not merge direct spawns from different or unknown runs", () => { + const emptyModel = { + workflows: [], + directAgents: [], + runningCount: 0, + waitingCount: 0, + idleCount: 0, + settledCount: 0, + totalTokens: 0, + hasAgents: false, + liveCount: 0, + } satisfies AgentPanelModel; + const result = collapseSubagentTimelineEntries({ + timelineEntries: [ + subagentTimelineEntry("direct-1", "run-1"), + subagentTimelineEntry("direct-2", "run-2"), + subagentTimelineEntry("direct-3", null), + subagentTimelineEntry("direct-4", null), + ], + agentPanelModel: emptyModel, + }); + + expect(result.timelineEntries).toHaveLength(4); + expect(result.ctaByItemId.size).toBe(4); + }); +}); describe("computeMessageDurationStart", () => { it("returns message createdAt when there is no preceding user message", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index fff0516f2f..3775f049f2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -13,6 +13,7 @@ import { type RunId, } from "@t3tools/contracts"; import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell"; +import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime"; import { formatPendingBackgroundWorkLabel } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { resolveT3McpToolPresentation, @@ -168,6 +169,68 @@ export type TimelineLatestRun = Pick< "runId" | "status" | "startedAt" | "completedAt" >; +export interface AgentSpawnCtaGroup { + readonly workflowId: string | null; + readonly agentIds: ReadonlyArray; +} + +/** + * Replaces the per-subagent V2 lifecycle cards with one stable CTA anchor per + * workflow, or one per-run batch for direct spawns. The Agents panel remains + * the only roster; timeline rows only retain enough identity to derive their + * live summary from that panel model. + */ +export function collapseSubagentTimelineEntries(input: { + readonly timelineEntries: ReadonlyArray; + readonly agentPanelModel: AgentPanelModel; +}): { + readonly timelineEntries: ReadonlyArray; + readonly ctaByItemId: ReadonlyMap; +} { + const workflowIdByAgentId = new Map(); + for (const group of input.agentPanelModel.workflows) { + workflowIdByAgentId.set(group.workflow.id, group.workflow.id); + for (const member of [ + ...group.phases.flatMap((phase) => phase.members), + ...group.unphasedMembers, + ]) { + workflowIdByAgentId.set(member.id, group.workflow.id); + } + } + + const timelineEntries: TimelineEntry[] = []; + const anchorItemIdByGroup = new Map(); + const ctaByItemId = new Map(); + for (const entry of input.timelineEntries) { + if (entry.kind !== "event" || entry.projectedItem.item.type !== "subagent") { + timelineEntries.push(entry); + continue; + } + + const item = entry.projectedItem.item; + const workflowId = workflowIdByAgentId.get(item.subagentId) ?? null; + const groupKey = + workflowId === null ? `direct:${item.runId ?? item.subagentId}` : `workflow:${workflowId}`; + const anchorItemId = anchorItemIdByGroup.get(groupKey); + if (anchorItemId === undefined) { + anchorItemIdByGroup.set(groupKey, item.id); + ctaByItemId.set(item.id, { workflowId, agentIds: [item.subagentId] }); + timelineEntries.push(entry); + continue; + } + + const current = ctaByItemId.get(anchorItemId); + if (current !== undefined && !current.agentIds.includes(item.subagentId)) { + ctaByItemId.set(anchorItemId, { + ...current, + agentIds: [...current.agentIds, item.subagentId], + }); + } + } + + return { timelineEntries, ctaByItemId }; +} + export type MessagesTimelineRow = | { kind: "work"; diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 41e635fd5f..f60286567c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1070,7 +1070,7 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain("Work Log"); }); - it("renders live subagent progress on the persistent linked card", async () => { + it("renders a live subagent as an Agents-panel CTA", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); + expect(markup).toContain('data-agent-spawn-cta="true"'); expect(markup).not.toContain('aria-label="Open Package audit"'); - expect(markup).toContain("Reading src/index.ts"); + expect(markup).toContain("Kicked off 1 subagent"); + expect(markup).toContain("1 working"); + expect(markup).toContain("Open Agents"); + expect(markup).not.toContain("Reading src/index.ts"); expect(markup).not.toContain("Inspect the package"); expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); expect(markup).not.toContain("Work Log"); }); - it("discloses the full Codex subagent result without projecting child events", async () => { + it("keeps completed subagent detail in the Agents panel", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); - expect(markup).toContain('data-v2-subagent-result-disclosure="true"'); - expect(markup).toContain('data-v2-subagent-result="true"'); - expect(markup).toContain('aria-label="Show full result for Isolation report"'); + expect(markup).toContain("Ran 1 subagent"); + expect(markup).toContain("completed"); + expect(markup).toContain("View"); + expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); + expect(markup).not.toContain('data-v2-subagent-result="true"'); expect(markup).not.toContain('aria-label="Open Isolation report"'); - expect(markup).toContain("Tests should be isolated."); - expect(markup).toContain("Result: no shared state."); + expect(markup).not.toContain("Tests should be isolated."); + expect(markup).not.toContain("Result: no shared state."); expect(markup).not.toContain("Explain test isolation"); }); - it("keeps live progress when a running subagent streams a partial result", async () => { + it("keeps streaming subagent detail out of the CTA roster summary", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { expect(markup).toContain('data-v2-item-type="subagent"'); expect(markup).not.toContain('aria-label="Open Package audit"'); - expect(markup).toContain("Reading src/index.ts"); + expect(markup).toContain("Kicked off 1 subagent"); + expect(markup).toContain("Open Agents"); + expect(markup).not.toContain("Reading src/index.ts"); expect(markup).not.toContain("Partial streamed answer so far"); expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); - it("shows the streamed result while a subagent runs without progress", async () => { + it("keeps a streamed result in the Agents panel while the CTA stays compact", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); - expect(markup).toContain("Streaming answer so far"); + expect(markup).toContain("Kicked off 1 subagent"); + expect(markup).toContain("Open Agents"); + expect(markup).not.toContain("Streaming answer so far"); expect(markup).not.toContain("Inspect the package"); expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); - it("treats a cancelled subagent result as partial output", async () => { + it("renders a cancelled subagent batch as stopped", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); - expect(markup).toContain("Partial output before cancel"); + expect(markup).toContain("Ran 1 subagent"); + expect(markup).toContain("1 stopped"); + expect(markup).not.toContain("Partial output before cancel"); expect(markup).not.toContain("Reading src/index.ts"); expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); - it("falls back to progress when a completed subagent result is whitespace-only", async () => { + it("renders a completed subagent batch without inline progress", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { ); expect(markup).toContain('data-v2-item-type="subagent"'); - expect(markup).toContain("Audited 12 packages"); + expect(markup).toContain("Ran 1 subagent"); + expect(markup).toContain("completed"); + expect(markup).not.toContain("Audited 12 packages"); expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index e8fc5955f8..a9db4d61e9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -11,6 +11,11 @@ import { } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; +import { + emptyAgentPanelModel, + formatSubagentTokenCount, + type AgentPanelModel, +} from "@t3tools/client-runtime/state/subagentRuntime"; import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; import { createContext, @@ -75,6 +80,7 @@ import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation"; import { MessageCopyButton } from "./MessageCopyButton"; import { computeStableMessagesTimelineRows, + collapseSubagentTimelineEntries, MAX_VISIBLE_WORK_LOG_ENTRIES, deriveMessagesTimelineRows, normalizeCompactToolLabel, @@ -88,6 +94,7 @@ import { resolveTimelineMinimapInteractiveWidth, resolveTimelineMinimapTopPercent, type StableMessagesTimelineRowsState, + type AgentSpawnCtaGroup, type MessagesTimelineRow, TIMELINE_MINIMAP_MIN_ITEMS, type TimelineLatestRun, @@ -172,8 +179,15 @@ interface TimelineRowActivityState { latestRunId: RunId | null; } +interface TimelineAgentSpawnState { + readonly agentPanelModel: AgentPanelModel; + readonly ctaByItemId: ReadonlyMap; + readonly onOpenAgents: () => void; +} + const TimelineRowCtx = createContext(null!); const TimelineRowActivityCtx = createContext(null!); +const TimelineAgentSpawnCtx = createContext(null!); const TIMELINE_LIST_HEADER =
; const TIMELINE_LIST_FADE_HEADER =
; const TIMELINE_LIST_FOOTER =
; @@ -188,6 +202,8 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END = { } as const; const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray = []; const EMPTY_TIMELINE_RUNS: ReadonlyArray = []; +const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel(); +const NOOP_OPEN_AGENTS = () => {}; // --------------------------------------------------------------------------- // Props (public API) @@ -201,6 +217,8 @@ export interface MessagesTimelineHistoryControls { } interface MessagesTimelineProps { + agentPanelModel?: AgentPanelModel; + onOpenAgents?: () => void; isWorking: boolean; activeTurnInProgress: boolean; activeTurnStartedAt: string | null; @@ -262,6 +280,8 @@ interface MessagesTimelineProps { // --------------------------------------------------------------------------- export const MessagesTimeline = memo(function MessagesTimeline({ + agentPanelModel = EMPTY_AGENT_PANEL_MODEL, + onOpenAgents = NOOP_OPEN_AGENTS, isWorking, activeTurnInProgress, activeTurnStartedAt, @@ -408,10 +428,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }); }, [latestRun]); + const agentSpawnTimeline = useMemo( + () => collapseSubagentTimelineEntries({ timelineEntries, agentPanelModel }), + [agentPanelModel, timelineEntries], + ); const rawRows = useMemo( () => deriveMessagesTimelineRows({ - timelineEntries, + timelineEntries: agentSpawnTimeline.timelineEntries, latestRun, expandedRunIds, expandedAttemptIds, @@ -422,7 +446,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ revertTurnCountByUserMessageId, }), [ - timelineEntries, + agentSpawnTimeline.timelineEntries, latestRun, expandedRunIds, expandedAttemptIds, @@ -591,6 +615,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }), [activeTurnInProgress, isRevertingCheckpoint, isWorking, latestRun?.runId], ); + const agentSpawnState = useMemo( + () => ({ + agentPanelModel, + ctaByItemId: agentSpawnTimeline.ctaByItemId, + onOpenAgents, + }), + [agentPanelModel, agentSpawnTimeline.ctaByItemId, onOpenAgents], + ); const listHeader = useMemo(() => { const leadingContent = parentThreadLink === null ? ( @@ -655,50 +687,52 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return ( -
- - ref={listRef} - data={rows} - keyExtractor={keyExtractor} - getItemType={getItemType} - renderItem={renderItem} - estimatedItemSize={90} - initialScrollAtEnd - {...(anchoredEndSpace ? { anchoredEndSpace } : {})} - contentInsetEndAdjustment={contentInsetEndAdjustment} - // LegendList owns ordinary end-follow (#5449): the app only turns - // it off while the user reads history (liveFollowEnabled), while a - // sent turn anchors near the top (anchoredEndSpace), or for the - // two-frame settle window of a fold toggle. - maintainScrollAtEnd={ - anchoredEndSpace || !liveFollowEnabled || disclosureToggleSettling - ? false - : TIMELINE_MAINTAIN_SCROLL_AT_END - } - maintainVisibleContentPosition={maintainVisibleContentPosition} - onScroll={handleScroll} - className={cn( - "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5", - topFadeEnabled && "chat-timeline-scroll-fade", - )} - ListHeaderComponent={listHeader} - ListFooterComponent={TIMELINE_LIST_FOOTER} - /> - { - onManualNavigation(); - void listRef.current?.scrollToIndex({ - index: item.rowIndex, - animated: true, - viewOffset: 24, - }); - }} - /> -
+ +
+ + ref={listRef} + data={rows} + keyExtractor={keyExtractor} + getItemType={getItemType} + renderItem={renderItem} + estimatedItemSize={90} + initialScrollAtEnd + {...(anchoredEndSpace ? { anchoredEndSpace } : {})} + contentInsetEndAdjustment={contentInsetEndAdjustment} + // LegendList owns ordinary end-follow (#5449): the app only turns + // it off while the user reads history (liveFollowEnabled), while a + // sent turn anchors near the top (anchoredEndSpace), or for the + // two-frame settle window of a fold toggle. + maintainScrollAtEnd={ + anchoredEndSpace || !liveFollowEnabled || disclosureToggleSettling + ? false + : TIMELINE_MAINTAIN_SCROLL_AT_END + } + maintainVisibleContentPosition={maintainVisibleContentPosition} + onScroll={handleScroll} + className={cn( + "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5", + topFadeEnabled && "chat-timeline-scroll-fade", + )} + ListHeaderComponent={listHeader} + ListFooterComponent={TIMELINE_LIST_FOOTER} + /> + { + onManualNavigation(); + void listRef.current?.scrollToIndex({ + index: item.rowIndex, + animated: true, + viewOffset: 24, + }); + }} + /> +
+
); @@ -1527,9 +1561,144 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { } } +/** One compact timeline anchor; the Agents panel remains the only roster. */ +const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { + readonly item: Extract; + readonly createdAt: string; +}) { + const shared = use(TimelineRowCtx); + const { agentPanelModel, ctaByItemId, onOpenAgents } = use(TimelineAgentSpawnCtx); + const spawn = ctaByItemId.get(props.item.id); + if (spawn === undefined) { + return ( + + ); + } + + const memberIds = new Set(spawn.agentIds); + const workflowGroup = + spawn.workflowId === null + ? undefined + : agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId); + const agents = + workflowGroup === undefined + ? agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id)) + : [ + ...workflowGroup.phases.flatMap((phase) => phase.members), + ...workflowGroup.unphasedMembers, + ]; + const fallbackMemberCount = + spawn.workflowId === null + ? memberIds.size + : [...memberIds].filter((id) => id !== spawn.workflowId).length; + const agentCount = Math.max(agents.length, fallbackMemberCount); + const useItemStatus = agents.length === 0; + const running = useItemStatus + ? props.item.status === "running" || props.item.status === "pending" + ? 1 + : 0 + : agents.filter((agent) => agent.status === "running" || agent.status === "pending").length; + const waiting = useItemStatus + ? props.item.status === "waiting" + ? 1 + : 0 + : agents.filter((agent) => agent.status === "waiting").length; + const idle = useItemStatus ? 0 : agents.filter((agent) => agent.status === "idle").length; + const failed = useItemStatus + ? props.item.status === "failed" + ? 1 + : 0 + : agents.filter((agent) => agent.status === "failed").length; + const stopped = useItemStatus + ? props.item.status === "cancelled" || props.item.status === "interrupted" + ? 1 + : 0 + : agents.filter((agent) => agent.status === "cancelled" || agent.status === "interrupted") + .length; + const coordinatorStatus = workflowGroup?.workflow.status; + const coordinatorSettled = + coordinatorStatus === "completed" || + coordinatorStatus === "failed" || + coordinatorStatus === "cancelled" || + coordinatorStatus === "interrupted"; + const live = workflowGroup === undefined ? running + waiting > 0 : !coordinatorSettled; + const totalTokens = agents.reduce( + (sum, agent) => sum + (agent.usage?.totalTokens ?? 0), + workflowGroup !== undefined && agents.length === 0 + ? (workflowGroup.workflow.usage?.totalTokens ?? 0) + : 0, + ); + const livePhase = workflowGroup?.phases.find((phase) => phase.state === "running"); + const workflowName = + workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null; + const working = running + waiting; + const dotClass = live + ? "bg-info" + : failed > 0 + ? "bg-destructive" + : idle > 0 + ? "bg-muted-foreground/50" + : "bg-success"; + const lead = + workflowGroup !== undefined && agentCount === 0 + ? live + ? "Started workflow" + : "Ran workflow" + : live + ? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}` + : `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`; + const status = live + ? livePhase + ? `${livePhase.title} · ${livePhase.activeCount} working` + : working > 0 + ? `${working} working` + : "working" + : failed > 0 + ? `${failed} failed` + : idle > 0 + ? `${idle} idle` + : stopped > 0 + ? `${stopped} stopped` + : "✓ completed"; + + return ( + + ); +}); + function V2EventTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const { item, visibility, sourceThreadId } = row.projectedItem; + if (item.type === "subagent") { + return ; + } if (isV2LifecycleItem(item)) { return ( { it("counts idle deliberately and waiting as active", () => { const model = deriveAgentPanelModel({ agents: roster }); expect(model.idleCount).toBe(1); - // wf-1 coordinator + member 1 running. + // A coordinator with live members is not double-counted in the footer. expect(model.runningCount).toBeGreaterThanOrEqual(1); + const renderedAgentCount = + model.directAgents.length + + model.workflows.reduce( + (count, group) => + count + + group.phases.reduce((phaseCount, phase) => phaseCount + phase.members.length, 0) + + group.unphasedMembers.length, + 0, + ); expect(model.idleCount + model.runningCount + model.waitingCount + model.settledCount).toBe( - roster.length, + renderedAgentCount, ); }); @@ -456,6 +476,40 @@ describe("deriveAgentPanelModel", () => { expect(model.workflows[0]!.phases[0]!.state).not.toBe("done"); }); + it("marks skipped empty phases done after the workflow settles", () => { + const settledRoster = fold([ + activity("task.started", { taskId: "wf-settled", taskType: "local_workflow" }), + activity("task.progress", { + taskId: "wf-settled", + phases: [{ index: 0, title: "Optional review" }], + }), + activity("task.completed", { + taskId: "wf-settled", + taskType: "local_workflow", + status: "completed", + }), + ]); + + expect(deriveAgentPanelModel({ agents: settledRoster }).workflows[0]?.phases[0]?.state).toBe( + "done", + ); + }); + + it("counts a live coordinator between settled-member phases", () => { + const betweenPhases = fold([ + activity("task.started", { taskId: "wf-live", taskType: "local_workflow" }), + activity("task.progress", { + taskId: "wf-live:wf:0", + parentAgentId: "wf-live", + status: "completed", + }), + ]); + const model = deriveAgentPanelModel({ agents: betweenPhases }); + + expect(model.runningCount).toBe(1); + expect(model.settledCount).toBe(1); + }); + it("v2 projection wins outright and sources are never merged", () => { const v2Agent = { ...roster[0]!, id: "v2-only", title: "From v2" }; const model = deriveAgentPanelModel({ agents: roster, v2Projection: [v2Agent] }); @@ -508,6 +562,98 @@ describe("workflowCardMembers", () => { }); }); +describe("projectedSubagentsToRuntime", () => { + it("preserves workflow, membership, usage, activity, and idle state", () => { + const now = DateTime.makeUnsafe("2026-08-13T10:00:00.000Z"); + const coordinatorId = NodeId.make("workflow-1"); + const memberId = NodeId.make("workflow-1:agent-0"); + const threadId = ThreadId.make("thread-1"); + const runId = RunId.make("run-1"); + const providerInstanceId = ProviderInstanceId.make("claude"); + const coordinator = { + id: coordinatorId, + threadId, + runId, + parentNodeId: NodeId.make("root-1"), + origin: "provider_native", + createdBy: "agent", + driver: ProviderDriverKind.make("claude"), + providerInstanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Run the review workflow", + title: "Review", + model: "claude-opus-4-1", + kind: "workflow", + role: { name: "coordinator", source: "provider" }, + status: "running", + progress: "Reviewing", + result: null, + usage: { totalTokens: 300 }, + currentActivationId: null, + activationCount: 1, + workflow: { + name: "review", + phases: [{ index: 0, title: "Inspect" }], + runId: "workflow-run-1", + scriptPath: "/tmp/review.js", + }, + workflowMembership: null, + recentActivity: [], + startedAt: now, + completedAt: null, + updatedAt: now, + } satisfies OrchestrationV2Subagent; + const member = { + ...coordinator, + id: memberId, + parentNodeId: coordinatorId, + prompt: "Inspect the implementation", + title: "Reviewer", + kind: "workflow_agent", + role: { name: "reviewer", source: "provider" }, + status: "idle", + progress: undefined, + usage: { totalTokens: 120, toolUses: 3 }, + activationCount: 2, + workflow: null, + workflowMembership: { + workflowSubagentId: coordinatorId, + agentIndex: 0, + phaseIndex: 0, + attempt: 2, + }, + recentActivity: [{ at: now, summary: "Inspected the implementation" }], + } satisfies OrchestrationV2Subagent; + + const runtime = projectedSubagentsToRuntime([coordinator, member]); + const model = deriveAgentPanelModel({ agents: [], v2Projection: runtime }); + + expect(model.workflows[0]?.workflow).toMatchObject({ + id: "workflow-1", + kind: "workflow", + workflowName: "review", + runHandles: { runId: "workflow-run-1", scriptPath: "/tmp/review.js" }, + }); + expect(model.workflows[0]?.phases[0]).toMatchObject({ + index: 0, + title: "Inspect", + state: "running", + }); + expect(model.workflows[0]?.phases[0]?.members[0]).toMatchObject({ + id: "workflow-1:agent-0", + status: "idle", + role: "reviewer", + activationCount: 2, + usage: { totalTokens: 120, toolUses: 3 }, + parentAgentId: "workflow-1", + phaseTitle: "Inspect", + progress: "Inspected the implementation", + }); + }); +}); + describe("timeline predicates", () => { it("recognizes subagent activity kinds as fold input", () => { for (const kind of [ diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index d044f4f0ab..e5ac4b47e8 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -18,7 +18,7 @@ * metadata). */ import * as DateTime from "effect/DateTime"; -import type { OrchestrationThreadActivity } from "@t3tools/contracts"; +import type { OrchestrationThreadActivity, OrchestrationV2Subagent } from "@t3tools/contracts"; export type RuntimeSubagentStatus = | "pending" @@ -724,56 +724,71 @@ export function emptyAgentPanelModel(): AgentPanelModel { * The panel/CTA components never see which source fed them. */ export function projectedSubagentsToRuntime( - subagents: ReadonlyArray<{ - readonly id: string; - readonly title: string | null; - readonly prompt: string; - readonly model: string | null; - readonly status: - | "pending" - | "running" - | "waiting" - | "completed" - | "failed" - | "cancelled" - | "interrupted"; - readonly progress?: string | undefined; - readonly result: string | null; - readonly startedAt: DateTime.Utc | null; - readonly completedAt: DateTime.Utc | null; - readonly updatedAt: DateTime.Utc; - }>, + subagents: ReadonlyArray, ): ReadonlyArray { + const subagentById = new Map(subagents.map((subagent) => [subagent.id, subagent])); return subagents.map((subagent) => { const updatedAt = DateTime.formatIso(subagent.updatedAt); const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt); + const membership = subagent.workflowMembership; + const coordinator = + membership === null ? undefined : subagentById.get(membership.workflowSubagentId); + const phaseTitle = + membership?.phaseIndex === null || membership?.phaseIndex === undefined + ? null + : (coordinator?.workflow?.phases.find((phase) => phase.index === membership.phaseIndex) + ?.title ?? null); + const latestActivity = subagent.recentActivity.at(-1); + const workflow = subagent.workflow; + const runHandles = + workflow !== null && + (workflow.runId !== undefined || + workflow.scriptPath !== undefined || + workflow.transcriptDir !== undefined || + workflow.sessionUrl !== undefined) + ? { + ...(workflow.runId === undefined ? {} : { runId: workflow.runId }), + ...(workflow.scriptPath === undefined ? {} : { scriptPath: workflow.scriptPath }), + ...(workflow.transcriptDir === undefined + ? {} + : { transcriptDir: workflow.transcriptDir }), + ...(workflow.sessionUrl === undefined ? {} : { sessionUrl: workflow.sessionUrl }), + } + : null; return { id: subagent.id, - kind: "subagent" as const, + kind: subagent.kind, title: subagent.title ?? (subagent.prompt.length > 80 ? `${subagent.prompt.slice(0, 77)}...` : subagent.prompt), - role: null, + role: subagent.role.name, model: subagent.model, effort: null, status: subagent.status, - activationCount: 1, - usage: null, - progress: subagent.progress ?? null, + activationCount: subagent.activationCount, + usage: subagent.usage === null ? null : (asUsage(subagent.usage) ?? null), + progress: subagent.progress ?? latestActivity?.summary ?? null, lastToolName: null, result: subagent.result, error: subagent.status === "failed" ? (subagent.result ?? null) : null, outputFile: null, - parentAgentId: null, - agentIndex: null, - phaseIndex: null, - phaseTitle: null, - attempt: null, - workflowName: null, - phases: [], - runHandles: null, - recentActivity: [], - firstSeenAt: startedAt ?? updatedAt, + parentAgentId: membership?.workflowSubagentId ?? null, + agentIndex: membership?.agentIndex ?? null, + phaseIndex: membership?.phaseIndex ?? null, + phaseTitle, + attempt: membership?.attempt ?? null, + workflowName: workflow?.name ?? null, + phases: workflow?.phases ?? [], + runHandles, + recentActivity: subagent.recentActivity.map((activity) => ({ + at: DateTime.formatIso(activity.at), + summary: activity.summary, + })), + firstSeenAt: + startedAt ?? + (subagent.recentActivity[0] === undefined + ? updatedAt + : DateTime.formatIso(subagent.recentActivity[0].at)), startedAt, completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt), updatedAt, @@ -858,7 +873,9 @@ export function deriveAgentPanelModel({ ).length; const state: "pending" | "running" | "done" = phaseMembers.length === 0 - ? "pending" + ? isTerminalSubagentStatus(workflow.status) + ? "done" + : "pending" : activeCount > 0 ? "running" : settledCount === phaseMembers.length @@ -889,11 +906,24 @@ export function deriveAgentPanelModel({ let idleCount = 0; let settledCount = 0; let totalTokens = 0; - for (const agent of source) { + const countedAgents = source.filter((agent) => { + if (agent.kind !== "workflow") { + return true; + } + const workflowMembers = members.get(agent.id) ?? []; + if (workflowMembers.length === 0) { + return true; + } + const hasActiveMember = workflowMembers.some((member) => isActiveSubagentStatus(member.status)); + return !hasActiveMember && !isTerminalSubagentStatus(agent.status); + }); + for (const agent of countedAgents) { if (agent.status === "running" || agent.status === "pending") runningCount += 1; else if (agent.status === "waiting") waitingCount += 1; else if (agent.status === "idle") idleCount += 1; else settledCount += 1; + } + for (const agent of source) { // Workflow coordinators aggregate member usage upstream in some providers; // avoid double counting by only summing leaf agents when members exist. if (agent.kind !== "workflow" || (members.get(agent.id) ?? []).length === 0) {