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 ExternalLinkIcon,
11 PlusIcon,
12 Trash2Icon,
13 XIcon,
14} from "lucide-react";
15import { Lock as LockGlyph, LockOpen } from "lucide";
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 AcpRegistryUrlAuthAction,
26 type EnvironmentId,
27 type ProjectId,
28 type ProviderDriverKind,
29 type ServerProvider,
30 type ServerProviderModel,
31} from "@t3tools/contracts";
32
33import {
34 type CustomModelDefinition,
35 readCustomModelEntries,
36 toCustomModelSetting,
37} from "@t3tools/shared/model";
38import { cn } from "../../lib/utils";
39import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
40import { normalizeProviderAccentColor } from "../../providerInstances";
41import { Badge } from "../ui/badge";
42import { Button } from "../ui/button";
43import { MorphIcon } from "~/components/MorphIcon";
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 );
83}
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 };
107}
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 );
126}
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);
136}
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;
142}
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;
161}
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];
186}
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 );
201}
202
203export function readProviderEnvironmentVariable(
204 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
205 name: string,
206): ProviderInstanceEnvironmentVariable | undefined {
207 return environment?.find((variable) => variable.name === name);
208}
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));
215}
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;
250}
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 );
297}
298
299export function 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 <MorphIcon
442 className="size-3"
443 icon={variable.sensitive ? LockGlyph : LockOpen}
444 />
445 </Button>
446 }
447 />
448 <TooltipPopup side="top">
449 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
450 </TooltipPopup>
451 </Tooltip>
452 <Button
453 type="button"
454 size="icon-micro"
455 variant="ghost-destructive"
456 onClick={() => removeVariable(variable.id)}
457 aria-label={`Remove environment variable ${variable.name || index + 1}`}
458 >
459 <XIcon className="size-3" />
460 </Button>
461 </div>
462 ))}
463 <p className="text-xs text-muted-foreground">
464 Sensitive values are stored separately and never returned to the app.
465 </p>
466 </div>
467 ) : null}
468 </SettingsRow>
469 );
470}
471
472interface ProviderInstanceCardProps {
473 readonly instanceId: ProviderInstanceId;
474 readonly instance: ProviderInstanceConfig;
475 readonly driverOption: DriverOption | undefined;
476 readonly liveProvider: ServerProvider | undefined;
477 readonly mode: "list" | "editor";
478 readonly selected?: boolean | undefined;
479 readonly onSelect?: (() => void) | undefined;
480 readonly readOnly?: boolean | undefined;
481 readonly canWriteSettings?: boolean;
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;
518}
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 canWriteSettings = true,
551 onUpdate,
552 onDelete,
553 headerAction,
554 setup,
555 runtime,
556 hiddenModels,
557 favoriteModels,
558 modelOrder,
559 onHiddenModelsChange,
560 onFavoriteModelsChange,
561 onModelOrderChange,
562 onRunUpdate,
563 onInstallRecommended,
564 isUpdating = false,
565 onAcceptUrlAuth,
566 environmentId,
567 acpProjects = EMPTY_ACP_PROJECTS,
568}: ProviderInstanceCardProps) {
569 const enabled = resolveProviderInstanceEnabled(instance);
570 const compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
571 // A locally disabled provider reads "Disabled" with a muted dot even if its
572 // last server status is stale. Enabled providers use the server status.
573 const statusKey: ProviderStatusKey = enabled
574 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
575 : "disabled";
576 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
577 const summary = enabled
578 ? getProviderSummary(liveProvider)
579 : { headline: "Disabled", detail: null };
580 const authEmail = liveProvider?.auth.email?.trim();
581 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
582 const authLabel =
583 enabled && liveProvider?.auth.status === "authenticated"
584 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
585 : null;
586 const versionLabel = getProviderVersionLabel(liveProvider?.version);
587 const versionAdvisory = getProviderVersionAdvisoryPresentation(
588 liveProvider?.versionAdvisory,
589 liveProvider?.compatibilityAdvisory,
590 enabled,
591 );
592 const updateCommand = versionAdvisory?.updateCommand ?? null;
593 const hasCompatibilityWarning =
594 compatibility !== undefined &&
595 compatibility.status !== "supported" &&
596 compatibility.status !== "unknown";
597 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
598 const onRunVersionAction = readOnly
599 ? undefined
600 : versionAdvisory?.targetVersion
601 ? onInstallRecommended
602 : onRunUpdate;
603 const urlAuthAction = liveProvider?.auth.action;
604 const displayName =
605 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
606 const accentColor = normalizeProviderAccentColor(instance.accentColor);
607 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
608 onCopy: ({ providerName }) => {
609 toastManager.add({
610 type: "success",
611 title: `${providerName} update command copied`,
612 description: "Run it in a terminal when you are ready to update.",
613 });
614 },
615 onError: (error, { providerName }) => {
616 toastManager.add(
617 stackedThreadToast({
618 type: "error",
619 title: `Could not copy ${providerName} update command`,
620 description: error.message,
621 }),
622 );
623 },
624 });
625
626 // Narrow `instance.driver` for callers that key on the closed
627 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
628 // fork drivers pass through as `null` and those callers fall back to
629 // verbatim behaviour.
630 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
631 ? instance.driver
632 : null;
633 const customModels =
634 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
635 // Server-returned models may lag behind settings writes. Treat server
636 // models as the source for built-ins only; custom rows come directly
637 // from the current instance config so add/remove reflects immediately.
638 const modelsForDisplay = deriveProviderModelsForDisplay({
639 liveModels: liveProvider?.models,
640 customModels,
641 });
642 const updateDisplayName = (value: string) => {
643 const trimmed = value.trim();
644 const { displayName: _omit, ...rest } = instance;
645 onUpdate(
646 trimmed.length > 0
647 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
648 : (rest as ProviderInstanceConfig),
649 );
650 };
651
652 const updateEnabled = (value: boolean) => {
653 onUpdate({ ...instance, enabled: value });
654 };
655
656 const updateAccentColor = (value: string) => {
657 const normalized = normalizeProviderAccentColor(value);
658 const { accentColor: _omit, ...rest } = instance;
659 onUpdate(
660 normalized
661 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
662 : (rest as ProviderInstanceConfig),
663 );
664 };
665
666 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
667 const { config: _omit, ...rest } = instance;
668 onUpdate(
669 nextConfig !== undefined
670 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
671 : (rest as ProviderInstanceConfig),
672 );
673 };
674
675 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
676 const nextConfig = nextConfigBlobWithValue(
677 instance.config,
678 "customModels",
679 next.map(toCustomModelSetting),
680 );
681 const { config: _omit, ...rest } = instance;
682 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
683 };
684
685 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
686 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
687 const { environment: _omit, ...rest } = instance;
688 onUpdate(
689 cleaned.length > 0
690 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
691 : (rest as ProviderInstanceConfig),
692 );
693 };
694 // Drivers that need a named secret (Cursor's API key) get a dedicated field;
695 // the generic editor only shows the remaining variables.
696 const environmentFields = driverOption?.environmentFields ?? [];
697 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
698 const genericEnvironment = providerEnvironmentWithoutNames(
699 instance.environment,
700 environmentFieldNames,
701 );
702 const updateGenericEnvironment = (
703 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
704 ) => {
705 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
706 environmentFieldNames.has(variable.name),
707 );
708 updateEnvironment([...dedicatedEnvironment, ...environment]);
709 };
710 const updateEnvironmentField = (field: ProviderEnvironmentFieldDefinition, value: string) => {
711 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
712 };
713 const removeEnvironmentField = (field: ProviderEnvironmentFieldDefinition) => {
714 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
715 };
716
717 const titleIconNode = (
718 <ProviderInstanceIcon
719 driverKind={driverKind ?? instance.driver}
720 displayName={displayName}
721 accentColor={accentColor}
722 acpRegistryAgentId={
723 readConfigString(instance.config, "source") === "local"
724 ? undefined
725 : (readConfigString(instance.config, "agentId") ?? undefined)
726 }
727 acpRegistryIconUrl={
728 readConfigString(instance.config, "source") === "local"
729 ? undefined
730 : (readConfigString(instance.config, "registryIconUrl") ?? undefined)
731 }
732 showBadge={Boolean(accentColor)}
733 className="size-5"
734 iconClassName="size-4 text-foreground/80"
735 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
736 />
737 );
738
739 const titleTailNode = headerAction ? (
740 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
741 ) : null;
742
743 const versionCodeNode = versionLabel ? (
744 <code className="text-xs text-muted-foreground">{versionLabel}</code>
745 ) : null;
746
747 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
748 const statusDotNode =
749 statusKey === "warning" || statusKey === "error" ? (
750 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
751 ) : null;
752 const needsAttention = statusKey === "warning" || statusKey === "error";
753 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
754 // Keep compatibility copy compact; the version popover carries the explanation.
755 const inlineStatusDetail = hasCompatibilityWarning
756 ? compatibility?.status === "broken"
757 ? "Incompatible"
758 : compatibility?.status === "unsupported"
759 ? "Unsupported"
760 : "Limited support"
761 : summary.detail;
762 const editorStatusNode =
763 isAuthenticated && authEmail ? (
764 <>
765 {needsAttention ? statusDotNode : null}
766 <span>Authenticated as</span>
767 <ProviderAuthEmail email={authEmail} />
768 {authLabel ? <span>· {authLabel}</span> : null}
769 {inlineStatusDetail ? (
770 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
771 ) : null}
772 </>
773 ) : (
774 <>
775 {statusDotNode}
776 <span>{summary.headline}</span>
777 {inlineStatusDetail ? (
778 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
779 ) : null}
780 </>
781 );
782 const versionAdvisoryNode = versionAdvisory ? (
783 <Popover>
784 <Tooltip>
785 <TooltipTrigger
786 render={
787 <PopoverTrigger
788 render={
789 <Button
790 type="button"
791 size={mode === "list" ? "icon-micro" : "icon-xs"}
792 variant="ghost-muted"
793 className={mode === "list" ? "pointer-events-auto relative shrink-0" : undefined}
794 aria-label={`${versionAdvisory.title} — view details`}
795 >
796 <VersionAdvisoryIcon
797 className={cn(
798 mode === "list" && "size-3.5",
799 hasCompatibilityWarning && "text-warning",
800 )}
801 />
802 </Button>
803 }
804 />
805 }
806 />
807 <TooltipPopup side="top">{versionAdvisory.title}</TooltipPopup>
808 </Tooltip>
809 <PopoverPopup side="bottom" align="end" width="md" aria-label={versionAdvisory.title}>
810 <div className="grid min-w-0 gap-3">
811 <div className="grid gap-0.5">
812 <p className="text-sm font-semibold leading-tight text-foreground">
813 {versionAdvisory.title}
814 </p>
815 <p
816 className={cn(
817 "text-xs leading-snug",
818 versionAdvisory.emphasis === "strong" ? "text-warning" : "text-muted-foreground",
819 )}
820 >
821 {versionAdvisory.detail}
822 </p>
823 </div>
824 {onRunVersionAction ? (
825 <Button
826 type="button"
827 size="xs"
828 variant="outline"
829 className="w-full"
830 disabled={isUpdating}
831 onClick={onRunVersionAction}
832 >
833 {isUpdating ? <Spinner /> : <DownloadIcon />}
834 {isUpdating
835 ? "Updating"
836 : versionAdvisory.targetVersion
837 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
838 : "Update now"}
839 </Button>
840 ) : null}
841 {onRunVersionAction && updateCommand ? (
842 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
843 <span aria-hidden className="h-px flex-1 bg-border" />
844 or, update manually using
845 <span aria-hidden className="h-px flex-1 bg-border" />
846 </div>
847 ) : null}
848 {updateCommand ? (
849 <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">
850 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
851 {updateCommand}
852 </code>
853 <Tooltip>
854 <TooltipTrigger
855 render={
856 <Button
857 type="button"
858 size="icon-xs"
859 variant="ghost-muted"
860 className="shrink-0"
861 onClick={() => copyToClipboard(updateCommand, { providerName: displayName })}
862 aria-label="Copy update command"
863 >
864 <CopyIcon className="size-3" />
865 </Button>
866 }
867 />
868 <TooltipPopup side="top">Copy command</TooltipPopup>
869 </Tooltip>
870 </div>
871 ) : null}
872 </div>
873 </PopoverPopup>
874 </Popover>
875 ) : null;
876
877 if (mode === "list") {
878 return (
879 <div
880 data-slot="settings-row"
881 className={cn(
882 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
883 selected ? "bg-muted/45" : "hover:bg-muted/25",
884 )}
885 >
886 <div
887 className={cn(
888 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
889 !enabled && !selected && "opacity-60 group-hover:opacity-100",
890 )}
891 >
892 <button
893 type="button"
894 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
895 onClick={onSelect}
896 aria-label={`Select ${displayName}`}
897 aria-pressed={selected}
898 />
899 {titleIconNode}
900 <span className="min-w-0 flex-1">
901 <span className="flex min-w-0 items-center gap-2">
902 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
903 {versionLabel ? (
904 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
905 {versionLabel}
906 </code>
907 ) : null}
908 {versionAdvisoryNode}
909 </span>
910 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
911 {statusDotNode ? (
912 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
913 ) : null}
914 <ProviderStatusDiagnostic detail={statusDiagnostic}>
915 <span
916 tabIndex={statusDiagnostic ? 0 : undefined}
917 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
918 >
919 {summary.headline}
920 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
921 </span>
922 </ProviderStatusDiagnostic>
923 </span>
924 </span>
925 </div>
926 <span className="flex h-5 shrink-0 items-center">
927 <Switch
928 checked={enabled}
929 disabled={readOnly}
930 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
931 aria-label={`Enable ${displayName}`}
932 />
933 </span>
934 </div>
935 );
936 }
937
938 const editorHeaderAction = (
939 <div className="flex shrink-0 items-center gap-1.5">
940 {driverOption?.badgeLabel ? (
941 <Badge variant="warning" size="sm" className="shrink-0">
942 {driverOption.badgeLabel}
943 </Badge>
944 ) : null}
945 {versionCodeNode}
946 {versionAdvisoryNode}
947 <span
948 inert={readOnly}
949 aria-disabled={readOnly || undefined}
950 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
951 >
952 {titleTailNode}
953 {onDelete ? (
954 <Button
955 type="button"
956 size="icon-xs"
957 variant="ghost-destructive"
958 disabled={readOnly}
959 onClick={onDelete}
960 aria-label={`Delete instance ${instanceId}`}
961 >
962 <Trash2Icon />
963 </Button>
964 ) : null}
965 </span>
966 </div>
967 );
968
969 const runtimeFields = driverOption ? (
970 <ProviderSettingsForm
971 definition={driverOption}
972 value={instance.config}
973 idPrefix={`provider-instance-${instanceId}`}
974 variant="settings"
975 onChange={updateConfig}
976 />
977 ) : (
978 <SettingsRow
979 title="Driver"
980 description={
981 <span>
982 This instance uses <code className="text-foreground">{String(instance.driver)}</code>,
983 which is not available in this build. Its configuration is preserved.
984 </span>
985 }
986 />
987 );
988
989 return (
990 <>
991 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
992 <SettingsRow
993 title="Display name"
994 status={
995 <>
996 <ProviderStatusDiagnostic detail={statusDiagnostic}>
997 <div
998 tabIndex={statusDiagnostic ? 0 : undefined}
999 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
1000 >
1001 {editorStatusNode}
1002 </div>
1003 </ProviderStatusDiagnostic>
1004 {urlAuthAction && onAcceptUrlAuth ? (
1005 <div className="grid max-w-xl gap-1.5 pt-1 text-xs">
1006 <p>{urlAuthAction.message}</p>
1007 <code className="break-all text-2xs">{urlAuthAction.url}</code>
1008 <Button
1009 render={
1010 <a
1011 href={urlAuthAction.url}
1012 target="_blank"
1013 rel="noopener noreferrer"
1014 onClick={() => onAcceptUrlAuth(urlAuthAction)}
1015 />
1016 }
1017 size="xs"
1018 variant="outline"
1019 className="w-fit"
1020 disabled={readOnly}
1021 >
1022 <ExternalLinkIcon />
1023 Continue authentication
1024 </Button>
1025 </div>
1026 ) : null}
1027 </>
1028 }
1029 control={
1030 <div
1031 inert={readOnly}
1032 aria-disabled={readOnly || undefined}
1033 className={cn(
1034 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
1035 readOnly && "opacity-50 select-none",
1036 )}
1037 >
1038 <ProviderAccentColorPicker
1039 layout="inline"
1040 displayName={displayName}
1041 value={accentColor}
1042 onCommit={updateAccentColor}
1043 commitDelayMs={120}
1044 />
1045 <DraftInput
1046 id={`provider-instance-${instanceId}-display-name`}
1047 size="sm"
1048 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
1049 value={instance.displayName ?? ""}
1050 onCommit={updateDisplayName}
1051 placeholder={driverOption?.label ?? "Instance label"}
1052 spellCheck={false}
1053 />
1054 </div>
1055 }
1056 />
1057 </SettingsSection>
1058
1059 {setup || environmentFields.length > 0 ? (
1060 <SettingsSection title="Setup">
1061 {setup}
1062 <div
1063 inert={readOnly}
1064 aria-disabled={readOnly || undefined}
1065 className={readOnly ? "opacity-50 select-none" : undefined}
1066 >
1067 {environmentFields.length > 0 ? (
1068 <>
1069 {environmentFields.map((field) => (
1070 <ProviderEnvironmentFieldRow
1071 key={field.name}
1072 field={field}
1073 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
1074 idPrefix={`provider-instance-${instanceId}`}
1075 onCommit={updateEnvironmentField}
1076 onRemove={removeEnvironmentField}
1077 />
1078 ))}
1079 </>
1080 ) : null}
1081 </div>
1082 </SettingsSection>
1083 ) : null}
1084
1085 {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? (
1086 <div
1087 inert={readOnly}
1088 aria-disabled={readOnly || undefined}
1089 className={readOnly ? "opacity-50 select-none" : undefined}
1090 >
1091 <FoldedSettingsSection
1092 key={instanceId}
1093 id={`provider-instance-${instanceId}-runtime`}
1094 title="Runtime"
1095 headerPlacement="outside"
1096 >
1097 {runtime ?? runtimeFields}
1098 </FoldedSettingsSection>
1099 </div>
1100 ) : !driverOption || deriveProviderSettingsFields(driverOption).length > 0 ? (
1101 <SettingsSection
1102 title="Runtime"
1103 inert={readOnly}
1104 aria-disabled={readOnly || undefined}
1105 className={readOnly ? "opacity-50 select-none" : undefined}
1106 >
1107 {runtimeFields}
1108 </SettingsSection>
1109 ) : null}
1110
1111 <SettingsSection
1112 title="Environment"
1113 inert={readOnly}
1114 aria-disabled={readOnly || undefined}
1115 className={readOnly ? "opacity-50 select-none" : undefined}
1116 >
1117 <ProviderEnvironmentSection
1118 environment={genericEnvironment}
1119 onChange={updateGenericEnvironment}
1120 />
1121 </SettingsSection>
1122 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1123 <AcpSessionManagementSection
1124 environmentId={environmentId}
1125 instanceId={instanceId}
1126 provider={liveProvider}
1127 projects={acpProjects}
1128 readOnly={readOnly}
1129 />
1130 ) : null}
1131
1132 {driverOption !== undefined ? (
1133 <SettingsSection title="Models">
1134 <div className="px-3 py-3 sm:px-4">
1135 <p className="mb-3 text-xs text-muted-foreground">
1136 Favorites, visibility, and ordering are saved on this device. Custom models are saved
1137 on the selected environment.
1138 </p>
1139 <ProviderModelsSection
1140 canManageCustomModels={!readOnly}
1141 canWritePreferences={canWriteSettings}
1142 instanceId={instanceId}
1143 driverKind={driverKind}
1144 models={modelsForDisplay}
1145 customModels={customModels}
1146 hiddenModels={hiddenModels}
1147 favoriteModels={favoriteModels}
1148 modelOrder={modelOrder}
1149 onChange={updateCustomModels}
1150 onHiddenModelsChange={onHiddenModelsChange}
1151 onFavoriteModelsChange={onFavoriteModelsChange}
1152 onModelOrderChange={onModelOrderChange}
1153 />
1154 </div>
1155 </SettingsSection>
1156 ) : null}
1157 </>
1158 );
1159}