feat(web): agents panel, live strip, and thread-agent derivation

New right-panel 'agents' surface (Option A) + collapsed live strip near the
composer (Option B). Roster derived latest-wins from agent.snapshot
activities via shared client-runtime helpers.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-21 19:59:36 -07:00
1 parent f49c1a97ca
commit 45783d5fab
8 files changed
+593 -4

No files matched your search

+319
View File
@@ -0,0 +1,319 @@
import { memo, useEffect, useRef, useState } from "react";
import type { ThreadAgentSnapshot } from "@t3tools/contracts";
import {
deriveAgentPanelState,
formatAgentTokenCount,
isTerminalAgentStatus,
type AgentPanelGroup,
type AgentPanelPhase,
} from "@t3tools/client-runtime/state/thread-agents";
import { BotIcon, BracesIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { ScrollArea } from "./ui/scroll-area";
import { formatDuration } from "../session-logic";
interface AgentsPanelProps {
agents: ReadonlyArray<ThreadAgentSnapshot>;
onOpenScript?: (scriptPath: string) => void;
mode?: "sheet" | "sidebar" | "embedded";
}
const STATUS_DOT_CLASS: Record<ThreadAgentSnapshot["status"], string> = {
pending: "bg-muted-foreground/40",
running: "bg-sky-500 animate-status-pulse",
waiting: "bg-warning animate-status-pulse",
idle: "bg-sky-500/50",
completed: "bg-success",
failed: "bg-destructive",
stopped: "bg-muted-foreground/60",
};
const STATUS_LABEL: Record<ThreadAgentSnapshot["status"], string> = {
pending: "Queued",
running: "Running",
waiting: "Waiting",
idle: "Idle · resumable",
completed: "Completed",
failed: "Failed",
stopped: "Stopped",
};
function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) {
return (
<span
className={cn("size-1.75 shrink-0 rounded-full", STATUS_DOT_CLASS[status])}
role="img"
aria-label={STATUS_LABEL[status]}
/>
);
}
/**
* Self-ticking elapsed label (WorkingTimer pattern): writes its own text node
* so per-second updates never cause React commits. Frozen once `endedAt` is
* set or the agent settles.
*/
function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) {
const textRef = useRef<HTMLSpanElement>(null);
const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle";
const startMs = Date.parse(agent.firstStartedAt);
const endMs = agent.endedAt
? Date.parse(agent.endedAt)
: settled
? Date.parse(agent.lastActivityAt)
: null;
const initialText = formatDuration((endMs ?? Date.now()) - startMs);
useEffect(() => {
if (endMs !== null) return;
const update = () => {
if (textRef.current) {
textRef.current.textContent = formatDuration(Date.now() - startMs);
}
};
update();
const id = setInterval(update, 1000);
return () => clearInterval(id);
}, [startMs, endMs]);
return (
<span ref={textRef} className="font-mono text-[11px] tabular-nums text-muted-foreground">
{initialText}
</span>
);
}
function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) {
const [expanded, setExpanded] = useState(false);
const settled = isTerminalAgentStatus(agent.status);
const activity =
agent.status === "waiting"
? "Waiting on approval"
: (agent.currentActivity ??
(agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
agent.resultSummary ??
agent.errorMessage);
const hasFeed = agent.recentActivity.length > 0;
return (
<button
type="button"
onClick={() => hasFeed && setExpanded((value) => !value)}
className={cn(
"w-full rounded-lg border border-border/60 bg-card px-3 py-2 text-left",
hasFeed && "cursor-pointer hover:border-border",
settled && "opacity-70",
)}
>
<div className="flex items-center gap-2">
<AgentStatusDot status={agent.status} />
<span className="truncate text-[12.5px] font-semibold">{agent.name}</span>
{agent.agentType ? (
<Badge variant="secondary" size="sm" className="shrink-0">
{agent.agentType}
</Badge>
) : null}
{agent.model ? (
<Badge variant="outline" size="sm" className="shrink-0 text-muted-foreground">
{agent.model}
</Badge>
) : null}
<span className="ml-auto shrink-0">
<AgentElapsed agent={agent} />
</span>
{agent.status === "completed" ? (
<CheckIcon className="size-3 shrink-0 text-success" />
) : null}
</div>
{activity ? (
<div
className={cn(
"mt-1 truncate text-[11.5px]",
agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",
)}
>
{activity}
</div>
) : null}
<div className="mt-1.5 flex items-center gap-2 text-[11px] text-muted-foreground">
{agent.usage ? (
<span className="font-mono tabular-nums text-foreground">
{formatAgentTokenCount(agent.usage.totalTokens)}{" "}
<span className="text-muted-foreground">tok</span>
{agent.status === "running" ? <span className="text-sky-500"> ↑</span> : null}
</span>
) : null}
{agent.usage?.toolUses ? (
<>
<span className="text-border">·</span>
<span>{agent.usage.toolUses} tools</span>
</>
) : null}
{agent.activationCount > 1 ? (
<>
<span className="text-border">·</span>
<span>run {agent.activationCount}</span>
</>
) : null}
{hasFeed ? (
<span className="ml-auto text-muted-foreground/70">
{expanded ? (
<ChevronDownIcon className="size-3" />
) : (
<ChevronRightIcon className="size-3" />
)}
</span>
) : null}
</div>
{expanded && hasFeed ? (
<div className="mt-2 space-y-0.5 border-t border-border/60 pt-2">
{agent.recentActivity.toReversed().map((entry) => (
<div key={`${entry.at}-${entry.summary}`} className="flex gap-2 text-[11px]">
<span className="shrink-0 font-mono tabular-nums text-muted-foreground/60">
{entry.at.slice(11, 19)}
</span>
<span className="truncate text-muted-foreground">{entry.summary}</span>
</div>
))}
</div>
) : null}
</button>
);
}
function PhaseHeader({ phase }: { phase: AgentPanelPhase }) {
const runningCount = phase.agents.filter((agent) => agent.status === "running").length;
const doneCount = phase.agents.filter((agent) => isTerminalAgentStatus(agent.status)).length;
return (
<div className="flex items-center gap-2 px-1 pt-2 pb-1 text-[10px] text-muted-foreground">
<span
className={cn(
"font-bold tracking-wider uppercase",
phase.status === "done" && "text-success-foreground",
phase.status === "running" && "text-sky-500",
phase.status === "pending" && "opacity-50",
)}
>
{phase.status === "done" ? "✓ " : ""}
{phase.title}
</span>
{phase.status === "running" ? (
<span>
{runningCount} running{doneCount > 0 ? ` · ${doneCount} done` : ""}
</span>
) : phase.status === "pending" ? (
<span>pending</span>
) : null}
<span className="h-px flex-1 bg-border/60" />
</div>
);
}
function AgentGroup({
group,
onOpenScript,
}: {
group: AgentPanelGroup;
onOpenScript?: ((scriptPath: string) => void) | undefined;
}) {
const scriptPath = group.workflow?.scriptPath;
return (
<div>
<div className="flex items-center gap-2 px-1 pb-1 text-[10.5px] font-bold tracking-wider text-muted-foreground uppercase">
{group.workflow ? (
<>
<span className="truncate">Workflow · {group.workflow.name}</span>
{scriptPath && onOpenScript ? (
<span
role="button"
tabIndex={0}
onClick={(event) => {
event.stopPropagation();
onOpenScript(scriptPath);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.stopPropagation();
onOpenScript(scriptPath);
}
}}
className="inline-flex cursor-pointer items-center gap-1 font-mono text-[10px] font-medium tracking-normal text-primary normal-case hover:underline"
>
<BracesIcon className="size-3" /> script
</span>
) : null}
</>
) : (
<span>Direct spawns</span>
)}
<span className="h-px flex-1 bg-border/60" />
</div>
{group.phases.map((phase) => (
<div key={phase.index}>
<PhaseHeader phase={phase} />
<div className="space-y-1.5">
{phase.agents.map((agent) => (
<AgentCard key={agent.agentId} agent={agent} />
))}
</div>
</div>
))}
{group.rest.length > 0 ? (
<div className={cn("space-y-1.5", group.phases.length > 0 && "pt-2")}>
{group.rest.map((agent) => (
<AgentCard key={agent.agentId} agent={agent} />
))}
</div>
) : null}
</div>
);
}
const AgentsPanel = memo(function AgentsPanel({ agents, onOpenScript, mode }: AgentsPanelProps) {
const state = deriveAgentPanelState(agents);
if (agents.length === 0) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<BotIcon className="size-8 text-muted-foreground/40" />
<p className="text-sm font-medium">No agents yet</p>
<p className="text-xs text-muted-foreground">
When this thread spawns subagents or runs a workflow, they show up here with live status
and token usage.
</p>
</div>
);
}
return (
<div className={cn("flex h-full min-h-0 flex-col", mode === "embedded" && "bg-transparent")}>
<ScrollArea className="min-h-0 flex-1">
<div className="space-y-4 p-3">
{state.groups.map((group, index) => (
<AgentGroup
key={group.workflow?.agentId ?? `direct-${index}`}
group={group}
onOpenScript={onOpenScript}
/>
))}
</div>
</ScrollArea>
<div className="flex items-center gap-3 border-t border-border/60 px-3.5 py-2 text-[11px] text-muted-foreground">
{state.runningCount > 0 ? (
<span className="flex items-center gap-1.5">
<span className="size-1.75 rounded-full bg-sky-500 animate-status-pulse" />
{state.runningCount} running
</span>
) : null}
{state.waitingCount > 0 ? <span>{state.waitingCount} waiting</span> : null}
{state.settledCount > 0 ? <span>{state.settledCount} settled</span> : null}
<span className="ml-auto font-mono tabular-nums">
Σ {formatAgentTokenCount(state.totalTokens)} tok
</span>
</div>
</div>
);
});
export default AgentsPanel;
+35
View File
@@ -85,6 +85,7 @@ import {
hasActionableProposedPlan,
isLatestTurnSettled,
} from "../session-logic";
import { deriveLatestAgentSnapshot } from "@t3tools/client-runtime/state/thread-agents";
import { type LegendListRef } from "@legendapp/list/react";
import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";
import {
@@ -136,6 +137,8 @@ import { RightPanelTabs } from "./RightPanelTabs";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import AgentsPanel from "./AgentsPanel";
import AgentsLiveStrip from "./chat/AgentsLiveStrip";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
@@ -1862,6 +1865,10 @@ function ChatViewContent(props: ChatViewProps) {
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const threadAgents = useMemo(
() => deriveLatestAgentSnapshot(threadActivities),
[threadActivities],
);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -2926,6 +2933,10 @@ function ChatViewContent(props: ChatViewProps) {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
}, [activeProject, activeThreadRef]);
const addAgentsSurface = useCallback(() => {
if (!activeThreadRef) return;
useRightPanelStore.getState().open(activeThreadRef, "agents");
}, [activeThreadRef]);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
@@ -2933,6 +2944,21 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeProject, activeThreadRef],
);
// Workflow scripts live in the provider's session directory, outside the
// workspace root the file surface can read. Open in-workspace paths in the
// file surface; copy the absolute path otherwise.
const openAgentScript = useCallback(
(scriptPath: string) => {
if (activeWorkspaceRoot && scriptPath.startsWith(`${activeWorkspaceRoot}/`)) {
openFileSurface(scriptPath.slice(activeWorkspaceRoot.length + 1));
return;
}
void navigator.clipboard.writeText(scriptPath).then(() => {
toastManager.add({ title: "Script path copied", description: scriptPath });
});
},
[activeWorkspaceRoot, openFileSurface],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
if (previewPanelOpen) {
@@ -5150,6 +5176,8 @@ function ChatViewContent(props: ChatViewProps) {
initialGitScope={initialDiffPanelGitScope}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "agents" ? (
<AgentsPanel agents={threadAgents} onOpenScript={openAgentScript} mode="embedded" />
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
activePlan={activePlan}
@@ -5352,6 +5380,11 @@ function ChatViewContent(props: ChatViewProps) {
) : (
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
)}
{threadAgents.length > 0 ? (
<div className="mb-1.5">
<AgentsLiveStrip agents={threadAgents} onOpen={addAgentsSurface} />
</div>
) : null}
<div
className="relative"
style={
@@ -5548,6 +5581,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
@@ -5575,6 +5609,7 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
+20 -1
View File
@@ -1,6 +1,6 @@
import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import { ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import { Bot, ClipboardList, FileDiff, Files, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type ReactElement,
@@ -44,6 +44,7 @@ interface RightPanelTabsProps {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
@@ -91,6 +92,7 @@ function RightPanelEmptyState(props: {
onAddTerminal: () => void;
onAddDiff: () => void;
onAddFiles: () => void;
onAddAgents: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
filesAvailable: boolean;
@@ -128,6 +130,14 @@ function RightPanelEmptyState(props: {
disabledReason: SURFACE_DISABLED_REASONS.diff,
onClick: props.onAddDiff,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
icon: Bot,
available: true,
disabledReason: null,
onClick: props.onAddAgents,
},
] as const;
return (
@@ -205,6 +215,8 @@ function surfaceTitle(
);
case "plan":
return "Plan";
case "agents":
return "Agents";
case "preview": {
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
@@ -266,6 +278,8 @@ function SurfaceIcon({
return <TerminalSquare className="size-3.5 shrink-0" />;
case "plan":
return <ClipboardList className="size-3.5 shrink-0" />;
case "agents":
return <Bot className="size-3.5 shrink-0" />;
}
}
@@ -470,6 +484,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<FileDiff />
Diff
</SurfaceMenuItem>
<SurfaceMenuItem available onClick={props.onAddAgents}>
<Bot />
Agents
</SurfaceMenuItem>
</MenuPopup>
</Menu>
) : null}
@@ -484,6 +502,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
onAddTerminal={props.onAddTerminal}
onAddDiff={props.onAddDiff}
onAddFiles={props.onAddFiles}
onAddAgents={props.onAddAgents}
browserAvailable={props.browserAvailable}
diffAvailable={props.diffAvailable}
filesAvailable={props.filesAvailable}
@@ -0,0 +1,63 @@
import { memo } from "react";
import type { ThreadAgentSnapshot } from "@t3tools/contracts";
import {
deriveAgentPanelState,
formatAgentTokenCount,
} from "@t3tools/client-runtime/state/thread-agents";
import { BotIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "~/lib/utils";
/**
* Collapsed one-line agent roster shown near the composer while agents are
* live. Clicking opens the Agents panel — this strip is awareness only.
*/
const AgentsLiveStrip = memo(function AgentsLiveStrip({
agents,
onOpen,
}: {
agents: ReadonlyArray<ThreadAgentSnapshot>;
onOpen: () => void;
}) {
const state = deriveAgentPanelState(agents);
const liveCount = state.runningCount + state.waitingCount;
if (liveCount === 0) {
return null;
}
const runningPhase = state.groups
.flatMap((group) => group.phases)
.find((phase) => phase.status === "running");
return (
<button
type="button"
onClick={onOpen}
className={cn(
"flex w-full items-center gap-2 rounded-xl border border-border/60 px-3 py-1.5",
"bg-card/60 text-left text-xs transition-colors hover:border-border hover:bg-card",
)}
aria-label={`${liveCount} agents active — open agents panel`}
>
<span className="size-1.75 shrink-0 rounded-full bg-sky-500 animate-status-pulse" />
<BotIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="font-semibold">
{liveCount} agent{liveCount === 1 ? "" : "s"}
</span>
{state.waitingCount > 0 ? (
<span className="text-warning-foreground">{state.waitingCount} waiting</span>
) : null}
{runningPhase ? (
<span className="truncate text-muted-foreground">
{runningPhase.title} · {runningPhase.agents.filter((a) => a.status === "running").length}{" "}
running
</span>
) : null}
<span className="ml-auto shrink-0 font-mono text-[11px] tabular-nums text-muted-foreground">
Σ {formatAgentTokenCount(state.totalTokens)}
</span>
<ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" />
</button>
);
});
export default AgentsLiveStrip;
+14 -3
View File
@@ -14,7 +14,15 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
export const RIGHT_PANEL_KINDS = [
"plan",
"diff",
"files",
"file",
"preview",
"terminal",
"agents",
] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
export type RightPanelSurface =
@@ -37,10 +45,11 @@ export type RightPanelSurface =
revealLine: number | null;
revealRequestId: number;
}
| { id: "plan"; kind: "plan" };
| { id: "plan"; kind: "plan" }
| { id: "agents"; kind: "agents" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
const RIGHT_PANEL_STORAGE_VERSION = 7;
const RIGHT_PANEL_STORAGE_VERSION = 8;
export interface ThreadRightPanelState {
isOpen: boolean;
@@ -92,6 +101,8 @@ const singletonSurface = (
return { id: "files", kind };
case "plan":
return { id: "plan", kind };
case "agents":
return { id: "agents", kind };
}
};
+1
View File
@@ -633,6 +633,7 @@ export function deriveWorkLogEntries(
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.kind === "agent.snapshot") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
+4
View File
@@ -119,6 +119,10 @@
"types": "./src/state/terminal.ts",
"default": "./src/state/terminal.ts"
},
"./state/thread-agents": {
"types": "./src/state/threadAgents.ts",
"default": "./src/state/threadAgents.ts"
},
"./state/threads": {
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
@@ -0,0 +1,137 @@
/**
* Derivation helpers for the thread agent roster.
*
* The server ships the full per-thread roster latest-wins in the payload of
* `agent.snapshot` activities (see `@t3tools/contracts` ThreadAgentsActivityPayload).
* Mirrors the `context-window.updated` pattern: scan activities newest-first,
* decode tolerantly, ignore rows that fail to decode.
*/
import {
THREAD_AGENT_TERMINAL_STATUSES,
THREAD_AGENTS_ACTIVITY_KIND,
ThreadAgentsActivityPayload,
type OrchestrationThreadActivity,
type ThreadAgentSnapshot,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
const decodePayload = Schema.decodeUnknownOption(ThreadAgentsActivityPayload);
export function deriveLatestAgentSnapshot(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<ThreadAgentSnapshot> {
for (let index = activities.length - 1; index >= 0; index -= 1) {
const activity = activities[index];
if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) {
continue;
}
const decoded = decodePayload(activity.payload);
if (decoded._tag === "Some") {
return decoded.value.agents;
}
}
return [];
}
export function isTerminalAgentStatus(status: ThreadAgentSnapshot["status"]): boolean {
return THREAD_AGENT_TERMINAL_STATUSES.has(status);
}
export interface AgentPanelGroup {
/** The workflow snapshot this group belongs to, or null for direct spawns. */
readonly workflow: ThreadAgentSnapshot | null;
/** Phase sections in declared order; agents without a phase land in `rest`. */
readonly phases: ReadonlyArray<AgentPanelPhase>;
readonly rest: ReadonlyArray<ThreadAgentSnapshot>;
}
export interface AgentPanelPhase {
readonly index: number;
readonly title: string;
readonly status: "pending" | "running" | "done";
readonly agents: ReadonlyArray<ThreadAgentSnapshot>;
}
export interface AgentPanelState {
readonly groups: ReadonlyArray<AgentPanelGroup>;
readonly runningCount: number;
readonly waitingCount: number;
readonly settledCount: number;
readonly totalTokens: number;
}
function phaseStatus(agents: ReadonlyArray<ThreadAgentSnapshot>): "pending" | "running" | "done" {
if (agents.length === 0) return "pending";
if (agents.every((agent) => isTerminalAgentStatus(agent.status))) return "done";
return "running";
}
export function deriveAgentPanelState(agents: ReadonlyArray<ThreadAgentSnapshot>): AgentPanelState {
const workflows = agents.filter((agent) => agent.kind === "workflow");
const byParent = new Map<string, ThreadAgentSnapshot[]>();
const direct: ThreadAgentSnapshot[] = [];
for (const agent of agents) {
if (agent.kind === "workflow") continue;
if (agent.parentAgentId) {
const list = byParent.get(agent.parentAgentId) ?? [];
list.push(agent);
byParent.set(agent.parentAgentId, list);
} else {
direct.push(agent);
}
}
const groups: AgentPanelGroup[] = [];
for (const workflow of workflows) {
const members = byParent.get(workflow.agentId) ?? [];
byParent.delete(workflow.agentId);
const declaredPhases = workflow.phases ?? [];
const phases: AgentPanelPhase[] = declaredPhases.map((phase) => {
const phaseAgents = members.filter((agent) => agent.phaseIndex === phase.index);
return {
index: phase.index,
title: phase.title,
status: phaseStatus(phaseAgents),
agents: phaseAgents,
};
});
const inDeclaredPhase = new Set(
phases.flatMap((phase) => phase.agents.map((agent) => agent.agentId)),
);
groups.push({
workflow,
phases,
rest: members.filter((agent) => !inDeclaredPhase.has(agent.agentId)),
});
}
// Orphaned parent groups (parent never materialized) fold into direct spawns.
for (const list of byParent.values()) {
direct.push(...list);
}
if (direct.length > 0) {
groups.push({ workflow: null, phases: [], rest: direct });
}
let runningCount = 0;
let waitingCount = 0;
let settledCount = 0;
let totalTokens = 0;
for (const agent of agents) {
if (agent.status === "running" || agent.status === "pending") runningCount += 1;
else if (agent.status === "waiting") waitingCount += 1;
else if (isTerminalAgentStatus(agent.status)) settledCount += 1;
totalTokens += agent.usage?.totalTokens ?? 0;
}
return { groups, runningCount, waitingCount, settledCount, totalTokens };
}
export function formatAgentTokenCount(totalTokens: number): string {
if (totalTokens >= 1_000_000) {
return `${(totalTokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
}
if (totalTokens >= 1_000) {
return `${(totalTokens / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
}
return `${totalTokens}`;
}