Open History to see the last commit
1"use client";
2
3import {
4 ArrowUpCircleIcon,
5 ChevronDownIcon,
6 CopyIcon,
7 DownloadIcon,
8 LoaderIcon,
9 PlusIcon,
10 Trash2Icon,
11 XIcon,
12} from "lucide-react";
13import * as Arr from "effect/Array";
14import * as Result from "effect/Result";
15import { useState, type ReactNode } from "react";
16import {
17 isProviderDriverKind,
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 { Collapsible, CollapsibleContent } from "../ui/collapsible";
33import { DraftInput } from "../ui/draft-input";
34import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
35import { ScrollArea } from "../ui/scroll-area";
36import { Switch } from "../ui/switch";
37import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
38import { stackedThreadToast, toastManager } from "../ui/toast";
39import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
40import type { DriverOption, ProviderEnvironmentFieldDefinition } from "./providerDriverMeta";
41import { ProviderSettingsForm } from "./ProviderSettingsForm";
42import { ProviderModelsSection } from "./ProviderModelsSection";
43import { ProviderInstanceIcon } 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
80/**
81 * Read a string[] at `key` from the opaque config blob, filtering out
82 * non-string entries. Used for `customModels`, which is always typed as
83 * `string[]` by the concrete driver schemas but arrives here as
84 * `Schema.Unknown`.
85 */
86function readConfigStringArray(config: unknown, key: string): ReadonlyArray<string> {
87 if (config === null || typeof config !== "object") return [];
88 const value = (config as Record<string, unknown>)[key];
89 if (!Array.isArray(value)) return [];
90 return value.filter((entry): entry is string => typeof entry === "string");
91}
92
93/**
94 * Set `key` to an arbitrary value on the opaque config blob. Unlike
95 * provider settings field updates, does not drop empty-looking values — the
96 * caller is responsible for deciding whether an empty array / empty
97 * object should be stored explicitly (e.g. `customModels: []` is a
98 * meaningful "user cleared their custom list" state distinct from
99 * "driver default").
100 */
101function nextConfigBlobWithValue(
102 config: unknown,
103 key: string,
104 value: unknown,
105): Record<string, unknown> {
106 const base: Record<string, unknown> =
107 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
108 base[key] = value;
109 return base;
110}
111
112export function readProviderEnvironmentVariable(
113 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
114 name: string,
115): ProviderInstanceEnvironmentVariable | undefined {
116 return environment?.find((variable) => variable.name === name);
117}
118
119export function providerEnvironmentWithoutNames(
120 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
121 names: ReadonlySet<string>,
122): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
123 return (environment ?? []).filter((variable) => !names.has(variable.name));
124}
125
126export function nextProviderEnvironmentWithFieldValue(
127 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
128 field: ProviderEnvironmentFieldDefinition,
129 value: string,
130): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
131 const trimmed = value.trim();
132 const next: ProviderInstanceEnvironmentVariable[] = [];
133 let found = false;
134
135 for (const variable of environment ?? []) {
136 if (variable.name !== field.name) {
137 next.push(variable);
138 continue;
139 }
140 found = true;
141 if (trimmed.length > 0) {
142 next.push({
143 name: variable.name,
144 value: trimmed,
145 sensitive: field.sensitive ?? true,
146 });
147 }
148 }
149
150 if (!found && trimmed.length > 0) {
151 next.push({
152 name: field.name,
153 value: trimmed,
154 sensitive: field.sensitive ?? true,
155 });
156 }
157
158 return next;
159}
160
161export function deriveProviderModelsForDisplay(input: {
162 readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
163 readonly customModels: ReadonlyArray<string>;
164}): ReadonlyArray<ServerProviderModel> {
165 const liveCustomModelsBySlug = new Map(
166 Arr.filterMap(input.liveModels ?? [], (model) =>
167 model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
168 ),
169 );
170 const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
171 const customModels = input.customModels.map(
172 (slug) =>
173 liveCustomModelsBySlug.get(slug) ?? {
174 slug,
175 name: slug,
176 isCustom: true,
177 capabilities: null,
178 },
179 );
180 return [...serverModels, ...customModels];
181}
182
183function ProviderAuthEmail(props: {
184 readonly email: string | undefined;
185 readonly prefix?: string;
186 readonly separator?: boolean;
187}) {
188 const trimmed = props.email?.trim();
189 if (!trimmed) return null;
190
191 return (
192 <span className="inline-flex min-w-0 items-center gap-1.5">
193 {props.separator ? <span aria-hidden>·</span> : null}
194 {props.prefix ? <span className="text-muted-foreground/80">{props.prefix}</span> : null}
195 <RedactedSensitiveText
196 value={trimmed}
197 ariaLabel="Toggle account email visibility"
198 revealTooltip="Click to reveal email"
199 hideTooltip="Click to hide email"
200 />
201 </span>
202 );
203}
204
205function ProviderEnvironmentSection(props: {
206 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
207 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
208}) {
209 const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
210 props.environment.map(makeEnvironmentDraftRow),
211 );
212
213 const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
214 const published: ProviderInstanceEnvironmentVariable[] = [];
215 for (const row of nextRows) {
216 const name = row.name.trim();
217 if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
218 if (
219 name.length > 0 ||
220 row.value.length > 0 ||
221 row.sensitive !== true ||
222 row.valueRedacted !== undefined
223 ) {
224 return;
225 }
226 continue;
227 }
228 const { id: _id, ...rest } = row;
229 published.push({ ...rest, name });
230 }
231 props.onChange(published);
232 };
233
234 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
235 const nextRows = rows.map((row) =>
236 row.id === id
237 ? {
238 ...row,
239 ...patch,
240 ...(patch.value !== undefined ? { valueRedacted: false } : {}),
241 }
242 : row,
243 );
244 setRows(nextRows);
245 publishRows(nextRows);
246 };
247
248 const removeVariable = (id: string) => {
249 const nextRows = rows.filter((row) => row.id !== id);
250 setRows(nextRows);
251 publishRows(nextRows);
252 };
253
254 return (
255 <div className="grid gap-2">
256 <div className="flex items-center justify-between gap-3">
257 <span className="text-xs font-medium text-foreground">Environment variables</span>
258 <Button
259 type="button"
260 size="sm"
261 variant="outline"
262 className="h-7 gap-1.5 px-2 text-xs"
263 onClick={() =>
264 setRows([
265 ...rows,
266 {
267 id: nextEnvironmentVariableDraftId(),
268 name: "",
269 value: "",
270 sensitive: true,
271 },
272 ])
273 }
274 >
275 <PlusIcon className="size-3" />
276 Add
277 </Button>
278 </div>
279 {rows.length === 0 ? (
280 <p className="text-xs text-muted-foreground">
281 Add variables to pass API keys, base URLs, or other per-instance CLI settings.
282 </p>
283 ) : (
284 <div className="overflow-hidden rounded-md border border-border/70">
285 <Table>
286 <TableHeader className="bg-muted/25 text-[11px] text-muted-foreground">
287 <TableRow className="hover:bg-transparent">
288 <TableHead>Variable</TableHead>
289 <TableHead>Value</TableHead>
290 <TableHead className="w-20">Sensitive</TableHead>
291 <TableHead className="w-12 text-right">
292 <span className="sr-only">Options</span>
293 </TableHead>
294 </TableRow>
295 </TableHeader>
296 <TableBody>
297 {rows.map((variable, index) => (
298 <TableRow
299 key={variable.id}
300 className="border-border/60 odd:bg-muted/20 even:bg-background/20"
301 >
302 <TableCell>
303 <DraftInput
304 value={variable.name}
305 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
306 placeholder="VARIABLE_NAME"
307 spellCheck={false}
308 aria-label={`Environment variable name ${index + 1}`}
309 />
310 </TableCell>
311 <TableCell>
312 <DraftInput
313 value={variable.valueRedacted ? "" : variable.value}
314 onCommit={(value) => updateVariable(variable.id, { value })}
315 type={variable.sensitive ? "password" : undefined}
316 autoComplete="off"
317 placeholder={
318 variable.valueRedacted
319 ? "Stored secret - enter a new value to replace"
320 : "Value"
321 }
322 spellCheck={false}
323 aria-label={`Environment variable value ${index + 1}`}
324 />
325 </TableCell>
326 <TableCell className="w-20">
327 <div className="flex h-8 items-center justify-center">
328 <Checkbox
329 checked={variable.sensitive}
330 onCheckedChange={(checked) => {
331 const sensitive = Boolean(checked);
332 updateVariable(variable.id, {
333 sensitive,
334 ...(sensitive && variable.valueRedacted === undefined
335 ? {}
336 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
337 });
338 }}
339 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
340 />
341 </div>
342 </TableCell>
343 <TableCell className="w-12">
344 <div className="flex justify-end">
345 <Button
346 type="button"
347 size="icon-sm"
348 variant="ghost"
349 className="size-8 text-muted-foreground hover:text-destructive"
350 onClick={() => removeVariable(variable.id)}
351 aria-label={`Remove environment variable ${variable.name || index + 1}`}
352 >
353 <XIcon className="size-3.5" />
354 </Button>
355 </div>
356 </TableCell>
357 </TableRow>
358 ))}
359 </TableBody>
360 </Table>
361 </div>
362 )}
363 <span className="text-xs text-muted-foreground">
364 Sensitive values are stored separately and are not returned to the app after saving.
365 </span>
366 </div>
367 );
368}
369
370function ProviderEnvironmentFieldRow(props: {
371 readonly field: ProviderEnvironmentFieldDefinition;
372 readonly variable: ProviderInstanceEnvironmentVariable | undefined;
373 readonly idPrefix: string;
374 readonly onCommit: (field: ProviderEnvironmentFieldDefinition, value: string) => void;
375 readonly onRemove: (field: ProviderEnvironmentFieldDefinition) => void;
376}) {
377 const inputId = `${props.idPrefix}-environment-${props.field.name}`;
378 const value = props.variable?.valueRedacted ? "" : (props.variable?.value ?? "");
379 const placeholder = props.variable?.valueRedacted
380 ? "Stored secret - enter a new value to replace"
381 : props.field.placeholder;
382
383 return (
384 <label htmlFor={inputId} className="block">
385 <span className="text-xs font-medium text-foreground">{props.field.label}</span>
386 <div className="mt-1.5 flex min-w-0 items-center gap-2">
387 <DraftInput
388 id={inputId}
389 className="min-w-0 flex-1"
390 type={props.field.sensitive === false ? undefined : "password"}
391 autoComplete="off"
392 value={value}
393 onCommit={(next) => props.onCommit(props.field, next)}
394 placeholder={placeholder}
395 spellCheck={false}
396 />
397 {props.variable ? (
398 <Button
399 type="button"
400 size="icon-sm"
401 variant="ghost"
402 className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
403 onClick={() => props.onRemove(props.field)}
404 aria-label={`Clear ${props.field.label}`}
405 >
406 <XIcon className="size-3.5" />
407 </Button>
408 ) : null}
409 </div>
410 {props.field.description ? (
411 <span className="mt-1 block text-xs text-muted-foreground">{props.field.description}</span>
412 ) : null}
413 </label>
414 );
415}
416
417interface ProviderInstanceCardProps {
418 readonly instanceId: ProviderInstanceId;
419 readonly instance: ProviderInstanceConfig;
420 readonly driverOption: DriverOption | undefined;
421 readonly liveProvider: ServerProvider | undefined;
422 readonly isExpanded: boolean;
423 readonly onExpandedChange: (open: boolean) => void;
424 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
425 /**
426 * Pass `undefined` to hide the delete button entirely. Built-in default
427 * instance slots use `undefined` — they can't be deleted without losing
428 * the slot, and their "reset to defaults" affordance lives on an outer
429 * reset button instead. Explicit `| undefined` in the type accommodates
430 * `exactOptionalPropertyTypes: true`, where an absent key and
431 * `{ onDelete: undefined }` are treated as distinct shapes.
432 */
433 readonly onDelete?: (() => void) | undefined;
434 /**
435 * Optional outer reset button rendered next to the driver icon. Built-in
436 * default slots supply a reset-to-factory control here; custom instances
437 * omit it.
438 */
439 readonly headerAction?: ReactNode | undefined;
440 readonly hiddenModels: ReadonlyArray<string>;
441 readonly favoriteModels: ReadonlyArray<string>;
442 readonly modelOrder: ReadonlyArray<string>;
443 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
444 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
445 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
446 readonly onRunUpdate?: (() => void) | undefined;
447 readonly isUpdating?: boolean | undefined;
448}
449
450/**
451 * A single configured provider-instance row in the Providers settings
452 * section. Used for every row — both the built-in default instance for a
453 * driver (rendered with `onDelete` omitted) and user-authored custom
454 * instances (`onDelete` supplied). The only UI difference between the two
455 * is whether the trash button is visible; every other field (display
456 * name, config fields, models) behaves identically.
457 *
458 * Behavior notes:
459 * - `liveProvider` is matched by the caller via `instanceId`; when no
460 * match is available (e.g. the server hasn't probed yet, or the
461 * driver is not shipped by the current build) the card still renders
462 * with a neutral "checking" summary.
463 * - Unknown drivers (`driverOption === undefined`) get a read-only
464 * notice instead of editable fields, so fork instances round-trip
465 * without accidentally destroying their config.
466 * - The enabled Switch writes to the envelope's `instance.enabled`
467 * field; the server's registry consults this at `entry.enabled ?? true`
468 * before materializing the instance, and the probe also checks its
469 * driver-specific `config.enabled`. We treat the envelope flag as the
470 * single source of truth from the UI — built-in cards used to write
471 * the inner flag, but on the promotion-to-instance path every edit
472 * flows through the envelope.
473 */
474export function ProviderInstanceCard({
475 instanceId,
476 instance,
477 driverOption,
478 liveProvider,
479 isExpanded,
480 onExpandedChange,
481 onUpdate,
482 onDelete,
483 headerAction,
484 hiddenModels,
485 favoriteModels,
486 modelOrder,
487 onHiddenModelsChange,
488 onFavoriteModelsChange,
489 onModelOrderChange,
490 onRunUpdate,
491 isUpdating = false,
492}: ProviderInstanceCardProps) {
493 const enabled = instance.enabled ?? true;
494 // The server-reported status wins when present; otherwise fall back to
495 // "disabled"/"warning" based on the local `enabled` flag so the dot
496 // reflects the persisted intent even before the first probe completes.
497 const statusKey: ProviderStatusKey =
498 (liveProvider?.status as ProviderStatusKey | undefined) ?? (enabled ? "warning" : "disabled");
499 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
500 const rawSummary = getProviderSummary(liveProvider);
501 const authEmail = liveProvider?.auth.email;
502 const hasAuthenticatedEmail =
503 liveProvider?.auth.status === "authenticated" && Boolean(authEmail?.trim());
504 const authenticatedDetail = hasAuthenticatedEmail
505 ? (liveProvider?.auth.label ?? liveProvider?.auth.type ?? null)
506 : null;
507 const summary = rawSummary;
508 const versionLabel = getProviderVersionLabel(liveProvider?.version);
509 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
510 const updateCommand = versionAdvisory?.updateCommand ?? null;
511 const FallbackIconComponent = driverOption?.icon;
512 const displayName =
513 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
514 const accentColor = normalizeProviderAccentColor(instance.accentColor);
515 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
516 onCopy: ({ providerName }) => {
517 toastManager.add({
518 type: "success",
519 title: `${providerName} update command copied`,
520 description: "Run it in a terminal when you are ready to update.",
521 });
522 },
523 onError: (error, { providerName }) => {
524 toastManager.add(
525 stackedThreadToast({
526 type: "error",
527 title: `Could not copy ${providerName} update command`,
528 description: error.message,
529 }),
530 );
531 },
532 });
533
534 // Narrow `instance.driver` for callers that key on the closed
535 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
536 // fork drivers pass through as `null` and those callers fall back to
537 // verbatim behaviour.
538 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
539 ? instance.driver
540 : null;
541
542 const customModels = readConfigStringArray(instance.config, "customModels");
543 const environmentFields = driverOption?.environmentFields ?? [];
544 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
545 const genericEnvironment = providerEnvironmentWithoutNames(
546 instance.environment,
547 environmentFieldNames,
548 );
549 // Server-returned models may lag behind settings writes. Treat probe
550 // models as the source for built-ins only; custom rows come directly
551 // from the current instance config so add/remove reflects immediately.
552 const modelsForDisplay = deriveProviderModelsForDisplay({
553 liveModels: liveProvider?.models,
554 customModels,
555 });
556
557 const updateDisplayName = (value: string) => {
558 const trimmed = value.trim();
559 const { displayName: _omit, ...rest } = instance;
560 onUpdate(
561 trimmed.length > 0
562 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
563 : (rest as ProviderInstanceConfig),
564 );
565 };
566
567 const updateEnabled = (value: boolean) => {
568 onUpdate({ ...instance, enabled: value });
569 };
570
571 const updateAccentColor = (value: string) => {
572 const normalized = normalizeProviderAccentColor(value);
573 const { accentColor: _omit, ...rest } = instance;
574 onUpdate(
575 normalized
576 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
577 : (rest as ProviderInstanceConfig),
578 );
579 };
580
581 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
582 const { config: _omit, ...rest } = instance;
583 onUpdate(
584 nextConfig !== undefined
585 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
586 : (rest as ProviderInstanceConfig),
587 );
588 };
589
590 const updateCustomModels = (next: ReadonlyArray<string>) => {
591 const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
592 const { config: _omit, ...rest } = instance;
593 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
594 };
595
596 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
597 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
598 const { environment: _omit, ...rest } = instance;
599 onUpdate(
600 cleaned.length > 0
601 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
602 : (rest as ProviderInstanceConfig),
603 );
604 };
605
606 const updateGenericEnvironment = (
607 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
608 ) => {
609 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
610 environmentFieldNames.has(variable.name),
611 );
612 updateEnvironment([...dedicatedEnvironment, ...environment]);
613 };
614
615 const updateEnvironmentField = (field: ProviderEnvironmentFieldDefinition, value: string) => {
616 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
617 };
618
619 const removeEnvironmentField = (field: ProviderEnvironmentFieldDefinition) => {
620 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
621 };
622
623 const titleIconNode = driverKind ? (
624 <ProviderInstanceIcon
625 driverKind={driverKind}
626 displayName={displayName}
627 accentColor={accentColor}
628 showBadge={Boolean(accentColor)}
629 statusDotClassName={statusStyle.dot}
630 indicatorBackground="var(--card)"
631 className="size-5"
632 iconClassName="size-4 text-foreground/80"
633 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
634 />
635 ) : FallbackIconComponent ? (
636 <span className="relative inline-flex size-5 shrink-0 items-center justify-center">
637 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
638 <span
639 className={cn(
640 "pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-card",
641 statusStyle.dot,
642 )}
643 aria-hidden
644 />
645 </span>
646 ) : (
647 <span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
648 );
649
650 const titleHeadNode = (
651 <>
652 {titleIconNode}
653 <h3 className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
654 {displayName}
655 </h3>
656 {String(instanceId) !== String(instance.driver) ? (
657 <code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
658 {instanceId}
659 </code>
660 ) : null}
661 {driverOption?.badgeLabel ? (
662 <Badge variant="warning" size="sm" className="shrink-0">
663 {driverOption.badgeLabel}
664 </Badge>
665 ) : null}
666 </>
667 );
668
669 const titleTailNode = (
670 <>
671 {headerAction ? (
672 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
673 {headerAction}
674 </span>
675 ) : null}
676 {onDelete ? (
677 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
678 <Tooltip>
679 <TooltipTrigger
680 render={
681 <Button
682 size="icon-xs"
683 variant="ghost"
684 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
685 onClick={onDelete}
686 aria-label={`Delete provider instance ${instanceId}`}
687 >
688 <Trash2Icon className="size-3" />
689 </Button>
690 }
691 />
692 <TooltipPopup side="top">Delete instance</TooltipPopup>
693 </Tooltip>
694 </span>
695 ) : null}
696 </>
697 );
698
699 const authRowNode = (
700 <p className="flex min-w-0 flex-wrap items-center gap-x-1 text-[13px] leading-[1.45] text-muted-foreground/80">
701 {hasAuthenticatedEmail ? (
702 <>
703 <span>Authenticated as</span>
704 <ProviderAuthEmail email={authEmail} />
705 {authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
706 </>
707 ) : (
708 <>
709 <span>{summary.headline}</span>
710 <ProviderAuthEmail email={authEmail} separator prefix="Email" />
711 </>
712 )}
713 {summary.detail ? <span>- {summary.detail}</span> : null}
714 </p>
715 );
716
717 const versionCodeNode = versionLabel ? (
718 <code className="text-xs text-muted-foreground">{versionLabel}</code>
719 ) : null;
720
721 return (
722 <div className="rounded-xl transition-colors hover:bg-muted/20">
723 <div className="px-3 py-3 sm:px-4">
724 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
725 <div className="min-w-0 flex-1 space-y-1">
726 <div className="flex min-w-0 flex-wrap items-center gap-2">
727 {titleHeadNode}
728 {versionCodeNode}
729 {versionAdvisory ? (
730 <Popover>
731 <PopoverTrigger
732 render={
733 <Button
734 type="button"
735 size="icon-xs"
736 variant="ghost"
737 className={cn(
738 "size-5 rounded-sm p-0",
739 versionAdvisory.emphasis === "strong"
740 ? "text-warning hover:text-warning"
741 : "text-primary hover:text-primary",
742 )}
743 aria-label="Update available — view details"
744 >
745 <ArrowUpCircleIcon className="size-3.5 [animation:bounce_2.4s_ease-in-out_infinite] motion-reduce:animate-none" />
746 </Button>
747 }
748 />
749 <PopoverPopup
750 side="bottom"
751 align="start"
752 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
753 >
754 <div className="grid min-w-0 gap-3">
755 <div className="grid gap-0.5">
756 <p className="text-[13px] font-semibold leading-tight text-foreground">
757 Update available
758 </p>
759 <p
760 className={cn(
761 "text-xs leading-snug",
762 versionAdvisory.emphasis === "strong"
763 ? "text-warning"
764 : "text-muted-foreground",
765 )}
766 >
767 {versionAdvisory.detail}
768 </p>
769 </div>
770 {onRunUpdate ? (
771 <Button
772 type="button"
773 size="xs"
774 variant="default"
775 className="w-full"
776 disabled={isUpdating}
777 onClick={onRunUpdate}
778 >
779 {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
780 {isUpdating ? "Updating" : "Update now"}
781 </Button>
782 ) : null}
783 {onRunUpdate && updateCommand ? (
784 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
785 <span aria-hidden className="h-px flex-1 bg-border" />
786 or, update manually using
787 <span aria-hidden className="h-px flex-1 bg-border" />
788 </div>
789 ) : null}
790 {updateCommand ? (
791 <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">
792 <ScrollArea scrollFade className="h-8 min-w-0 flex-1 rounded-none">
793 <code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-[11px] text-foreground">
794 {updateCommand}
795 </code>
796 </ScrollArea>
797 <Tooltip>
798 <TooltipTrigger
799 render={
800 <Button
801 type="button"
802 size="icon-xs"
803 variant="ghost"
804 className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
805 onClick={() =>
806 copyToClipboard(updateCommand, {
807 providerName: displayName,
808 })
809 }
810 aria-label="Copy update command"
811 >
812 <CopyIcon className="size-3" />
813 </Button>
814 }
815 />
816 <TooltipPopup side="top">Copy command</TooltipPopup>
817 </Tooltip>
818 </div>
819 ) : null}
820 </div>
821 </PopoverPopup>
822 </Popover>
823 ) : null}
824 {titleTailNode}
825 </div>
826 {authRowNode}
827 </div>
828 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
829 <Button
830 size="sm"
831 variant="ghost"
832 className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
833 onClick={() => onExpandedChange(!isExpanded)}
834 aria-label={`Toggle ${displayName} details`}
835 >
836 <ChevronDownIcon
837 className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
838 />
839 </Button>
840 <Switch
841 checked={enabled}
842 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
843 aria-label={`Enable ${displayName}`}
844 />
845 </div>
846 </div>
847 </div>
848
849 <Collapsible open={isExpanded} onOpenChange={onExpandedChange}>
850 <CollapsibleContent>
851 <div className="space-y-5 px-3 pb-4 pt-2 sm:px-4">
852 <div>
853 <label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
854 <span className="text-xs font-medium text-foreground">Display name</span>
855 <DraftInput
856 id={`provider-instance-${instanceId}-display-name`}
857 className="mt-1.5"
858 value={instance.displayName ?? ""}
859 onCommit={updateDisplayName}
860 placeholder={driverOption?.label ?? "Instance label"}
861 spellCheck={false}
862 />
863 <span className="mt-1 block text-xs text-muted-foreground">
864 Optional label shown in the provider list.
865 </span>
866 </label>
867 </div>
868
869 <div>
870 <ProviderAccentColorPicker
871 displayName={displayName}
872 value={accentColor}
873 onCommit={updateAccentColor}
874 commitDelayMs={120}
875 description="Used to distinguish this instance in picker rails and model lists."
876 />
877 </div>
878
879 <div className="border-t border-border/60 px-4 py-3 sm:px-5">
880 {environmentFields.length > 0 ? (
881 <div className="mb-4 grid gap-3">
882 {environmentFields.map((field) => (
883 <ProviderEnvironmentFieldRow
884 key={field.name}
885 field={field}
886 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
887 idPrefix={`provider-instance-${instanceId}`}
888 onCommit={updateEnvironmentField}
889 onRemove={removeEnvironmentField}
890 />
891 ))}
892 </div>
893 ) : null}
894 <ProviderEnvironmentSection
895 environment={genericEnvironment}
896 onChange={updateGenericEnvironment}
897 />
898 </div>
899
900 {driverOption ? (
901 <ProviderSettingsForm
902 definition={driverOption}
903 value={instance.config}
904 idPrefix={`provider-instance-${instanceId}`}
905 variant="card"
906 onChange={updateConfig}
907 />
908 ) : null}
909
910 {driverOption !== undefined ? (
911 <ProviderModelsSection
912 instanceId={instanceId}
913 driverKind={driverKind}
914 models={modelsForDisplay}
915 customModels={customModels}
916 hiddenModels={hiddenModels}
917 favoriteModels={favoriteModels}
918 modelOrder={modelOrder}
919 onChange={updateCustomModels}
920 onHiddenModelsChange={onHiddenModelsChange}
921 onFavoriteModelsChange={onFavoriteModelsChange}
922 onModelOrderChange={onModelOrderChange}
923 />
924 ) : (
925 <div>
926 <p className="text-xs text-muted-foreground">
927 This instance uses a driver (
928 <code className="text-foreground">{String(instance.driver)}</code>) that is not
929 shipped with the current build. Configuration values are preserved but cannot be
930 edited from this surface.
931 </p>
932 </div>
933 )}
934 </div>
935 </CollapsibleContent>
936 </Collapsible>
937 </div>
938 );
939}