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