Open History to see the last commit
1import { Fragment } from "react";
2import {
3 ProviderDriverKind,
4 type OrchestrationV2Run,
5 type OrchestrationV2TurnItem,
6 type ProviderInstanceId,
7 type ServerProvider,
8 type ThreadId,
9} from "@t3tools/contracts";
10import type { TimestampFormat } from "@t3tools/contracts/settings";
11import {
12 ArrowRightLeftIcon,
13 ArrowRightIcon,
14 BotIcon,
15 GitForkIcon,
16 MessageSquareIcon,
17 MinusIcon,
18 XIcon,
19} from "lucide-react";
20
21import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
22import { cn } from "../../lib/utils";
23import { getProviderInstanceEntry } from "../../providerInstances";
24import { formatShortTimestamp } from "../../timestampFormat";
25import { getTriggerDisplayModelName } from "./providerIconUtils";
26import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
27import { TimelineSystemDivider } from "./TimelineSystemDivider";
28import { T3Wordmark } from "../T3Wordmark";
29
30const LIFECYCLE_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
31 "run_interrupt_request",
32 "run_interrupt_result",
33 "compaction",
34 "handoff",
35 "fork",
36 "subagent",
37 "thread_created",
38]);
39
40export function isV2LifecycleItem(item: OrchestrationV2TurnItem): boolean {
41 return LIFECYCLE_TYPES.has(item.type);
42}
43
44// Once a subagent stops, its last streamed result says more than the stale
45// progress line; while it runs, live progress comes first.
46const TERMINAL_SUBAGENT_STATUSES = new Set<OrchestrationV2TurnItem["status"]>([
47 "completed",
48 "failed",
49 "cancelled",
50 "interrupted",
51]);
52
53/**
54 * The subset of a projection run that handoff rows read. Kept minimal so the
55 * timeline can hold a content-stable snapshot: run status/timestamps churn on
56 * every stream event, but these fields only change when a run is added.
57 */
58export type HandoffTimelineRun = Pick<
59 OrchestrationV2Run,
60 "id" | "ordinal" | "providerInstanceId" | "modelSelection"
61>;
62
63export function V2LifecycleRow(props: {
64 readonly item: OrchestrationV2TurnItem;
65 readonly resourceSummary?: boolean | undefined;
66 readonly createdAt: string;
67 readonly timestampFormat: TimestampFormat;
68 readonly providerStatuses: ReadonlyArray<ServerProvider>;
69 readonly runs: ReadonlyArray<HandoffTimelineRun>;
70 readonly onOpenThread: (threadId: ThreadId) => void;
71}) {
72 const { item } = props;
73 if (item.type === "run_interrupt_request") {
74 return (
75 <div className="flex justify-end px-1 py-1" data-v2-item-type={item.type}>
76 <div className="flex max-w-[80%] items-center gap-2 text-xs text-destructive">
77 <span aria-hidden="true" className="font-mono">
78 ■
79 </span>
80 <span className="font-medium">Interrupt requested</span>
81 <span aria-hidden="true" className="opacity-50">
82 ·
83 </span>
84 <span className="font-medium">{item.message}</span>
85 <span className="text-[10px] text-muted-foreground">
86 {formatShortTimestamp(props.createdAt, props.timestampFormat)}
87 </span>
88 </div>
89 </div>
90 );
91 }
92 if (item.type === "run_interrupt_result") {
93 return (
94 <TimelineSystemDivider
95 label="Run interrupted"
96 detail={item.message}
97 tone="danger"
98 icon={XIcon}
99 />
100 );
101 }
102 if (item.type === "compaction") {
103 const tokenDetail =
104 item.beforeTokenCount === undefined && item.afterTokenCount === undefined
105 ? null
106 : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`;
107 const label =
108 item.status === "failed"
109 ? "Context compaction failed"
110 : item.status === "cancelled" || item.status === "interrupted"
111 ? "Context compaction stopped"
112 : item.status === "pending" || item.status === "running" || item.status === "waiting"
113 ? "Compacting context"
114 : "Context compacted";
115 return (
116 <TimelineSystemDivider label={label} detail={item.summary ?? tokenDetail} icon={MinusIcon} />
117 );
118 }
119 if (item.type === "handoff") {
120 // Items persisted before models were stamped only carry instance ids;
121 // recover the models from the thread's runs (the handoff's own run is
122 // the target, the newest earlier run per source instance is the origin).
123 // HandoffEndpoint falls back to the provider display name when neither
124 // source has a model.
125 const handoffRun =
126 item.runId === null ? undefined : props.runs.find((run) => run.id === item.runId);
127 const toModel =
128 item.toModel ??
129 (handoffRun !== undefined && handoffRun.providerInstanceId === item.toProviderInstanceId
130 ? handoffRun.modelSelection.model
131 : undefined);
132 const fromEndpoints: ReadonlyArray<{
133 readonly instanceId: ProviderInstanceId;
134 readonly model?: string | undefined;
135 }> =
136 item.fromModelSelections !== undefined && item.fromModelSelections.length > 0
137 ? item.fromModelSelections
138 : item.fromProviderInstanceIds.map((instanceId) => ({
139 instanceId,
140 model: latestRunModelBefore(props.runs, instanceId, handoffRun?.ordinal),
141 }));
142 return (
143 <TimelineSystemDivider
144 label="Context handoff"
145 icon={ArrowRightLeftIcon}
146 showDetailSeparator={false}
147 tone={item.status === "failed" ? "danger" : "neutral"}
148 detail={
149 <span className="inline-flex min-w-0 items-center gap-1.5">
150 {fromEndpoints.map((endpoint, index) => (
151 <Fragment key={`${endpoint.instanceId}:${endpoint.model ?? ""}`}>
152 {index > 0 ? (
153 <span aria-hidden="true" className="-ml-1">
154 ,
155 </span>
156 ) : null}
157 <HandoffEndpoint
158 providers={props.providerStatuses}
159 instanceId={endpoint.instanceId}
160 model={endpoint.model}
161 />
162 </Fragment>
163 ))}
164 {fromEndpoints.length > 0 ? (
165 <ArrowRightIcon aria-hidden="true" className="size-3 shrink-0" />
166 ) : null}
167 <HandoffEndpoint
168 providers={props.providerStatuses}
169 instanceId={item.toProviderInstanceId}
170 model={toModel}
171 />
172 </span>
173 }
174 />
175 );
176 }
177 if (item.type === "fork") {
178 const relatedThreadId = item.source.type === "run" ? item.source.threadId : item.targetThreadId;
179 return (
180 <TimelineSystemDivider
181 label={item.source.type === "run" ? "Forked from conversation" : "Conversation fork"}
182 icon={GitForkIcon}
183 actionLabel={item.source.type === "run" ? "Open source conversation" : "Open fork"}
184 onAction={() => props.onOpenThread(relatedThreadId)}
185 />
186 );
187 }
188 if (item.type === "thread_created") {
189 if (props.resourceSummary) {
190 return (
191 <div
192 data-v2-item-type={item.type}
193 className="flex min-w-0 items-center gap-3 rounded-lg border border-border/60 p-3"
194 >
195 <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted/60">
196 <MessageSquareIcon className="size-4 text-secondary-label" aria-hidden />
197 </span>
198 <span className="min-w-0 flex-1 truncate text-sm font-medium">
199 {item.title ?? "Created thread"}
200 </span>
201 <button
202 type="button"
203 aria-label={`Open ${item.title ?? "created thread"}`}
204 onClick={() => props.onOpenThread(item.targetThreadId)}
205 className="shrink-0 rounded-md border border-border px-2.5 py-1 text-sm hover:bg-accent/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
206 >
207 Open chat
208 </button>
209 </div>
210 );
211 }
212 return (
213 <div
214 className="flex min-w-0 items-center gap-1.5 px-0.5 py-0.5 text-sm leading-relaxed text-secondary-label"
215 data-v2-item-type={item.type}
216 >
217 <span className="flex size-6 shrink-0 items-center justify-center">
218 <T3Wordmark className="size-4 text-icon-muted" aria-hidden />
219 </span>
220 <span className="min-w-0 flex-1 truncate">
221 Created thread{item.title ? ` · ${item.title}` : ""}
222 </span>
223 <button
224 type="button"
225 aria-label={`Open ${item.title ?? "created thread"}`}
226 onClick={() => props.onOpenThread(item.targetThreadId)}
227 className="shrink-0 rounded-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
228 >
229 Open chat
230 </button>
231 </div>
232 );
233 }
234 if (item.type === "subagent") {
235 const streamedResult = item.result?.trim() ? item.result : null;
236 const detail = TERMINAL_SUBAGENT_STATUSES.has(item.status)
237 ? (streamedResult ?? item.progress ?? item.prompt)
238 : (item.progress ?? streamedResult ?? item.prompt);
239 return (
240 <SubagentTimelineLink
241 status={item.status}
242 title={subagentDisplayTitle(item.title ?? "Subagent")}
243 detail={detail}
244 threadId={item.childThreadId}
245 onOpenThread={props.onOpenThread}
246 />
247 );
248 }
249 return null;
250}
251
252function SubagentTimelineLink(props: {
253 readonly title: string;
254 readonly detail: string;
255 readonly status: OrchestrationV2TurnItem["status"];
256 readonly threadId: ThreadId | null;
257 readonly onOpenThread: (threadId: ThreadId) => void;
258}) {
259 const threadId = props.threadId;
260 const statusLabel = props.status.replaceAll("_", " ");
261 const content = (
262 <>
263 <span className="relative flex size-6 shrink-0 items-center justify-center">
264 <BotIcon className="size-4 text-icon-muted" aria-hidden />
265 <span
266 role="img"
267 aria-label={statusLabel}
268 className={cn(
269 "absolute right-0.5 bottom-0.5 size-1.5 rounded-full ring-2 ring-background",
270 props.status === "failed"
271 ? "bg-destructive"
272 : props.status === "completed"
273 ? "bg-success"
274 : props.status === "cancelled" || props.status === "interrupted"
275 ? "bg-muted-foreground/60"
276 : "bg-info",
277 )}
278 />
279 </span>
280 <span className="min-w-0 truncate">{props.title}</span>
281 </>
282 );
283 return (
284 <div
285 data-v2-item-type="subagent"
286 className="flex min-w-0 max-w-full items-center gap-0.5 text-sm text-secondary-label"
287 >
288 <Tooltip>
289 <TooltipTrigger
290 render={
291 threadId === null ? (
292 <span
293 aria-description={`${statusLabel}: ${props.detail}`}
294 className="flex min-w-0 items-center gap-1.5 px-0.5 py-0.5 leading-relaxed"
295 >
296 {content}
297 </span>
298 ) : (
299 <button
300 type="button"
301 aria-label={`Open ${props.title}`}
302 aria-description={`${statusLabel}: ${props.detail}`}
303 onClick={() => props.onOpenThread(threadId)}
304 className="flex min-w-0 items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left leading-relaxed hover:bg-accent/20 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
305 >
306 {content}
307 </button>
308 )
309 }
310 />
311 <TooltipPopup className="max-w-80 whitespace-pre-wrap break-words">
312 {props.title} · {statusLabel}
313 {props.detail ? `\n${props.detail}` : ""}
314 </TooltipPopup>
315 </Tooltip>
316 </div>
317 );
318}
319
320function subagentDisplayTitle(title: string): string {
321 return title.replace(/^Subagent:\s*/i, "");
322}
323
324/**
325 * Model of the newest run for `instanceId` that started before the handoff's
326 * own run. Legacy handoff items don't record their source models, but the
327 * covered runs are still in the projection.
328 */
329function latestRunModelBefore(
330 runs: ReadonlyArray<HandoffTimelineRun>,
331 instanceId: ProviderInstanceId,
332 beforeOrdinal: number | undefined,
333): string | undefined {
334 let latest: HandoffTimelineRun | undefined;
335 for (const run of runs) {
336 if (run.providerInstanceId !== instanceId) continue;
337 if (beforeOrdinal !== undefined && run.ordinal >= beforeOrdinal) continue;
338 if (latest === undefined || run.ordinal > latest.ordinal) latest = run;
339 }
340 return latest?.modelSelection.model;
341}
342
343/** Provider icon with the resolved handoff model available on hover or focus. */
344function HandoffEndpoint(props: {
345 readonly providers: ReadonlyArray<ServerProvider>;
346 readonly instanceId: ProviderInstanceId;
347 readonly model?: string | undefined;
348}) {
349 const entry = getProviderInstanceEntry(props.providers, props.instanceId);
350 const model = props.model?.trim();
351 const providerModel =
352 model === undefined || model.length === 0
353 ? undefined
354 : entry?.models.find((candidate) => candidate.slug === model);
355 const label =
356 providerModel !== undefined
357 ? getTriggerDisplayModelName(providerModel)
358 : model !== undefined && model.length > 0
359 ? model
360 : (entry?.displayName ?? props.instanceId);
361 return (
362 <Tooltip>
363 <TooltipTrigger
364 render={
365 <span
366 tabIndex={0}
367 role="img"
368 aria-label={label}
369 className="inline-flex shrink-0 items-center justify-center rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
370 >
371 <ProviderInstanceIcon
372 driverKind={entry?.driverKind ?? ProviderDriverKind.make(props.instanceId)}
373 displayName={entry?.displayName ?? props.instanceId}
374 acpRegistryAgentId={entry?.acpRegistryAgentId}
375 acpRegistryIconUrl={entry?.acpRegistryIconUrl}
376 iconClassName="size-3"
377 />
378 </span>
379 }
380 />
381 <TooltipPopup>{label}</TooltipPopup>
382 </Tooltip>
383 );
384}