Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentsPanel.tsx

585 lines20.6 KB

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 );
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`;
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);
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 );
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 );
139​
140/** Flat, non-interactive agent status line. No unfold. */
141function AgentRow({ agent }: { agent: RuntimeSubagent }) {
142 const visuals = STATUS_VISUALS[agent.status];
143 const statusLabel =
144 agent.kind === "subagent_batch" && agent.status === "idle" ? "Idle" : visuals.label;
145 const activity = agentActivityText(agent);
146 const modelLabel = formatSubagentModelLabel(agent.model, agent.effort);
147 const role =
148 agent.role?.trim().toLocaleLowerCase() === agent.title.trim().toLocaleLowerCase()
149 ? null
150 : agent.role;
151 const metadata = [
152 modelLabel,
153 agent.usage ? `${formatSubagentTokenCount(agent.usage.totalTokens)} tok` : "— tok",
154 agent.usage?.toolUses !== undefined ? `${agent.usage.toolUses} tools` : null,
155 agent.activationCount > 1 ? `run ${agent.activationCount}` : null,
156 ].filter((value): value is string => value !== null);
157​
158 return (
159 <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">
160 <span className="col-start-1 row-start-1 flex items-center">
161 <StatusDot status={agent.status} />
162 </span>
163 <span className="col-start-2 row-start-1 flex min-w-0 items-baseline gap-2">
164 <span className="min-w-0 truncate text-sm font-medium">{agent.title}</span>
165 {role ? (
166 <span className="max-w-28 shrink-0 truncate rounded-sm border border-border/60 px-1 font-mono text-[.65rem] text-muted-foreground">
167 {role}
168 </span>
169 ) : null}
170 </span>
171 <span className="col-start-3 row-start-1 min-w-14 text-right font-mono text-[.7rem] text-muted-foreground/80">
172 <span className="inline-flex items-center gap-1">
173 <AgentElapsed agent={agent} />
174 {agent.status === "completed" ? (
175 <Check aria-hidden className="size-3 text-success" />
176 ) : null}
177 </span>
178 </span>
179 <span
180 className={cn(
181 "col-start-2 col-end-4 row-start-2 block truncate text-xs",
182 agent.status === "failed" ? "text-destructive-foreground" : "text-muted-foreground",
183 )}
184 >
185 {activity ?? statusLabel}
186 </span>
187 <span className="col-start-2 col-end-4 row-start-3 truncate font-mono text-[.7rem] tabular-nums text-muted-foreground/70">
188 {metadata.join(" · ")}
189 </span>
190 <span className="sr-only">{statusLabel}</span>
191 </div>
192 );
194​
195function workflowIsLive(group: AgentPanelWorkflowGroup): boolean {
196 const status = group.workflow.status;
197 return (
198 status !== "completed" &&
199 status !== "failed" &&
200 status !== "cancelled" &&
201 status !== "interrupted"
202 );
204​
205function workflowMembers(group: AgentPanelWorkflowGroup): ReadonlyArray<RuntimeSubagent> {
206 return [...group.phases.flatMap((phase) => phase.members), ...group.unphasedMembers];
208​
209/**
210 * Phase rail: the run's shape at a glance. One segment per phase in order,
211 * separated by chevrons; each segment shows title + one dot per member.
212 * The whole arc (done → live → pending) is visible without scrolling the
213 * member list.
214 */
215function PhaseRail({ group }: { group: AgentPanelWorkflowGroup }) {
216 if (group.phases.length === 0) {
217 return null;
218 }
219 return (
220 <div className="flex flex-wrap items-center gap-x-1 gap-y-1 px-1.5 pb-1 pt-1.5">
221 {group.phases.map((phase, index) => (
222 <div key={phase.index} className="flex items-center gap-1">
223 {index > 0 ? (
224 <ChevronRight aria-hidden className="size-3 text-muted-foreground/40" />
225 ) : null}
226 <div
227 className={cn(
228 "flex items-center gap-1 rounded-sm border px-1.5 py-0.5",
229 phase.state === "running"
230 ? "border-info/40"
231 : phase.state === "done"
232 ? "border-success/30"
233 : "border-border/50",
234 )}
235 >
236 <span
237 className={cn(
238 "font-mono text-[.65rem]",
239 phase.state === "running"
240 ? "text-info-foreground"
241 : phase.state === "done"
242 ? "text-success-foreground"
243 : "text-muted-foreground/70",
244 )}
245 >
246 {phase.state === "done" ? "✓ " : ""}
247 {phase.title}
248 </span>
249 <span className="flex items-center gap-0.5">
250 {phase.members.length === 0 ? (
251 <span className="font-mono text-[.6rem] text-muted-foreground/50">–</span>
252 ) : (
253 phase.members.map((member) => <StatusDot key={member.id} status={member.status} />)
254 )}
255 </span>
256 </div>
257 </div>
258 ))}
259 </div>
260 );
262​
263/**
264 * Read-only workflow script viewer, fetched through the contained
265 * getWorkflowScript RPC (never a raw filesystem read from the client).
266 */
267function WorkflowScriptView({
268 environmentId,
269 threadId,
270 scriptPath,
271 onClose,
272}: {
273 environmentId: EnvironmentId;
274 threadId: ThreadId;
275 scriptPath: string;
276 onClose: () => void;
277}) {
278 const result = useAtomValue(
279 orchestrationEnvironment.workflowScript({ environmentId, input: { threadId, scriptPath } }),
280 );
281 return (
282 <div className="mx-1.5 mb-1 rounded-md border border-border/60 bg-background/60">
283 <div className="flex items-center gap-2 border-b border-border/50 px-2 py-1">
284 <Braces aria-hidden className="size-3 text-muted-foreground" />
285 <span className="truncate font-mono text-[.65rem] text-muted-foreground">
286 {scriptPath.split("/").at(-1)}
287 </span>
288 <Button
289 size="icon-micro"
290 variant="ghost-muted"
291 onClick={onClose}
292 aria-label="Close script"
293 className="ml-auto"
294 >
295 <X aria-hidden className="size-3" />
296 </Button>
297 </div>
298 <div className="max-h-72 overflow-auto p-2">
299 {result._tag === "Success" ? (
300 <pre className="whitespace-pre-wrap break-words font-mono text-[.7rem] leading-relaxed text-foreground/90">
301 {result.value.contents}
302 {result.value.truncated ? "\n… (truncated)" : ""}
303 </pre>
304 ) : result._tag === "Failure" ? (
305 <p className="text-xs text-destructive-foreground">Could not load the script.</p>
306 ) : (
307 <p className="text-xs text-muted-foreground">Loading…</p>
308 )}
309 </div>
310 </div>
311 );
313​
314/**
315 * Collapsible phase section. A phase opens when it becomes active, then keeps
316 * that shape as it settles so completion never yanks rows out from under the
317 * user. Manual toggles stick until a later activation begins.
318 */
319function PhaseSection({
320 phase,
321 defaultOpen = false,
322}: {
323 phase: AgentPanelWorkflowGroup["phases"][number];
324 defaultOpen?: boolean;
325}) {
326 const [open, setOpen] = useState(defaultOpen || phase.state === "running");
327 const previousState = useRef(phase.state);
328​
329 useEffect(() => {
330 if (previousState.current !== "running" && phase.state === "running") {
331 setOpen(true);
332 }
333 previousState.current = phase.state;
334 }, [phase.state]);
335​
336 return (
337 <div>
338 <button
339 type="button"
340 onClick={() => setOpen((value) => !value)}
341 aria-expanded={open}
342 className={cn(
343 "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",
344 phase.state === "done"
345 ? "text-success-foreground"
346 : phase.state === "running"
347 ? "text-info-foreground"
348 : "text-muted-foreground/70",
349 )}
350 >
351 {open ? (
352 <ChevronDown aria-hidden className="size-3 shrink-0" />
353 ) : (
354 <ChevronRight aria-hidden className="size-3 shrink-0" />
355 )}
356 {phase.state === "done" ? <Check aria-hidden className="size-3" /> : null}
357 <span>{phase.title}</span>
358 <span className="font-normal normal-case text-muted-foreground/70">
359 {phase.state === "pending" && phase.members.length === 0
360 ? "pending"
361 : phase.state === "done"
362 ? `${phase.settledCount} done`
363 : `${phase.activeCount} active · ${phase.settledCount} done`}
364 </span>
365 {!open && phase.members.length > 0 ? (
366 <span className="ml-auto flex items-center gap-0.5">
367 {phase.members.map((member) => (
368 <StatusDot key={member.id} status={member.status} />
369 ))}
370 </span>
371 ) : null}
372 </button>
373 {open ? phase.members.map((member) => <AgentRow key={member.id} agent={member} />) : null}
374 </div>
375 );
377​
378/** Expanded workflow: phase rail + full phase tree. */
379function ExpandedWorkflowSection({
380 group,
381 environmentId,
382 threadId,
383 onCollapse,
384}: {
385 group: AgentPanelWorkflowGroup;
386 environmentId: EnvironmentId | null;
387 threadId: ThreadId | null;
388 onCollapse: () => void;
389}) {
390 const [scriptOpen, setScriptOpen] = useState(false);
391 const members = workflowMembers(group);
392 const settled = members.filter(
393 (member) =>
394 member.status === "completed" ||
395 member.status === "failed" ||
396 member.status === "cancelled" ||
397 member.status === "interrupted",
398 ).length;
399 const scriptPath = group.workflow.runHandles?.scriptPath;
400 const canShowScript = scriptPath !== undefined && environmentId !== null && threadId !== null;
401 return (
402 <section className="rounded-lg border border-border/50 bg-card/30 p-1.5">
403 <div className="flex items-center gap-2 px-1.5 pt-0.5 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
404 <StatusDot status={group.workflow.status} />
405 <span className="min-w-0 truncate">
406 {group.workflow.workflowName ?? group.workflow.title}
407 </span>
408 {canShowScript ? (
409 <button
410 type="button"
411 onClick={() => setScriptOpen((value) => !value)}
412 className={cn(
413 "rounded-sm border border-border/60 px-1 font-mono normal-case hover:text-foreground",
414 scriptOpen && "text-foreground",
415 )}
416 aria-expanded={scriptOpen}
417 >
418 {"{}"} script
419 </button>
420 ) : null}
421 <span className="ml-auto font-mono normal-case text-muted-foreground/80">
422 {settled}/{members.length} settled
423 </span>
424 <Button
425 size="icon-micro"
426 variant="ghost-muted"
427 onClick={onCollapse}
428 aria-label="Collapse workflow"
429 >
430 <ChevronDown aria-hidden className="size-3" />
431 </Button>
432 </div>
433 <PhaseRail group={group} />
434 {scriptOpen && canShowScript ? (
435 <WorkflowScriptView
436 environmentId={environmentId}
437 threadId={threadId}
438 scriptPath={scriptPath}
439 onClose={() => setScriptOpen(false)}
440 />
441 ) : null}
442 {group.phases.map((phase) => (
443 <PhaseSection key={phase.index} phase={phase} defaultOpen={!workflowIsLive(group)} />
444 ))}
445 {group.unphasedMembers.map((member) => (
446 <AgentRow key={member.id} agent={member} />
447 ))}
448 {group.phases.length === 0 && group.unphasedMembers.length === 0 ? (
449 <AgentRow agent={group.workflow} />
450 ) : null}
451 </section>
452 );
454​
455/**
456 * Collapsed workflow: one summary line. The parent owns expansion so a live
457 * workflow keeps its shape when it settles.
458 */
459function CollapsedWorkflowSection({
460 group,
461 onExpand,
462}: {
463 group: AgentPanelWorkflowGroup;
464 onExpand: () => void;
465}) {
466 const members = workflowMembers(group);
467 const failed = members.filter((member) => member.status === "failed").length;
468 // Coordinator usage may already aggregate members (panel-footer rule):
469 // count it only when there are no member rows to sum.
470 const totalTokens = members.reduce(
471 (sum, member) => sum + (member.usage?.totalTokens ?? 0),
472 members.length === 0 ? (group.workflow.usage?.totalTokens ?? 0) : 0,
473 );
474 const elapsed =
475 group.workflow.startedAt && group.workflow.completedAt
476 ? elapsedBetween(group.workflow.startedAt, group.workflow.completedAt)
477 : null;
478 return (
479 <section>
480 <button
481 type="button"
482 onClick={onExpand}
483 className="flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left hover:bg-accent/40"
484 aria-expanded={false}
485 >
486 <StatusDot status={failed > 0 ? "failed" : group.workflow.status} />
487 <span className="truncate text-sm">
488 {group.workflow.workflowName ?? group.workflow.title}
489 </span>
490 <span className="ml-auto flex items-center gap-1.5 font-mono text-[.7rem] text-muted-foreground/80">
491 {failed > 0 ? <span className="text-destructive-foreground">{failed} failed</span> : null}
492 <span>{members.length} agents</span>
493 <span className="tabular-nums">· {formatSubagentTokenCount(totalTokens)} tok</span>
494 {elapsed ? <span className="tabular-nums">· {elapsed}</span> : null}
495 <ChevronRight aria-hidden className="size-3" />
496 </span>
497 </button>
498 </section>
499 );
501​
502/** A workflow's open state is presentation state, not a status derivative. */
503function WorkflowSection({
504 group,
505 environmentId,
506 threadId,
507}: {
508 group: AgentPanelWorkflowGroup;
509 environmentId: EnvironmentId | null;
510 threadId: ThreadId | null;
511}) {
512 const [open, setOpen] = useState(() => workflowIsLive(group));
513 return open ? (
514 <ExpandedWorkflowSection
515 group={group}
516 environmentId={environmentId}
517 threadId={threadId}
518 onCollapse={() => setOpen(false)}
519 />
520 ) : (
521 <CollapsedWorkflowSection group={group} onExpand={() => setOpen(true)} />
522 );
524​
525export function AgentsPanel({
526 model,
527 environmentId = null,
528 threadId = null,
529}: {
530 model: AgentPanelModel;
531 environmentId?: EnvironmentId | null;
532 threadId?: ThreadId | null;
533}) {
534 if (!model.hasAgents) {
535 return (
536 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
537 <Bot aria-hidden className="size-6 text-muted-foreground/60" />
538 <p className="text-sm font-medium">No agents yet</p>
539 <p className="max-w-56 text-xs text-muted-foreground">
540 When this thread spawns subagents or runs a workflow, they show up here with live status,
541 activity, and token usage.
542 </p>
543 </div>
544 );
545 }
546​
547 return (
548 <div className="flex h-full min-h-0 flex-col">
549 <ScrollArea className="min-h-0 flex-1">
550 <div className="flex flex-col gap-2 p-2">
551 {model.workflows.map((group) => (
552 <WorkflowSection
553 key={group.workflow.id}
554 group={group}
555 environmentId={environmentId}
556 threadId={threadId}
557 />
558 ))}
559 {model.directAgents.length > 0 ? (
560 <section>
561 <div className="px-1.5 pt-1 text-[.65rem] font-medium uppercase tracking-wider text-muted-foreground">
562 Direct spawns
563 </div>
564 {model.directAgents.map((agent) => (
565 <AgentRow key={agent.id} agent={agent} />
566 ))}
567 </section>
568 ) : null}
569 </div>
570 </ScrollArea>
571 <footer className="flex items-center justify-between border-t border-border/60 px-3 py-1.5 font-mono text-[.7rem] text-muted-foreground">
572 <span className="flex items-center gap-2">
573 {model.runningCount + model.waitingCount > 0 ? (
574 <span className="text-info-foreground">
575 ● {model.runningCount + model.waitingCount} working
576 </span>
577 ) : null}
578 {model.idleCount > 0 ? <span>{model.idleCount} idle</span> : null}
579 {model.settledCount > 0 ? <span>{model.settledCount} settled</span> : null}
580 </span>
581 <span className="tabular-nums">Σ {formatSubagentTokenCount(model.totalTokens)} tok</span>
582 </footer>
583 </div>
584 );