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