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