diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 626c7c7e34..a514a2883b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -32,6 +32,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -60,6 +61,7 @@ import { claudeMcpQueryOverrides, claudeQueryMessages, claudeRuntimeQueryPolicyForRuntimePolicy, + commitClaudeSubagentRegistryEntry, loggedClaudeQueryOptions, makeClaudeAdapterV2, makeClaudeAgentSdkProtocolLogger, @@ -81,6 +83,32 @@ const CLAUDE_TEST_RUNTIME_POLICY = ProviderAdapterV2RuntimePolicy.make({ cwd: "/workspace", }); +describe("ClaudeAdapterV2 subagent registry", () => { + it.effect("rejects an active update that loses the registry race to a terminal update", () => + Effect.gen(function* () { + type RegistryEntry = { + readonly task: { readonly status: "running" | "waiting" | "completed" }; + }; + const observed: RegistryEntry = { task: { status: "running" } }; + const terminal: RegistryEntry = { task: { status: "completed" } }; + const stale: RegistryEntry = { task: { status: "waiting" } }; + const registry = yield* Ref.make(new Map([["task-race", terminal]])); + + const committed = yield* commitClaudeSubagentRegistryEntry({ + registry, + taskId: "task-race", + observed, + candidate: stale, + activeStart: true, + isReopen: false, + }); + + assert.isFalse(committed); + assert.strictEqual((yield* Ref.get(registry)).get("task-race"), terminal); + }), + ); +}); + function makeClaudeTestAppThread(input: { readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index eff751c27a..256c018bab 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2230,6 +2230,38 @@ interface ActiveClaudeProviderRetry { readonly itemOrdinal: number; } +interface ClaudeSubagentRegistryEntry { + readonly task: Pick; +} + +export const commitClaudeSubagentRegistryEntry = Effect.fnUntraced(function* < + Entry extends ClaudeSubagentRegistryEntry, +>(input: { + readonly registry: Ref.Ref>; + readonly taskId: string; + readonly observed: Entry | undefined; + readonly candidate: Entry; + readonly activeStart: boolean; + readonly isReopen: boolean; +}) { + return yield* Ref.modify(input.registry, (current) => { + const registered = current.get(input.taskId); + const registeredSettled = + registered !== undefined && + (registered.task.status === "completed" || + registered.task.status === "failed" || + registered.task.status === "cancelled"); + if ( + registeredSettled && + input.activeStart && + !(input.isReopen && registered === input.observed) + ) { + return [false, current] as const; + } + return [true, new Map(current).set(input.taskId, input.candidate)] as const; + }); +}); + interface ActiveClaudeSubagent { task: OrchestrationV2Subagent; activation: OrchestrationV2SubagentActivation; @@ -3022,9 +3054,6 @@ export function makeClaudeAdapterV2( driver: CLAUDE_PROVIDER, nativeThreadId: `${input.context.input.providerThread.id}:${input.taskId}`, }); - if (existingSubagent === undefined) { - input.context.subagentNodesByTaskId.set(input.taskId, nodeId); - } const turnItemOrdinal = existingSubagent?.turnItemOrdinal ?? (yield* resolveItemOrdinal(input.context, `${nativeItemId}:subagent`)); @@ -3159,10 +3188,6 @@ export function makeClaudeAdapterV2( // Consumed once the reopen it was recording has been applied. resumePending: isReopen ? false : (existingSubagent?.resumePending ?? false), } satisfies ActiveClaudeSubagent; - input.context.subagentsByTaskId.set(input.taskId, subagent); - if (input.toolUseId !== undefined) { - input.context.subagentsByToolUseId.set(input.toolUseId, subagent); - } // The same terminal protection, applied atomically: a concurrent // fiber (live stream vs continuation drain) may have terminalized // the registry entry after this update's lookup read it. A resume @@ -3170,22 +3195,25 @@ export function makeClaudeAdapterV2( // is still the terminal generation the lookup resolved; if a // concurrent fiber installed a newer terminal entry meanwhile, the // re-open must not clobber its result. - yield* Ref.update(sessionSubagentsByTaskId, (current) => { - const registered = current.get(input.taskId); - const registeredSettled = - registered !== undefined && - (registered.task.status === "completed" || - registered.task.status === "failed" || - registered.task.status === "cancelled"); - if ( - registeredSettled && - activeStart && - !(isReopen && registered === existingSubagent) - ) { - return current; - } - return new Map(current).set(input.taskId, subagent); + const committed = yield* commitClaudeSubagentRegistryEntry({ + registry: sessionSubagentsByTaskId, + taskId: input.taskId, + observed: existingSubagent, + candidate: subagent, + activeStart, + isReopen, }); + if (!committed) { + return; + } + + if (existingSubagent === undefined) { + input.context.subagentNodesByTaskId.set(input.taskId, nodeId); + } + input.context.subagentsByTaskId.set(input.taskId, subagent); + if (input.toolUseId !== undefined) { + input.context.subagentsByToolUseId.set(input.toolUseId, subagent); + } if (existingSubagent === undefined) { const childThread = makeSubagentChildThread({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index f215894b79..f44455d08a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -362,6 +362,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_SUBAGENT_ACTIVATIONS: OrchestrationV2ThreadProjection["subagentActivations"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; @@ -6420,6 +6421,9 @@ function ChatViewContent(props: ChatViewProps) { {/* Messages — LegendList handles virtualization and scrolling internally */} { expect(result.ctaByItemId.get("item:member-1")).toEqual({ workflowId: "workflow-1", agentIds: ["member-1", "workflow-1", "member-2"], + itemStates: [ + { id: "member-1", status: "running", totalTokens: 0 }, + { id: "workflow-1", status: "running", totalTokens: 0 }, + { id: "member-2", status: "running", totalTokens: 0 }, + ], }); expect(result.ctaByItemId.get("item:direct-1")).toEqual({ workflowId: null, agentIds: ["direct-1", "direct-2"], + itemStates: [ + { id: "direct-1", status: "running", totalTokens: 0 }, + { id: "direct-2", status: "running", totalTokens: 0 }, + ], }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 3775f049f2..bf81905398 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -9,6 +9,8 @@ import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../.. import { type MessageId, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2SubagentActivation, + type OrchestrationV2TurnItemStatus, type RunAttemptId, type RunId, } from "@t3tools/contracts"; @@ -172,6 +174,73 @@ export type TimelineLatestRun = Pick< export interface AgentSpawnCtaGroup { readonly workflowId: string | null; readonly agentIds: ReadonlyArray; + readonly itemStates: ReadonlyArray; +} + +export interface AgentSpawnCtaAgentState { + readonly id: string; + readonly status: OrchestrationV2TurnItemStatus; + readonly totalTokens: number; +} + +interface AgentSpawnCtaActivationState extends AgentSpawnCtaAgentState { + readonly ordinal: number; +} + +export type AgentSpawnCtaActivationIndex = ReadonlyMap< + RunId, + ReadonlyMap +>; + +export function indexAgentSpawnCtaActivations( + activations: ReadonlyArray, +): AgentSpawnCtaActivationIndex { + const index = new Map>(); + for (const activation of activations) { + if (activation.runId === null) { + continue; + } + const runStates = index.get(activation.runId) ?? new Map(); + const previous = runStates.get(activation.subagentId); + runStates.set(activation.subagentId, { + id: activation.subagentId, + status: + previous === undefined || activation.ordinal >= previous.ordinal + ? activation.status + : previous.status, + totalTokens: (previous?.totalTokens ?? 0) + (activation.usage?.totalTokens ?? 0), + ordinal: Math.max(previous?.ordinal ?? 0, activation.ordinal), + }); + index.set(activation.runId, runStates); + } + return index; +} + +/** + * Resolves direct-agent CTA state from immutable activation records for the + * row's run. Durable agent identities are reusable, so the live roster cannot + * truthfully describe an older spawn row. + */ +export function resolveDirectAgentSpawnStates(input: { + readonly group: AgentSpawnCtaGroup; + readonly runId: RunId | null; + readonly activationIndex: AgentSpawnCtaActivationIndex; +}): ReadonlyArray { + if (input.runId === null) { + return input.group.itemStates; + } + + const activationStateByAgentId = input.activationIndex.get(input.runId); + const itemStateByAgentId = new Map(input.group.itemStates.map((state) => [state.id, state])); + return input.group.agentIds.flatMap((agentId) => { + const activationState = activationStateByAgentId?.get(agentId); + if (activationState !== undefined) { + const { ordinal: _ordinal, ...state } = activationState; + return [state]; + } + const itemState = itemStateByAgentId.get(agentId); + return itemState === undefined ? [] : [itemState]; + }); } /** @@ -214,7 +283,11 @@ export function collapseSubagentTimelineEntries(input: { const anchorItemId = anchorItemIdByGroup.get(groupKey); if (anchorItemId === undefined) { anchorItemIdByGroup.set(groupKey, item.id); - ctaByItemId.set(item.id, { workflowId, agentIds: [item.subagentId] }); + ctaByItemId.set(item.id, { + workflowId, + agentIds: [item.subagentId], + itemStates: [{ id: item.subagentId, status: item.status, totalTokens: 0 }], + }); timelineEntries.push(entry); continue; } @@ -224,6 +297,10 @@ export function collapseSubagentTimelineEntries(input: { ctaByItemId.set(anchorItemId, { ...current, agentIds: [...current.agentIds, item.subagentId], + itemStates: [ + ...current.itemStates, + { id: item.subagentId, status: item.status, totalTokens: 0 }, + ], }); } } diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index f60286567c..81d5c9c52f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -1,8 +1,23 @@ -import { CheckpointRef, EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; +import { + CheckpointRef, + EnvironmentId, + MessageId, + NodeId, + RunId, + SubagentActivationId, + ThreadId, + type OrchestrationV2SubagentActivation, +} from "@t3tools/contracts"; +import type { + AgentPanelModel, + RuntimeSubagent, +} from "@t3tools/client-runtime/state/subagentRuntime"; +import type { TimelineEntry } from "../../session-logic"; import { createRef, type ReactNode, type Ref } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { beforeAll, describe, expect, it, vi } from "vite-plus/test"; import type { LegendListRef } from "@legendapp/list/react"; +import * as DateTime from "effect/DateTime"; vi.mock("@legendapp/list/react", async () => { const legendListTestId = "legend-list"; @@ -207,6 +222,82 @@ function buildProps() { }; } +function runtimeAgent(id: string, overrides: Partial = {}): 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: MESSAGE_CREATED_AT, + startedAt: MESSAGE_CREATED_AT, + completedAt: null, + updatedAt: MESSAGE_CREATED_AT, + ...overrides, + }; +} + +function subagentTimelineEntry(input: { + readonly itemId: string; + readonly subagentId: string; + readonly runId: string; + readonly status: "pending" | "running" | "waiting" | "completed" | "failed" | "cancelled"; +}): TimelineEntry { + return { + id: input.itemId, + kind: "event", + createdAt: MESSAGE_CREATED_AT, + projectedItem: { + position: 0, + visibility: "local", + sourceThreadId: "thread-1", + sourceItemId: input.itemId, + item: { + id: input.itemId, + threadId: "thread-1", + runId: input.runId, + nodeId: input.subagentId, + providerThreadId: "provider-thread-1", + providerTurnId: "provider-turn-1", + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: input.status, + title: input.subagentId, + startedAt: null, + completedAt: null, + updatedAt: {}, + type: "subagent", + subagentId: input.subagentId, + origin: "provider_native", + driver: "codex", + providerInstanceId: "codex", + childThreadId: null, + prompt: "", + result: null, + }, + } as never, + }; +} + function buildLongUserMessageText(tail = "deep hidden detail only after expand") { return Array.from({ length: 9 }, (_, index) => index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`, @@ -1240,60 +1331,6 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); - 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("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("renders a cancelled subagent batch as stopped", async () => { const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( @@ -1348,57 +1385,130 @@ describe("MessagesTimeline", () => { expect(markup).not.toContain('data-v2-subagent-result-disclosure="true"'); }); - it("renders a completed subagent batch without inline progress", async () => { - const { MessagesTimeline } = await import("./MessagesTimeline"); + it("renders a failed workflow coordinator as failed after its members settle", () => { + const coordinator = runtimeAgent("workflow-review", { + kind: "workflow", + status: "failed", + workflowName: "Review", + phases: [{ index: 0, title: "Inspect" }], + }); + const member = runtimeAgent("workflow-review:member", { + kind: "workflow_agent", + status: "completed", + parentAgentId: coordinator.id, + phaseIndex: 0, + completedAt: MESSAGE_CREATED_AT, + }); + const agentPanelModel = { + workflows: [ + { + workflow: coordinator, + phases: [ + { + index: 0, + title: "Inspect", + members: [member], + state: "done", + activeCount: 0, + settledCount: 1, + }, + ], + unphasedMembers: [], + }, + ], + directAgents: [], + runningCount: 0, + waitingCount: 0, + idleCount: 0, + settledCount: 2, + totalTokens: 0, + hasAgents: true, + liveCount: 0, + } satisfies AgentPanelModel; const markup = renderToStaticMarkup( , ); - expect(markup).toContain('data-v2-item-type="subagent"'); 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"'); + expect(markup).toContain("1 failed"); + expect(markup).not.toContain("✓ completed"); + }); + + it("keeps an older CTA on its activation after the agent identity is reused", () => { + const now = DateTime.makeUnsafe(MESSAGE_CREATED_AT); + const subagentId = NodeId.make("node-subagent-reused"); + const oldRunId = RunId.make("run-subagent-old"); + const newRunId = RunId.make("run-subagent-new"); + const currentAgent = runtimeAgent(subagentId, { + status: "running", + usage: { totalTokens: 900 }, + activationCount: 2, + }); + const agentPanelModel = { + workflows: [], + directAgents: [currentAgent], + runningCount: 1, + waitingCount: 0, + idleCount: 0, + settledCount: 0, + totalTokens: 900, + hasAgents: true, + liveCount: 1, + } satisfies AgentPanelModel; + const activation = ( + runId: RunId, + ordinal: number, + status: OrchestrationV2SubagentActivation["status"], + totalTokens: number, + ) => + ({ + id: SubagentActivationId.make(`${subagentId}:activation:${ordinal}`), + threadId: ThreadId.make("thread-1"), + subagentId, + runId, + providerTurnId: null, + ordinal, + status, + usage: { totalTokens }, + startedAt: now, + completedAt: status === "running" ? null : now, + updatedAt: now, + }) satisfies OrchestrationV2SubagentActivation; + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Ran 1 subagent"); + expect(markup).toContain("✓ completed"); + expect(markup).toContain("Σ 120"); + expect(markup).not.toContain("Σ 900"); + expect(markup).not.toContain("working"); }); it("renders V2 provider failures as standalone error rows", async () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index a9db4d61e9..0690b4158b 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 OrchestrationV2SubagentActivation, type OrchestrationV2TurnItem, type RunAttemptId, type ScopedThreadRef, @@ -81,11 +82,13 @@ import { MessageCopyButton } from "./MessageCopyButton"; import { computeStableMessagesTimelineRows, collapseSubagentTimelineEntries, + indexAgentSpawnCtaActivations, MAX_VISIBLE_WORK_LOG_ENTRIES, deriveMessagesTimelineRows, normalizeCompactToolLabel, resolveTimelineToolPresentation, resolveAssistantMessageCopyState, + resolveDirectAgentSpawnStates, resolveTimelineIsAtEnd, resolveTimelineMinimapHasPersistentGutter, resolveTimelineMinimapHeightStyle, @@ -94,6 +97,7 @@ import { resolveTimelineMinimapInteractiveWidth, resolveTimelineMinimapTopPercent, type StableMessagesTimelineRowsState, + type AgentSpawnCtaActivationIndex, type AgentSpawnCtaGroup, type MessagesTimelineRow, TIMELINE_MINIMAP_MIN_ITEMS, @@ -181,6 +185,7 @@ interface TimelineRowActivityState { interface TimelineAgentSpawnState { readonly agentPanelModel: AgentPanelModel; + readonly activationIndex: AgentSpawnCtaActivationIndex; readonly ctaByItemId: ReadonlyMap; readonly onOpenAgents: () => void; } @@ -202,6 +207,7 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END = { } as const; const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray = []; const EMPTY_TIMELINE_RUNS: ReadonlyArray = []; +const EMPTY_SUBAGENT_ACTIVATIONS: ReadonlyArray = []; const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel(); const NOOP_OPEN_AGENTS = () => {}; @@ -218,6 +224,7 @@ export interface MessagesTimelineHistoryControls { interface MessagesTimelineProps { agentPanelModel?: AgentPanelModel; + subagentActivations?: ReadonlyArray; onOpenAgents?: () => void; isWorking: boolean; activeTurnInProgress: boolean; @@ -281,6 +288,7 @@ interface MessagesTimelineProps { export const MessagesTimeline = memo(function MessagesTimeline({ agentPanelModel = EMPTY_AGENT_PANEL_MODEL, + subagentActivations = EMPTY_SUBAGENT_ACTIVATIONS, onOpenAgents = NOOP_OPEN_AGENTS, isWorking, activeTurnInProgress, @@ -432,6 +440,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({ () => collapseSubagentTimelineEntries({ timelineEntries, agentPanelModel }), [agentPanelModel, timelineEntries], ); + const agentSpawnActivationIndex = useMemo( + () => indexAgentSpawnCtaActivations(subagentActivations), + [subagentActivations], + ); const rawRows = useMemo( () => deriveMessagesTimelineRows({ @@ -618,10 +630,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({ const agentSpawnState = useMemo( () => ({ agentPanelModel, + activationIndex: agentSpawnActivationIndex, ctaByItemId: agentSpawnTimeline.ctaByItemId, onOpenAgents, }), - [agentPanelModel, agentSpawnTimeline.ctaByItemId, onOpenAgents], + [agentPanelModel, agentSpawnActivationIndex, agentSpawnTimeline.ctaByItemId, onOpenAgents], ); const listHeader = useMemo(() => { const leadingContent = @@ -1567,7 +1580,8 @@ const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { readonly createdAt: string; }) { const shared = use(TimelineRowCtx); - const { agentPanelModel, ctaByItemId, onOpenAgents } = use(TimelineAgentSpawnCtx); + const { agentPanelModel, activationIndex, ctaByItemId, onOpenAgents } = + use(TimelineAgentSpawnCtx); const spawn = ctaByItemId.get(props.item.id); if (spawn === undefined) { return ( @@ -1587,51 +1601,52 @@ const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { spawn.workflowId === null ? undefined : agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId); - const agents = + const agentStates = workflowGroup === undefined - ? agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id)) + ? resolveDirectAgentSpawnStates({ + group: spawn, + runId: props.item.runId, + activationIndex, + }) : [ ...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers, - ]; + ].map((agent) => ({ + id: agent.id, + status: agent.status, + totalTokens: agent.usage?.totalTokens ?? 0, + })); 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 agentCount = Math.max(agentStates.length, fallbackMemberCount); + const useItemStatus = agentStates.length === 0; + let running = 0; + let waiting = 0; + let idle = 0; + let failed = 0; + let stopped = 0; + const statuses = useItemStatus ? [props.item.status] : agentStates.map((agent) => agent.status); + for (const status of statuses) { + if (status === "running" || status === "pending") running += 1; + else if (status === "waiting") waiting += 1; + else if (status === "idle") idle += 1; + else if (status === "failed") failed += 1; + else if (status === "cancelled" || status === "interrupted") stopped += 1; + } const coordinatorStatus = workflowGroup?.workflow.status; + if (coordinatorStatus === "failed") failed += 1; + if (coordinatorStatus === "cancelled" || coordinatorStatus === "interrupted") stopped += 1; 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 + const totalTokens = agentStates.reduce( + (sum, agent) => sum + agent.totalTokens, + workflowGroup !== undefined && agentStates.length === 0 ? (workflowGroup.workflow.usage?.totalTokens ?? 0) : 0, ); @@ -1643,7 +1658,7 @@ const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { ? "bg-info" : failed > 0 ? "bg-destructive" - : idle > 0 + : idle > 0 || stopped > 0 ? "bg-muted-foreground/50" : "bg-success"; const lead =