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

ProviderInstanceCard.tsx

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