Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderInstanceCard.tsx

877 lines32.2 KB

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