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

ProviderInstanceCard.tsx

983 lines35.8 KB

1"use client";
2​
3import { Spinner } from "~/components/ui/spinner";
4​
5import {
6 AlertTriangleIcon,
7 ArrowUpCircleIcon,
8 CopyIcon,
9 DownloadIcon,
10 LockIcon,
11 LockOpenIcon,
12 PlusIcon,
13 Trash2Icon,
14 XIcon,
15} from "lucide-react";
16import * as Arr from "effect/Array";
17import * as Result from "effect/Result";
18import { useEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
19import {
20 isProviderDriverKind,
21 resolveProviderInstanceEnabled,
22 type ProviderInstanceConfig,
23 type ProviderInstanceEnvironmentVariable,
24 type ProviderInstanceId,
25 type ProviderDriverKind,
26 type ServerProvider,
27 type ServerProviderModel,
28} from "@t3tools/contracts";
29​
30import {
31 type CustomModelDefinition,
32 readCustomModelEntries,
33 toCustomModelSetting,
34} from "@t3tools/shared/model";
35import { cn } from "../../lib/utils";
36import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
37import { normalizeProviderAccentColor } from "../../providerInstances";
38import { Badge } from "../ui/badge";
39import { Button } from "../ui/button";
40import { DraftInput } from "../ui/draft-input";
41import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
42import { Switch } from "../ui/switch";
43import { stackedThreadToast, toastManager } from "../ui/toast";
44import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
45import type { DriverOption } from "./providerDriverMeta";
46import { ProviderSettingsForm } from "./ProviderSettingsForm";
47import { ProviderModelsSection } from "./ProviderModelsSection";
48import { ProviderInstanceIcon, providerInstanceInitials } from "../chat/ProviderInstanceIcon";
49import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
50import { RedactedSensitiveText } from "./RedactedSensitiveText";
51import { SettingsRow, SettingsSection } from "./settingsLayout";
52import {
53 getProviderVersionAdvisoryPresentation,
54 PROVIDER_STATUS_STYLES,
55 getProviderSummary,
56 getProviderVersionLabel,
57 type ProviderStatusKey,
58} from "./providerStatus";
59​
60const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
61​
62function ProviderStatusDiagnostic({
63 detail,
64 children,
65}: {
66 detail: string | null;
67 children: ReactElement;
68}) {
69 if (!detail) return children;
70 return (
71 <Tooltip>
72 <TooltipTrigger render={children} />
73 <TooltipPopup side="top">{detail}</TooltipPopup>
74 </Tooltip>
75 );
77​
78let environmentVariableDraftId = 0;
79const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;
80​
81type EnvironmentDraftRow = {
82 readonly id: string;
83 readonly name: string;
84 readonly value: string;
85 readonly sensitive: boolean;
86 readonly valueRedacted?: boolean;
87};
88​
89function makeEnvironmentDraftRow(
90 variable: ProviderInstanceEnvironmentVariable,
91 index: number,
92): EnvironmentDraftRow {
93 return {
94 id: `${index}:${variable.name}`,
95 name: variable.name,
96 value: variable.value,
97 sensitive: variable.sensitive,
98 ...(variable.valueRedacted !== undefined ? { valueRedacted: variable.valueRedacted } : {}),
99 };
101​
102function providerEnvironmentsEqual(
103 left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
104 right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
105): boolean {
106 return (
107 left.length === right.length &&
108 left.every((variable, index) => {
109 const other = right[index];
110 return (
111 other !== undefined &&
112 variable.name === other.name &&
113 variable.value === other.value &&
114 variable.sensitive === other.sensitive &&
115 variable.valueRedacted === other.valueRedacted
116 );
117 })
118 );
120​
121/**
122 * Read `customModels` from the opaque config blob. The concrete driver
123 * schemas type it as `CustomModelSetting[]`, but it arrives here as
124 * `Schema.Unknown`, so the shared reader does the shape checking.
125 */
126function readConfigCustomModels(config: unknown): ReadonlyArray<CustomModelDefinition> {
127 if (config === null || typeof config !== "object") return [];
128 return readCustomModelEntries((config as Record<string, unknown>).customModels);
130​
131/**
132 * Set `key` to an arbitrary value on the opaque config blob. Unlike
133 * provider settings field updates, does not drop empty-looking values — the
134 * caller is responsible for deciding whether an empty array / empty
135 * object should be stored explicitly (e.g. `customModels: []` is a
136 * meaningful "user cleared their custom list" state distinct from
137 * "driver default").
138 */
139function nextConfigBlobWithValue(
140 config: unknown,
141 key: string,
142 value: unknown,
143): Record<string, unknown> {
144 const base: Record<string, unknown> =
145 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
146 base[key] = value;
147 return base;
149​
150/**
151 * Custom rows come from current settings so name/descriptor edits show
152 * instantly; a bare entry falls back to the live row's driver-default
153 * capabilities (the server fills those in on its next probe).
154 */
155export function deriveProviderModelsForDisplay(input: {
156 readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
157 readonly customModels: ReadonlyArray<CustomModelDefinition>;
158}): ReadonlyArray<ServerProviderModel> {
159 const liveCustomModelsBySlug = new Map(
160 Arr.filterMap(input.liveModels ?? [], (model) =>
161 model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
162 ),
163 );
164 const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
165 const customModels = input.customModels.map((entry) => ({
166 slug: entry.slug,
167 name: entry.name,
168 isCustom: true,
169 capabilities:
170 entry.capabilities ?? liveCustomModelsBySlug.get(entry.slug)?.capabilities ?? null,
171 }));
172 return [...serverModels, ...customModels];
174​
175function ProviderAuthEmail(props: { readonly email: string | undefined }) {
176 const email = props.email?.trim();
177 if (!email) return null;
178​
179 return (
180 <RedactedSensitiveText
181 value={email}
182 ariaLabel="Toggle account email visibility"
183 revealTooltip="Click to reveal email"
184 hideTooltip="Click to hide email"
185 className="max-w-full truncate"
186 />
187 );
189​
190function ProviderEnvironmentSection(props: {
191 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
192 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
193}) {
194 const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
195 props.environment.map(makeEnvironmentDraftRow),
196 );
197 const previousEnvironmentRef = useRef(props.environment);
198 const lastPublishedEnvironmentRef = useRef<
199 ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
200 >(undefined);
201​
202 useEffect(() => {
203 const previousEnvironment = previousEnvironmentRef.current;
204 const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
205 previousEnvironmentRef.current = props.environment;
206 lastPublishedEnvironmentRef.current = undefined;
207 if (
208 previousEnvironment === props.environment ||
209 providerEnvironmentsEqual(previousEnvironment, props.environment) ||
210 (lastPublishedEnvironment !== undefined &&
211 providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
212 ) {
213 return;
214 }
215 setRows(props.environment.map(makeEnvironmentDraftRow));
216 }, [props.environment]);
217​
218 const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
219 const published: ProviderInstanceEnvironmentVariable[] = [];
220 for (const row of nextRows) {
221 const name = row.name.trim();
222 if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
223 if (
224 name.length > 0 ||
225 row.value.length > 0 ||
226 row.sensitive !== true ||
227 row.valueRedacted !== undefined
228 ) {
229 return;
230 }
231 continue;
232 }
233 const { id: _id, ...rest } = row;
234 published.push({ ...rest, name });
235 }
236 lastPublishedEnvironmentRef.current = published;
237 props.onChange(published);
238 };
239​
240 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
241 const nextRows = rows.map((row) =>
242 row.id === id
243 ? {
244 ...row,
245 ...patch,
246 ...(patch.value !== undefined ? { valueRedacted: false } : {}),
247 }
248 : row,
249 );
250 setRows(nextRows);
251 publishRows(nextRows);
252 };
253​
254 const removeVariable = (id: string) => {
255 const nextRows = rows.filter((row) => row.id !== id);
256 setRows(nextRows);
257 publishRows(nextRows);
258 };
259​
260 const addVariable = () =>
261 setRows([
262 ...rows,
263 {
264 id: nextEnvironmentVariableDraftId(),
265 name: "",
266 value: "",
267 sensitive: true,
268 },
269 ]);
270​
271 return (
272 <SettingsRow
273 title="Variables"
274 description="API keys, base URLs, and other per-instance CLI settings."
275 control={
276 <Button type="button" size="sm" variant="outline" onClick={addVariable}>
277 <PlusIcon className="size-3" />
278 Add variable
279 </Button>
280 }
281 >
282 {rows.length > 0 ? (
283 <div className="mt-3 min-w-0 space-y-2 pb-2">
284 {rows.map((variable, index) => (
285 <div key={variable.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
286 <DraftInput
287 size="sm"
288 font="mono"
289 className="w-full min-w-0 sm:w-44 sm:shrink-0"
290 value={variable.name}
291 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
292 placeholder="VARIABLE_NAME"
293 spellCheck={false}
294 aria-label={`Environment variable name ${index + 1}`}
295 />
296 <span className="hidden text-xs text-muted-foreground sm:inline" aria-hidden>
297 =
298 </span>
299 <DraftInput
300 size="sm"
301 font="mono"
302 className="min-w-0 flex-1"
303 value={variable.valueRedacted ? "" : variable.value}
304 onCommit={(value) => updateVariable(variable.id, { value })}
305 type={variable.sensitive ? "password" : undefined}
306 autoComplete="off"
307 placeholder={
308 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
309 }
310 spellCheck={false}
311 aria-label={`Environment variable value ${index + 1}`}
312 />
313 <Tooltip>
314 <TooltipTrigger
315 render={
316 <Button
317 type="button"
318 size="icon-micro"
319 variant="ghost-muted"
320 onClick={() => {
321 const sensitive = !variable.sensitive;
322 updateVariable(variable.id, {
323 sensitive,
324 ...(sensitive && variable.valueRedacted === undefined
325 ? {}
326 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
327 });
328 }}
329 aria-pressed={variable.sensitive}
330 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
331 >
332 {variable.sensitive ? (
333 <LockIcon className="size-3" />
334 ) : (
335 <LockOpenIcon className="size-3" />
336 )}
337 </Button>
338 }
339 />
340 <TooltipPopup side="top">
341 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
342 </TooltipPopup>
343 </Tooltip>
344 <Button
345 type="button"
346 size="icon-micro"
347 variant="ghost-destructive"
348 onClick={() => removeVariable(variable.id)}
349 aria-label={`Remove environment variable ${variable.name || index + 1}`}
350 >
351 <XIcon className="size-3" />
352 </Button>
353 </div>
354 ))}
355 <p className="text-xs text-muted-foreground">
356 Sensitive values are stored separately and never returned to the app.
357 </p>
358 </div>
359 ) : null}
360 </SettingsRow>
361 );
363​
364interface ProviderInstanceCardProps {
365 readonly instanceId: ProviderInstanceId;
366 readonly instance: ProviderInstanceConfig;
367 readonly driverOption: DriverOption | undefined;
368 readonly liveProvider: ServerProvider | undefined;
369 readonly mode: "list" | "editor";
370 readonly selected?: boolean | undefined;
371 readonly onSelect?: (() => void) | undefined;
372 readonly readOnly?: boolean | undefined;
373 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
374 /**
375 * Pass `undefined` to hide the delete footer entirely. Built-in default
376 * instance slots use `undefined` — they can't be deleted without losing
377 * the slot, and their "reset to defaults" affordance lives on an outer
378 * reset button instead. Explicit `| undefined` in the type accommodates
379 * `exactOptionalPropertyTypes: true`, where an absent key and
380 * `{ onDelete: undefined }` are treated as distinct shapes.
381 */
382 readonly onDelete?: (() => void) | undefined;
383 /**
384 * Optional outer reset button rendered next to the driver icon. Built-in
385 * default slots supply a reset-to-factory control here; custom instances
386 * omit it.
387 */
388 readonly headerAction?: ReactNode | undefined;
389 readonly setup?: ReactNode;
390 readonly hiddenModels: ReadonlyArray<string>;
391 readonly favoriteModels: ReadonlyArray<string>;
392 readonly modelOrder: ReadonlyArray<string>;
393 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
394 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
395 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
396 readonly onRunUpdate?: (() => void) | undefined;
397 readonly onInstallRecommended?: (() => void) | undefined;
398 readonly isUpdating?: boolean | undefined;
400​
401/**
402 * Renders one provider instance as either a compact selectable list row or
403 * the full editor shown beside that list. Both modes use the same enabled
404 * state and provider metadata.
405 *
406 * Behavior notes:
407 * - `liveProvider` is matched by the caller via `instanceId`; when no
408 * match is available (e.g. the server hasn't probed yet, or the
409 * driver is not shipped by the current build) the card still renders
410 * with a neutral "checking" summary.
411 * - Unknown drivers (`driverOption === undefined`) get a read-only
412 * notice instead of editable fields, so fork instances round-trip
413 * without accidentally destroying their config.
414 * - The enabled Switch writes to the envelope's `instance.enabled`
415 * field, which is the single enabled flag: the server folds any legacy
416 * driver-specific `config.enabled` into the envelope on load and both
417 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
418 * false wins, then envelope, then config, then the driver default).
419 */
420export function ProviderInstanceCard({
421 instanceId,
422 instance,
423 driverOption,
424 liveProvider,
425 mode,
426 selected = false,
427 onSelect,
428 readOnly = false,
429 onUpdate,
430 onDelete,
431 headerAction,
432 setup,
433 hiddenModels,
434 favoriteModels,
435 modelOrder,
436 onHiddenModelsChange,
437 onFavoriteModelsChange,
438 onModelOrderChange,
439 onRunUpdate,
440 onInstallRecommended,
441 isUpdating = false,
442}: ProviderInstanceCardProps) {
443 const enabled = resolveProviderInstanceEnabled(instance);
444 const compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
445 // A locally disabled provider reads "Disabled" with a muted dot even if its
446 // last server status is stale. Enabled providers use the server status.
447 const statusKey: ProviderStatusKey = enabled
448 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
449 : "disabled";
450 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
451 const summary = enabled
452 ? getProviderSummary(liveProvider)
453 : { headline: "Disabled", detail: null };
454 const authEmail = liveProvider?.auth.email?.trim();
455 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
456 const authLabel =
457 enabled && liveProvider?.auth.status === "authenticated"
458 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
459 : null;
460 const versionLabel = getProviderVersionLabel(liveProvider?.version);
461 const versionAdvisory = getProviderVersionAdvisoryPresentation(
462 liveProvider?.versionAdvisory,
463 liveProvider?.compatibilityAdvisory,
464 enabled,
465 );
466 const updateCommand = versionAdvisory?.updateCommand ?? null;
467 const hasCompatibilityWarning =
468 compatibility !== undefined &&
469 compatibility.status !== "supported" &&
470 compatibility.status !== "unknown";
471 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
472 const onRunVersionAction = versionAdvisory?.targetVersion ? onInstallRecommended : onRunUpdate;
473 const FallbackIconComponent = driverOption?.icon;
474 const displayName =
475 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
476 const accentColor = normalizeProviderAccentColor(instance.accentColor);
477 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
478 onCopy: ({ providerName }) => {
479 toastManager.add({
480 type: "success",
481 title: `${providerName} update command copied`,
482 description: "Run it in a terminal when you are ready to update.",
483 });
484 },
485 onError: (error, { providerName }) => {
486 toastManager.add(
487 stackedThreadToast({
488 type: "error",
489 title: `Could not copy ${providerName} update command`,
490 description: error.message,
491 }),
492 );
493 },
494 });
495​
496 // Narrow `instance.driver` for callers that key on the closed
497 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
498 // fork drivers pass through as `null` and those callers fall back to
499 // verbatim behaviour.
500 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
501 ? instance.driver
502 : null;
503 // Antigravity has no custom-model surface. Cursor still shows persisted
504 // customModels so users can inspect/remove them; Add is blocked in
505 // ProviderModelsSection via providerSupportsCustomModels.
506 const customModels =
507 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
508 // Server-returned models may lag behind settings writes. Treat probe
509 // models as the source for built-ins only; custom rows come directly
510 // from the current instance config so add/remove reflects immediately.
511 const modelsForDisplay = deriveProviderModelsForDisplay({
512 liveModels: liveProvider?.models,
513 customModels,
514 });
515 const updateDisplayName = (value: string) => {
516 const trimmed = value.trim();
517 const { displayName: _omit, ...rest } = instance;
518 onUpdate(
519 trimmed.length > 0
520 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
521 : (rest as ProviderInstanceConfig),
522 );
523 };
524​
525 const updateEnabled = (value: boolean) => {
526 onUpdate({ ...instance, enabled: value });
527 };
528​
529 const updateAccentColor = (value: string) => {
530 const normalized = normalizeProviderAccentColor(value);
531 const { accentColor: _omit, ...rest } = instance;
532 onUpdate(
533 normalized
534 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
535 : (rest as ProviderInstanceConfig),
536 );
537 };
538​
539 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
540 const { config: _omit, ...rest } = instance;
541 onUpdate(
542 nextConfig !== undefined
543 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
544 : (rest as ProviderInstanceConfig),
545 );
546 };
547​
548 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
549 const nextConfig = nextConfigBlobWithValue(
550 instance.config,
551 "customModels",
552 next.map(toCustomModelSetting),
553 );
554 const { config: _omit, ...rest } = instance;
555 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
556 };
557​
558 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
559 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
560 const { environment: _omit, ...rest } = instance;
561 onUpdate(
562 cleaned.length > 0
563 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
564 : (rest as ProviderInstanceConfig),
565 );
566 };
567​
568 const titleIconNode = driverKind ? (
569 <ProviderInstanceIcon
570 driverKind={driverKind}
571 displayName={displayName}
572 accentColor={accentColor}
573 showBadge={Boolean(accentColor)}
574 className="size-5"
575 iconClassName="size-4 text-foreground/80"
576 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
577 />
578 ) : FallbackIconComponent ? (
579 <span className="inline-flex size-5 shrink-0 items-center justify-center">
580 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
581 </span>
582 ) : (
583 <span
584 className="inline-flex size-5 shrink-0 items-center justify-center text-3xs font-semibold leading-none text-foreground/80"
585 aria-hidden
586 >
587 {providerInstanceInitials(displayName)}
588 </span>
589 );
590​
591 const titleTailNode = headerAction ? (
592 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
593 ) : null;
594​
595 const versionCodeNode = versionLabel ? (
596 <code className="text-xs text-muted-foreground">{versionLabel}</code>
597 ) : null;
598​
599 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
600 const statusDotNode =
601 statusKey === "warning" || statusKey === "error" ? (
602 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
603 ) : null;
604 const needsAttention = statusKey === "warning" || statusKey === "error";
605 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
606 // Keep compatibility copy compact; the version popover carries the explanation.
607 const inlineStatusDetail = hasCompatibilityWarning
608 ? compatibility?.status === "broken"
609 ? "Incompatible"
610 : compatibility?.status === "unsupported"
611 ? "Unsupported"
612 : "Limited support"
613 : summary.detail;
614 const editorStatusNode =
615 isAuthenticated && authEmail ? (
616 <>
617 {needsAttention ? statusDotNode : null}
618 <span>Authenticated as</span>
619 <ProviderAuthEmail email={authEmail} />
620 {authLabel ? <span>· {authLabel}</span> : null}
621 {inlineStatusDetail ? (
622 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
623 ) : null}
624 </>
625 ) : (
626 <>
627 {statusDotNode}
628 <span>{summary.headline}</span>
629 {inlineStatusDetail ? (
630 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
631 ) : null}
632 </>
633 );
634 if (mode === "list") {
635 return (
636 <div
637 data-slot="settings-row"
638 className={cn(
639 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
640 selected ? "bg-muted/45" : "hover:bg-muted/25",
641 )}
642 >
643 <div
644 className={cn(
645 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
646 !enabled && !selected && "opacity-60 group-hover:opacity-100",
647 )}
648 >
649 <button
650 type="button"
651 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
652 onClick={onSelect}
653 aria-label={`Select ${displayName}`}
654 aria-pressed={selected}
655 />
656 {titleIconNode}
657 <span className="min-w-0 flex-1">
658 <span className="flex min-w-0 items-center gap-2">
659 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
660 {String(instanceId) !== String(instance.driver) ? (
661 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-3xs text-muted-foreground">
662 {instanceId}
663 </code>
664 ) : null}
665 {versionLabel ? (
666 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
667 {versionLabel}
668 </code>
669 ) : null}
670 {versionAdvisory ? (
671 hasCompatibilityWarning ? (
672 <Tooltip>
673 <TooltipTrigger
674 render={
675 <span
676 tabIndex={0}
677 role="img"
678 aria-label={versionAdvisory.title}
679 className="pointer-events-auto relative inline-flex shrink-0 text-warning"
680 >
681 <VersionAdvisoryIcon className="size-3.5" />
682 </span>
683 }
684 />
685 <TooltipPopup side="top">{versionAdvisory.detail}</TooltipPopup>
686 </Tooltip>
687 ) : updateCommand ? (
688 <Tooltip>
689 <TooltipTrigger
690 render={
691 <Button
692 type="button"
693 size="icon-micro"
694 variant="ghost-muted"
695 className="pointer-events-auto relative shrink-0"
696 aria-label={`Copy ${displayName} update command`}
697 onClick={() =>
698 copyToClipboard(updateCommand, { providerName: displayName })
699 }
700 >
701 <ArrowUpCircleIcon className="size-3.5" />
702 </Button>
703 }
704 />
705 <TooltipPopup side="top">Copy update command</TooltipPopup>
706 </Tooltip>
707 ) : (
708 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
709 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
710 </span>
711 )
712 ) : null}
713 </span>
714 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
715 {statusDotNode ? (
716 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
717 ) : null}
718 <ProviderStatusDiagnostic detail={statusDiagnostic}>
719 <span
720 tabIndex={statusDiagnostic ? 0 : undefined}
721 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
722 >
723 {summary.headline}
724 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
725 </span>
726 </ProviderStatusDiagnostic>
727 </span>
728 </span>
729 </div>
730 <span className="flex h-5 shrink-0 items-center">
731 <Switch
732 checked={enabled}
733 disabled={readOnly}
734 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
735 aria-label={`Enable ${displayName}`}
736 />
737 </span>
738 </div>
739 );
740 }
741​
742 const editorHeaderAction = (
743 <div className="flex shrink-0 items-center gap-1.5">
744 {driverOption?.badgeLabel ? (
745 <Badge variant="warning" size="sm" className="shrink-0">
746 {driverOption.badgeLabel}
747 </Badge>
748 ) : null}
749 {versionCodeNode}
750 <span
751 inert={readOnly}
752 aria-disabled={readOnly || undefined}
753 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
754 >
755 {versionAdvisory ? (
756 <Popover>
757 <Tooltip>
758 <TooltipTrigger
759 render={
760 <PopoverTrigger
761 render={
762 <Button
763 type="button"
764 size="icon-xs"
765 variant="ghost-muted"
766 aria-label={`${versionAdvisory.title} — view details`}
767 >
768 <VersionAdvisoryIcon
769 className={cn(hasCompatibilityWarning && "text-warning")}
770 />
771 </Button>
772 }
773 />
774 }
775 />
776 <TooltipPopup side="top">{versionAdvisory.title}</TooltipPopup>
777 </Tooltip>
778 <PopoverPopup side="bottom" align="end" width="md">
779 <div className="grid min-w-0 gap-3">
780 <div className="grid gap-0.5">
781 <p className="text-sm font-semibold leading-tight text-foreground">
782 {versionAdvisory.title}
783 </p>
784 <p
785 className={cn(
786 "text-xs leading-snug",
787 versionAdvisory.emphasis === "strong"
788 ? "text-warning"
789 : "text-muted-foreground",
790 )}
791 >
792 {versionAdvisory.detail}
793 </p>
794 </div>
795 {onRunVersionAction ? (
796 <Button
797 type="button"
798 size="xs"
799 variant="outline"
800 className="w-full"
801 disabled={isUpdating}
802 onClick={onRunVersionAction}
803 >
804 {isUpdating ? <Spinner /> : <DownloadIcon />}
805 {isUpdating
806 ? "Updating"
807 : versionAdvisory.targetVersion
808 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
809 : "Update now"}
810 </Button>
811 ) : null}
812 {onRunVersionAction && updateCommand ? (
813 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
814 <span aria-hidden className="h-px flex-1 bg-border" />
815 or, update manually using
816 <span aria-hidden className="h-px flex-1 bg-border" />
817 </div>
818 ) : null}
819 {updateCommand ? (
820 <div className="flex min-w-0 items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
821 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
822 {updateCommand}
823 </code>
824 <Tooltip>
825 <TooltipTrigger
826 render={
827 <Button
828 type="button"
829 size="icon-xs"
830 variant="ghost-muted"
831 className="shrink-0"
832 onClick={() =>
833 copyToClipboard(updateCommand, { providerName: displayName })
834 }
835 aria-label="Copy update command"
836 >
837 <CopyIcon className="size-3" />
838 </Button>
839 }
840 />
841 <TooltipPopup side="top">Copy command</TooltipPopup>
842 </Tooltip>
843 </div>
844 ) : null}
845 </div>
846 </PopoverPopup>
847 </Popover>
848 ) : null}
849 {titleTailNode}
850 {onDelete ? (
851 <Button
852 type="button"
853 size="icon-xs"
854 variant="ghost-destructive"
855 disabled={readOnly}
856 onClick={onDelete}
857 aria-label={`Delete instance ${instanceId}`}
858 >
859 <Trash2Icon />
860 </Button>
861 ) : null}
862 </span>
863 </div>
864 );
865​
866 return (
867 <>
868 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
869 <SettingsRow
870 title="Display name"
871 status={
872 <ProviderStatusDiagnostic detail={statusDiagnostic}>
873 <div
874 tabIndex={statusDiagnostic ? 0 : undefined}
875 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
876 >
877 {editorStatusNode}
878 </div>
879 </ProviderStatusDiagnostic>
880 }
881 control={
882 <div
883 inert={readOnly}
884 aria-disabled={readOnly || undefined}
885 className={cn(
886 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
887 readOnly && "opacity-50 select-none",
888 )}
889 >
890 <ProviderAccentColorPicker
891 layout="inline"
892 displayName={displayName}
893 value={accentColor}
894 onCommit={updateAccentColor}
895 commitDelayMs={120}
896 />
897 <DraftInput
898 id={`provider-instance-${instanceId}-display-name`}
899 size="sm"
900 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
901 value={instance.displayName ?? ""}
902 onCommit={updateDisplayName}
903 placeholder={driverOption?.label ?? "Instance label"}
904 spellCheck={false}
905 />
906 </div>
907 }
908 />
909 </SettingsSection>
910​
911 {setup ? <SettingsSection title="Setup">{setup}</SettingsSection> : null}
912​
913 <SettingsSection
914 title="Runtime"
915 inert={readOnly}
916 aria-disabled={readOnly || undefined}
917 className={readOnly ? "opacity-50 select-none" : undefined}
918 >
919 {driverOption ? (
920 <ProviderSettingsForm
921 definition={driverOption}
922 value={instance.config}
923 idPrefix={`provider-instance-${instanceId}`}
924 variant="settings"
925 onChange={updateConfig}
926 />
927 ) : (
928 <SettingsRow
929 title="Driver"
930 description={
931 <span>
932 This instance uses{" "}
933 <code className="text-foreground">{String(instance.driver)}</code>, which is not
934 available in this build. Its configuration is preserved.
935 </span>
936 }
937 />
938 )}
939 </SettingsSection>
940​
941 <SettingsSection
942 title="Environment"
943 inert={readOnly}
944 aria-disabled={readOnly || undefined}
945 className={readOnly ? "opacity-50 select-none" : undefined}
946 >
947 <ProviderEnvironmentSection
948 environment={instance.environment ?? []}
949 onChange={updateEnvironment}
950 />
951 </SettingsSection>
952​
953 {driverOption !== undefined ? (
954 <SettingsSection
955 title="Models"
956 inert={readOnly}
957 aria-disabled={readOnly || undefined}
958 className={readOnly ? "opacity-50 select-none" : undefined}
959 >
960 <div className="px-3 py-3 sm:px-4">
961 <p className="mb-3 text-xs text-muted-foreground">
962 Favorites, visibility, and ordering are saved on this device. Custom models are saved
963 on the selected environment.
964 </p>
965 <ProviderModelsSection
966 instanceId={instanceId}
967 driverKind={driverKind}
968 models={modelsForDisplay}
969 customModels={customModels}
970 hiddenModels={hiddenModels}
971 favoriteModels={favoriteModels}
972 modelOrder={modelOrder}
973 onChange={updateCustomModels}
974 onHiddenModelsChange={onHiddenModelsChange}
975 onFavoriteModelsChange={onFavoriteModelsChange}
976 onModelOrderChange={onModelOrderChange}
977 />
978 </div>
979 </SettingsSection>
980 ) : null}
981 </>
982 );