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

ProviderInstanceCard.tsx

1,189 lines43.0 KB

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