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