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

V2LifecycleRow.tsx

608 lines21.0 KB

1import { ThreadHoverCardPopup } from "../ThreadHoverCard";
2import { AgentElapsed } from "./AgentElapsed";
3import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime";
4import type { ReactNode } from "react";
5import { useThreadShell, useProject } from "../../state/entities";
6import { SubagentTooltipContent } from "./SubagentTooltipContent";
7import { useAtomValue } from "@effect/atom-react";
8import { scopeThreadRef, scopeProjectRef } from "@t3tools/client-runtime/environment";
9import { environmentThreadDetails } from "../../state/threads";
10import { MiddleTruncate } from "../ui/middle-truncate";
11import * as DateTime from "effect/DateTime";
12import { WorkLogRow } from "./WorkLog";
13import { resolveHandoffEndpoints, type HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
14import { Fragment } from "react";
15import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
16import {
17 ProviderDriverKind,
18 type OrchestrationV2Notification,
19 type OrchestrationV2TurnItem,
20 type ProviderInstanceId,
21 type ServerProvider,
22 type ThreadId,
23 type EnvironmentId,
24 type NodeId,
25 type ScopedThreadRef,
26} from "@t3tools/contracts";
27import type { TimestampFormat } from "@t3tools/contracts/settings";
28import {
29 BotIcon,
30 ChevronRightIcon,
31 ArrowRightLeftIcon,
32 ArrowRightIcon,
33 GitForkIcon,
34 MessageSquareIcon,
35 MinusIcon,
36 XIcon,
37} from "lucide-react";
38​
39import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
40import { getProviderInstanceEntry } from "../../providerInstances";
41import { formatShortTimestamp } from "../../timestampFormat";
42import { getTriggerDisplayModelName } from "./providerIconUtils";
43import { ProviderInstanceIcon, providerTextColorClassName } from "./ProviderInstanceIcon";
44import { cn } from "~/lib/utils";
45import { TimelineSystemDivider } from "./TimelineSystemDivider";
46import { Button, InlineButton } from "../ui/button";
47import { T3Wordmark } from "../T3Wordmark";
48​
49const LIFECYCLE_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
50 "run_interrupt_request",
51 "run_interrupt_result",
52 "compaction",
53 "handoff",
54 "fork",
55 "subagent",
56 "thread_created",
57]);
58​
59export function isV2LifecycleItem(item: OrchestrationV2TurnItem): boolean {
60 return LIFECYCLE_TYPES.has(item.type);
62​
63export type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
64​
65export function V2LifecycleRow(props: {
66 readonly item: OrchestrationV2TurnItem;
67 readonly environmentId: EnvironmentId;
68 readonly resourceSummary?: boolean | undefined;
69 readonly createdAt: string;
70 readonly timestampFormat: TimestampFormat;
71 readonly providerStatuses: ReadonlyArray<ServerProvider>;
72 readonly runs: ReadonlyArray<HandoffTimelineRun>;
73 readonly onOpenThread: (threadId: ThreadId) => void;
74}) {
75 const { item } = props;
76 if (item.type === "run_interrupt_request") {
77 return (
78 <div className="flex justify-end px-1 py-1" data-v2-item-type={item.type}>
79 <div className="flex max-w-[80%] items-center gap-2 text-xs text-destructive">
80 <span aria-hidden="true" className="font-mono">
81 ■
82 </span>
83 <span className="font-medium">Interrupt requested</span>
84 <span aria-hidden="true" className="opacity-50">
85 ·
86 </span>
87 <span className="font-medium">{item.message}</span>
88 <span className="text-3xs text-muted-foreground">
89 {formatShortTimestamp(props.createdAt, props.timestampFormat)}
90 </span>
91 </div>
92 </div>
93 );
94 }
95 if (item.type === "run_interrupt_result") {
96 return (
97 <TimelineSystemDivider
98 label="Run interrupted"
99 detail={item.message}
100 tone="danger"
101 icon={XIcon}
102 />
103 );
104 }
105 if (item.type === "compaction") {
106 const tokenDetail =
107 item.beforeTokenCount === undefined && item.afterTokenCount === undefined
108 ? null
109 : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`;
110 const label =
111 item.status === "failed"
112 ? "Context compaction failed"
113 : item.status === "cancelled" || item.status === "interrupted"
114 ? "Context compaction stopped"
115 : item.status === "pending" || item.status === "running" || item.status === "waiting"
116 ? "Compacting context"
117 : "Context compacted";
118 return (
119 <TimelineSystemDivider label={label} detail={item.summary ?? tokenDetail} icon={MinusIcon} />
120 );
121 }
122 if (item.type === "handoff") {
123 const { from: fromEndpoints, to } = resolveHandoffEndpoints(item, props.runs);
124 return (
125 <TimelineSystemDivider
126 label="Context handoff"
127 icon={ArrowRightLeftIcon}
128 showDetailSeparator={false}
129 tone={item.status === "failed" ? "danger" : "neutral"}
130 detail={
131 <span className="inline-flex min-w-0 flex-wrap items-center justify-center gap-1.5">
132 {fromEndpoints.map((endpoint, index) => (
133 <Fragment key={`${endpoint.instanceId}:${endpoint.model ?? ""}`}>
134 {index > 0 ? (
135 <span aria-hidden="true" className="-ml-1">
136 ,
137 </span>
138 ) : null}
139 <HandoffEndpoint
140 providers={props.providerStatuses}
141 instanceId={endpoint.instanceId}
142 model={endpoint.model}
143 />
144 </Fragment>
145 ))}
146 {fromEndpoints.length > 0 ? (
147 <ArrowRightIcon aria-hidden="true" className="size-3 shrink-0" />
148 ) : null}
149 <HandoffEndpoint
150 providers={props.providerStatuses}
151 instanceId={item.toProviderInstanceId}
152 model={to.model}
153 />
154 </span>
155 }
156 />
157 );
158 }
159 if (item.type === "fork") {
160 const relatedThreadId = item.source.type === "run" ? item.source.threadId : item.targetThreadId;
161 return (
162 <TimelineSystemDivider
163 label={item.source.type === "run" ? "Forked from conversation" : "Conversation fork"}
164 icon={GitForkIcon}
165 actionLabel={item.source.type === "run" ? "Open source conversation" : "Open fork"}
166 onAction={() => props.onOpenThread(relatedThreadId)}
167 />
168 );
169 }
170 if (item.type === "thread_created") {
171 if (props.resourceSummary) {
172 return (
173 <div
174 data-v2-item-type={item.type}
175 className="flex min-w-0 items-center gap-3 rounded-lg border border-border/60 p-3"
176 >
177 <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted/60">
178 <MessageSquareIcon className="size-4 text-secondary-label" aria-hidden />
179 </span>
180 <span className="min-w-0 flex-1 truncate text-sm font-medium">
181 {item.title ?? "Created thread"}
182 </span>
183 <Button
184 size="xs"
185 variant="outline"
186 aria-label={`Open ${item.title ?? "created thread"}`}
187 onClick={() => props.onOpenThread(item.targetThreadId)}
188 >
189 Open chat
190 </Button>
191 </div>
192 );
193 }
194 return (
195 <WorkLogRow
196 data-v2-item-type={item.type}
197 icon={<T3Wordmark className="size-4 text-icon-muted" aria-hidden />}
198 label={<>Created thread{item.title ? ` · ${item.title}` : ""}</>}
199 trailing={
200 <InlineButton
201 aria-label={`Open ${item.title ?? "created thread"}`}
202 onClick={() => props.onOpenThread(item.targetThreadId)}
203 >
204 Open chat
205 </InlineButton>
206 }
207 />
208 );
209 }
210 if (item.type === "subagent") {
211 return (
212 <SubagentTimelineLink
213 parentRef={scopeThreadRef(props.environmentId, item.threadId)}
214 subagentId={item.subagentId}
215 status={item.status}
216 driver={item.driver}
217 provider={props.providerStatuses.find(
218 (provider) => provider.instanceId === item.providerInstanceId,
219 )}
220 providers={props.providerStatuses}
221 title={formatSubagentDisplayTitle(item.title ?? "Subagent")}
222 result={item.result}
223 progress={item.progress}
224 startedAt={item.startedAt}
225 completedAt={item.completedAt}
226 threadId={item.childThreadId}
227 onOpenThread={props.onOpenThread}
228 />
229 );
230 }
231 return null;
233​
234/**
235 * In-flight states all present as Working, the way the agents fleet view did:
236 * detail belongs in the activity line, and a waiting or queued subagent is
237 * still the fleet doing its job. Only settled states differentiate. Idle reads
238 * as settled rather than in progress, since a resting child looks done unless
239 * resumed.
240 */
241const STATUS_VISUALS: Record<
242 OrchestrationV2TurnItem["status"],
243 { dotClass: string; label: string }
244> = {
245 pending: { dotClass: "bg-info", label: "Queued" },
246 running: { dotClass: "bg-info", label: "Running" },
247 waiting: { dotClass: "bg-info", label: "Waiting" },
248 idle: { dotClass: "bg-muted-foreground/50", label: "Idle · resumable" },
249 completed: { dotClass: "bg-success", label: "Completed" },
250 failed: { dotClass: "bg-destructive", label: "Failed" },
251 cancelled: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
252 interrupted: { dotClass: "bg-muted-foreground/60", label: "Stopped" },
253};
254​
255function subagentStatusVisual(status: OrchestrationV2TurnItem["status"]) {
256 return STATUS_VISUALS[status];
258​
259const SETTLED_SUBAGENT_STATUSES = new Set<OrchestrationV2TurnItem["status"]>([
260 "completed",
261 "failed",
262 "cancelled",
263 "interrupted",
264]);
265​
266/** The server's placeholder when a child ends without output; the status dot already says it. */
267const GENERIC_CHILD_END = /^Child task ended with status\b/i;
268​
269/** One line of a markdown result: drop list bullets, code ticks, and link targets. */
270function plainDetail(text: string): string {
271 return text
272 .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
273 .replace(/`/g, "")
274 .replace(/^[ \t]*[-*][ \t]+/gm, "")
275 .replace(/\s+/g, " ")
276 .trim();
278​
279function isoOrNull(value: DateTime.Utc | null | undefined): string | null {
280 return value ? DateTime.formatIso(value) : null;
282​
283export function SubagentElapsed({ agent }: { agent: Parameters<typeof AgentElapsed>[0]["agent"] }) {
284 return <AgentElapsed agent={agent} />;
286​
287/** Round provider tile with the agents panel's status dot; rings let a header stack overlap. */
288export function SubagentAvatar({
289 driver,
290 provider,
291 status,
292 className,
293}: {
294 driver?: ProviderDriverKind | undefined;
295 provider?: ServerProvider | undefined;
296 /** Omitted inside an overlapped stack, where a covered dot would only add noise. */
297 status?: OrchestrationV2TurnItem["status"] | undefined;
298 className?: string;
299}) {
300 return (
301 <span
302 aria-hidden
303 className={cn(
304 "relative inline-flex size-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted ring-2 ring-background",
305 className,
306 )}
307 >
308 {driver ? (
309 <ProviderInstanceIcon
310 driverKind={driver}
311 displayName={provider?.displayName ?? driver}
312 acpRegistryIconUrl={provider?.iconUrl}
313 className="z-auto"
314 iconClassName="size-3.5"
315 />
316 ) : (
317 <BotIcon className="size-3.5 text-muted-foreground" />
318 )}
319 {status ? (
320 <span
321 className={cn(
322 "absolute -right-px -bottom-px size-2 rounded-full ring-2 ring-background",
323 subagentStatusVisual(status).dotClass,
324 )}
325 />
326 ) : null}
327 </span>
328 );
330​
331/** The status a notification reported, frozen at the time it arrived. */
332const NOTIFICATION_OUTCOME_STATUS: Record<
333 OrchestrationV2Notification["outcome"],
334 OrchestrationV2TurnItem["status"] | null
335> = {
336 completed: "completed",
337 failed: "failed",
338 cancelled: "cancelled",
339 updated: null,
340 unknown: null,
341};
342​
343const NOTIFICATION_OUTCOME_LABEL: Record<OrchestrationV2Notification["outcome"], string> = {
344 completed: "Finished",
345 failed: "Failed",
346 cancelled: "Stopped",
347 updated: "Updated",
348 unknown: "Finished",
349};
350​
351/** A notification about one subagent, drawn as that subagent's card. Renders `fallback` when the parent has no record of it. */
352export function SubagentNotificationLink(props: {
353 readonly parentRef: ScopedThreadRef;
354 readonly childThreadId: ThreadId;
355 readonly outcome: OrchestrationV2Notification["outcome"];
356 readonly createdAt: string;
357 readonly timestampFormat: TimestampFormat;
358 readonly providerStatuses: ReadonlyArray<ServerProvider>;
359 readonly onOpenThread: (threadId: ThreadId) => void;
360 readonly fallback: ReactNode;
361}) {
362 const agent = useAtomValue(
363 environmentThreadDetails.threadAtom(props.parentRef),
364 (thread) =>
365 thread?.projection.subagents.find((agent) => agent.childThreadId === props.childThreadId) ??
366 null,
367 );
368 if (agent === null) return props.fallback;
369 return (
370 <SubagentTimelineLink
371 parentRef={props.parentRef}
372 subagentId={agent.id}
373 status={agent.status}
374 driver={agent.driver}
375 provider={props.providerStatuses.find(
376 (provider) => provider.instanceId === agent.providerInstanceId,
377 )}
378 providers={props.providerStatuses}
379 title={formatSubagentDisplayTitle(agent.title ?? "Subagent")}
380 result={agent.result}
381 progress={agent.progress}
382 startedAt={agent.startedAt}
383 completedAt={agent.completedAt}
384 threadId={props.childThreadId}
385 onOpenThread={props.onOpenThread}
386 event={{
387 status: NOTIFICATION_OUTCOME_STATUS[props.outcome],
388 label: NOTIFICATION_OUTCOME_LABEL[props.outcome],
389 timestamp: formatShortTimestamp(props.createdAt, props.timestampFormat),
390 }}
391 />
392 );
394​
395function SubagentTimelineLink(props: {
396 readonly parentRef: ScopedThreadRef;
397 readonly subagentId: NodeId;
398 readonly driver: ProviderDriverKind;
399 readonly provider: ServerProvider | undefined;
400 readonly providers: ReadonlyArray<ServerProvider>;
401 readonly title: string;
402 readonly result: string | null;
403 readonly progress: string | undefined;
404 readonly status: OrchestrationV2TurnItem["status"];
405 readonly startedAt: DateTime.Utc | null;
406 readonly completedAt: DateTime.Utc | null;
407 readonly threadId: ThreadId | null;
408 readonly onOpenThread: (threadId: ThreadId) => void;
409 /** Draws a past event about the subagent: its status then, and when it happened instead of elapsed time. */
410 readonly event?: {
411 readonly status: OrchestrationV2TurnItem["status"] | null;
412 readonly label: string;
413 readonly timestamp: string;
414 };
415}) {
416 const agent = useAtomValue(
417 environmentThreadDetails.threadAtom(props.parentRef),
418 (thread) => thread?.projection.subagents.find((agent) => agent.id === props.subagentId) ?? null,
419 );
420 const threadId = props.threadId;
421 const liveStatus = agent?.status ?? props.status;
422 const status = props.event ? props.event.status : liveStatus;
423 const statusLabel = props.event?.label ?? subagentStatusVisual(liveStatus).label;
424 const result = (agent?.result ?? props.result)?.trim();
425 const progress = (agent?.progress ?? props.progress)?.trim();
426 const settled = SETTLED_SUBAGENT_STATUSES.has(status ?? liveStatus);
427 const rawDetail = settled ? result || progress : progress || result;
428 const detail =
429 rawDetail && !GENERIC_CHILD_END.test(rawDetail) ? plainDetail(rawDetail) || null : null;
430 const failed = status === "failed";
431 const timing = {
432 status: liveStatus,
433 startedAt: isoOrNull(agent?.startedAt ?? props.startedAt),
434 completedAt: isoOrNull(agent?.completedAt ?? props.completedAt),
435 };
436 const content = (
437 <>
438 <SubagentAvatar
439 driver={props.driver}
440 provider={props.provider}
441 status={status ?? undefined}
442 />
443 <span className="min-w-0 flex-1">
444 <span className="flex items-baseline gap-2">
445 <span className="min-w-0 truncate text-xs font-medium text-foreground">
446 {props.title}
447 </span>
448 {detail !== null && (props.event !== undefined || status !== "completed") ? (
449 <span
450 className={cn(
451 "shrink-0 text-3xs",
452 failed ? "text-destructive" : "text-muted-foreground",
453 )}
454 >
455 {statusLabel}
456 </span>
457 ) : null}
458 </span>
459 <span
460 className={cn(
461 "block text-2xs leading-relaxed",
462 failed ? "text-destructive" : "text-muted-foreground",
463 )}
464 >
465 {detail === null ? (
466 statusLabel
467 ) : detail.includes("/") && !detail.includes(" ") ? (
468 <MiddleTruncate value={detail} showTitle={false} className="flex" />
469 ) : (
470 <span className="block truncate">{detail}</span>
471 )}
472 </span>
473 </span>
474 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
475 {props.event ? props.event.timestamp : <SubagentElapsed agent={timing} />}
476 </span>
477 {threadId !== null ? (
478 <ChevronRightIcon
479 aria-hidden
480 className="size-3.5 shrink-0 text-muted-foreground/60 transition-colors group-hover/subagent:text-foreground"
481 />
482 ) : null}
483 </>
484 );
485 const className =
486 "group/subagent flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left";
487 return (
488 <Tooltip>
489 <TooltipTrigger
490 delay={200}
491 render={
492 threadId === null ? (
493 <div data-v2-item-type="subagent" aria-description={statusLabel} className={className}>
494 {content}
495 </div>
496 ) : (
497 <button
498 type="button"
499 data-v2-item-type="subagent"
500 aria-label={`Open ${props.title}`}
501 aria-description={statusLabel}
502 onClick={() => props.onOpenThread(threadId)}
503 className={cn(
504 className,
505 "cursor-pointer transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
506 )}
507 >
508 {content}
509 </button>
510 )
511 }
512 />
513 <ThreadHoverCardPopup>
514 <SubagentTimelineTooltip
515 {...props}
516 elapsed={agent ? <AgentElapsed agent={projectedSubagentsToRuntime([agent])[0]!} /> : null}
517 model={agent?.model ?? null}
518 status={liveStatus}
519 result={agent?.result ?? props.result}
520 progress={agent?.progress ?? props.progress}
521 />
522 </ThreadHoverCardPopup>
523 </Tooltip>
524 );
526​
527function SubagentTimelineTooltip(
528 props: Parameters<typeof SubagentTimelineLink>[0] & { model: string | null; elapsed: ReactNode },
529) {
530 const environmentId = props.parentRef.environmentId;
531 const parent = useThreadShell(props.parentRef)?.source;
532 const child = useThreadShell(
533 props.threadId ? scopeThreadRef(environmentId, props.threadId) : null,
534 )?.source;
535 const parentProject = useProject(
536 parent ? scopeProjectRef(environmentId, parent.projectId) : null,
537 );
538 const childProject = useProject(child ? scopeProjectRef(environmentId, child.projectId) : null);
539 return (
540 <SubagentTooltipContent
541 title={formatSubagentDisplayTitle(child?.title ?? props.title)}
542 model={props.model}
543 provider={props.provider}
544 providers={props.providers}
545 driver={props.driver}
546 elapsed={props.elapsed}
547 status={props.status}
548 result={props.result}
549 progress={props.progress}
550 parentThread={parent}
551 childThread={child}
552 parentProject={parentProject ?? undefined}
553 childProject={childProject ?? undefined}
554 />
555 );
557​
558function HandoffEndpoint(props: {
559 readonly providers: ReadonlyArray<ServerProvider>;
560 readonly instanceId: ProviderInstanceId;
561 readonly model?: string | undefined;
562}) {
563 const entry = getProviderInstanceEntry(props.providers, props.instanceId);
564 const model = props.model?.trim();
565 const providerModel =
566 model === undefined || model.length === 0
567 ? undefined
568 : entry?.models.find((candidate) => candidate.slug === model);
569 const label =
570 providerModel !== undefined
571 ? getTriggerDisplayModelName(providerModel)
572 : model !== undefined && model.length > 0
573 ? model
574 : (entry?.displayName ?? props.instanceId);
575 return (
576 <Tooltip>
577 <TooltipTrigger
578 render={
579 <span
580 tabIndex={0}
581 className="inline-flex min-w-0 items-center gap-1 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
582 >
583 <ProviderInstanceIcon
584 driverKind={entry?.driverKind ?? ProviderDriverKind.make(props.instanceId)}
585 displayName={entry?.displayName ?? props.instanceId}
586 acpRegistryAgentId={entry?.acpRegistryAgentId}
587 acpRegistryIconUrl={entry?.acpRegistryIconUrl}
588 iconClassName="size-3"
589 />
590 <span
591 className={cn(
592 "truncate font-medium",
593 providerTextColorClassName(
594 entry?.driverKind ?? ProviderDriverKind.make(props.instanceId),
595 ),
596 )}
597 >
598 {label}
599 </span>
600 </span>
601 }
602 />
603 <TooltipPopup>
604 {entry?.displayName ?? props.instanceId} · {label}
605 </TooltipPopup>
606 </Tooltip>
607 );