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