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

ProviderInstanceCard.tsx

892 lines32.0 KB

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