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

AgentsPanel.tsx

584 lines20.5 KB

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