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