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