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