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