diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index f528286026..f8c479f0f9 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -342,6 +342,7 @@ const EMPTY_PROVIDERS: ServerProvider[] = []; const VISIT_DISPATCH_THROTTLE_MS = 10_000; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_PROJECTION_RUNS: OrchestrationV2ThreadProjection["runs"] = []; +const EMPTY_PROJECTION_SUBAGENTS: OrchestrationV2ThreadProjection["subagents"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; @@ -6280,6 +6281,8 @@ function ChatViewContent(props: ChatViewProps) { skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS} providerStatuses={providerStatuses} runs={serverProjection?.runs ?? EMPTY_PROJECTION_RUNS} + subagents={serverProjection?.subagents ?? EMPTY_PROJECTION_SUBAGENTS} + onOpenAgentsPanel={addAgentsSurface} anchorMessageId={timelineAnchorMessageId} onAnchorReady={onTimelineAnchorReady} onAnchorSizeChanged={onTimelineAnchorSizeChanged} diff --git a/apps/web/src/components/WorkflowRunCardV2.test.tsx b/apps/web/src/components/WorkflowRunCardV2.test.tsx new file mode 100644 index 0000000000..a7fb45dc27 --- /dev/null +++ b/apps/web/src/components/WorkflowRunCardV2.test.tsx @@ -0,0 +1,192 @@ +import { + NodeId, + ProviderDriverKind, + ProviderInstanceId, + RunId, + ThreadId, + type OrchestrationV2Subagent, +} from "@t3tools/contracts"; +import { deriveOrchestrationV2WorkflowRunCard } from "@t3tools/client-runtime/state/orchestration-v2-subagents"; +import * as DateTime from "effect/DateTime"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vite-plus/test"; + +import { WorkflowRunCardV2, safeWorkflowSessionUrl } from "./WorkflowRunCardV2"; + +const now = DateTime.makeUnsafe("2026-07-26T00:00:00.000Z"); +const workflowId = NodeId.make("workflow-1"); + +const agent = (id: string, input: Partial = {}): OrchestrationV2Subagent => + ({ + id: NodeId.make(id), + threadId: ThreadId.make("thread-test"), + runId: RunId.make("run-test"), + parentNodeId: NodeId.make("root-node"), + origin: "provider_native", + createdBy: "agent", + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Work", + title: id, + model: "claude-opus-4-1", + kind: "subagent", + role: { name: "general-purpose", source: "provider" }, + status: "running", + result: null, + usage: null, + currentActivationId: null, + activationCount: 1, + workflow: null, + workflowMembership: null, + recentActivity: [], + startedAt: now, + completedAt: null, + updatedAt: now, + ...input, + }) as OrchestrationV2Subagent; + +const membership = (agentIndex: number, phaseIndex: number | null) => ({ + workflowSubagentId: workflowId, + agentIndex, + phaseIndex, + attempt: 1, +}); + +const renderCard = (subagents: ReadonlyArray) => { + const card = deriveOrchestrationV2WorkflowRunCard({ coordinatorId: workflowId, subagents }); + if (card === null) throw new Error("expected a workflow run card"); + return renderToStaticMarkup(); +}; + +describe("WorkflowRunCardV2", () => { + const coordinator = agent("workflow-1", { + kind: "workflow", + title: "Research and implement", + status: "running", + usage: { totalTokens: 1500 }, + workflow: { + phases: [ + { index: 0, title: "Research" }, + { index: 1, title: "Implement" }, + ], + name: "research-implement", + }, + }); + + it("renders phases, member rows, and the usage rollup", () => { + const html = renderCard([ + coordinator, + agent("member-research", { + kind: "workflow_agent", + title: "Researcher", + status: "completed", + usage: { totalTokens: 400 }, + workflowMembership: membership(0, 0), + }), + agent("member-implement", { + kind: "workflow_agent", + title: "Implementer", + status: "running", + usage: { totalTokens: 500 }, + workflowMembership: membership(1, 1), + }), + ]); + + expect(html).toContain("Research and implement"); + expect(html).toContain("Research"); + expect(html).toContain("Implement"); + expect(html).toContain("Researcher"); + expect(html).toContain("Implementer"); + expect(html).toContain("1/2 agents"); + expect(html).toContain("1.5k tok"); + expect(html).toContain('data-workflow-status="running"'); + }); + + it("shows failed member rows with their error text and a failed chip on the coordinator", () => { + const html = renderCard([ + agent("workflow-1", { + ...coordinator, + status: "failed", + }), + agent("member-broken", { + kind: "workflow_agent", + title: "Broken agent", + status: "failed", + result: "TypeError: cannot read x", + workflowMembership: membership(0, 0), + }), + ]); + + expect(html).toContain('data-workflow-status="failed"'); + expect(html).toContain("TypeError: cannot read x"); + }); + + it("caps member rows and reports the hidden remainder", () => { + const members = Array.from({ length: 11 }, (_, index) => + agent(`member-${index}`, { + kind: "workflow_agent", + title: `Agent ${index}`, + status: "completed", + workflowMembership: membership(index, 0), + }), + ); + const html = renderCard([ + agent("workflow-1", { + ...coordinator, + workflow: { phases: [{ index: 0, title: "Sweep" }], name: "sweep" }, + }), + ...members, + ]); + + expect(html).toContain("+3 more agents"); + }); + + it("renders a remote run as a session link instead of member rows", () => { + const html = renderCard([ + agent("workflow-1", { + ...coordinator, + workflow: { + phases: [], + name: "remote-run", + sessionUrl: "https://claude.ai/session/abc", + }, + }), + ]); + + expect(html).toContain("Running in the cloud"); + expect(html).toContain('href="https://claude.ai/session/abc"'); + }); + + it("shows the coordinator warning when present", () => { + const html = renderCard([ + agent("workflow-1", { + ...coordinator, + workflow: { + phases: [], + name: "warned", + warning: "workflow exceeded the size guideline", + }, + }), + ]); + + expect(html).toContain("workflow exceeded the size guideline"); + }); +}); + +describe("safeWorkflowSessionUrl", () => { + it("only lets web URLs through", () => { + expect(safeWorkflowSessionUrl("https://claude.ai/session/abc")).toBe( + "https://claude.ai/session/abc", + ); + expect(safeWorkflowSessionUrl("http://localhost:3000/run")).toBe("http://localhost:3000/run"); + // A hostile payload persisted before the adapter-side filter existed + // must not reach an anchor href. + expect(safeWorkflowSessionUrl("javascript:alert(1)")).toBeUndefined(); + expect(safeWorkflowSessionUrl("file:///etc/passwd")).toBeUndefined(); + expect(safeWorkflowSessionUrl("not a url")).toBeUndefined(); + expect(safeWorkflowSessionUrl(undefined)).toBeUndefined(); + }); +}); diff --git a/apps/web/src/components/WorkflowRunCardV2.tsx b/apps/web/src/components/WorkflowRunCardV2.tsx new file mode 100644 index 0000000000..aedd8c6eb1 --- /dev/null +++ b/apps/web/src/components/WorkflowRunCardV2.tsx @@ -0,0 +1,307 @@ +import { + formatSubagentTokenCount, + type OrchestrationV2WorkflowRunCardState, +} from "@t3tools/client-runtime/state/orchestration-v2-subagents"; +import type { OrchestrationV2Subagent } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { ExternalLinkIcon, WorkflowIcon } from "lucide-react"; + +import { cn } from "~/lib/utils"; +import { Button } from "./ui/button"; + +const MAX_CARD_AGENT_ROWS = 8; + +type WorkflowRunStatus = "running" | "completed" | "failed" | "stopped"; + +const RUN_STATUS_VISUALS: Record< + WorkflowRunStatus, + { label: string; dotClass: string; textClass: string; pulse: boolean } +> = { + running: { label: "Running", dotClass: "bg-info", textClass: "text-info", pulse: true }, + completed: { + label: "Completed", + dotClass: "bg-success", + textClass: "text-success", + pulse: false, + }, + failed: { + label: "Failed", + dotClass: "bg-destructive", + textClass: "text-destructive", + pulse: false, + }, + stopped: { + label: "Stopped", + dotClass: "bg-muted-foreground", + textClass: "text-muted-foreground", + pulse: false, + }, +}; + +export function workflowRunCardStatus( + status: OrchestrationV2Subagent["status"], +): WorkflowRunStatus { + switch (status) { + case "pending": + case "running": + case "waiting": + return "running"; + case "completed": + case "idle": + return "completed"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; + } +} + +const AGENT_STATUS_DOT: Record = { + pending: "bg-muted-foreground/50", + running: "bg-info animate-pulse", + waiting: "bg-warning animate-pulse", + idle: "bg-success", + completed: "bg-success", + failed: "bg-destructive", + cancelled: "bg-muted-foreground", + interrupted: "bg-muted-foreground", +}; + +/** + * Only web URLs may reach an anchor href. The adapter already filters the + * scheme at ingestion; this guards payloads persisted before that filter + * (and any other producer) as defense in depth. + */ +export function safeWorkflowSessionUrl(sessionUrl: string | undefined): string | undefined { + if (sessionUrl === undefined) return undefined; + try { + const parsed = new URL(sessionUrl); + return parsed.protocol === "https:" || parsed.protocol === "http:" ? sessionUrl : undefined; + } catch { + return undefined; + } +} + +const agentActive = (agent: OrchestrationV2Subagent) => + agent.status === "running" || agent.status === "waiting" || agent.status === "failed"; + +/** Which member rows survive the card cap: running and failed first, then + * most recently updated. The full list lives in the Agents panel. */ +function visibleMemberIds( + members: ReadonlyArray, +): Set { + const prioritized = [...members].sort((left, right) => { + const leftUrgent = agentActive(left) ? 0 : 1; + const rightUrgent = agentActive(right) ? 0 : 1; + if (leftUrgent !== rightUrgent) return leftUrgent - rightUrgent; + return DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt); + }); + return new Set(prioritized.slice(0, MAX_CARD_AGENT_ROWS).map((agent) => agent.id)); +} + +function MemberRow({ agent }: { agent: OrchestrationV2Subagent }) { + const failed = agent.status === "failed"; + // Failures often surface only in the streamed result (a thrown value the + // runner stringified) — fall back to it so red rows always explain why. + const errorText = failed ? agent.result?.trim() || agent.progress?.trim() : undefined; + const meta = [ + agent.model, + agent.usage === null ? undefined : `${formatSubagentTokenCount(agent.usage.totalTokens)} tok`, + failed ? undefined : agent.progress?.trim() || undefined, + ] + .filter((part): part is string => part !== undefined && part !== null && part.length > 0) + .join(" · "); + const attempt = agent.workflowMembership?.attempt ?? 1; + return ( +
+ + + +
+
+ {agent.title?.trim() || agent.role.name} +
+ {(meta.length > 0 || attempt > 1 || errorText !== undefined) && ( +
+ {meta.length > 0 && {meta}} + {attempt > 1 && ( + + retry {attempt} + + )} + {errorText !== undefined && ( + {errorText} + )} +
+ )} +
+
+ ); +} + +function PhaseHeader(props: { title: string; done: number; total: number }) { + return ( +
+ + {props.title} + + {props.total > 0 && ( + + {props.done}/{props.total} + + )} +
+ ); +} + +const isSettledMember = (agent: OrchestrationV2Subagent) => + agent.status !== "pending" && agent.status !== "running" && agent.status !== "waiting"; + +export function WorkflowRunCardV2(props: { + card: OrchestrationV2WorkflowRunCardState; + onOpenDetails?: (() => void) | undefined; + onStop?: (() => void) | undefined; +}) { + const { card, onOpenDetails, onStop } = props; + const { coordinator } = card; + const status = workflowRunCardStatus(coordinator.status); + const visual = RUN_STATUS_VISUALS[status]; + const title = coordinator.title?.trim() || coordinator.workflow?.name?.trim() || "Workflow"; + const sessionUrl = safeWorkflowSessionUrl(coordinator.workflow?.sessionUrl); + const remote = coordinator.workflow?.sessionUrl !== undefined; + const members = [...card.phases.flatMap((phase) => phase.agents), ...card.unphasedAgents]; + const overCap = members.length > MAX_CARD_AGENT_ROWS; + const visibleIds = overCap ? visibleMemberIds(members) : null; + const hiddenCount = overCap ? members.length - MAX_CARD_AGENT_ROWS : 0; + const showStop = onStop !== undefined && status === "running"; + + return ( +
+
+ + {title} + + + {visual.pulse && ( + + )} + + + {visual.label} + +
+
+ {card.memberCount > 0 && ( + + {card.settledMemberCount}/{card.memberCount} agents + + )} + {card.totalTokens !== null && ( + {formatSubagentTokenCount(card.totalTokens)} tok + )} +
+ {(showStop || onOpenDetails !== undefined) && ( +
+ {showStop && ( + + )} + {onOpenDetails !== undefined && ( + + )} +
+ )} +
+
+ + {remote ? ( + sessionUrl === undefined ? ( +

+ Running in the cloud +

+ ) : ( + + + Running in the cloud — open session + + ) + ) : members.length > 0 ? ( +
+ {card.phases.map((phase) => { + const rows = phase.agents.filter( + (agent) => visibleIds === null || visibleIds.has(agent.id), + ); + if (rows.length === 0) return null; + return ( +
+ + {rows.map((agent) => ( + + ))} +
+ ); + })} + {card.unphasedAgents + .filter((agent) => visibleIds === null || visibleIds.has(agent.id)) + .map((agent) => ( + + ))} + {hiddenCount > 0 && ( + + )} +
+ ) : null} + + {coordinator.workflow?.warning !== undefined && ( +

{coordinator.workflow.warning}

+ )} +
+ ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 9d585ffdd9..a3bd9ca7d2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,6 +1,7 @@ import { type EnvironmentId, type MessageId, + type OrchestrationV2Subagent, type OrchestrationV2TurnItem, type RunAttemptId, type ScopedThreadRef, @@ -10,6 +11,10 @@ import { type ThreadId, } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { + deriveOrchestrationV2WorkflowRunCard, + orchestrationV2WorkflowMemberIds, +} from "@t3tools/client-runtime/state/orchestration-v2-subagents"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; import { @@ -67,6 +72,7 @@ import { ZapIcon, } from "lucide-react"; import { Button } from "../ui/button"; +import { WorkflowRunCardV2 } from "../WorkflowRunCardV2"; import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { ChangedFilesCard } from "./ChangedFilesTree"; @@ -162,6 +168,8 @@ interface TimelineRowSharedState { }) => void; onToggleTurnFold: (runId: RunId) => void; onToggleAttemptFold: (attemptId: RunAttemptId) => void; + /** Opens the right-panel Agents surface; null when the host view has none. */ + onOpenAgentsPanel: (() => void) | null; } interface TimelineRowActivityState { @@ -173,12 +181,19 @@ interface TimelineRowActivityState { const TimelineRowCtx = createContext(null!); const TimelineRowActivityCtx = createContext(null!); +/** + * Live projection subagents, kept out of TimelineRowCtx on purpose: they + * churn on every progress tick, and only subagent rows (workflow run cards) + * should re-render for that — not every row in the list. + */ +const TimelineSubagentsCtx = createContext>([]); const TIMELINE_LIST_HEADER =
; const TIMELINE_LIST_FADE_HEADER =
; const TIMELINE_LIST_FOOTER =
; const EMPTY_TIMELINE_SKILLS: ReadonlyArray> = []; const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray = []; const EMPTY_TIMELINE_RUNS: ReadonlyArray = []; +const EMPTY_TIMELINE_SUBAGENTS: ReadonlyArray = []; // --------------------------------------------------------------------------- // Props (public API) @@ -219,6 +234,9 @@ interface MessagesTimelineProps { skills?: ReadonlyArray>; providerStatuses?: ReadonlyArray; runs?: ReadonlyArray; + /** Live projection subagents — feeds the inline workflow run cards. */ + subagents?: ReadonlyArray; + onOpenAgentsPanel?: (() => void) | null; anchorMessageId: MessageId | null; onAnchorReady: (messageId: MessageId, anchorIndex: number) => void; onAnchorSizeChanged: (messageId: MessageId, size: number) => void; @@ -259,6 +277,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ skills = EMPTY_TIMELINE_SKILLS, providerStatuses = EMPTY_TIMELINE_PROVIDERS, runs: runsProp = EMPTY_TIMELINE_RUNS, + subagents = EMPTY_TIMELINE_SUBAGENTS, + onOpenAgentsPanel = null, anchorMessageId, onAnchorReady, onAnchorSizeChanged, @@ -476,6 +496,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRollbackCheckpoint, onToggleTurnFold, onToggleAttemptFold, + onOpenAgentsPanel, }), [ timestampFormat, @@ -495,6 +516,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onRollbackCheckpoint, onToggleTurnFold, onToggleAttemptFold, + onOpenAgentsPanel, ], ); const activityState = useMemo( @@ -555,51 +577,53 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return ( -
- - ref={listRef} - data={rows} - keyExtractor={keyExtractor} - getItemType={getItemType} - renderItem={renderItem} - estimatedItemSize={90} - initialScrollAtEnd - {...(anchoredEndSpace ? { anchoredEndSpace } : {})} - contentInsetEndAdjustment={contentInsetEndAdjustment} - // The app owns end-following (ChatView live-follow + scroll-to-end - // pill), which respects the user's scroll gestures. LegendList's - // internal maintainScrollAtEnd races post-mount measurement: it - // caches its at-end flag while a maintain cycle is active, so - // overlapping item-layout reconciliations keep snapping the view - // to stale content ends even after the user scrolled away. - maintainScrollAtEnd={false} - 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={ - topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : 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} + // The app owns end-following (ChatView live-follow + scroll-to-end + // pill), which respects the user's scroll gestures. LegendList's + // internal maintainScrollAtEnd races post-mount measurement: it + // caches its at-end flag while a maintain cycle is active, so + // overlapping item-layout reconciliations keep snapping the view + // to stale content ends even after the user scrolled away. + maintainScrollAtEnd={false} + 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={ + topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : listHeader + } + ListFooterComponent={TIMELINE_LIST_FOOTER} + /> + { + onManualNavigation(); + void listRef.current?.scrollToIndex({ + index: item.rowIndex, + animated: true, + viewOffset: 24, + }); + }} + /> +
+
); @@ -1399,9 +1423,52 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): { } } +/** + * A subagent event row that knows about workflows: a coordinator renders as + * the inline run card, a member of a present coordinator renders nothing + * (the card already shows it), and everything else falls back to the plain + * lifecycle card. Split from V2EventTimelineRow so only subagent rows + * subscribe to the live subagents context. + */ +function V2SubagentEventRow(props: { + readonly item: Extract; + readonly createdAt: string; +}) { + const ctx = use(TimelineRowCtx); + const subagents = use(TimelineSubagentsCtx); + const card = useMemo( + () => + deriveOrchestrationV2WorkflowRunCard({ + coordinatorId: props.item.subagentId, + subagents, + }), + [props.item.subagentId, subagents], + ); + const hiddenMemberIds = useMemo(() => orchestrationV2WorkflowMemberIds(subagents), [subagents]); + if (card !== null) { + return ; + } + if (hiddenMemberIds.has(props.item.subagentId)) { + return null; + } + 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 ( { expect(formatSubagentTokenCount(2_000_000)).toBe("2M"); }); }); + +describe("deriveOrchestrationV2WorkflowRunCard", () => { + const workflow = agent("workflow-1", { + kind: "workflow", + role: { name: "workflow-coordinator", source: "app_default" }, + usage: { totalTokens: 1500 }, + workflow: { + phases: [ + { index: 0, title: "Research" }, + { index: 1, title: "Implement" }, + ], + name: "research-implement", + runId: "wf_run_1", + }, + }); + const researcher = agent("member-research", { + kind: "workflow_agent", + status: "completed", + usage: { totalTokens: 400 }, + workflowMembership: { + workflowSubagentId: workflowId, + agentIndex: 0, + phaseIndex: 0, + attempt: 1, + }, + }); + const implementer = agent("member-implement", { + kind: "workflow_agent", + status: "running", + usage: { totalTokens: 500 }, + workflowMembership: { + workflowSubagentId: workflowId, + agentIndex: 1, + phaseIndex: 1, + attempt: 1, + }, + }); + + it("derives phases, counts, and the coordinator's usage for a coordinator id", () => { + const card = deriveOrchestrationV2WorkflowRunCard({ + coordinatorId: workflowId, + subagents: [workflow, researcher, implementer, agent("unrelated")], + }); + + expect(card?.coordinator.id).toBe(workflowId); + expect(card?.phases.map((phase) => [phase.title, phase.status])).toEqual([ + ["Research", "done"], + ["Implement", "running"], + ]); + expect(card?.memberCount).toBe(2); + expect(card?.settledMemberCount).toBe(1); + expect(card?.failedMemberCount).toBe(0); + expect(card?.totalTokens).toBe(1500); + expect(card?.unphasedAgents).toEqual([]); + }); + + it("returns null for anything that is not a workflow coordinator", () => { + const subagents = [workflow, researcher]; + expect( + deriveOrchestrationV2WorkflowRunCard({ + coordinatorId: researcher.id, + subagents, + }), + ).toBeNull(); + expect( + deriveOrchestrationV2WorkflowRunCard({ + coordinatorId: NodeId.make("missing"), + subagents, + }), + ).toBeNull(); + }); + + it("keeps members without a declared phase visible and sums their usage as fallback", () => { + const silentCoordinator = agent("workflow-1", { + kind: "workflow", + workflow: { phases: [{ index: 0, title: "Research" }] }, + }); + const phaseless = agent("member-phaseless", { + kind: "workflow_agent", + usage: { totalTokens: 250 }, + workflowMembership: { + workflowSubagentId: workflowId, + agentIndex: 2, + phaseIndex: null, + attempt: 1, + }, + }); + const card = deriveOrchestrationV2WorkflowRunCard({ + coordinatorId: workflowId, + subagents: [silentCoordinator, phaseless], + }); + + expect(card?.unphasedAgents.map((member) => member.id)).toEqual([phaseless.id]); + // No coordinator total reported — the member sum is better than + // "usage unavailable" for a workflow that visibly spent tokens. + expect(card?.totalTokens).toBe(250); + }); +}); + +describe("orchestrationV2WorkflowMemberIds", () => { + it("hides only members whose coordinator reached the projection", () => { + const workflow = agent("workflow-1", { kind: "workflow" }); + const member = agent("member-1", { + kind: "workflow_agent", + workflowMembership: { + workflowSubagentId: workflowId, + agentIndex: 0, + phaseIndex: 0, + attempt: 1, + }, + }); + const orphan = agent("member-orphan", { + kind: "workflow_agent", + workflowMembership: { + workflowSubagentId: NodeId.make("missing-workflow"), + agentIndex: 0, + phaseIndex: 0, + attempt: 1, + }, + }); + const direct = agent("direct-1"); + + const hidden = orchestrationV2WorkflowMemberIds([workflow, member, orphan, direct]); + expect([...hidden]).toEqual([member.id]); + }); +}); diff --git a/packages/client-runtime/src/state/orchestrationV2Subagents.ts b/packages/client-runtime/src/state/orchestrationV2Subagents.ts index c8006fcc04..f1e8050022 100644 --- a/packages/client-runtime/src/state/orchestrationV2Subagents.ts +++ b/packages/client-runtime/src/state/orchestrationV2Subagents.ts @@ -141,6 +141,89 @@ export function deriveOrchestrationV2SubagentPanelState(input: { }; } +export interface OrchestrationV2WorkflowRunCardState { + readonly coordinator: OrchestrationV2Subagent; + readonly phases: ReadonlyArray; + /** Members that claim no declared phase — rendered after the phased ones + * rather than dropped, so a provider that omits phase indices still shows + * every agent. */ + readonly unphasedAgents: ReadonlyArray; + readonly memberCount: number; + readonly settledMemberCount: number; + readonly failedMemberCount: number; + readonly totalTokens: number | null; +} + +/** + * The inline run card for one workflow coordinator. Returns null unless + * `coordinatorId` names a workflow-kind subagent, so callers can probe any + * subagent turn item with it. + */ +export function deriveOrchestrationV2WorkflowRunCard(input: { + readonly coordinatorId: OrchestrationV2Subagent["id"]; + readonly subagents: ReadonlyArray; +}): OrchestrationV2WorkflowRunCardState | null { + const coordinator = input.subagents.find( + (agent) => agent.id === input.coordinatorId && agent.kind === "workflow", + ); + if (coordinator === undefined) return null; + const members = input.subagents + .filter( + (agent) => + agent.kind !== "workflow" && + agent.workflowMembership?.workflowSubagentId === coordinator.id, + ) + .toSorted( + (left, right) => + (left.workflowMembership?.agentIndex ?? 0) - (right.workflowMembership?.agentIndex ?? 0), + ); + const phases = (coordinator.workflow?.phases ?? []).map((phase) => { + const agents = members.filter((agent) => agent.workflowMembership?.phaseIndex === phase.index); + return { ...phase, status: phaseStatus(agents), agents }; + }); + const phasedIds = new Set(phases.flatMap((phase) => phase.agents.map((agent) => agent.id))); + // The coordinator's usage already covers its members (the panel derivation + // relies on the same invariant); fall back to the member sum only when the + // provider reported no coordinator total at all. + const memberUsage = members.flatMap((agent) => + agent.usage === null ? [] : [agent.usage.totalTokens], + ); + return { + coordinator, + phases, + unphasedAgents: members.filter((agent) => !phasedIds.has(agent.id)), + memberCount: members.length, + settledMemberCount: members.filter(isSettledOrchestrationV2Subagent).length, + failedMemberCount: members.filter((agent) => agent.status === "failed").length, + totalTokens: + coordinator.usage?.totalTokens ?? + (memberUsage.length === 0 ? null : memberUsage.reduce((total, tokens) => total + tokens, 0)), + }; +} + +/** + * Ids of workflow members whose coordinator is present as a workflow-kind + * subagent. The timeline hides these rows — the coordinator's run card + * already renders them — while members orphaned by a missing coordinator + * keep their own row rather than disappearing. + */ +export function orchestrationV2WorkflowMemberIds( + subagents: ReadonlyArray, +): ReadonlySet { + const coordinatorIds = new Set( + subagents.flatMap((agent) => (agent.kind === "workflow" ? [agent.id] : [])), + ); + return new Set( + subagents.flatMap((agent) => + agent.kind !== "workflow" && + agent.workflowMembership !== null && + coordinatorIds.has(agent.workflowMembership.workflowSubagentId) + ? [agent.id] + : [], + ), + ); +} + export const formatSubagentTokenCount = (totalTokens: number) => totalTokens >= 999_500 ? `${(totalTokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`