Open History to see the last commit
1/**
2 * Agents right-panel surface: the fleet view over the native subagent fold,
3 * and the ONLY place the roster renders (the chat carries one CTA row per
4 * spawn batch).
5 *
6 * Visualization rules (from live-test feedback):
7 * - Spawn order is stable. Activity and completion update rows in place.
8 * - Agent rows reserve three fixed lines for identity, activity, and metrics;
9 * changing data must never change their height.
10 * - Workflow expansion is presentation state. A live run stays expanded when
11 * it settles; older collapsed runs can still be opened at run granularity.
12 * - Static status dots, DOM-write elapsed timers, plain token counters.
13 */
14import { useAtomValue } from "@effect/atom-react";
15import type {
16 AgentPanelModel,
17 AgentPanelWorkflowGroup,
18 RuntimeSubagent,
19} from "@t3tools/client-runtime/state/subagentRuntime";
20import {
21 formatSubagentModelLabel,
22 formatSubagentTokenCount,
23} from "@t3tools/client-runtime/state/subagentRuntime";
24import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
25import { Bot, Braces, Check, ChevronDown, ChevronRight, X } from "lucide-react";
26import { useEffect, useRef, useState } from "react";
27
28import { cn } from "~/lib/utils";
29import { orchestrationEnvironment } from "~/state/orchestration";
30import { ScrollArea } from "~/components/ui/scroll-area";
31import { Button } from "~/components/ui/button";
32
33/**
34 * In-flight states all present as Working (one steady state, per the
35 * monitoring-pill design: detail belongs in the activity sub-line, and a
36 * stalled/waiting/queued subagent is still the fleet doing its job, not a
37 * user problem). Only settled states differentiate.
38 */
39const STATUS_VISUALS: Record<RuntimeSubagent["status"], { dotClass: string; label: string }> = {
40 pending: { dotClass: "bg-info", label: "Working" },
41 running: { dotClass: "bg-info", label: "Working" },
42 waiting: { dotClass: "bg-info", label: "Working" },
43 // Idle reads as settled (muted, not sky): a resting Codex child looks done
44 // unless resumed — live-test: sky idle dots read as stuck in-progress.
45 idle: { dotClass: "bg-muted-foreground/50", label: "Idle · resumable" },
46 completed: { dotClass: "bg-success", label: "Completed" },
47 failed: { dotClass: "bg-destructive", label: "Failed" },
48 cancelled: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
49 interrupted: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
50};
51
52function StatusDot({ status }: { status: RuntimeSubagent["status"] }) {
53 return (
54 <span
55 aria-hidden
56 className={cn("size-1.5 shrink-0 rounded-full", STATUS_VISUALS[status].dotClass)}
57 />
58 );
59}
60
61function formatElapsedSeconds(totalSeconds: number): string {
62 const seconds = Math.max(0, Math.floor(totalSeconds));
63 const minutes = Math.floor(seconds / 60);
64 if (minutes === 0) {
65 return `${seconds}s`;
66 }
67 const hours = Math.floor(minutes / 60);
68 if (hours === 0) {
69 return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
70 }
71 return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;
72}
73
74function elapsedBetween(startedAt: string, endIso: string | null): string {
75 const start = Date.parse(startedAt);
76 const end = endIso ? Date.parse(endIso) : Date.now();
77 if (Number.isNaN(start) || Number.isNaN(end)) {
78 return "";
79 }
80 return formatElapsedSeconds((end - start) / 1000);
81}
82
83/**
84 * Elapsed time for the current activation. Live agents self-tick via DOM
85 * writes (zero React commits per tick); settled agents freeze at completedAt.
86 */
87function AgentElapsed({ agent }: { agent: RuntimeSubagent }) {
88 const textRef = useRef<HTMLSpanElement>(null);
89 const live = agent.status === "running" || agent.status === "waiting";
90 const startedAt = agent.startedAt;
91
92 useEffect(() => {
93 if (!live || !startedAt) {
94 return;
95 }
96 const update = () => {
97 if (textRef.current) {
98 textRef.current.textContent = elapsedBetween(startedAt, null);
99 }
100 };
101 update();
102 const id = setInterval(update, 1000);
103 return () => clearInterval(id);
104 }, [live, startedAt]);
105
106 if (!startedAt) {
107 return null;
108 }
109 return (
110 <span ref={textRef} className="tabular-nums">
111 {elapsedBetween(startedAt, live ? null : agent.completedAt)}
112 </span>
113 );
114}
115
116/**
117 * Status-dependent activity line. Live rows lead with what is happening now;
118 * settled rows lead with the outcome. Errors are the only inline previews on
119 * failed rows because they explain a red row at a glance.
120 */
121function agentActivityText(agent: RuntimeSubagent): string | null {
122 const live =
123 agent.status === "running" || agent.status === "pending" || agent.status === "waiting";
124 if (live) {
125 return (
126 agent.progress ??
127 (agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ??
128 agent.result ??
129 agent.error
130 );
131 }
132 return (
133 agent.error ??
134 agent.result ??
135 agent.progress ??
136 (agent.lastToolName ? `▸ ${agent.lastToolName}` : null)
137 );
138}
139
140/** Flat, non-interactive agent status line. No unfold. */
141function AgentRow({ agent }: { agent: RuntimeSubagent }) {
142 const visuals = STATUS_VISUALS[agent.status];
143 const activity = agentActivityText(agent);
144 const modelLabel = formatSubagentModelLabel(agent.model, agent.effort);
145 const role =
146 agent.role?.trim().toLocaleLowerCase() === agent.title.trim().toLocaleLowerCase()
147 ? null
148 : agent.role;
149 const metadata = [
150 modelLabel,
151 agent.usage ? `${formatSubagentTokenCount(agent.usage.totalTokens)} tok` : "— tok",
152 agent.usage?.toolUses !== undefined ? `${agent.usage.toolUses} tools` : null,
153 agent.activationCount > 1 ? `run ${agent.activationCount}` : null,
154 ].filter((value): value is string => value !== null);
155
156 return (
157 <div className="grid h-[3.875rem] grid-cols-[0.375rem_minmax(0,1fr)_auto] grid-rows-[1.25rem_1.125rem_1rem] items-center gap-x-2 rounded-md px-1.5 py-1">
158 <span className="col-start-1 row-start-1 flex items-center">
159 <StatusDot status={agent.status} />
160 </span>
161 <span className="col-start-2 row-start-1 flex min-w-0 items-baseline gap-2">
162 <span className="min-w-0 truncate text-sm font-medium">{agent.title}</span>
163 {role ? (
164 <span className="max-w-28 shrink-0 truncate rounded-sm border border-border/60 px-1 font-mono text-[.65rem] text-muted-foreground">
165 {role}
166 </span>
167 ) : null}
168 </span>
169 <span className="col-start-3 row-start-1 min-w-14 text-right font-mono text-[.7rem] text-muted-foreground/80">
170 <span className="inline-flex items-center gap-1">
171 <AgentElapsed agent={agent} />
172 {agent.status === "completed" ? (
173 <Check aria-hidden className="size-3 text-success" />
174 ) : null}
175 </span>
176 </span>
177 <span
178 className={cn(
179 "col-start-2 col-end-4 row-start-2 block truncate text-xs",
180 agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",
181 )}
182 >
183 {activity ?? visuals.label}
184 </span>
185 <span className="col-start-2 col-end-4 row-start-3 truncate font-mono text-[.7rem] tabular-nums text-muted-foreground/70">
186 {metadata.join(" · ")}
187 </span>
188 <span className="sr-only">{visuals.label}</span>
189 </div>
190 );
191}
192
193function workflowIsLive(group: AgentPanelWorkflowGroup): boolean {
194 const status = group.workflow.status;
195 return (
196 status !== "completed" &&
197 status !== "failed" &&
198 status !== "cancelled" &&
199 status !== "interrupted"
200 );
201}
202
203function workflowMembers(group: AgentPanelWorkflowGroup): ReadonlyArray<RuntimeSubagent> {
204 return [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
205}
206
207/**
208 * Phase rail: the run's shape at a glance. One segment per phase in order,
209 * separated by chevrons; each segment shows title + one dot per member.
210 * The whole arc (done → live → pending) is visible without scrolling the
211 * member list.
212 */
213function PhaseRail({ group }: { group: AgentPanelWorkflowGroup }) {
214 if (group.phases.length === 0) {
215 return null;
216 }
217 return (
218 <div className="flex flex-wrap items-center gap-x-1 gap-y-1 px-1.5 pb-1 pt-1.5">
219 {group.phases.map((phase, index) => (
220 <div key={phase.index} className="flex items-center gap-1">
221 {index > 0 ? (
222 <ChevronRight aria-hidden className="size-3 text-muted-foreground/40" />
223 ) : null}
224 <div
225 className={cn(
226 "flex items-center gap-1 rounded-sm border px-1.5 py-0.5",
227 phase.state === "running"
228 ? "border-info/40"
229 : phase.state === "done"
230 ? "border-success/30"
231 : "border-border/50",
232 )}
233 >
234 <span
235 className={cn(
236 "font-mono text-[.65rem]",
237 phase.state === "running"
238 ? "text-info-foreground"
239 : phase.state === "done"
240 ? "text-success-foreground"
241 : "text-muted-foreground/70",
242 )}
243 >
244 {phase.state === "done" ? "✓ " : ""}
245 {phase.title}
246 </span>
247 <span className="flex items-center gap-0.5">
248 {phase.members.length === 0 ? (
249 <span className="font-mono text-[.6rem] text-muted-foreground/50">–</span>
250 ) : (
251 phase.members.map((member) => <StatusDot key={member.id} status={member.status} />)
252 )}
253 </span>
254 </div>
255 </div>
256 ))}
257 </div>
258 );
259}
260
261/**
262 * Read-only workflow script viewer, fetched through the contained
263 * getWorkflowScript RPC (never a raw filesystem read from the client).
264 */
265function WorkflowScriptView({
266 environmentId,
267 threadId,
268 scriptPath,
269 onClose,
270}: {
271 environmentId: EnvironmentId;
272 threadId: ThreadId;
273 scriptPath: string;
274 onClose: () => void;
275}) {
276 const result = useAtomValue(
277 orchestrationEnvironment.workflowScript({ environmentId, input: { threadId, scriptPath } }),
278 );
279 return (
280 <div className="mx-1.5 mb-1 rounded-md border border-border/60 bg-background/60">
281 <div className="flex items-center gap-2 border-b border-border/50 px-2 py-1">
282 <Braces aria-hidden className="size-3 text-muted-foreground" />
283 <span className="truncate font-mono text-[.65rem] text-muted-foreground">
284 {scriptPath.split("/").at(-1)}
285 </span>
286 <Button
287 size="icon-micro"
288 variant="ghost-muted"
289 onClick={onClose}
290 aria-label="Close script"
291 className="ml-auto"
292 >
293 <X aria-hidden className="size-3" />
294 </Button>
295 </div>
296 <div className="max-h-72 overflow-auto p-2">
297 {result._tag === "Success" ? (
298 <pre className="whitespace-pre-wrap break-words font-mono text-[.7rem] leading-relaxed text-foreground/90">
299 {result.value.contents}
300 {result.value.truncated ? "\n… (truncated)" : ""}
301 </pre>
302 ) : result._tag === "Failure" ? (
303 <p className="text-xs text-destructive-foreground">Could not load the script.</p>
304 ) : (
305 <p className="text-xs text-muted-foreground">Loading…</p>
306 )}
307 </div>
308 </div>
309 );
310}
311
312/**
313 * Collapsible phase section. A phase opens when it becomes active, then keeps
314 * that shape as it settles so completion never yanks rows out from under the
315 * user. Manual toggles stick until a later activation begins.
316 */
317function PhaseSection({
318 phase,
319 defaultOpen = false,
320}: {
321 phase: AgentPanelWorkflowGroup["phases"][number];
322 defaultOpen?: boolean;
323}) {
324 const [open, setOpen] = useState(defaultOpen || phase.state === "running");
325 const previousState = useRef(phase.state);
326
327 useEffect(() => {
328 if (previousState.current !== "running" && phase.state === "running") {
329 setOpen(true);
330 }
331 previousState.current = phase.state;
332 }, [phase.state]);
333
334 return (
335 <div>
336 <button
337 type="button"
338 onClick={() => setOpen((value) => !value)}
339 aria-expanded={open}
340 className={cn(
341 "mt-2 flex w-full items-center gap-1.5 rounded-sm px-1.5 text-left text-[.65rem] font-medium uppercase tracking-wider hover:bg-accent/40",
342 phase.state === "done"
343 ? "text-success-foreground"
344 : phase.state === "running"
345 ? "text-info-foreground"
346 : "text-muted-foreground/70",
347 )}
348 >
349 {open ? (
350 <ChevronDown aria-hidden className="size-3 shrink-0" />
351 ) : (
352 <ChevronRight aria-hidden className="size-3 shrink-0" />
353 )}
354 {phase.state === "done" ? <Check aria-hidden className="size-3" /> : null}
355 <span>{phase.title}</span>
356 <span className="font-normal normal-case text-muted-foreground/70">
357 {phase.state === "pending" && phase.members.length === 0
358 ? "pending"
359 : phase.state === "done"
360 ? `${phase.settledCount} done`
361 : `${phase.activeCount} active · ${phase.settledCount} done`}
362 </span>
363 {!open && phase.members.length > 0 ? (
364 <span className="ml-auto flex items-center gap-0.5">
365 {phase.members.map((member) => (
366 <StatusDot key={member.id} status={member.status} />
367 ))}
368 </span>
369 ) : null}
370 </button>
371 {open ? phase.members.map((member) => <AgentRow key={member.id} agent={member} />) : null}
372 </div>
373 );
374}
375
376/** Expanded workflow: phase rail + full phase tree. */
377function ExpandedWorkflowSection({
378 group,
379 environmentId,
380 threadId,
381 onCollapse,
382}: {
383 group: AgentPanelWorkflowGroup;
384 environmentId: EnvironmentId | null;
385 threadId: ThreadId | null;
386 onCollapse: () => void;
387}) {
388 const [scriptOpen, setScriptOpen] = useState(false);
389 const members = workflowMembers(group);
390 const settled = members.filter(
391 (member) =>
392 member.status === "completed" ||
393 member.status === "failed" ||
394 member.status === "cancelled" ||
395 member.status === "interrupted",
396 ).length;
397 const scriptPath = group.workflow.runHandles?.scriptPath;
398 const canShowScript = scriptPath !== undefined && environmentId !== null && threadId !== null;
399 return (
400 <section className="rounded-lg border border-border/50 bg-card/30 p-1.5">
401 <div className="flex items-center gap-2 px-1.5 pt-0.5 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
402 <StatusDot status={group.workflow.status} />
403 <span className="min-w-0 truncate">
404 {group.workflow.workflowName ?? group.workflow.title}
405 </span>
406 {canShowScript ? (
407 <button
408 type="button"
409 onClick={() => setScriptOpen((value) => !value)}
410 className={cn(
411 "rounded-sm border border-border/60 px-1 font-mono normal-case hover:text-foreground",
412 scriptOpen && "text-foreground",
413 )}
414 aria-expanded={scriptOpen}
415 >
416 {"{}"} script
417 </button>
418 ) : null}
419 <span className="ml-auto font-mono normal-case text-muted-foreground/80">
420 {settled}/{members.length} settled
421 </span>
422 <Button
423 size="icon-micro"
424 variant="ghost-muted"
425 onClick={onCollapse}
426 aria-label="Collapse workflow"
427 >
428 <ChevronDown aria-hidden className="size-3" />
429 </Button>
430 </div>
431 <PhaseRail group={group} />
432 {scriptOpen && canShowScript ? (
433 <WorkflowScriptView
434 environmentId={environmentId}
435 threadId={threadId}
436 scriptPath={scriptPath}
437 onClose={() => setScriptOpen(false)}
438 />
439 ) : null}
440 {group.phases.map((phase) => (
441 <PhaseSection key={phase.index} phase={phase} defaultOpen={!workflowIsLive(group)} />
442 ))}
443 {group.unphasedMembers.map((member) => (
444 <AgentRow key={member.id} agent={member} />
445 ))}
446 {group.phases.length === 0 && group.unphasedMembers.length === 0 ? (
447 <AgentRow agent={group.workflow} />
448 ) : null}
449 </section>
450 );
451}
452
453/**
454 * Collapsed workflow: one summary line. The parent owns expansion so a live
455 * workflow keeps its shape when it settles.
456 */
457function CollapsedWorkflowSection({
458 group,
459 onExpand,
460}: {
461 group: AgentPanelWorkflowGroup;
462 onExpand: () => void;
463}) {
464 const members = workflowMembers(group);
465 const failed = members.filter((member) => member.status === "failed").length;
466 // Coordinator usage may already aggregate members (panel-footer rule):
467 // count it only when there are no member rows to sum.
468 const totalTokens = members.reduce(
469 (sum, member) => sum + (member.usage?.totalTokens ?? 0),
470 members.length === 0 ? (group.workflow.usage?.totalTokens ?? 0) : 0,
471 );
472 const elapsed =
473 group.workflow.startedAt && group.workflow.completedAt
474 ? elapsedBetween(group.workflow.startedAt, group.workflow.completedAt)
475 : null;
476 return (
477 <section>
478 <button
479 type="button"
480 onClick={onExpand}
481 className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left hover:bg-accent/40"
482 aria-expanded={false}
483 >
484 <StatusDot status={failed > 0 ? "failed" : group.workflow.status} />
485 <span className="truncate text-sm">
486 {group.workflow.workflowName ?? group.workflow.title}
487 </span>
488 <span className="ml-auto flex items-center gap-1.5 font-mono text-[.7rem] text-muted-foreground/80">
489 {failed > 0 ? <span className="text-destructive-foreground">{failed} failed</span> : null}
490 <span>{members.length} agents</span>
491 <span className="tabular-nums">· {formatSubagentTokenCount(totalTokens)} tok</span>
492 {elapsed ? <span className="tabular-nums">· {elapsed}</span> : null}
493 <ChevronRight aria-hidden className="size-3" />
494 </span>
495 </button>
496 </section>
497 );
498}
499
500/** A workflow's open state is presentation state, not a status derivative. */
501function WorkflowSection({
502 group,
503 environmentId,
504 threadId,
505}: {
506 group: AgentPanelWorkflowGroup;
507 environmentId: EnvironmentId | null;
508 threadId: ThreadId | null;
509}) {
510 const [open, setOpen] = useState(() => workflowIsLive(group));
511 return open ? (
512 <ExpandedWorkflowSection
513 group={group}
514 environmentId={environmentId}
515 threadId={threadId}
516 onCollapse={() => setOpen(false)}
517 />
518 ) : (
519 <CollapsedWorkflowSection group={group} onExpand={() => setOpen(true)} />
520 );
521}
522
523export function AgentsPanel({
524 model,
525 environmentId = null,
526 threadId = null,
527}: {
528 model: AgentPanelModel;
529 environmentId?: EnvironmentId | null;
530 threadId?: ThreadId | null;
531}) {
532 if (!model.hasAgents) {
533 return (
534 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
535 <Bot aria-hidden className="size-6 text-muted-foreground/60" />
536 <p className="text-sm font-medium">No agents yet</p>
537 <p className="max-w-56 text-xs text-muted-foreground">
538 When this thread spawns subagents or runs a workflow, they show up here with live status,
539 activity, and token usage.
540 </p>
541 </div>
542 );
543 }
544
545 return (
546 <div className="flex h-full min-h-0 flex-col">
547 <ScrollArea className="min-h-0 flex-1">
548 <div className="flex flex-col gap-2 p-2">
549 {model.workflows.map((group) => (
550 <WorkflowSection
551 key={group.workflow.id}
552 group={group}
553 environmentId={environmentId}
554 threadId={threadId}
555 />
556 ))}
557 {model.directAgents.length > 0 ? (
558 <section>
559 <div className="px-1.5 pt-1 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
560 Direct spawns
561 </div>
562 {model.directAgents.map((agent) => (
563 <AgentRow key={agent.id} agent={agent} />
564 ))}
565 </section>
566 ) : null}
567 </div>
568 </ScrollArea>
569 <footer className="flex items-center justify-between border-t border-border/60 px-3 py-1.5 font-mono text-[.7rem] text-muted-foreground">
570 <span className="flex items-center gap-2">
571 {model.runningCount + model.waitingCount > 0 ? (
572 <span className="text-info-foreground">
573 ● {model.runningCount + model.waitingCount} working
574 </span>
575 ) : null}
576 {model.idleCount > 0 ? <span>{model.idleCount} idle</span> : null}
577 {model.settledCount > 0 ? <span>{model.settledCount} settled</span> : null}
578 </span>
579 <span className="tabular-nums">Σ {formatSubagentTokenCount(model.totalTokens)} tok</span>
580 </footer>
581 </div>
582 );
583}