Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

V2LifecycleRow.tsx

776 lines27.0 KB

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