Open History to see the last commit
1"use client";
2
3import { Spinner } from "~/components/ui/spinner";
4
5import {
6 AlertTriangleIcon,
7 ArrowUpCircleIcon,
8 CopyIcon,
9 DownloadIcon,
10 LockIcon,
11 LockOpenIcon,
12 PlusIcon,
13 Trash2Icon,
14 XIcon,
15} from "lucide-react";
16import * as Arr from "effect/Array";
17import * as Result from "effect/Result";
18import { useEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
19import {
20 isProviderDriverKind,
21 resolveProviderInstanceEnabled,
22 type ProviderInstanceConfig,
23 type ProviderInstanceEnvironmentVariable,
24 type ProviderInstanceId,
25 type ProviderDriverKind,
26 type ServerProvider,
27 type ServerProviderModel,
28} from "@t3tools/contracts";
29
30import {
31 type CustomModelDefinition,
32 readCustomModelEntries,
33 toCustomModelSetting,
34} from "@t3tools/shared/model";
35import { cn } from "../../lib/utils";
36import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
37import { normalizeProviderAccentColor } from "../../providerInstances";
38import { Badge } from "../ui/badge";
39import { Button } from "../ui/button";
40import { DraftInput } from "../ui/draft-input";
41import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
42import { Switch } from "../ui/switch";
43import { stackedThreadToast, toastManager } from "../ui/toast";
44import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
45import type { DriverOption } from "./providerDriverMeta";
46import { ProviderSettingsForm } from "./ProviderSettingsForm";
47import { ProviderModelsSection } from "./ProviderModelsSection";
48import { ProviderInstanceIcon, providerInstanceInitials } from "../chat/ProviderInstanceIcon";
49import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
50import { RedactedSensitiveText } from "./RedactedSensitiveText";
51import { SettingsRow, SettingsSection } from "./settingsLayout";
52import { FoldedSettingsSection } from "./FoldedSettingsSection";
53import { readCodexSetupMode } from "./CodexSetupSection.logic";
54import {
55 getProviderVersionAdvisoryPresentation,
56 PROVIDER_STATUS_STYLES,
57 getProviderSummary,
58 getProviderVersionLabel,
59 type ProviderStatusKey,
60} from "./providerStatus";
61
62const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
63
64function ProviderStatusDiagnostic({
65 detail,
66 children,
67}: {
68 detail: string | null;
69 children: ReactElement;
70}) {
71 if (!detail) return children;
72 return (
73 <Tooltip>
74 <TooltipTrigger render={children} />
75 <TooltipPopup side="top">{detail}</TooltipPopup>
76 </Tooltip>
77 );
78}
79
80let environmentVariableDraftId = 0;
81const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;
82
83type EnvironmentDraftRow = {
84 readonly id: string;
85 readonly name: string;
86 readonly value: string;
87 readonly sensitive: boolean;
88 readonly valueRedacted?: boolean;
89};
90
91function makeEnvironmentDraftRow(
92 variable: ProviderInstanceEnvironmentVariable,
93 index: number,
94): EnvironmentDraftRow {
95 return {
96 id: `${index}:${variable.name}`,
97 name: variable.name,
98 value: variable.value,
99 sensitive: variable.sensitive,
100 ...(variable.valueRedacted !== undefined ? { valueRedacted: variable.valueRedacted } : {}),
101 };
102}
103
104function providerEnvironmentsEqual(
105 left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
106 right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
107): boolean {
108 return (
109 left.length === right.length &&
110 left.every((variable, index) => {
111 const other = right[index];
112 return (
113 other !== undefined &&
114 variable.name === other.name &&
115 variable.value === other.value &&
116 variable.sensitive === other.sensitive &&
117 variable.valueRedacted === other.valueRedacted
118 );
119 })
120 );
121}
122
123/**
124 * Read `customModels` from the opaque config blob. The concrete driver
125 * schemas type it as `CustomModelSetting[]`, but it arrives here as
126 * `Schema.Unknown`, so the shared reader does the shape checking.
127 */
128function readConfigCustomModels(config: unknown): ReadonlyArray<CustomModelDefinition> {
129 if (config === null || typeof config !== "object") return [];
130 return readCustomModelEntries((config as Record<string, unknown>).customModels);
131}
132
133/**
134 * Set `key` to an arbitrary value on the opaque config blob. Unlike
135 * provider settings field updates, does not drop empty-looking values — the
136 * caller is responsible for deciding whether an empty array / empty
137 * object should be stored explicitly (e.g. `customModels: []` is a
138 * meaningful "user cleared their custom list" state distinct from
139 * "driver default").
140 */
141function nextConfigBlobWithValue(
142 config: unknown,
143 key: string,
144 value: unknown,
145): Record<string, unknown> {
146 const base: Record<string, unknown> =
147 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
148 base[key] = value;
149 return base;
150}
151
152/**
153 * Custom rows come from current settings so name/descriptor edits show
154 * instantly; a bare entry falls back to the live row's driver-default
155 * capabilities (the server fills those in on its next probe).
156 */
157export function deriveProviderModelsForDisplay(input: {
158 readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
159 readonly customModels: ReadonlyArray<CustomModelDefinition>;
160}): ReadonlyArray<ServerProviderModel> {
161 const liveCustomModelsBySlug = new Map(
162 Arr.filterMap(input.liveModels ?? [], (model) =>
163 model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
164 ),
165 );
166 const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
167 const customModels = input.customModels.map((entry) => ({
168 slug: entry.slug,
169 name: entry.name,
170 isCustom: true,
171 capabilities:
172 entry.capabilities ?? liveCustomModelsBySlug.get(entry.slug)?.capabilities ?? null,
173 }));
174 return [...serverModels, ...customModels];
175}
176
177function ProviderAuthEmail(props: { readonly email: string | undefined }) {
178 const email = props.email?.trim();
179 if (!email) return null;
180
181 return (
182 <RedactedSensitiveText
183 value={email}
184 ariaLabel="Toggle account email visibility"
185 revealTooltip="Click to reveal email"
186 hideTooltip="Click to hide email"
187 className="max-w-full truncate"
188 />
189 );
190}
191
192function ProviderEnvironmentSection(props: {
193 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
194 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
195}) {
196 const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
197 props.environment.map(makeEnvironmentDraftRow),
198 );
199 const previousEnvironmentRef = useRef(props.environment);
200 const lastPublishedEnvironmentRef = useRef<
201 ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
202 >(undefined);
203
204 useEffect(() => {
205 const previousEnvironment = previousEnvironmentRef.current;
206 const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
207 previousEnvironmentRef.current = props.environment;
208 lastPublishedEnvironmentRef.current = undefined;
209 if (
210 previousEnvironment === props.environment ||
211 providerEnvironmentsEqual(previousEnvironment, props.environment) ||
212 (lastPublishedEnvironment !== undefined &&
213 providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
214 ) {
215 return;
216 }
217 setRows(props.environment.map(makeEnvironmentDraftRow));
218 }, [props.environment]);
219
220 const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
221 const published: ProviderInstanceEnvironmentVariable[] = [];
222 for (const row of nextRows) {
223 const name = row.name.trim();
224 if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
225 if (
226 name.length > 0 ||
227 row.value.length > 0 ||
228 row.sensitive !== true ||
229 row.valueRedacted !== undefined
230 ) {
231 return;
232 }
233 continue;
234 }
235 const { id: _id, ...rest } = row;
236 published.push({ ...rest, name });
237 }
238 lastPublishedEnvironmentRef.current = published;
239 props.onChange(published);
240 };
241
242 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
243 const nextRows = rows.map((row) =>
244 row.id === id
245 ? {
246 ...row,
247 ...patch,
248 ...(patch.value !== undefined ? { valueRedacted: false } : {}),
249 }
250 : row,
251 );
252 setRows(nextRows);
253 publishRows(nextRows);
254 };
255
256 const removeVariable = (id: string) => {
257 const nextRows = rows.filter((row) => row.id !== id);
258 setRows(nextRows);
259 publishRows(nextRows);
260 };
261
262 const addVariable = () =>
263 setRows([
264 ...rows,
265 {
266 id: nextEnvironmentVariableDraftId(),
267 name: "",
268 value: "",
269 sensitive: true,
270 },
271 ]);
272
273 return (
274 <SettingsRow
275 title="Variables"
276 description="API keys, base URLs, and other per-instance CLI settings."
277 control={
278 <Button type="button" size="sm" variant="outline" onClick={addVariable}>
279 <PlusIcon className="size-3" />
280 Add variable
281 </Button>
282 }
283 >
284 {rows.length > 0 ? (
285 <div className="mt-3 min-w-0 space-y-2 pb-2">
286 {rows.map((variable, index) => (
287 <div key={variable.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
288 <DraftInput
289 size="sm"
290 font="mono"
291 className="w-full min-w-0 sm:w-44 sm:shrink-0"
292 value={variable.name}
293 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
294 placeholder="VARIABLE_NAME"
295 spellCheck={false}
296 aria-label={`Environment variable name ${index + 1}`}
297 />
298 <span className="hidden text-xs text-muted-foreground sm:inline" aria-hidden>
299 =
300 </span>
301 <DraftInput
302 size="sm"
303 font="mono"
304 className="min-w-0 flex-1"
305 value={variable.valueRedacted ? "" : variable.value}
306 onCommit={(value) => updateVariable(variable.id, { value })}
307 type={variable.sensitive ? "password" : undefined}
308 autoComplete="off"
309 placeholder={
310 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
311 }
312 spellCheck={false}
313 aria-label={`Environment variable value ${index + 1}`}
314 />
315 <Tooltip>
316 <TooltipTrigger
317 render={
318 <Button
319 type="button"
320 size="icon-micro"
321 variant="ghost-muted"
322 onClick={() => {
323 const sensitive = !variable.sensitive;
324 updateVariable(variable.id, {
325 sensitive,
326 ...(sensitive && variable.valueRedacted === undefined
327 ? {}
328 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
329 });
330 }}
331 aria-pressed={variable.sensitive}
332 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
333 >
334 {variable.sensitive ? (
335 <LockIcon className="size-3" />
336 ) : (
337 <LockOpenIcon className="size-3" />
338 )}
339 </Button>
340 }
341 />
342 <TooltipPopup side="top">
343 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
344 </TooltipPopup>
345 </Tooltip>
346 <Button
347 type="button"
348 size="icon-micro"
349 variant="ghost-destructive"
350 onClick={() => removeVariable(variable.id)}
351 aria-label={`Remove environment variable ${variable.name || index + 1}`}
352 >
353 <XIcon className="size-3" />
354 </Button>
355 </div>
356 ))}
357 <p className="text-xs text-muted-foreground">
358 Sensitive values are stored separately and never returned to the app.
359 </p>
360 </div>
361 ) : null}
362 </SettingsRow>
363 );
364}
365
366interface ProviderInstanceCardProps {
367 readonly instanceId: ProviderInstanceId;
368 readonly instance: ProviderInstanceConfig;
369 readonly driverOption: DriverOption | undefined;
370 readonly liveProvider: ServerProvider | undefined;
371 readonly mode: "list" | "editor";
372 readonly selected?: boolean | undefined;
373 readonly onSelect?: (() => void) | undefined;
374 readonly readOnly?: boolean | undefined;
375 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
376 /**
377 * Pass `undefined` to hide the delete footer entirely. Built-in default
378 * instance slots use `undefined` — they can't be deleted without losing
379 * the slot, and their "reset to defaults" affordance lives on an outer
380 * reset button instead. Explicit `| undefined` in the type accommodates
381 * `exactOptionalPropertyTypes: true`, where an absent key and
382 * `{ onDelete: undefined }` are treated as distinct shapes.
383 */
384 readonly onDelete?: (() => void) | undefined;
385 /**
386 * Optional outer reset button rendered next to the driver icon. Built-in
387 * default slots supply a reset-to-factory control here; custom instances
388 * omit it.
389 */
390 readonly headerAction?: ReactNode | undefined;
391 readonly setup?: ReactNode;
392 readonly runtime?: ReactNode;
393 readonly hiddenModels: ReadonlyArray<string>;
394 readonly favoriteModels: ReadonlyArray<string>;
395 readonly modelOrder: ReadonlyArray<string>;
396 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
397 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
398 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
399 readonly onRunUpdate?: (() => void) | undefined;
400 readonly onInstallRecommended?: (() => void) | undefined;
401 readonly isUpdating?: boolean | undefined;
402}
403
404/**
405 * Renders one provider instance as either a compact selectable list row or
406 * the full editor shown beside that list. Both modes use the same enabled
407 * state and provider metadata.
408 *
409 * Behavior notes:
410 * - `liveProvider` is matched by the caller via `instanceId`; when no
411 * match is available (e.g. the server hasn't probed yet, or the
412 * driver is not shipped by the current build) the card still renders
413 * with a neutral "checking" summary.
414 * - Unknown drivers (`driverOption === undefined`) get a read-only
415 * notice instead of editable fields, so fork instances round-trip
416 * without accidentally destroying their config.
417 * - The enabled Switch writes to the envelope's `instance.enabled`
418 * field, which is the single enabled flag: the server folds any legacy
419 * driver-specific `config.enabled` into the envelope on load and both
420 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
421 * false wins, then envelope, then config, then the driver default).
422 */
423export function ProviderInstanceCard({
424 instanceId,
425 instance,
426 driverOption,
427 liveProvider,
428 mode,
429 selected = false,
430 onSelect,
431 readOnly = false,
432 onUpdate,
433 onDelete,
434 headerAction,
435 setup,
436 runtime,
437 hiddenModels,
438 favoriteModels,
439 modelOrder,
440 onHiddenModelsChange,
441 onFavoriteModelsChange,
442 onModelOrderChange,
443 onRunUpdate,
444 onInstallRecommended,
445 isUpdating = false,
446}: ProviderInstanceCardProps) {
447 const enabled = resolveProviderInstanceEnabled(instance);
448 const compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
449 // A locally disabled provider reads "Disabled" with a muted dot even if its
450 // last server status is stale. Enabled providers use the server status.
451 const statusKey: ProviderStatusKey = enabled
452 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
453 : "disabled";
454 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
455 const summary = enabled
456 ? getProviderSummary(liveProvider)
457 : { headline: "Disabled", detail: null };
458 const authEmail = liveProvider?.auth.email?.trim();
459 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
460 const authLabel =
461 enabled && liveProvider?.auth.status === "authenticated"
462 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
463 : null;
464 const versionLabel = getProviderVersionLabel(liveProvider?.version);
465 const versionAdvisory = getProviderVersionAdvisoryPresentation(
466 liveProvider?.versionAdvisory,
467 liveProvider?.compatibilityAdvisory,
468 enabled,
469 );
470 const updateCommand = versionAdvisory?.updateCommand ?? null;
471 const hasCompatibilityWarning =
472 compatibility !== undefined &&
473 compatibility.status !== "supported" &&
474 compatibility.status !== "unknown";
475 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
476 const onRunVersionAction = versionAdvisory?.targetVersion ? onInstallRecommended : onRunUpdate;
477 const FallbackIconComponent = driverOption?.icon;
478 const displayName =
479 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
480 const accentColor = normalizeProviderAccentColor(instance.accentColor);
481 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
482 onCopy: ({ providerName }) => {
483 toastManager.add({
484 type: "success",
485 title: `${providerName} update command copied`,
486 description: "Run it in a terminal when you are ready to update.",
487 });
488 },
489 onError: (error, { providerName }) => {
490 toastManager.add(
491 stackedThreadToast({
492 type: "error",
493 title: `Could not copy ${providerName} update command`,
494 description: error.message,
495 }),
496 );
497 },
498 });
499
500 // Narrow `instance.driver` for callers that key on the closed
501 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
502 // fork drivers pass through as `null` and those callers fall back to
503 // verbatim behaviour.
504 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
505 ? instance.driver
506 : null;
507 const customModels =
508 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
509 // Server-returned models may lag behind settings writes. Treat probe
510 // models as the source for built-ins only; custom rows come directly
511 // from the current instance config so add/remove reflects immediately.
512 const modelsForDisplay = deriveProviderModelsForDisplay({
513 liveModels: liveProvider?.models,
514 customModels,
515 });
516 const updateDisplayName = (value: string) => {
517 const trimmed = value.trim();
518 const { displayName: _omit, ...rest } = instance;
519 onUpdate(
520 trimmed.length > 0
521 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
522 : (rest as ProviderInstanceConfig),
523 );
524 };
525
526 const updateEnabled = (value: boolean) => {
527 onUpdate({ ...instance, enabled: value });
528 };
529
530 const updateAccentColor = (value: string) => {
531 const normalized = normalizeProviderAccentColor(value);
532 const { accentColor: _omit, ...rest } = instance;
533 onUpdate(
534 normalized
535 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
536 : (rest as ProviderInstanceConfig),
537 );
538 };
539
540 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
541 const { config: _omit, ...rest } = instance;
542 onUpdate(
543 nextConfig !== undefined
544 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
545 : (rest as ProviderInstanceConfig),
546 );
547 };
548
549 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
550 const nextConfig = nextConfigBlobWithValue(
551 instance.config,
552 "customModels",
553 next.map(toCustomModelSetting),
554 );
555 const { config: _omit, ...rest } = instance;
556 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
557 };
558
559 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
560 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
561 const { environment: _omit, ...rest } = instance;
562 onUpdate(
563 cleaned.length > 0
564 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
565 : (rest as ProviderInstanceConfig),
566 );
567 };
568
569 const titleIconNode = driverKind ? (
570 <ProviderInstanceIcon
571 driverKind={driverKind}
572 displayName={displayName}
573 accentColor={accentColor}
574 showBadge={Boolean(accentColor)}
575 className="size-5"
576 iconClassName="size-4 text-foreground/80"
577 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
578 />
579 ) : FallbackIconComponent ? (
580 <span className="inline-flex size-5 shrink-0 items-center justify-center">
581 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
582 </span>
583 ) : (
584 <span
585 className="inline-flex size-5 shrink-0 items-center justify-center text-3xs font-semibold leading-none text-foreground/80"
586 aria-hidden
587 >
588 {providerInstanceInitials(displayName)}
589 </span>
590 );
591
592 const titleTailNode = headerAction ? (
593 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
594 ) : null;
595
596 const versionCodeNode = versionLabel ? (
597 <code className="text-xs text-muted-foreground">{versionLabel}</code>
598 ) : null;
599
600 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
601 const statusDotNode =
602 statusKey === "warning" || statusKey === "error" ? (
603 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
604 ) : null;
605 const needsAttention = statusKey === "warning" || statusKey === "error";
606 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
607 // Keep compatibility copy compact; the version popover carries the explanation.
608 const inlineStatusDetail = hasCompatibilityWarning
609 ? compatibility?.status === "broken"
610 ? "Incompatible"
611 : compatibility?.status === "unsupported"
612 ? "Unsupported"
613 : "Limited support"
614 : summary.detail;
615 const editorStatusNode =
616 isAuthenticated && authEmail ? (
617 <>
618 {needsAttention ? statusDotNode : null}
619 <span>Authenticated as</span>
620 <ProviderAuthEmail email={authEmail} />
621 {authLabel ? <span>· {authLabel}</span> : null}
622 {inlineStatusDetail ? (
623 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
624 ) : null}
625 </>
626 ) : (
627 <>
628 {statusDotNode}
629 <span>{summary.headline}</span>
630 {inlineStatusDetail ? (
631 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
632 ) : null}
633 </>
634 );
635 if (mode === "list") {
636 return (
637 <div
638 data-slot="settings-row"
639 className={cn(
640 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
641 selected ? "bg-muted/45" : "hover:bg-muted/25",
642 )}
643 >
644 <div
645 className={cn(
646 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
647 !enabled && !selected && "opacity-60 group-hover:opacity-100",
648 )}
649 >
650 <button
651 type="button"
652 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
653 onClick={onSelect}
654 aria-label={`Select ${displayName}`}
655 aria-pressed={selected}
656 />
657 {titleIconNode}
658 <span className="min-w-0 flex-1">
659 <span className="flex min-w-0 items-center gap-2">
660 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
661 {versionLabel ? (
662 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
663 {versionLabel}
664 </code>
665 ) : null}
666 {versionAdvisory ? (
667 hasCompatibilityWarning ? (
668 <Tooltip>
669 <TooltipTrigger
670 render={
671 <span
672 tabIndex={0}
673 role="img"
674 aria-label={versionAdvisory.title}
675 className="pointer-events-auto relative inline-flex shrink-0 text-warning"
676 >
677 <VersionAdvisoryIcon className="size-3.5" />
678 </span>
679 }
680 />
681 <TooltipPopup side="top">{versionAdvisory.detail}</TooltipPopup>
682 </Tooltip>
683 ) : updateCommand ? (
684 <Tooltip>
685 <TooltipTrigger
686 render={
687 <Button
688 type="button"
689 size="icon-micro"
690 variant="ghost-muted"
691 className="pointer-events-auto relative shrink-0"
692 aria-label={`Copy ${displayName} update command`}
693 onClick={() =>
694 copyToClipboard(updateCommand, { providerName: displayName })
695 }
696 >
697 <ArrowUpCircleIcon className="size-3.5" />
698 </Button>
699 }
700 />
701 <TooltipPopup side="top">Copy update command</TooltipPopup>
702 </Tooltip>
703 ) : (
704 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
705 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
706 </span>
707 )
708 ) : null}
709 </span>
710 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
711 {statusDotNode ? (
712 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
713 ) : null}
714 <ProviderStatusDiagnostic detail={statusDiagnostic}>
715 <span
716 tabIndex={statusDiagnostic ? 0 : undefined}
717 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
718 >
719 {summary.headline}
720 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
721 </span>
722 </ProviderStatusDiagnostic>
723 </span>
724 </span>
725 </div>
726 <span className="flex h-5 shrink-0 items-center">
727 <Switch
728 checked={enabled}
729 disabled={readOnly}
730 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
731 aria-label={`Enable ${displayName}`}
732 />
733 </span>
734 </div>
735 );
736 }
737
738 const editorHeaderAction = (
739 <div className="flex shrink-0 items-center gap-1.5">
740 {driverOption?.badgeLabel ? (
741 <Badge variant="warning" size="sm" className="shrink-0">
742 {driverOption.badgeLabel}
743 </Badge>
744 ) : null}
745 {versionCodeNode}
746 <span
747 inert={readOnly}
748 aria-disabled={readOnly || undefined}
749 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
750 >
751 {versionAdvisory ? (
752 <Popover>
753 <Tooltip>
754 <TooltipTrigger
755 render={
756 <PopoverTrigger
757 render={
758 <Button
759 type="button"
760 size="icon-xs"
761 variant="ghost-muted"
762 aria-label={`${versionAdvisory.title} — view details`}
763 >
764 <VersionAdvisoryIcon
765 className={cn(hasCompatibilityWarning && "text-warning")}
766 />
767 </Button>
768 }
769 />
770 }
771 />
772 <TooltipPopup side="top">{versionAdvisory.title}</TooltipPopup>
773 </Tooltip>
774 <PopoverPopup side="bottom" align="end" width="md">
775 <div className="grid min-w-0 gap-3">
776 <div className="grid gap-0.5">
777 <p className="text-sm font-semibold leading-tight text-foreground">
778 {versionAdvisory.title}
779 </p>
780 <p
781 className={cn(
782 "text-xs leading-snug",
783 versionAdvisory.emphasis === "strong"
784 ? "text-warning"
785 : "text-muted-foreground",
786 )}
787 >
788 {versionAdvisory.detail}
789 </p>
790 </div>
791 {onRunVersionAction ? (
792 <Button
793 type="button"
794 size="xs"
795 variant="outline"
796 className="w-full"
797 disabled={isUpdating}
798 onClick={onRunVersionAction}
799 >
800 {isUpdating ? <Spinner /> : <DownloadIcon />}
801 {isUpdating
802 ? "Updating"
803 : versionAdvisory.targetVersion
804 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
805 : "Update now"}
806 </Button>
807 ) : null}
808 {onRunVersionAction && updateCommand ? (
809 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
810 <span aria-hidden className="h-px flex-1 bg-border" />
811 or, update manually using
812 <span aria-hidden className="h-px flex-1 bg-border" />
813 </div>
814 ) : null}
815 {updateCommand ? (
816 <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">
817 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
818 {updateCommand}
819 </code>
820 <Tooltip>
821 <TooltipTrigger
822 render={
823 <Button
824 type="button"
825 size="icon-xs"
826 variant="ghost-muted"
827 className="shrink-0"
828 onClick={() =>
829 copyToClipboard(updateCommand, { providerName: displayName })
830 }
831 aria-label="Copy update command"
832 >
833 <CopyIcon className="size-3" />
834 </Button>
835 }
836 />
837 <TooltipPopup side="top">Copy command</TooltipPopup>
838 </Tooltip>
839 </div>
840 ) : null}
841 </div>
842 </PopoverPopup>
843 </Popover>
844 ) : null}
845 {titleTailNode}
846 {onDelete ? (
847 <Button
848 type="button"
849 size="icon-xs"
850 variant="ghost-destructive"
851 disabled={readOnly}
852 onClick={onDelete}
853 aria-label={`Delete instance ${instanceId}`}
854 >
855 <Trash2Icon />
856 </Button>
857 ) : null}
858 </span>
859 </div>
860 );
861
862 const runtimeFields = driverOption ? (
863 <ProviderSettingsForm
864 definition={driverOption}
865 value={instance.config}
866 idPrefix={`provider-instance-${instanceId}`}
867 variant="settings"
868 onChange={updateConfig}
869 />
870 ) : (
871 <SettingsRow
872 title="Driver"
873 description={
874 <span>
875 This instance uses <code className="text-foreground">{String(instance.driver)}</code>,
876 which is not available in this build. Its configuration is preserved.
877 </span>
878 }
879 />
880 );
881
882 return (
883 <>
884 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
885 <SettingsRow
886 title="Display name"
887 status={
888 <ProviderStatusDiagnostic detail={statusDiagnostic}>
889 <div
890 tabIndex={statusDiagnostic ? 0 : undefined}
891 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
892 >
893 {editorStatusNode}
894 </div>
895 </ProviderStatusDiagnostic>
896 }
897 control={
898 <div
899 inert={readOnly}
900 aria-disabled={readOnly || undefined}
901 className={cn(
902 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
903 readOnly && "opacity-50 select-none",
904 )}
905 >
906 <ProviderAccentColorPicker
907 layout="inline"
908 displayName={displayName}
909 value={accentColor}
910 onCommit={updateAccentColor}
911 commitDelayMs={120}
912 />
913 <DraftInput
914 id={`provider-instance-${instanceId}-display-name`}
915 size="sm"
916 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
917 value={instance.displayName ?? ""}
918 onCommit={updateDisplayName}
919 placeholder={driverOption?.label ?? "Instance label"}
920 spellCheck={false}
921 />
922 </div>
923 }
924 />
925 </SettingsSection>
926
927 {setup ? <SettingsSection title="Setup">{setup}</SettingsSection> : null}
928
929 {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? (
930 <div
931 inert={readOnly}
932 aria-disabled={readOnly || undefined}
933 className={readOnly ? "opacity-50 select-none" : undefined}
934 >
935 <FoldedSettingsSection
936 key={instanceId}
937 id={`provider-instance-${instanceId}-runtime`}
938 title="Runtime"
939 headerPlacement="outside"
940 >
941 {runtime ?? runtimeFields}
942 </FoldedSettingsSection>
943 </div>
944 ) : (
945 <SettingsSection
946 title="Runtime"
947 inert={readOnly}
948 aria-disabled={readOnly || undefined}
949 className={readOnly ? "opacity-50 select-none" : undefined}
950 >
951 {runtimeFields}
952 </SettingsSection>
953 )}
954
955 <SettingsSection
956 title="Environment"
957 inert={readOnly}
958 aria-disabled={readOnly || undefined}
959 className={readOnly ? "opacity-50 select-none" : undefined}
960 >
961 <ProviderEnvironmentSection
962 environment={instance.environment ?? []}
963 onChange={updateEnvironment}
964 />
965 </SettingsSection>
966
967 {driverOption !== undefined ? (
968 <SettingsSection
969 title="Models"
970 inert={readOnly}
971 aria-disabled={readOnly || undefined}
972 className={readOnly ? "opacity-50 select-none" : undefined}
973 >
974 <div className="px-3 py-3 sm:px-4">
975 <p className="mb-3 text-xs text-muted-foreground">
976 Favorites, visibility, and ordering are saved on this device. Custom models are saved
977 on the selected environment.
978 </p>
979 <ProviderModelsSection
980 instanceId={instanceId}
981 driverKind={driverKind}
982 models={modelsForDisplay}
983 customModels={customModels}
984 hiddenModels={hiddenModels}
985 favoriteModels={favoriteModels}
986 modelOrder={modelOrder}
987 onChange={updateCustomModels}
988 onHiddenModelsChange={onHiddenModelsChange}
989 onFavoriteModelsChange={onFavoriteModelsChange}
990 onModelOrderChange={onModelOrderChange}
991 />
992 </div>
993 </SettingsSection>
994 ) : null}
995 </>
996 );
997}