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

AgentsPanel.tsx

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