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

AgentsPanel.tsx

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