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

ProviderInstanceCard.tsx

939 lines35.8 KB

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 };
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 );
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");
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;
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];
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 );
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 );
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;
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<"configuration" | "models">("configuration");
430 const enabled = resolveProviderInstanceEnabled(instance);
431 // A locally disabled provider reads "Disabled" with a muted dot even if its
432 // last server status is stale. Enabled providers use the server status.
433 const statusKey: ProviderStatusKey = enabled
434 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
435 : "disabled";
436 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
437 const summary = enabled
438 ? getProviderSummary(liveProvider)
439 : { headline: "Disabled", detail: null };
440 const authEmail = liveProvider?.auth.email?.trim();
441 // The editor header folds the account email into the status line —
442 // "Authenticated as <email> · <plan>" — with the email redacted until its
443 // reveal toggle is clicked.
444 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
445 const authLabel =
446 enabled && liveProvider?.auth.status === "authenticated"
447 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
448 : null;
449 const versionLabel = getProviderVersionLabel(liveProvider?.version);
450 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
451 const updateCommand = versionAdvisory?.updateCommand ?? null;
452 const FallbackIconComponent = driverOption?.icon;
453 const displayName =
454 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
455 const accentColor = normalizeProviderAccentColor(instance.accentColor);
456 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
457 onCopy: ({ providerName }) => {
458 toastManager.add({
459 type: "success",
460 title: `${providerName} update command copied`,
461 description: "Run it in a terminal when you are ready to update.",
462 });
463 },
464 onError: (error, { providerName }) => {
465 toastManager.add(
466 stackedThreadToast({
467 type: "error",
468 title: `Could not copy ${providerName} update command`,
469 description: error.message,
470 }),
471 );
472 },
473 });
474​
475 // Narrow `instance.driver` for callers that key on the closed
476 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
477 // fork drivers pass through as `null` and those callers fall back to
478 // verbatim behaviour.
479 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
480 ? instance.driver
481 : null;
482 const visibleTab = driverOption === undefined ? "configuration" : activeTab;
483​
484 const customModels = readConfigStringArray(instance.config, "customModels");
485 // Server-returned models may lag behind settings writes. Treat probe
486 // models as the source for built-ins only; custom rows come directly
487 // from the current instance config so add/remove reflects immediately.
488 const modelsForDisplay = deriveProviderModelsForDisplay({
489 liveModels: liveProvider?.models,
490 customModels,
491 });
492​
493 const updateDisplayName = (value: string) => {
494 const trimmed = value.trim();
495 const { displayName: _omit, ...rest } = instance;
496 onUpdate(
497 trimmed.length > 0
498 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
499 : (rest as ProviderInstanceConfig),
500 );
501 };
502​
503 const updateEnabled = (value: boolean) => {
504 onUpdate({ ...instance, enabled: value });
505 };
506​
507 const updateAccentColor = (value: string) => {
508 const normalized = normalizeProviderAccentColor(value);
509 const { accentColor: _omit, ...rest } = instance;
510 onUpdate(
511 normalized
512 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
513 : (rest as ProviderInstanceConfig),
514 );
515 };
516​
517 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
518 const { config: _omit, ...rest } = instance;
519 onUpdate(
520 nextConfig !== undefined
521 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
522 : (rest as ProviderInstanceConfig),
523 );
524 };
525​
526 const updateCustomModels = (next: ReadonlyArray<string>) => {
527 const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
528 const { config: _omit, ...rest } = instance;
529 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
530 };
531​
532 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
533 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
534 const { environment: _omit, ...rest } = instance;
535 onUpdate(
536 cleaned.length > 0
537 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
538 : (rest as ProviderInstanceConfig),
539 );
540 };
541​
542 const titleIconNode = driverKind ? (
543 <ProviderInstanceIcon
544 driverKind={driverKind}
545 displayName={displayName}
546 accentColor={accentColor}
547 showBadge={Boolean(accentColor)}
548 className="size-5"
549 iconClassName="size-4 text-foreground/80"
550 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
551 />
552 ) : FallbackIconComponent ? (
553 <span className="inline-flex size-5 shrink-0 items-center justify-center">
554 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
555 </span>
556 ) : (
557 <span
558 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
559 aria-hidden
560 >
561 {providerInstanceInitials(displayName)}
562 </span>
563 );
564​
565 const titleHeadNode = (
566 <>
567 {titleIconNode}
568 <h3 className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
569 {displayName}
570 </h3>
571 {String(instanceId) !== String(instance.driver) ? (
572 <code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
573 {instanceId}
574 </code>
575 ) : null}
576 {driverOption?.badgeLabel ? (
577 <Badge variant="warning" size="sm" className="shrink-0">
578 {driverOption.badgeLabel}
579 </Badge>
580 ) : null}
581 </>
582 );
583​
584 const titleTailNode = (
585 <>
586 {headerAction ? (
587 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
588 {headerAction}
589 </span>
590 ) : null}
591 {onDelete ? (
592 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
593 <Tooltip>
594 <TooltipTrigger
595 render={
596 <Button
597 size="icon-micro"
598 variant="ghost"
599 className="text-muted-foreground hover:text-destructive"
600 onClick={onDelete}
601 aria-label={`Delete provider instance ${instanceId}`}
602 >
603 <Trash2Icon className="size-3" />
604 </Button>
605 }
606 />
607 <TooltipPopup side="top">Delete instance</TooltipPopup>
608 </Tooltip>
609 </span>
610 ) : null}
611 </>
612 );
613​
614 const versionCodeNode = versionLabel ? (
615 <code className="text-xs text-muted-foreground">{versionLabel}</code>
616 ) : null;
617​
618 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
619 const statusDotNode =
620 statusKey === "warning" || statusKey === "error" ? (
621 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
622 ) : null;
623 const statusHeadlineNode = <span>{summary.headline}</span>;
624 // Trouble states carry the server's explanation (a failed probe, a shadow
625 // home entry that is not a symlink, a missing binary). Show it wherever the
626 // headline shows so the user can act without opening the editor.
627 const needsAttention = statusKey === "warning" || statusKey === "error";
628 const statusLineClassName =
629 "flex min-w-0 flex-wrap items-center gap-x-1.5 text-[13px] leading-[1.45] text-muted-foreground/80";
630​
631 if (mode === "list") {
632 return (
633 <div
634 className={cn(
635 // Sidebar-style selection with a fixed row height so the list stays
636 // even; the status line clamps to two lines instead of growing.
637 "group flex h-19 items-start gap-3 rounded-md px-3 py-2 transition-colors",
638 // Foreground-alpha tint so the fill reads the same in light and dark themes.
639 selected ? "bg-foreground/8" : "hover:bg-foreground/4",
640 )}
641 >
642 <button
643 type="button"
644 className={cn(
645 "flex min-w-0 flex-1 cursor-pointer items-start gap-3 rounded-sm text-left outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring",
646 !enabled && !selected && "opacity-60 group-hover:opacity-100",
647 )}
648 onClick={onSelect}
649 aria-pressed={selected}
650 >
651 {titleIconNode}
652 <span className="min-w-0 flex-1">
653 <span className="flex min-w-0 items-center gap-2">
654 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
655 {String(instanceId) !== String(instance.driver) ? (
656 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
657 {instanceId}
658 </code>
659 ) : null}
660 {versionCodeNode}
661 {versionAdvisory ? (
662 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
663 <ArrowUpCircleIcon className="size-3.5 text-update-foreground" />
664 </span>
665 ) : null}
666 </span>
667 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
668 {statusDotNode ? (
669 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
670 ) : null}
671 <span className="line-clamp-2 [overflow-wrap:anywhere]">
672 {summary.headline}
673 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
674 </span>
675 </span>
676 </span>
677 </button>
678 <span className="flex h-5 shrink-0 items-center">
679 <Switch
680 checked={enabled}
681 disabled={readOnly}
682 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
683 aria-label={`Enable ${displayName}`}
684 />
685 </span>
686 </div>
687 );
688 }
689​
690 return (
691 <div className="min-w-0 lg:flex lg:h-full lg:min-h-0 lg:flex-col">
692 <div className="flex min-h-16 shrink-0 items-start justify-between gap-3 border-b border-border/70 px-4 py-3">
693 <div className="min-w-0 flex-1 space-y-1">
694 <div className="flex min-w-0 flex-wrap items-center gap-2">
695 {titleHeadNode}
696 {versionCodeNode}
697 {/*
698 Only the write actions go inert on read-only sessions; the
699 status line below keeps its email reveal clickable.
700 */}
701 <span
702 inert={readOnly}
703 aria-disabled={readOnly || undefined}
704 className={cn("inline-flex items-center gap-2", readOnly && "opacity-50")}
705 >
706 {versionAdvisory ? (
707 <Popover>
708 <PopoverTrigger
709 render={
710 <Button
711 type="button"
712 size="icon-xs"
713 variant="ghost"
714 className={cn(
715 "size-5 rounded-sm p-0",
716 versionAdvisory.emphasis === "strong"
717 ? "text-warning hover:text-warning"
718 : "text-update-foreground hover:text-update-foreground",
719 )}
720 aria-label="Update available — view details"
721 >
722 <ArrowUpCircleIcon className="size-3.5" />
723 </Button>
724 }
725 />
726 <PopoverPopup
727 side="bottom"
728 align="start"
729 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
730 >
731 <div className="grid min-w-0 gap-3">
732 <div className="grid gap-0.5">
733 <p className="text-[13px] font-semibold leading-tight text-foreground">
734 Update available
735 </p>
736 <p
737 className={cn(
738 "text-xs leading-snug",
739 versionAdvisory.emphasis === "strong"
740 ? "text-warning"
741 : "text-muted-foreground",
742 )}
743 >
744 {versionAdvisory.detail}
745 </p>
746 </div>
747 {onRunUpdate ? (
748 <Button
749 type="button"
750 size="xs"
751 variant="default"
752 className="w-full"
753 disabled={isUpdating}
754 onClick={onRunUpdate}
755 >
756 {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
757 {isUpdating ? "Updating" : "Update now"}
758 </Button>
759 ) : null}
760 {onRunUpdate && updateCommand ? (
761 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
762 <span aria-hidden className="h-px flex-1 bg-border" />
763 or, update manually using
764 <span aria-hidden className="h-px flex-1 bg-border" />
765 </div>
766 ) : null}
767 {updateCommand ? (
768 <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">
769 <ScrollArea scrollFade className="h-8 min-w-0 flex-1 rounded-none">
770 <code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-[11px] text-foreground">
771 {updateCommand}
772 </code>
773 </ScrollArea>
774 <Tooltip>
775 <TooltipTrigger
776 render={
777 <Button
778 type="button"
779 size="icon-xs"
780 variant="ghost"
781 className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
782 onClick={() =>
783 copyToClipboard(updateCommand, {
784 providerName: displayName,
785 })
786 }
787 aria-label="Copy update command"
788 >
789 <CopyIcon className="size-3" />
790 </Button>
791 }
792 />
793 <TooltipPopup side="top">Copy command</TooltipPopup>
794 </Tooltip>
795 </div>
796 ) : null}
797 </div>
798 </PopoverPopup>
799 </Popover>
800 ) : null}
801 {titleTailNode}
802 </span>
803 </div>
804 <p className={statusLineClassName}>
805 {statusDotNode}
806 {isAuthenticated && authEmail ? (
807 <>
808 <span>Authenticated as</span>
809 <ProviderAuthEmail email={authEmail} />
810 {authLabel ? <span>· {authLabel}</span> : null}
811 </>
812 ) : (
813 statusHeadlineNode
814 )}
815 {summary.detail && !needsAttention ? <span>· {summary.detail}</span> : null}
816 </p>
817 {summary.detail && needsAttention ? (
818 <p className="text-[13px] leading-[1.45] text-muted-foreground/80 [overflow-wrap:anywhere]">
819 {summary.detail}
820 </p>
821 ) : null}
822 </div>
823 </div>
824​
825 <div className="flex h-11 shrink-0 border-b border-border/70 px-1">
826 <button
827 type="button"
828 aria-pressed={visibleTab === "configuration"}
829 className={providerSettingsTabClassName(visibleTab === "configuration")}
830 onClick={() => setActiveTab("configuration")}
831 >
832 Configuration
833 </button>
834 {driverOption !== undefined ? (
835 <button
836 type="button"
837 aria-pressed={visibleTab === "models"}
838 className={providerSettingsTabClassName(visibleTab === "models")}
839 onClick={() => setActiveTab("models")}
840 >
841 Models
842 </button>
843 ) : null}
844 </div>
845​
846 <div className="lg:min-h-0 lg:flex-1">
847 <ScrollArea
848 scrollFade
849 chainVerticalScroll
850 className="lg:h-full"
851 hidden={visibleTab !== "configuration"}
852 >
853 <div
854 inert={readOnly}
855 aria-disabled={readOnly || undefined}
856 className={cn("space-y-5 px-4 py-5", readOnly && "opacity-50 select-none")}
857 >
858 <div>
859 <label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
860 <span className="text-xs font-medium text-foreground">Display name</span>
861 <DraftInput
862 id={`provider-instance-${instanceId}-display-name`}
863 className="mt-1.5"
864 value={instance.displayName ?? ""}
865 onCommit={updateDisplayName}
866 placeholder={driverOption?.label ?? "Instance label"}
867 spellCheck={false}
868 />
869 <span className="mt-1 block text-xs text-muted-foreground">
870 Optional label shown in the provider list.
871 </span>
872 </label>
873 </div>
874​
875 <div>
876 <ProviderAccentColorPicker
877 displayName={displayName}
878 value={accentColor}
879 onCommit={updateAccentColor}
880 commitDelayMs={120}
881 description="Used to distinguish this instance in picker rails and model lists."
882 />
883 </div>
884​
885 <div>
886 <ProviderEnvironmentSection
887 environment={instance.environment ?? []}
888 onChange={updateEnvironment}
889 />
890 </div>
891​
892 {driverOption ? (
893 <ProviderSettingsForm
894 definition={driverOption}
895 value={instance.config}
896 idPrefix={`provider-instance-${instanceId}`}
897 variant="card"
898 onChange={updateConfig}
899 />
900 ) : null}
901​
902 {driverOption === undefined ? (
903 <div>
904 <p className="text-xs text-muted-foreground">
905 This instance uses a driver (
906 <code className="text-foreground">{String(instance.driver)}</code>) that is not
907 shipped with the current build. Configuration values are preserved but cannot be
908 edited from this surface.
909 </p>
910 </div>
911 ) : null}
912 </div>
913 </ScrollArea>
914 {driverOption !== undefined ? (
915 <div
916 inert={readOnly}
917 aria-disabled={readOnly || undefined}
918 className={cn("px-4 py-5 lg:h-full lg:min-h-0", readOnly && "opacity-50 select-none")}
919 hidden={visibleTab !== "models"}
920 >
921 <ProviderModelsSection
922 instanceId={instanceId}
923 driverKind={driverKind}
924 models={modelsForDisplay}
925 customModels={customModels}
926 hiddenModels={hiddenModels}
927 favoriteModels={favoriteModels}
928 modelOrder={modelOrder}
929 onChange={updateCustomModels}
930 onHiddenModelsChange={onHiddenModelsChange}
931 onFavoriteModelsChange={onFavoriteModelsChange}
932 onModelOrderChange={onModelOrderChange}
933 />
934 </div>
935 ) : null}
936 </div>
937 </div>
938 );