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

ProviderInstanceCard.tsx

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