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 {
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, ProviderEnvironmentFieldDefinition } 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 };
82}
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 );
101}
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);
111}
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;
130}
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];
155}
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 );
170}
171
172export function readProviderEnvironmentVariable(
173 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
174 name: string,
175): ProviderInstanceEnvironmentVariable | undefined {
176 return environment?.find((variable) => variable.name === name);
177}
178
179export function providerEnvironmentWithoutNames(
180 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
181 names: ReadonlySet<string>,
182): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
183 return (environment ?? []).filter((variable) => !names.has(variable.name));
184}
185
186export function nextProviderEnvironmentWithFieldValue(
187 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
188 field: ProviderEnvironmentFieldDefinition,
189 value: string,
190): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
191 const trimmed = value.trim();
192 const next: ProviderInstanceEnvironmentVariable[] = [];
193 let found = false;
194
195 for (const variable of environment ?? []) {
196 if (variable.name !== field.name) {
197 next.push(variable);
198 continue;
199 }
200 found = true;
201 if (trimmed.length > 0) {
202 next.push({
203 name: variable.name,
204 value: trimmed,
205 sensitive: field.sensitive ?? true,
206 });
207 }
208 }
209
210 if (!found && trimmed.length > 0) {
211 next.push({
212 name: field.name,
213 value: trimmed,
214 sensitive: field.sensitive ?? true,
215 });
216 }
217
218 return next;
219}
220
221function ProviderEnvironmentFieldRow(props: {
222 readonly field: ProviderEnvironmentFieldDefinition;
223 readonly variable: ProviderInstanceEnvironmentVariable | undefined;
224 readonly idPrefix: string;
225 readonly onCommit: (field: ProviderEnvironmentFieldDefinition, value: string) => void;
226 readonly onRemove: (field: ProviderEnvironmentFieldDefinition) => void;
227}) {
228 const inputId = `${props.idPrefix}-environment-${props.field.name}`;
229 const value = props.variable?.valueRedacted ? "" : (props.variable?.value ?? "");
230 const placeholder = props.variable?.valueRedacted
231 ? "Stored secret - enter a new value to replace"
232 : props.field.placeholder;
233
234 return (
235 <label htmlFor={inputId} className="block">
236 <span className="text-xs font-medium text-foreground">{props.field.label}</span>
237 <div className="mt-1.5 flex min-w-0 items-center gap-2">
238 <DraftInput
239 id={inputId}
240 className="min-w-0 flex-1"
241 type={props.field.sensitive === false ? undefined : "password"}
242 autoComplete="off"
243 value={value}
244 onCommit={(next) => props.onCommit(props.field, next)}
245 placeholder={placeholder}
246 spellCheck={false}
247 />
248 {props.variable ? (
249 <Button
250 type="button"
251 size="icon-sm"
252 variant="ghost"
253 className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
254 onClick={() => props.onRemove(props.field)}
255 aria-label={`Clear ${props.field.label}`}
256 >
257 <XIcon className="size-3.5" />
258 </Button>
259 ) : null}
260 </div>
261 {props.field.description ? (
262 <span className="mt-1 block text-xs text-muted-foreground">{props.field.description}</span>
263 ) : null}
264 </label>
265 );
266}
267
268function ProviderEnvironmentSection(props: {
269 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
270 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
271}) {
272 const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
273 props.environment.map(makeEnvironmentDraftRow),
274 );
275 const previousEnvironmentRef = useRef(props.environment);
276 const lastPublishedEnvironmentRef = useRef<
277 ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
278 >(undefined);
279
280 useEffect(() => {
281 const previousEnvironment = previousEnvironmentRef.current;
282 const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
283 previousEnvironmentRef.current = props.environment;
284 lastPublishedEnvironmentRef.current = undefined;
285 if (
286 previousEnvironment === props.environment ||
287 providerEnvironmentsEqual(previousEnvironment, props.environment) ||
288 (lastPublishedEnvironment !== undefined &&
289 providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
290 ) {
291 return;
292 }
293 setRows(props.environment.map(makeEnvironmentDraftRow));
294 }, [props.environment]);
295
296 const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
297 const published: ProviderInstanceEnvironmentVariable[] = [];
298 for (const row of nextRows) {
299 const name = row.name.trim();
300 if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
301 if (
302 name.length > 0 ||
303 row.value.length > 0 ||
304 row.sensitive !== true ||
305 row.valueRedacted !== undefined
306 ) {
307 return;
308 }
309 continue;
310 }
311 const { id: _id, ...rest } = row;
312 published.push({ ...rest, name });
313 }
314 lastPublishedEnvironmentRef.current = published;
315 props.onChange(published);
316 };
317
318 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
319 const nextRows = rows.map((row) =>
320 row.id === id
321 ? {
322 ...row,
323 ...patch,
324 ...(patch.value !== undefined ? { valueRedacted: false } : {}),
325 }
326 : row,
327 );
328 setRows(nextRows);
329 publishRows(nextRows);
330 };
331
332 const removeVariable = (id: string) => {
333 const nextRows = rows.filter((row) => row.id !== id);
334 setRows(nextRows);
335 publishRows(nextRows);
336 };
337
338 const addVariable = () =>
339 setRows([
340 ...rows,
341 {
342 id: nextEnvironmentVariableDraftId(),
343 name: "",
344 value: "",
345 sensitive: true,
346 },
347 ]);
348
349 return (
350 <div className="mt-3 min-w-0 space-y-2">
351 {rows.map((variable, index) => (
352 <div key={variable.id} className="flex min-w-0 items-center gap-1.5">
353 <DraftInput
354 size="sm"
355 className="w-44 shrink-0 font-mono"
356 value={variable.name}
357 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
358 placeholder="VARIABLE_NAME"
359 spellCheck={false}
360 aria-label={`Environment variable name ${index + 1}`}
361 />
362 <span className="text-xs text-muted-foreground" aria-hidden>
363 =
364 </span>
365 <DraftInput
366 size="sm"
367 className="min-w-0 flex-1 font-mono"
368 value={variable.valueRedacted ? "" : variable.value}
369 onCommit={(value) => updateVariable(variable.id, { value })}
370 type={variable.sensitive ? "password" : undefined}
371 autoComplete="off"
372 placeholder={
373 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
374 }
375 spellCheck={false}
376 aria-label={`Environment variable value ${index + 1}`}
377 />
378 <Tooltip>
379 <TooltipTrigger
380 render={
381 <Button
382 type="button"
383 size="icon-micro"
384 variant="ghost-muted"
385 className={cn(
386 "[--control-icon-color:currentColor]",
387 variable.sensitive && "text-foreground",
388 )}
389 onClick={() => {
390 const sensitive = !variable.sensitive;
391 updateVariable(variable.id, {
392 sensitive,
393 ...(sensitive && variable.valueRedacted === undefined
394 ? {}
395 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
396 });
397 }}
398 aria-pressed={variable.sensitive}
399 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
400 >
401 {variable.sensitive ? (
402 <LockIcon className="size-3" />
403 ) : (
404 <LockOpenIcon className="size-3" />
405 )}
406 </Button>
407 }
408 />
409 <TooltipPopup side="top">
410 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
411 </TooltipPopup>
412 </Tooltip>
413 <Button
414 type="button"
415 size="icon-micro"
416 variant="ghost-muted"
417 className="[--control-icon-color:currentColor] hover:text-destructive"
418 onClick={() => removeVariable(variable.id)}
419 aria-label={`Remove environment variable ${variable.name || index + 1}`}
420 >
421 <XIcon className="size-3" />
422 </Button>
423 </div>
424 ))}
425 <div className="flex min-h-[1.875rem] flex-wrap items-center justify-end gap-x-3 gap-y-1">
426 {rows.length > 0 ? (
427 <span className="mr-auto text-xs text-muted-foreground">
428 Sensitive values are stored separately and never returned to the app.
429 </span>
430 ) : null}
431 <Button type="button" size="xs" variant="ghost-muted" onClick={addVariable}>
432 <PlusIcon className="size-3" />
433 Add variable
434 </Button>
435 </div>
436 </div>
437 );
438}
439
440interface ProviderInstanceCardProps {
441 readonly instanceId: ProviderInstanceId;
442 readonly instance: ProviderInstanceConfig;
443 readonly driverOption: DriverOption | undefined;
444 readonly liveProvider: ServerProvider | undefined;
445 readonly mode: "list" | "editor";
446 readonly selected?: boolean | undefined;
447 readonly onSelect?: (() => void) | undefined;
448 readonly readOnly?: boolean | undefined;
449 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
450 /**
451 * Pass `undefined` to hide the delete footer entirely. Built-in default
452 * instance slots use `undefined` — they can't be deleted without losing
453 * the slot, and their "reset to defaults" affordance lives on an outer
454 * reset button instead. Explicit `| undefined` in the type accommodates
455 * `exactOptionalPropertyTypes: true`, where an absent key and
456 * `{ onDelete: undefined }` are treated as distinct shapes.
457 */
458 readonly onDelete?: (() => void) | undefined;
459 /**
460 * Optional outer reset button rendered next to the driver icon. Built-in
461 * default slots supply a reset-to-factory control here; custom instances
462 * omit it.
463 */
464 readonly headerAction?: ReactNode | undefined;
465 readonly setup?: ReactNode;
466 readonly hiddenModels: ReadonlyArray<string>;
467 readonly favoriteModels: ReadonlyArray<string>;
468 readonly modelOrder: ReadonlyArray<string>;
469 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
470 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
471 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
472 readonly onRunUpdate?: (() => void) | undefined;
473 readonly isUpdating?: boolean | undefined;
474}
475
476/**
477 * Renders one provider instance as either a compact selectable list row or
478 * the full editor shown beside that list. Both modes use the same enabled
479 * state and provider metadata.
480 *
481 * Behavior notes:
482 * - `liveProvider` is matched by the caller via `instanceId`; when no
483 * match is available (e.g. the server hasn't probed yet, or the
484 * driver is not shipped by the current build) the card still renders
485 * with a neutral "checking" summary.
486 * - Unknown drivers (`driverOption === undefined`) get a read-only
487 * notice instead of editable fields, so fork instances round-trip
488 * without accidentally destroying their config.
489 * - The enabled Switch writes to the envelope's `instance.enabled`
490 * field, which is the single enabled flag: the server folds any legacy
491 * driver-specific `config.enabled` into the envelope on load and both
492 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
493 * false wins, then envelope, then config, then the driver default).
494 */
495export function ProviderInstanceCard({
496 instanceId,
497 instance,
498 driverOption,
499 liveProvider,
500 mode,
501 selected = false,
502 onSelect,
503 readOnly = false,
504 onUpdate,
505 onDelete,
506 headerAction,
507 setup,
508 hiddenModels,
509 favoriteModels,
510 modelOrder,
511 onHiddenModelsChange,
512 onFavoriteModelsChange,
513 onModelOrderChange,
514 onRunUpdate,
515 isUpdating = false,
516}: ProviderInstanceCardProps) {
517 const enabled = resolveProviderInstanceEnabled(instance);
518 // A locally disabled provider reads "Disabled" with a muted dot even if its
519 // last server status is stale. Enabled providers use the server status.
520 const statusKey: ProviderStatusKey = enabled
521 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
522 : "disabled";
523 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
524 const summary = enabled
525 ? getProviderSummary(liveProvider)
526 : { headline: "Disabled", detail: null };
527 const authEmail = liveProvider?.auth.email?.trim();
528 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
529 const authLabel =
530 enabled && liveProvider?.auth.status === "authenticated"
531 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
532 : null;
533 const versionLabel = getProviderVersionLabel(liveProvider?.version);
534 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
535 const updateCommand = versionAdvisory?.updateCommand ?? null;
536 const FallbackIconComponent = driverOption?.icon;
537 const displayName =
538 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
539 const accentColor = normalizeProviderAccentColor(instance.accentColor);
540 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
541 onCopy: ({ providerName }) => {
542 toastManager.add({
543 type: "success",
544 title: `${providerName} update command copied`,
545 description: "Run it in a terminal when you are ready to update.",
546 });
547 },
548 onError: (error, { providerName }) => {
549 toastManager.add(
550 stackedThreadToast({
551 type: "error",
552 title: `Could not copy ${providerName} update command`,
553 description: error.message,
554 }),
555 );
556 },
557 });
558
559 // Narrow `instance.driver` for callers that key on the closed
560 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
561 // fork drivers pass through as `null` and those callers fall back to
562 // verbatim behaviour.
563 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
564 ? instance.driver
565 : null;
566 const customModels =
567 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
568 // Server-returned models may lag behind settings writes. Treat probe
569 // models as the source for built-ins only; custom rows come directly
570 // from the current instance config so add/remove reflects immediately.
571 const modelsForDisplay = deriveProviderModelsForDisplay({
572 liveModels: liveProvider?.models,
573 customModels,
574 });
575 const updateDisplayName = (value: string) => {
576 const trimmed = value.trim();
577 const { displayName: _omit, ...rest } = instance;
578 onUpdate(
579 trimmed.length > 0
580 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
581 : (rest as ProviderInstanceConfig),
582 );
583 };
584
585 const updateEnabled = (value: boolean) => {
586 onUpdate({ ...instance, enabled: value });
587 };
588
589 const updateAccentColor = (value: string) => {
590 const normalized = normalizeProviderAccentColor(value);
591 const { accentColor: _omit, ...rest } = instance;
592 onUpdate(
593 normalized
594 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
595 : (rest as ProviderInstanceConfig),
596 );
597 };
598
599 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
600 const { config: _omit, ...rest } = instance;
601 onUpdate(
602 nextConfig !== undefined
603 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
604 : (rest as ProviderInstanceConfig),
605 );
606 };
607
608 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
609 const nextConfig = nextConfigBlobWithValue(
610 instance.config,
611 "customModels",
612 next.map(toCustomModelSetting),
613 );
614 const { config: _omit, ...rest } = instance;
615 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
616 };
617
618 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
619 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
620 const { environment: _omit, ...rest } = instance;
621 onUpdate(
622 cleaned.length > 0
623 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
624 : (rest as ProviderInstanceConfig),
625 );
626 };
627 // Drivers that need a named secret (Cursor's API key) get a dedicated field;
628 // the generic editor only shows the remaining variables.
629 const environmentFields = driverOption?.environmentFields ?? [];
630 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
631 const genericEnvironment = providerEnvironmentWithoutNames(
632 instance.environment,
633 environmentFieldNames,
634 );
635 const updateGenericEnvironment = (
636 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
637 ) => {
638 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
639 environmentFieldNames.has(variable.name),
640 );
641 updateEnvironment([...dedicatedEnvironment, ...environment]);
642 };
643 const updateEnvironmentField = (field: ProviderEnvironmentFieldDefinition, value: string) => {
644 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
645 };
646 const removeEnvironmentField = (field: ProviderEnvironmentFieldDefinition) => {
647 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
648 };
649
650 const titleIconNode = driverKind ? (
651 <ProviderInstanceIcon
652 driverKind={driverKind}
653 displayName={displayName}
654 accentColor={accentColor}
655 showBadge={Boolean(accentColor)}
656 className="size-5"
657 iconClassName="size-4 text-foreground/80"
658 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
659 />
660 ) : FallbackIconComponent ? (
661 <span className="inline-flex size-5 shrink-0 items-center justify-center">
662 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
663 </span>
664 ) : (
665 <span
666 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
667 aria-hidden
668 >
669 {providerInstanceInitials(displayName)}
670 </span>
671 );
672
673 const titleTailNode = headerAction ? (
674 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
675 ) : null;
676
677 const versionCodeNode = versionLabel ? (
678 <code className="text-xs text-muted-foreground">{versionLabel}</code>
679 ) : null;
680
681 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
682 const statusDotNode =
683 statusKey === "warning" || statusKey === "error" ? (
684 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
685 ) : null;
686 // Trouble states carry the server's explanation (a failed probe, a shadow
687 // home entry that is not a symlink, a missing binary). Show it wherever the
688 // headline shows so the user can act without opening the editor.
689 const needsAttention = statusKey === "warning" || statusKey === "error";
690 const editorStatusNode =
691 isAuthenticated && authEmail ? (
692 <>
693 {needsAttention ? statusDotNode : null}
694 <span>Authenticated as</span>
695 <ProviderAuthEmail email={authEmail} />
696 {authLabel ? <span>· {authLabel}</span> : null}
697 {summary.detail ? (
698 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
699 ) : null}
700 </>
701 ) : (
702 <>
703 {statusDotNode}
704 <span>{summary.headline}</span>
705 {summary.detail ? (
706 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
707 ) : null}
708 </>
709 );
710 if (mode === "list") {
711 return (
712 <div
713 data-slot="settings-row"
714 className={cn(
715 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
716 selected ? "bg-muted/45" : "hover:bg-muted/25",
717 )}
718 >
719 <button
720 type="button"
721 className={cn(
722 "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",
723 !enabled && !selected && "opacity-60 group-hover:opacity-100",
724 )}
725 onClick={onSelect}
726 aria-pressed={selected}
727 >
728 {titleIconNode}
729 <span className="min-w-0 flex-1">
730 <span className="flex min-w-0 items-center gap-2">
731 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
732 {String(instanceId) !== String(instance.driver) ? (
733 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
734 {instanceId}
735 </code>
736 ) : null}
737 {versionLabel ? (
738 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
739 {versionLabel}
740 </code>
741 ) : null}
742 {versionAdvisory ? (
743 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
744 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
745 </span>
746 ) : null}
747 </span>
748 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
749 {statusDotNode ? (
750 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
751 ) : null}
752 <span className="line-clamp-2 [overflow-wrap:anywhere]">
753 {summary.headline}
754 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
755 </span>
756 </span>
757 </span>
758 </button>
759 <span className="flex h-5 shrink-0 items-center">
760 <Switch
761 checked={enabled}
762 disabled={readOnly}
763 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
764 aria-label={`Enable ${displayName}`}
765 />
766 </span>
767 </div>
768 );
769 }
770
771 const editorHeaderAction = (
772 <div className="flex min-w-0 items-center gap-1.5">
773 {driverOption?.badgeLabel ? (
774 <Badge variant="warning" size="sm" className="shrink-0">
775 {driverOption.badgeLabel}
776 </Badge>
777 ) : null}
778 {versionCodeNode}
779 <span
780 inert={readOnly}
781 aria-disabled={readOnly || undefined}
782 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
783 >
784 {versionAdvisory ? (
785 <Popover>
786 <PopoverTrigger
787 render={
788 <Button
789 type="button"
790 size="icon-micro"
791 variant="ghost"
792 className={cn(
793 "[--control-icon-color:currentColor]",
794 versionAdvisory.emphasis === "strong"
795 ? "text-warning hover:text-warning"
796 : "text-muted-foreground hover:text-foreground",
797 )}
798 aria-label="Update available — view details"
799 >
800 <ArrowUpCircleIcon className="size-3.5" />
801 </Button>
802 }
803 />
804 <PopoverPopup
805 side="bottom"
806 align="end"
807 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
808 >
809 <div className="grid min-w-0 gap-3">
810 <div className="grid gap-0.5">
811 <p className="text-[13px] font-semibold leading-tight text-foreground">
812 Update available
813 </p>
814 <p
815 className={cn(
816 "text-xs leading-snug",
817 versionAdvisory.emphasis === "strong"
818 ? "text-warning"
819 : "text-muted-foreground",
820 )}
821 >
822 {versionAdvisory.detail}
823 </p>
824 </div>
825 {onRunUpdate ? (
826 <Button
827 type="button"
828 size="xs"
829 variant="outline"
830 className="w-full"
831 disabled={isUpdating}
832 onClick={onRunUpdate}
833 >
834 {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
835 {isUpdating ? "Updating" : "Update now"}
836 </Button>
837 ) : null}
838 {onRunUpdate && updateCommand ? (
839 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
840 <span aria-hidden className="h-px flex-1 bg-border" />
841 or, update manually using
842 <span aria-hidden className="h-px flex-1 bg-border" />
843 </div>
844 ) : null}
845 {updateCommand ? (
846 <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">
847 <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground">
848 {updateCommand}
849 </code>
850 <Tooltip>
851 <TooltipTrigger
852 render={
853 <Button
854 type="button"
855 size="icon-xs"
856 variant="ghost"
857 className="shrink-0 text-muted-foreground hover:text-foreground"
858 onClick={() =>
859 copyToClipboard(updateCommand, { providerName: displayName })
860 }
861 aria-label="Copy update command"
862 >
863 <CopyIcon className="size-3" />
864 </Button>
865 }
866 />
867 <TooltipPopup side="top">Copy command</TooltipPopup>
868 </Tooltip>
869 </div>
870 ) : null}
871 </div>
872 </PopoverPopup>
873 </Popover>
874 ) : null}
875 {titleTailNode}
876 {onDelete ? (
877 <Button
878 type="button"
879 size="icon-micro"
880 variant="ghost-muted"
881 disabled={readOnly}
882 className="[--control-icon-color:currentColor] hover:text-destructive"
883 onClick={onDelete}
884 aria-label={`Delete instance ${instanceId}`}
885 >
886 <Trash2Icon className="size-3" />
887 </Button>
888 ) : null}
889 </span>
890 </div>
891 );
892
893 return (
894 <>
895 <SettingsSection
896 title={displayName}
897 description={editorStatusNode}
898 icon={titleIconNode}
899 headerAction={editorHeaderAction}
900 >
901 <SettingsRow
902 title="Display name"
903 control={
904 <div
905 inert={readOnly}
906 aria-disabled={readOnly || undefined}
907 className={cn(
908 "flex w-full items-center justify-end gap-2 sm:w-auto",
909 readOnly && "opacity-50 select-none",
910 )}
911 >
912 <ProviderAccentColorPicker
913 layout="inline"
914 displayName={displayName}
915 value={accentColor}
916 onCommit={updateAccentColor}
917 commitDelayMs={120}
918 />
919 <DraftInput
920 id={`provider-instance-${instanceId}-display-name`}
921 size="sm"
922 className="min-w-0 flex-1 sm:w-56 sm:flex-none"
923 value={instance.displayName ?? ""}
924 onCommit={updateDisplayName}
925 placeholder={driverOption?.label ?? "Instance label"}
926 spellCheck={false}
927 />
928 </div>
929 }
930 />
931 </SettingsSection>
932
933 {setup ? (
934 <SettingsSection title="Setup">
935 <div className="px-3 py-3 sm:px-4">{setup}</div>
936 </SettingsSection>
937 ) : null}
938
939 <SettingsSection
940 title="Runtime"
941 inert={readOnly}
942 aria-disabled={readOnly || undefined}
943 className={readOnly ? "opacity-50 select-none" : undefined}
944 >
945 {driverOption ? (
946 <ProviderSettingsForm
947 definition={driverOption}
948 value={instance.config}
949 idPrefix={`provider-instance-${instanceId}`}
950 variant="settings"
951 onChange={updateConfig}
952 />
953 ) : (
954 <SettingsRow
955 title="Driver"
956 description={
957 <span>
958 This instance uses{" "}
959 <code className="text-foreground">{String(instance.driver)}</code>, which is not
960 available in this build. Its configuration is preserved.
961 </span>
962 }
963 />
964 )}
965 </SettingsSection>
966
967 <SettingsSection
968 title="Environment"
969 inert={readOnly}
970 aria-disabled={readOnly || undefined}
971 className={readOnly ? "opacity-50 select-none" : undefined}
972 >
973 {environmentFields.length > 0 ? (
974 <div className="grid gap-3 px-3 py-3 sm:px-4">
975 {environmentFields.map((field) => (
976 <ProviderEnvironmentFieldRow
977 key={field.name}
978 field={field}
979 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
980 idPrefix={`provider-instance-${instanceId}`}
981 onCommit={updateEnvironmentField}
982 onRemove={removeEnvironmentField}
983 />
984 ))}
985 </div>
986 ) : null}
987 <SettingsRow
988 title="Variables"
989 description="API keys, base URLs, and other per-instance CLI settings."
990 >
991 <ProviderEnvironmentSection
992 environment={genericEnvironment}
993 onChange={updateGenericEnvironment}
994 />
995 </SettingsRow>
996 </SettingsSection>
997
998 {driverOption !== undefined ? (
999 <SettingsSection
1000 title="Models"
1001 inert={readOnly}
1002 aria-disabled={readOnly || undefined}
1003 className={readOnly ? "opacity-50 select-none" : undefined}
1004 >
1005 <div className="px-3 py-3 sm:px-4">
1006 <ProviderModelsSection
1007 instanceId={instanceId}
1008 driverKind={driverKind}
1009 models={modelsForDisplay}
1010 customModels={customModels}
1011 hiddenModels={hiddenModels}
1012 favoriteModels={favoriteModels}
1013 modelOrder={modelOrder}
1014 onChange={updateCustomModels}
1015 onHiddenModelsChange={onHiddenModelsChange}
1016 onFavoriteModelsChange={onFavoriteModelsChange}
1017 onModelOrderChange={onModelOrderChange}
1018 />
1019 </div>
1020 </SettingsSection>
1021 ) : null}
1022 </>
1023 );
1024}