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 className="w-full min-w-0 font-mono sm:w-44 sm:shrink-0"
272 value={variable.name}
273 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
274 placeholder="VARIABLE_NAME"
275 spellCheck={false}
276 aria-label={`Environment variable name ${index + 1}`}
277 />
278 <span className="hidden text-xs text-muted-foreground sm:inline" aria-hidden>
279 =
280 </span>
281 <DraftInput
282 size="sm"
283 className="min-w-0 flex-1 font-mono"
284 value={variable.valueRedacted ? "" : variable.value}
285 onCommit={(value) => updateVariable(variable.id, { value })}
286 type={variable.sensitive ? "password" : undefined}
287 autoComplete="off"
288 placeholder={
289 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
290 }
291 spellCheck={false}
292 aria-label={`Environment variable value ${index + 1}`}
293 />
294 <Tooltip>
295 <TooltipTrigger
296 render={
297 <Button
298 type="button"
299 size="icon-micro"
300 variant="ghost-muted"
301 className={cn(
302 "[--control-icon-color:currentColor]",
303 variable.sensitive && "text-foreground",
304 )}
305 onClick={() => {
306 const sensitive = !variable.sensitive;
307 updateVariable(variable.id, {
308 sensitive,
309 ...(sensitive && variable.valueRedacted === undefined
310 ? {}
311 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
312 });
313 }}
314 aria-pressed={variable.sensitive}
315 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
316 >
317 {variable.sensitive ? (
318 <LockIcon className="size-3" />
319 ) : (
320 <LockOpenIcon className="size-3" />
321 )}
322 </Button>
323 }
324 />
325 <TooltipPopup side="top">
326 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
327 </TooltipPopup>
328 </Tooltip>
329 <Button
330 type="button"
331 size="icon-micro"
332 variant="ghost-muted"
333 className="[--control-icon-color:currentColor] hover:text-destructive"
334 onClick={() => removeVariable(variable.id)}
335 aria-label={`Remove environment variable ${variable.name || index + 1}`}
336 >
337 <XIcon className="size-3" />
338 </Button>
339 </div>
340 ))}
341 <p className="text-xs text-muted-foreground">
342 Sensitive values are stored separately and never returned to the app.
343 </p>
344 </div>
345 ) : null}
346 </SettingsRow>
347 );
348}
349
350interface ProviderInstanceCardProps {
351 readonly instanceId: ProviderInstanceId;
352 readonly instance: ProviderInstanceConfig;
353 readonly driverOption: DriverOption | undefined;
354 readonly liveProvider: ServerProvider | undefined;
355 readonly mode: "list" | "editor";
356 readonly selected?: boolean | undefined;
357 readonly onSelect?: (() => void) | undefined;
358 readonly readOnly?: boolean | undefined;
359 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
360 /**
361 * Pass `undefined` to hide the delete footer entirely. Built-in default
362 * instance slots use `undefined` — they can't be deleted without losing
363 * the slot, and their "reset to defaults" affordance lives on an outer
364 * reset button instead. Explicit `| undefined` in the type accommodates
365 * `exactOptionalPropertyTypes: true`, where an absent key and
366 * `{ onDelete: undefined }` are treated as distinct shapes.
367 */
368 readonly onDelete?: (() => void) | undefined;
369 /**
370 * Optional outer reset button rendered next to the driver icon. Built-in
371 * default slots supply a reset-to-factory control here; custom instances
372 * omit it.
373 */
374 readonly headerAction?: ReactNode | undefined;
375 readonly setup?: ReactNode;
376 readonly hiddenModels: ReadonlyArray<string>;
377 readonly favoriteModels: ReadonlyArray<string>;
378 readonly modelOrder: ReadonlyArray<string>;
379 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
380 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
381 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
382 readonly onRunUpdate?: (() => void) | undefined;
383 readonly isUpdating?: boolean | undefined;
384}
385
386/**
387 * Renders one provider instance as either a compact selectable list row or
388 * the full editor shown beside that list. Both modes use the same enabled
389 * state and provider metadata.
390 *
391 * Behavior notes:
392 * - `liveProvider` is matched by the caller via `instanceId`; when no
393 * match is available (e.g. the server hasn't probed yet, or the
394 * driver is not shipped by the current build) the card still renders
395 * with a neutral "checking" summary.
396 * - Unknown drivers (`driverOption === undefined`) get a read-only
397 * notice instead of editable fields, so fork instances round-trip
398 * without accidentally destroying their config.
399 * - The enabled Switch writes to the envelope's `instance.enabled`
400 * field, which is the single enabled flag: the server folds any legacy
401 * driver-specific `config.enabled` into the envelope on load and both
402 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
403 * false wins, then envelope, then config, then the driver default).
404 */
405export function ProviderInstanceCard({
406 instanceId,
407 instance,
408 driverOption,
409 liveProvider,
410 mode,
411 selected = false,
412 onSelect,
413 readOnly = false,
414 onUpdate,
415 onDelete,
416 headerAction,
417 setup,
418 hiddenModels,
419 favoriteModels,
420 modelOrder,
421 onHiddenModelsChange,
422 onFavoriteModelsChange,
423 onModelOrderChange,
424 onRunUpdate,
425 isUpdating = false,
426}: ProviderInstanceCardProps) {
427 const enabled = resolveProviderInstanceEnabled(instance);
428 // A locally disabled provider reads "Disabled" with a muted dot even if its
429 // last server status is stale. Enabled providers use the server status.
430 const statusKey: ProviderStatusKey = enabled
431 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
432 : "disabled";
433 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
434 const summary = enabled
435 ? getProviderSummary(liveProvider)
436 : { headline: "Disabled", detail: null };
437 const authEmail = liveProvider?.auth.email?.trim();
438 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
439 const authLabel =
440 enabled && liveProvider?.auth.status === "authenticated"
441 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
442 : null;
443 const versionLabel = getProviderVersionLabel(liveProvider?.version);
444 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
445 const updateCommand = versionAdvisory?.updateCommand ?? null;
446 const FallbackIconComponent = driverOption?.icon;
447 const displayName =
448 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
449 const accentColor = normalizeProviderAccentColor(instance.accentColor);
450 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
451 onCopy: ({ providerName }) => {
452 toastManager.add({
453 type: "success",
454 title: `${providerName} update command copied`,
455 description: "Run it in a terminal when you are ready to update.",
456 });
457 },
458 onError: (error, { providerName }) => {
459 toastManager.add(
460 stackedThreadToast({
461 type: "error",
462 title: `Could not copy ${providerName} update command`,
463 description: error.message,
464 }),
465 );
466 },
467 });
468
469 // Narrow `instance.driver` for callers that key on the closed
470 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
471 // fork drivers pass through as `null` and those callers fall back to
472 // verbatim behaviour.
473 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
474 ? instance.driver
475 : null;
476 const customModels =
477 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
478 // Server-returned models may lag behind settings writes. Treat probe
479 // models as the source for built-ins only; custom rows come directly
480 // from the current instance config so add/remove reflects immediately.
481 const modelsForDisplay = deriveProviderModelsForDisplay({
482 liveModels: liveProvider?.models,
483 customModels,
484 });
485 const updateDisplayName = (value: string) => {
486 const trimmed = value.trim();
487 const { displayName: _omit, ...rest } = instance;
488 onUpdate(
489 trimmed.length > 0
490 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
491 : (rest as ProviderInstanceConfig),
492 );
493 };
494
495 const updateEnabled = (value: boolean) => {
496 onUpdate({ ...instance, enabled: value });
497 };
498
499 const updateAccentColor = (value: string) => {
500 const normalized = normalizeProviderAccentColor(value);
501 const { accentColor: _omit, ...rest } = instance;
502 onUpdate(
503 normalized
504 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
505 : (rest as ProviderInstanceConfig),
506 );
507 };
508
509 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
510 const { config: _omit, ...rest } = instance;
511 onUpdate(
512 nextConfig !== undefined
513 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
514 : (rest as ProviderInstanceConfig),
515 );
516 };
517
518 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
519 const nextConfig = nextConfigBlobWithValue(
520 instance.config,
521 "customModels",
522 next.map(toCustomModelSetting),
523 );
524 const { config: _omit, ...rest } = instance;
525 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
526 };
527
528 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
529 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
530 const { environment: _omit, ...rest } = instance;
531 onUpdate(
532 cleaned.length > 0
533 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
534 : (rest as ProviderInstanceConfig),
535 );
536 };
537
538 const titleIconNode = driverKind ? (
539 <ProviderInstanceIcon
540 driverKind={driverKind}
541 displayName={displayName}
542 accentColor={accentColor}
543 showBadge={Boolean(accentColor)}
544 className="size-5"
545 iconClassName="size-4 text-foreground/80"
546 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
547 />
548 ) : FallbackIconComponent ? (
549 <span className="inline-flex size-5 shrink-0 items-center justify-center">
550 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
551 </span>
552 ) : (
553 <span
554 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
555 aria-hidden
556 >
557 {providerInstanceInitials(displayName)}
558 </span>
559 );
560
561 const titleTailNode = headerAction ? (
562 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
563 ) : null;
564
565 const versionCodeNode = versionLabel ? (
566 <code className="text-xs text-muted-foreground">{versionLabel}</code>
567 ) : null;
568
569 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
570 const statusDotNode =
571 statusKey === "warning" || statusKey === "error" ? (
572 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
573 ) : null;
574 // Trouble states carry the server's explanation (a failed probe, a shadow
575 // home entry that is not a symlink, a missing binary). Show it wherever the
576 // headline shows so the user can act without opening the editor.
577 const needsAttention = statusKey === "warning" || statusKey === "error";
578 const editorStatusNode =
579 isAuthenticated && authEmail ? (
580 <>
581 {needsAttention ? statusDotNode : null}
582 <span>Authenticated as</span>
583 <ProviderAuthEmail email={authEmail} />
584 {authLabel ? <span>· {authLabel}</span> : null}
585 {summary.detail ? (
586 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
587 ) : null}
588 </>
589 ) : (
590 <>
591 {statusDotNode}
592 <span>{summary.headline}</span>
593 {summary.detail ? (
594 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
595 ) : null}
596 </>
597 );
598 if (mode === "list") {
599 return (
600 <div
601 data-slot="settings-row"
602 className={cn(
603 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
604 selected ? "bg-muted/45" : "hover:bg-muted/25",
605 )}
606 >
607 <div
608 className={cn(
609 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
610 !enabled && !selected && "opacity-60 group-hover:opacity-100",
611 )}
612 >
613 <button
614 type="button"
615 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
616 onClick={onSelect}
617 aria-label={`Select ${displayName}`}
618 aria-pressed={selected}
619 />
620 {titleIconNode}
621 <span className="min-w-0 flex-1">
622 <span className="flex min-w-0 items-center gap-2">
623 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
624 {String(instanceId) !== String(instance.driver) ? (
625 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
626 {instanceId}
627 </code>
628 ) : null}
629 {versionLabel ? (
630 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
631 {versionLabel}
632 </code>
633 ) : null}
634 {versionAdvisory ? (
635 updateCommand ? (
636 <Tooltip>
637 <TooltipTrigger
638 render={
639 <Button
640 type="button"
641 size="icon-micro"
642 variant="ghost-muted"
643 className="pointer-events-auto relative shrink-0"
644 aria-label={`Copy ${displayName} update command`}
645 onClick={() =>
646 copyToClipboard(updateCommand, { providerName: displayName })
647 }
648 >
649 <ArrowUpCircleIcon className="size-3.5" />
650 </Button>
651 }
652 />
653 <TooltipPopup side="top">Copy update command</TooltipPopup>
654 </Tooltip>
655 ) : (
656 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
657 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
658 </span>
659 )
660 ) : null}
661 </span>
662 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
663 {statusDotNode ? (
664 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
665 ) : null}
666 <span className="line-clamp-2 [overflow-wrap:anywhere]">
667 {summary.headline}
668 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
669 </span>
670 </span>
671 </span>
672 </div>
673 <span className="flex h-5 shrink-0 items-center">
674 <Switch
675 checked={enabled}
676 disabled={readOnly}
677 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
678 aria-label={`Enable ${displayName}`}
679 />
680 </span>
681 </div>
682 );
683 }
684
685 const editorHeaderAction = (
686 <div className="flex shrink-0 items-center gap-1.5">
687 {driverOption?.badgeLabel ? (
688 <Badge variant="warning" size="sm" className="shrink-0">
689 {driverOption.badgeLabel}
690 </Badge>
691 ) : null}
692 {versionCodeNode}
693 <span
694 inert={readOnly}
695 aria-disabled={readOnly || undefined}
696 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
697 >
698 {versionAdvisory ? (
699 <Popover>
700 <PopoverTrigger
701 render={
702 <Button
703 type="button"
704 size="icon-xs"
705 variant="ghost"
706 className={cn(
707 "[--control-icon-color:currentColor]",
708 versionAdvisory.emphasis === "strong"
709 ? "text-warning hover:text-warning"
710 : "text-muted-foreground hover:text-foreground",
711 )}
712 aria-label="Update available — view details"
713 >
714 <ArrowUpCircleIcon />
715 </Button>
716 }
717 />
718 <PopoverPopup
719 side="bottom"
720 align="end"
721 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
722 >
723 <div className="grid min-w-0 gap-3">
724 <div className="grid gap-0.5">
725 <p className="text-[13px] font-semibold leading-tight text-foreground">
726 Update available
727 </p>
728 <p
729 className={cn(
730 "text-xs leading-snug",
731 versionAdvisory.emphasis === "strong"
732 ? "text-warning"
733 : "text-muted-foreground",
734 )}
735 >
736 {versionAdvisory.detail}
737 </p>
738 </div>
739 {onRunUpdate ? (
740 <Button
741 type="button"
742 size="xs"
743 variant="outline"
744 className="w-full"
745 disabled={isUpdating}
746 onClick={onRunUpdate}
747 >
748 {isUpdating ? <Spinner /> : <DownloadIcon />}
749 {isUpdating ? "Updating" : "Update now"}
750 </Button>
751 ) : null}
752 {onRunUpdate && updateCommand ? (
753 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
754 <span aria-hidden className="h-px flex-1 bg-border" />
755 or, update manually using
756 <span aria-hidden className="h-px flex-1 bg-border" />
757 </div>
758 ) : null}
759 {updateCommand ? (
760 <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">
761 <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground">
762 {updateCommand}
763 </code>
764 <Tooltip>
765 <TooltipTrigger
766 render={
767 <Button
768 type="button"
769 size="icon-xs"
770 variant="ghost"
771 className="shrink-0 text-muted-foreground hover:text-foreground"
772 onClick={() =>
773 copyToClipboard(updateCommand, { providerName: displayName })
774 }
775 aria-label="Copy update command"
776 >
777 <CopyIcon className="size-3" />
778 </Button>
779 }
780 />
781 <TooltipPopup side="top">Copy command</TooltipPopup>
782 </Tooltip>
783 </div>
784 ) : null}
785 </div>
786 </PopoverPopup>
787 </Popover>
788 ) : null}
789 {titleTailNode}
790 {onDelete ? (
791 <Button
792 type="button"
793 size="icon-xs"
794 variant="ghost-muted"
795 disabled={readOnly}
796 className="[--control-icon-color:currentColor] hover:text-destructive"
797 onClick={onDelete}
798 aria-label={`Delete instance ${instanceId}`}
799 >
800 <Trash2Icon />
801 </Button>
802 ) : null}
803 </span>
804 </div>
805 );
806
807 return (
808 <>
809 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
810 <SettingsRow
811 title="Display name"
812 status={
813 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5">{editorStatusNode}</div>
814 }
815 control={
816 <div
817 inert={readOnly}
818 aria-disabled={readOnly || undefined}
819 className={cn(
820 "flex w-full items-center justify-end gap-2 sm:w-auto",
821 readOnly && "opacity-50 select-none",
822 )}
823 >
824 <ProviderAccentColorPicker
825 layout="inline"
826 displayName={displayName}
827 value={accentColor}
828 onCommit={updateAccentColor}
829 commitDelayMs={120}
830 />
831 <DraftInput
832 id={`provider-instance-${instanceId}-display-name`}
833 size="sm"
834 className="min-w-0 flex-1 sm:w-56 sm:flex-none"
835 value={instance.displayName ?? ""}
836 onCommit={updateDisplayName}
837 placeholder={driverOption?.label ?? "Instance label"}
838 spellCheck={false}
839 />
840 </div>
841 }
842 />
843 </SettingsSection>
844
845 {setup ? <SettingsSection title="Setup">{setup}</SettingsSection> : null}
846
847 <SettingsSection
848 title="Runtime"
849 inert={readOnly}
850 aria-disabled={readOnly || undefined}
851 className={readOnly ? "opacity-50 select-none" : undefined}
852 >
853 {driverOption ? (
854 <ProviderSettingsForm
855 definition={driverOption}
856 value={instance.config}
857 idPrefix={`provider-instance-${instanceId}`}
858 variant="settings"
859 onChange={updateConfig}
860 />
861 ) : (
862 <SettingsRow
863 title="Driver"
864 description={
865 <span>
866 This instance uses{" "}
867 <code className="text-foreground">{String(instance.driver)}</code>, which is not
868 available in this build. Its configuration is preserved.
869 </span>
870 }
871 />
872 )}
873 </SettingsSection>
874
875 <SettingsSection
876 title="Environment"
877 inert={readOnly}
878 aria-disabled={readOnly || undefined}
879 className={readOnly ? "opacity-50 select-none" : undefined}
880 >
881 <ProviderEnvironmentSection
882 environment={instance.environment ?? []}
883 onChange={updateEnvironment}
884 />
885 </SettingsSection>
886
887 {driverOption !== undefined ? (
888 <SettingsSection
889 title="Models"
890 inert={readOnly}
891 aria-disabled={readOnly || undefined}
892 className={readOnly ? "opacity-50 select-none" : undefined}
893 >
894 <div className="px-3 py-3 sm:px-4">
895 <p className="mb-3 text-xs text-muted-foreground">
896 Favorites, visibility, and ordering are saved on this device. Custom models are saved
897 on the selected environment.
898 </p>
899 <ProviderModelsSection
900 instanceId={instanceId}
901 driverKind={driverKind}
902 models={modelsForDisplay}
903 customModels={customModels}
904 hiddenModels={hiddenModels}
905 favoriteModels={favoriteModels}
906 modelOrder={modelOrder}
907 onChange={updateCustomModels}
908 onHiddenModelsChange={onHiddenModelsChange}
909 onFavoriteModelsChange={onFavoriteModelsChange}
910 onModelOrderChange={onModelOrderChange}
911 />
912 </div>
913 </SettingsSection>
914 ) : null}
915 </>
916 );
917}