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