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

ProviderInstanceCard.tsx

980 lines35.6 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 const customModels =
504 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
505 // Server-returned models may lag behind settings writes. Treat probe
506 // models as the source for built-ins only; custom rows come directly
507 // from the current instance config so add/remove reflects immediately.
508 const modelsForDisplay = deriveProviderModelsForDisplay({
509 liveModels: liveProvider?.models,
510 customModels,
511 });
512 const updateDisplayName = (value: string) => {
513 const trimmed = value.trim();
514 const { displayName: _omit, ...rest } = instance;
515 onUpdate(
516 trimmed.length > 0
517 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
518 : (rest as ProviderInstanceConfig),
519 );
520 };
521​
522 const updateEnabled = (value: boolean) => {
523 onUpdate({ ...instance, enabled: value });
524 };
525​
526 const updateAccentColor = (value: string) => {
527 const normalized = normalizeProviderAccentColor(value);
528 const { accentColor: _omit, ...rest } = instance;
529 onUpdate(
530 normalized
531 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
532 : (rest as ProviderInstanceConfig),
533 );
534 };
535​
536 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
537 const { config: _omit, ...rest } = instance;
538 onUpdate(
539 nextConfig !== undefined
540 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
541 : (rest as ProviderInstanceConfig),
542 );
543 };
544​
545 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
546 const nextConfig = nextConfigBlobWithValue(
547 instance.config,
548 "customModels",
549 next.map(toCustomModelSetting),
550 );
551 const { config: _omit, ...rest } = instance;
552 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
553 };
554​
555 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
556 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
557 const { environment: _omit, ...rest } = instance;
558 onUpdate(
559 cleaned.length > 0
560 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
561 : (rest as ProviderInstanceConfig),
562 );
563 };
564​
565 const titleIconNode = driverKind ? (
566 <ProviderInstanceIcon
567 driverKind={driverKind}
568 displayName={displayName}
569 accentColor={accentColor}
570 showBadge={Boolean(accentColor)}
571 className="size-5"
572 iconClassName="size-4 text-foreground/80"
573 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
574 />
575 ) : FallbackIconComponent ? (
576 <span className="inline-flex size-5 shrink-0 items-center justify-center">
577 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
578 </span>
579 ) : (
580 <span
581 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
582 aria-hidden
583 >
584 {providerInstanceInitials(displayName)}
585 </span>
586 );
587​
588 const titleTailNode = headerAction ? (
589 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
590 ) : null;
591​
592 const versionCodeNode = versionLabel ? (
593 <code className="text-xs text-muted-foreground">{versionLabel}</code>
594 ) : null;
595​
596 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
597 const statusDotNode =
598 statusKey === "warning" || statusKey === "error" ? (
599 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
600 ) : null;
601 const needsAttention = statusKey === "warning" || statusKey === "error";
602 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
603 // Keep compatibility copy compact; the version popover carries the explanation.
604 const inlineStatusDetail = hasCompatibilityWarning
605 ? compatibility?.status === "broken"
606 ? "Incompatible"
607 : compatibility?.status === "unsupported"
608 ? "Unsupported"
609 : "Limited support"
610 : summary.detail;
611 const editorStatusNode =
612 isAuthenticated && authEmail ? (
613 <>
614 {needsAttention ? statusDotNode : null}
615 <span>Authenticated as</span>
616 <ProviderAuthEmail email={authEmail} />
617 {authLabel ? <span>· {authLabel}</span> : null}
618 {inlineStatusDetail ? (
619 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
620 ) : null}
621 </>
622 ) : (
623 <>
624 {statusDotNode}
625 <span>{summary.headline}</span>
626 {inlineStatusDetail ? (
627 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
628 ) : null}
629 </>
630 );
631 if (mode === "list") {
632 return (
633 <div
634 data-slot="settings-row"
635 className={cn(
636 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
637 selected ? "bg-muted/45" : "hover:bg-muted/25",
638 )}
639 >
640 <div
641 className={cn(
642 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
643 !enabled && !selected && "opacity-60 group-hover:opacity-100",
644 )}
645 >
646 <button
647 type="button"
648 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
649 onClick={onSelect}
650 aria-label={`Select ${displayName}`}
651 aria-pressed={selected}
652 />
653 {titleIconNode}
654 <span className="min-w-0 flex-1">
655 <span className="flex min-w-0 items-center gap-2">
656 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
657 {String(instanceId) !== String(instance.driver) ? (
658 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
659 {instanceId}
660 </code>
661 ) : null}
662 {versionLabel ? (
663 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
664 {versionLabel}
665 </code>
666 ) : null}
667 {versionAdvisory ? (
668 hasCompatibilityWarning ? (
669 <Tooltip>
670 <TooltipTrigger
671 render={
672 <span
673 tabIndex={0}
674 role="img"
675 aria-label={versionAdvisory.title}
676 className="pointer-events-auto relative inline-flex shrink-0 text-warning"
677 >
678 <VersionAdvisoryIcon className="size-3.5" />
679 </span>
680 }
681 />
682 <TooltipPopup side="top">{versionAdvisory.detail}</TooltipPopup>
683 </Tooltip>
684 ) : updateCommand ? (
685 <Tooltip>
686 <TooltipTrigger
687 render={
688 <Button
689 type="button"
690 size="icon-micro"
691 variant="ghost-muted"
692 className="pointer-events-auto relative shrink-0"
693 aria-label={`Copy ${displayName} update command`}
694 onClick={() =>
695 copyToClipboard(updateCommand, { providerName: displayName })
696 }
697 >
698 <ArrowUpCircleIcon className="size-3.5" />
699 </Button>
700 }
701 />
702 <TooltipPopup side="top">Copy update command</TooltipPopup>
703 </Tooltip>
704 ) : (
705 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
706 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
707 </span>
708 )
709 ) : null}
710 </span>
711 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
712 {statusDotNode ? (
713 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
714 ) : null}
715 <ProviderStatusDiagnostic detail={statusDiagnostic}>
716 <span
717 tabIndex={statusDiagnostic ? 0 : undefined}
718 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
719 >
720 {summary.headline}
721 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
722 </span>
723 </ProviderStatusDiagnostic>
724 </span>
725 </span>
726 </div>
727 <span className="flex h-5 shrink-0 items-center">
728 <Switch
729 checked={enabled}
730 disabled={readOnly}
731 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
732 aria-label={`Enable ${displayName}`}
733 />
734 </span>
735 </div>
736 );
737 }
738​
739 const editorHeaderAction = (
740 <div className="flex shrink-0 items-center gap-1.5">
741 {driverOption?.badgeLabel ? (
742 <Badge variant="warning" size="sm" className="shrink-0">
743 {driverOption.badgeLabel}
744 </Badge>
745 ) : null}
746 {versionCodeNode}
747 <span
748 inert={readOnly}
749 aria-disabled={readOnly || undefined}
750 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
751 >
752 {versionAdvisory ? (
753 <Popover>
754 <Tooltip>
755 <TooltipTrigger
756 render={
757 <PopoverTrigger
758 render={
759 <Button
760 type="button"
761 size="icon-xs"
762 variant="ghost-muted"
763 aria-label={`${versionAdvisory.title} — view details`}
764 >
765 <VersionAdvisoryIcon
766 className={cn(hasCompatibilityWarning && "text-warning")}
767 />
768 </Button>
769 }
770 />
771 }
772 />
773 <TooltipPopup side="top">{versionAdvisory.title}</TooltipPopup>
774 </Tooltip>
775 <PopoverPopup side="bottom" align="end" width="md">
776 <div className="grid min-w-0 gap-3">
777 <div className="grid gap-0.5">
778 <p className="text-[13px] font-semibold leading-tight text-foreground">
779 {versionAdvisory.title}
780 </p>
781 <p
782 className={cn(
783 "text-xs leading-snug",
784 versionAdvisory.emphasis === "strong"
785 ? "text-warning"
786 : "text-muted-foreground",
787 )}
788 >
789 {versionAdvisory.detail}
790 </p>
791 </div>
792 {onRunVersionAction ? (
793 <Button
794 type="button"
795 size="xs"
796 variant="outline"
797 className="w-full"
798 disabled={isUpdating}
799 onClick={onRunVersionAction}
800 >
801 {isUpdating ? <Spinner /> : <DownloadIcon />}
802 {isUpdating
803 ? "Updating"
804 : versionAdvisory.targetVersion
805 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
806 : "Update now"}
807 </Button>
808 ) : null}
809 {onRunVersionAction && updateCommand ? (
810 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
811 <span aria-hidden className="h-px flex-1 bg-border" />
812 or, update manually using
813 <span aria-hidden className="h-px flex-1 bg-border" />
814 </div>
815 ) : null}
816 {updateCommand ? (
817 <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">
818 <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground">
819 {updateCommand}
820 </code>
821 <Tooltip>
822 <TooltipTrigger
823 render={
824 <Button
825 type="button"
826 size="icon-xs"
827 variant="ghost-muted"
828 className="shrink-0"
829 onClick={() =>
830 copyToClipboard(updateCommand, { providerName: displayName })
831 }
832 aria-label="Copy update command"
833 >
834 <CopyIcon className="size-3" />
835 </Button>
836 }
837 />
838 <TooltipPopup side="top">Copy command</TooltipPopup>
839 </Tooltip>
840 </div>
841 ) : null}
842 </div>
843 </PopoverPopup>
844 </Popover>
845 ) : null}
846 {titleTailNode}
847 {onDelete ? (
848 <Button
849 type="button"
850 size="icon-xs"
851 variant="ghost-destructive"
852 disabled={readOnly}
853 onClick={onDelete}
854 aria-label={`Delete instance ${instanceId}`}
855 >
856 <Trash2Icon />
857 </Button>
858 ) : null}
859 </span>
860 </div>
861 );
862​
863 return (
864 <>
865 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
866 <SettingsRow
867 title="Display name"
868 status={
869 <ProviderStatusDiagnostic detail={statusDiagnostic}>
870 <div
871 tabIndex={statusDiagnostic ? 0 : undefined}
872 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
873 >
874 {editorStatusNode}
875 </div>
876 </ProviderStatusDiagnostic>
877 }
878 control={
879 <div
880 inert={readOnly}
881 aria-disabled={readOnly || undefined}
882 className={cn(
883 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
884 readOnly && "opacity-50 select-none",
885 )}
886 >
887 <ProviderAccentColorPicker
888 layout="inline"
889 displayName={displayName}
890 value={accentColor}
891 onCommit={updateAccentColor}
892 commitDelayMs={120}
893 />
894 <DraftInput
895 id={`provider-instance-${instanceId}-display-name`}
896 size="sm"
897 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
898 value={instance.displayName ?? ""}
899 onCommit={updateDisplayName}
900 placeholder={driverOption?.label ?? "Instance label"}
901 spellCheck={false}
902 />
903 </div>
904 }
905 />
906 </SettingsSection>
907​
908 {setup ? <SettingsSection title="Setup">{setup}</SettingsSection> : null}
909​
910 <SettingsSection
911 title="Runtime"
912 inert={readOnly}
913 aria-disabled={readOnly || undefined}
914 className={readOnly ? "opacity-50 select-none" : undefined}
915 >
916 {driverOption ? (
917 <ProviderSettingsForm
918 definition={driverOption}
919 value={instance.config}
920 idPrefix={`provider-instance-${instanceId}`}
921 variant="settings"
922 onChange={updateConfig}
923 />
924 ) : (
925 <SettingsRow
926 title="Driver"
927 description={
928 <span>
929 This instance uses{" "}
930 <code className="text-foreground">{String(instance.driver)}</code>, which is not
931 available in this build. Its configuration is preserved.
932 </span>
933 }
934 />
935 )}
936 </SettingsSection>
937​
938 <SettingsSection
939 title="Environment"
940 inert={readOnly}
941 aria-disabled={readOnly || undefined}
942 className={readOnly ? "opacity-50 select-none" : undefined}
943 >
944 <ProviderEnvironmentSection
945 environment={instance.environment ?? []}
946 onChange={updateEnvironment}
947 />
948 </SettingsSection>
949​
950 {driverOption !== undefined ? (
951 <SettingsSection
952 title="Models"
953 inert={readOnly}
954 aria-disabled={readOnly || undefined}
955 className={readOnly ? "opacity-50 select-none" : undefined}
956 >
957 <div className="px-3 py-3 sm:px-4">
958 <p className="mb-3 text-xs text-muted-foreground">
959 Favorites, visibility, and ordering are saved on this device. Custom models are saved
960 on the selected environment.
961 </p>
962 <ProviderModelsSection
963 instanceId={instanceId}
964 driverKind={driverKind}
965 models={modelsForDisplay}
966 customModels={customModels}
967 hiddenModels={hiddenModels}
968 favoriteModels={favoriteModels}
969 modelOrder={modelOrder}
970 onChange={updateCustomModels}
971 onHiddenModelsChange={onHiddenModelsChange}
972 onFavoriteModelsChange={onFavoriteModelsChange}
973 onModelOrderChange={onModelOrderChange}
974 />
975 </div>
976 </SettingsSection>
977 ) : null}
978 </>
979 );