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