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