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
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 <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 onUpdate: (nextInstance: ProviderInstanceConfig) => void;
482 /**
483 * Pass `undefined` to hide the delete footer entirely. Built-in default
484 * instance slots use `undefined` — they can't be deleted without losing
485 * the slot, and their "reset to defaults" affordance lives on an outer
486 * reset button instead. Explicit `| undefined` in the type accommodates
487 * `exactOptionalPropertyTypes: true`, where an absent key and
488 * `{ onDelete: undefined }` are treated as distinct shapes.
489 */
490 readonly onDelete?: (() => void) | undefined;
491 /**
492 * Optional outer reset button rendered next to the driver icon. Built-in
493 * default slots supply a reset-to-factory control here; custom instances
494 * omit it.
495 */
496 readonly headerAction?: ReactNode | undefined;
497 readonly setup?: ReactNode;
498 readonly runtime?: ReactNode;
499 readonly hiddenModels: ReadonlyArray<string>;
500 readonly favoriteModels: ReadonlyArray<string>;
501 readonly modelOrder: ReadonlyArray<string>;
502 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
503 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
504 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
505 readonly onRunUpdate?: (() => void) | undefined;
506 readonly onInstallRecommended?: (() => void) | undefined;
507 readonly isUpdating?: boolean | undefined;
508 readonly onAcceptUrlAuth?: ((action: AcpRegistryUrlAuthAction) => void) | undefined;
509 readonly environmentId?: EnvironmentId | undefined;
510 readonly acpProjects?:
511 | ReadonlyArray<{
512 readonly id: ProjectId;
513 readonly title: string;
514 readonly workspaceRoot: string;
515 }>
516 | undefined;
517}
518
519const EMPTY_ACP_PROJECTS: NonNullable<ProviderInstanceCardProps["acpProjects"]> = [];
520
521/**
522 * Renders one provider instance as either a compact selectable list row or
523 * the full editor shown beside that list. Both modes use the same enabled
524 * state and provider metadata.
525 *
526 * Behavior notes:
527 * - `liveProvider` is matched by the caller via `instanceId`; when no
528 * match is available (e.g. the server hasn't checked it yet, or the
529 * driver is not shipped by the current build) the card still renders
530 * with a neutral "checking" summary.
531 * - Unknown drivers (`driverOption === undefined`) get a read-only
532 * notice instead of editable fields, so fork instances round-trip
533 * without accidentally destroying their config.
534 * - The enabled Switch writes to the envelope's `instance.enabled`
535 * field, which is the single enabled flag: the server folds any legacy
536 * driver-specific `config.enabled` into the envelope on load and both
537 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
538 * false wins, then envelope, then config, then the driver default).
539 */
540export function ProviderInstanceCard({
541 instanceId,
542 instance,
543 driverOption,
544 liveProvider,
545 mode,
546 selected = false,
547 onSelect,
548 readOnly = false,
549 onUpdate,
550 onDelete,
551 headerAction,
552 setup,
553 runtime,
554 hiddenModels,
555 favoriteModels,
556 modelOrder,
557 onHiddenModelsChange,
558 onFavoriteModelsChange,
559 onModelOrderChange,
560 onRunUpdate,
561 onInstallRecommended,
562 isUpdating = false,
563 onAcceptUrlAuth,
564 environmentId,
565 acpProjects = EMPTY_ACP_PROJECTS,
566}: ProviderInstanceCardProps) {
567 const enabled = resolveProviderInstanceEnabled(instance);
568 const compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
569 // A locally disabled provider reads "Disabled" with a muted dot even if its
570 // last server status is stale. Enabled providers use the server status.
571 const statusKey: ProviderStatusKey = enabled
572 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
573 : "disabled";
574 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
575 const summary = enabled
576 ? getProviderSummary(liveProvider)
577 : { headline: "Disabled", detail: null };
578 const authEmail = liveProvider?.auth.email?.trim();
579 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
580 const authLabel =
581 enabled && liveProvider?.auth.status === "authenticated"
582 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
583 : null;
584 const versionLabel = getProviderVersionLabel(liveProvider?.version);
585 const versionAdvisory = getProviderVersionAdvisoryPresentation(
586 liveProvider?.versionAdvisory,
587 liveProvider?.compatibilityAdvisory,
588 enabled,
589 );
590 const updateCommand = versionAdvisory?.updateCommand ?? null;
591 const hasCompatibilityWarning =
592 compatibility !== undefined &&
593 compatibility.status !== "supported" &&
594 compatibility.status !== "unknown";
595 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
596 const onRunVersionAction = versionAdvisory?.targetVersion ? onInstallRecommended : onRunUpdate;
597 const urlAuthAction = liveProvider?.auth.action;
598 const displayName =
599 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
600 const accentColor = normalizeProviderAccentColor(instance.accentColor);
601 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
602 onCopy: ({ providerName }) => {
603 toastManager.add({
604 type: "success",
605 title: `${providerName} update command copied`,
606 description: "Run it in a terminal when you are ready to update.",
607 });
608 },
609 onError: (error, { providerName }) => {
610 toastManager.add(
611 stackedThreadToast({
612 type: "error",
613 title: `Could not copy ${providerName} update command`,
614 description: error.message,
615 }),
616 );
617 },
618 });
619
620 // Narrow `instance.driver` for callers that key on the closed
621 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
622 // fork drivers pass through as `null` and those callers fall back to
623 // verbatim behaviour.
624 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
625 ? instance.driver
626 : null;
627 const customModels =
628 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
629 // Server-returned models may lag behind settings writes. Treat server
630 // models as the source for built-ins only; custom rows come directly
631 // from the current instance config so add/remove reflects immediately.
632 const modelsForDisplay = deriveProviderModelsForDisplay({
633 liveModels: liveProvider?.models,
634 customModels,
635 });
636 const updateDisplayName = (value: string) => {
637 const trimmed = value.trim();
638 const { displayName: _omit, ...rest } = instance;
639 onUpdate(
640 trimmed.length > 0
641 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
642 : (rest as ProviderInstanceConfig),
643 );
644 };
645
646 const updateEnabled = (value: boolean) => {
647 onUpdate({ ...instance, enabled: value });
648 };
649
650 const updateAccentColor = (value: string) => {
651 const normalized = normalizeProviderAccentColor(value);
652 const { accentColor: _omit, ...rest } = instance;
653 onUpdate(
654 normalized
655 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
656 : (rest as ProviderInstanceConfig),
657 );
658 };
659
660 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
661 const { config: _omit, ...rest } = instance;
662 onUpdate(
663 nextConfig !== undefined
664 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
665 : (rest as ProviderInstanceConfig),
666 );
667 };
668
669 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
670 const nextConfig = nextConfigBlobWithValue(
671 instance.config,
672 "customModels",
673 next.map(toCustomModelSetting),
674 );
675 const { config: _omit, ...rest } = instance;
676 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
677 };
678
679 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
680 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
681 const { environment: _omit, ...rest } = instance;
682 onUpdate(
683 cleaned.length > 0
684 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
685 : (rest as ProviderInstanceConfig),
686 );
687 };
688 // Drivers that need a named secret (Cursor's API key) get a dedicated field;
689 // the generic editor only shows the remaining variables.
690 const environmentFields = driverOption?.environmentFields ?? [];
691 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
692 const genericEnvironment = providerEnvironmentWithoutNames(
693 instance.environment,
694 environmentFieldNames,
695 );
696 const updateGenericEnvironment = (
697 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
698 ) => {
699 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
700 environmentFieldNames.has(variable.name),
701 );
702 updateEnvironment([...dedicatedEnvironment, ...environment]);
703 };
704 const updateEnvironmentField = (field: ProviderEnvironmentFieldDefinition, value: string) => {
705 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
706 };
707 const removeEnvironmentField = (field: ProviderEnvironmentFieldDefinition) => {
708 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
709 };
710
711 const titleIconNode = (
712 <ProviderInstanceIcon
713 driverKind={driverKind ?? instance.driver}
714 displayName={displayName}
715 accentColor={accentColor}
716 acpRegistryAgentId={readConfigString(instance.config, "agentId") ?? undefined}
717 acpRegistryIconUrl={readConfigString(instance.config, "registryIconUrl") ?? undefined}
718 showBadge={Boolean(accentColor)}
719 className="size-5"
720 iconClassName="size-4 text-foreground/80"
721 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
722 />
723 );
724
725 const titleTailNode = headerAction ? (
726 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
727 ) : null;
728
729 const versionCodeNode = versionLabel ? (
730 <code className="text-xs text-muted-foreground">{versionLabel}</code>
731 ) : null;
732
733 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
734 const statusDotNode =
735 statusKey === "warning" || statusKey === "error" ? (
736 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
737 ) : null;
738 const needsAttention = statusKey === "warning" || statusKey === "error";
739 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
740 // Keep compatibility copy compact; the version popover carries the explanation.
741 const inlineStatusDetail = hasCompatibilityWarning
742 ? compatibility?.status === "broken"
743 ? "Incompatible"
744 : compatibility?.status === "unsupported"
745 ? "Unsupported"
746 : "Limited support"
747 : summary.detail;
748 const editorStatusNode =
749 isAuthenticated && authEmail ? (
750 <>
751 {needsAttention ? statusDotNode : null}
752 <span>Authenticated as</span>
753 <ProviderAuthEmail email={authEmail} />
754 {authLabel ? <span>· {authLabel}</span> : null}
755 {inlineStatusDetail ? (
756 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
757 ) : null}
758 </>
759 ) : (
760 <>
761 {statusDotNode}
762 <span>{summary.headline}</span>
763 {inlineStatusDetail ? (
764 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
765 ) : null}
766 </>
767 );
768 if (mode === "list") {
769 return (
770 <div
771 data-slot="settings-row"
772 className={cn(
773 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
774 selected ? "bg-muted/45" : "hover:bg-muted/25",
775 )}
776 >
777 <div
778 className={cn(
779 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
780 !enabled && !selected && "opacity-60 group-hover:opacity-100",
781 )}
782 >
783 <button
784 type="button"
785 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
786 onClick={onSelect}
787 aria-label={`Select ${displayName}`}
788 aria-pressed={selected}
789 />
790 {titleIconNode}
791 <span className="min-w-0 flex-1">
792 <span className="flex min-w-0 items-center gap-2">
793 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
794 {versionLabel ? (
795 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
796 {versionLabel}
797 </code>
798 ) : null}
799 {versionAdvisory ? (
800 hasCompatibilityWarning ? (
801 <Tooltip>
802 <TooltipTrigger
803 render={
804 <span
805 tabIndex={0}
806 role="img"
807 aria-label={versionAdvisory.title}
808 className="pointer-events-auto relative inline-flex shrink-0 text-warning"
809 >
810 <VersionAdvisoryIcon className="size-3.5" />
811 </span>
812 }
813 />
814 <TooltipPopup side="top">{versionAdvisory.detail}</TooltipPopup>
815 </Tooltip>
816 ) : updateCommand ? (
817 <Tooltip>
818 <TooltipTrigger
819 render={
820 <Button
821 type="button"
822 size="icon-micro"
823 variant="ghost-muted"
824 className="pointer-events-auto relative shrink-0"
825 aria-label={`Copy ${displayName} update command`}
826 onClick={() =>
827 copyToClipboard(updateCommand, { providerName: displayName })
828 }
829 >
830 <ArrowUpCircleIcon className="size-3.5" />
831 </Button>
832 }
833 />
834 <TooltipPopup side="top">Copy update command</TooltipPopup>
835 </Tooltip>
836 ) : (
837 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
838 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
839 </span>
840 )
841 ) : null}
842 </span>
843 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
844 {statusDotNode ? (
845 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
846 ) : null}
847 <ProviderStatusDiagnostic detail={statusDiagnostic}>
848 <span
849 tabIndex={statusDiagnostic ? 0 : undefined}
850 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
851 >
852 {summary.headline}
853 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
854 </span>
855 </ProviderStatusDiagnostic>
856 </span>
857 </span>
858 </div>
859 <span className="flex h-5 shrink-0 items-center">
860 <Switch
861 checked={enabled}
862 disabled={readOnly}
863 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
864 aria-label={`Enable ${displayName}`}
865 />
866 </span>
867 </div>
868 );
869 }
870
871 const editorHeaderAction = (
872 <div className="flex shrink-0 items-center gap-1.5">
873 {driverOption?.badgeLabel ? (
874 <Badge variant="warning" size="sm" className="shrink-0">
875 {driverOption.badgeLabel}
876 </Badge>
877 ) : null}
878 {versionCodeNode}
879 <span
880 inert={readOnly}
881 aria-disabled={readOnly || undefined}
882 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
883 >
884 {versionAdvisory ? (
885 <Popover>
886 <Tooltip>
887 <TooltipTrigger
888 render={
889 <PopoverTrigger
890 render={
891 <Button
892 type="button"
893 size="icon-xs"
894 variant="ghost-muted"
895 aria-label={`${versionAdvisory.title} — view details`}
896 >
897 <VersionAdvisoryIcon
898 className={cn(hasCompatibilityWarning && "text-warning")}
899 />
900 </Button>
901 }
902 />
903 }
904 />
905 <TooltipPopup side="top">{versionAdvisory.title}</TooltipPopup>
906 </Tooltip>
907 <PopoverPopup side="bottom" align="end" width="md">
908 <div className="grid min-w-0 gap-3">
909 <div className="grid gap-0.5">
910 <p className="text-sm font-semibold leading-tight text-foreground">
911 {versionAdvisory.title}
912 </p>
913 <p
914 className={cn(
915 "text-xs leading-snug",
916 versionAdvisory.emphasis === "strong"
917 ? "text-warning"
918 : "text-muted-foreground",
919 )}
920 >
921 {versionAdvisory.detail}
922 </p>
923 </div>
924 {onRunVersionAction ? (
925 <Button
926 type="button"
927 size="xs"
928 variant="outline"
929 className="w-full"
930 disabled={isUpdating}
931 onClick={onRunVersionAction}
932 >
933 {isUpdating ? <Spinner /> : <DownloadIcon />}
934 {isUpdating
935 ? "Updating"
936 : versionAdvisory.targetVersion
937 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
938 : "Update now"}
939 </Button>
940 ) : null}
941 {onRunVersionAction && updateCommand ? (
942 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
943 <span aria-hidden className="h-px flex-1 bg-border" />
944 or, update manually using
945 <span aria-hidden className="h-px flex-1 bg-border" />
946 </div>
947 ) : null}
948 {updateCommand ? (
949 <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">
950 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
951 {updateCommand}
952 </code>
953 <Tooltip>
954 <TooltipTrigger
955 render={
956 <Button
957 type="button"
958 size="icon-xs"
959 variant="ghost-muted"
960 className="shrink-0"
961 onClick={() =>
962 copyToClipboard(updateCommand, { providerName: displayName })
963 }
964 aria-label="Copy update command"
965 >
966 <CopyIcon className="size-3" />
967 </Button>
968 }
969 />
970 <TooltipPopup side="top">Copy command</TooltipPopup>
971 </Tooltip>
972 </div>
973 ) : null}
974 </div>
975 </PopoverPopup>
976 </Popover>
977 ) : null}
978 {titleTailNode}
979 {onDelete ? (
980 <Button
981 type="button"
982 size="icon-xs"
983 variant="ghost-destructive"
984 disabled={readOnly}
985 onClick={onDelete}
986 aria-label={`Delete instance ${instanceId}`}
987 >
988 <Trash2Icon />
989 </Button>
990 ) : null}
991 </span>
992 </div>
993 );
994
995 const runtimeFields = driverOption ? (
996 <ProviderSettingsForm
997 definition={driverOption}
998 value={instance.config}
999 idPrefix={`provider-instance-${instanceId}`}
1000 variant="settings"
1001 onChange={updateConfig}
1002 />
1003 ) : (
1004 <SettingsRow
1005 title="Driver"
1006 description={
1007 <span>
1008 This instance uses <code className="text-foreground">{String(instance.driver)}</code>,
1009 which is not available in this build. Its configuration is preserved.
1010 </span>
1011 }
1012 />
1013 );
1014
1015 return (
1016 <>
1017 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
1018 <SettingsRow
1019 title="Display name"
1020 status={
1021 <>
1022 <ProviderStatusDiagnostic detail={statusDiagnostic}>
1023 <div
1024 tabIndex={statusDiagnostic ? 0 : undefined}
1025 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
1026 >
1027 {editorStatusNode}
1028 </div>
1029 </ProviderStatusDiagnostic>
1030 {urlAuthAction && onAcceptUrlAuth ? (
1031 <div className="grid max-w-xl gap-1.5 pt-1 text-xs">
1032 <p>{urlAuthAction.message}</p>
1033 <code className="break-all text-2xs">{urlAuthAction.url}</code>
1034 <Button
1035 render={
1036 <a
1037 href={urlAuthAction.url}
1038 target="_blank"
1039 rel="noopener noreferrer"
1040 onClick={() => onAcceptUrlAuth(urlAuthAction)}
1041 />
1042 }
1043 size="xs"
1044 variant="outline"
1045 className="w-fit"
1046 disabled={readOnly}
1047 >
1048 <ExternalLinkIcon />
1049 Continue authentication
1050 </Button>
1051 </div>
1052 ) : null}
1053 </>
1054 }
1055 control={
1056 <div
1057 inert={readOnly}
1058 aria-disabled={readOnly || undefined}
1059 className={cn(
1060 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
1061 readOnly && "opacity-50 select-none",
1062 )}
1063 >
1064 <ProviderAccentColorPicker
1065 layout="inline"
1066 displayName={displayName}
1067 value={accentColor}
1068 onCommit={updateAccentColor}
1069 commitDelayMs={120}
1070 />
1071 <DraftInput
1072 id={`provider-instance-${instanceId}-display-name`}
1073 size="sm"
1074 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
1075 value={instance.displayName ?? ""}
1076 onCommit={updateDisplayName}
1077 placeholder={driverOption?.label ?? "Instance label"}
1078 spellCheck={false}
1079 />
1080 </div>
1081 }
1082 />
1083 </SettingsSection>
1084
1085 {setup || environmentFields.length > 0 ? (
1086 <SettingsSection title="Setup">
1087 {setup}
1088 <div
1089 inert={readOnly}
1090 aria-disabled={readOnly || undefined}
1091 className={readOnly ? "opacity-50 select-none" : undefined}
1092 >
1093 {environmentFields.length > 0 ? (
1094 <>
1095 {environmentFields.map((field) => (
1096 <ProviderEnvironmentFieldRow
1097 key={field.name}
1098 field={field}
1099 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
1100 idPrefix={`provider-instance-${instanceId}`}
1101 onCommit={updateEnvironmentField}
1102 onRemove={removeEnvironmentField}
1103 />
1104 ))}
1105 </>
1106 ) : null}
1107 </div>
1108 </SettingsSection>
1109 ) : null}
1110
1111 {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? (
1112 <div
1113 inert={readOnly}
1114 aria-disabled={readOnly || undefined}
1115 className={readOnly ? "opacity-50 select-none" : undefined}
1116 >
1117 <FoldedSettingsSection
1118 key={instanceId}
1119 id={`provider-instance-${instanceId}-runtime`}
1120 title="Runtime"
1121 headerPlacement="outside"
1122 >
1123 {runtime ?? runtimeFields}
1124 </FoldedSettingsSection>
1125 </div>
1126 ) : !driverOption || deriveProviderSettingsFields(driverOption).length > 0 ? (
1127 <SettingsSection
1128 title="Runtime"
1129 inert={readOnly}
1130 aria-disabled={readOnly || undefined}
1131 className={readOnly ? "opacity-50 select-none" : undefined}
1132 >
1133 {runtimeFields}
1134 </SettingsSection>
1135 ) : null}
1136
1137 <SettingsSection
1138 title="Environment"
1139 inert={readOnly}
1140 aria-disabled={readOnly || undefined}
1141 className={readOnly ? "opacity-50 select-none" : undefined}
1142 >
1143 <ProviderEnvironmentSection
1144 environment={genericEnvironment}
1145 onChange={updateGenericEnvironment}
1146 />
1147 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1148 <AcpSessionManagementSection
1149 environmentId={environmentId}
1150 instanceId={instanceId}
1151 provider={liveProvider}
1152 projects={acpProjects}
1153 readOnly={readOnly}
1154 />
1155 ) : null}
1156 </SettingsSection>
1157
1158 {driverOption !== undefined ? (
1159 <SettingsSection
1160 title="Models"
1161 inert={readOnly}
1162 aria-disabled={readOnly || undefined}
1163 className={readOnly ? "opacity-50 select-none" : undefined}
1164 >
1165 <div className="px-3 py-3 sm:px-4">
1166 <p className="mb-3 text-xs text-muted-foreground">
1167 Favorites, visibility, and ordering are saved on this device. Custom models are saved
1168 on the selected environment.
1169 </p>
1170 <ProviderModelsSection
1171 instanceId={instanceId}
1172 driverKind={driverKind}
1173 models={modelsForDisplay}
1174 customModels={customModels}
1175 hiddenModels={hiddenModels}
1176 favoriteModels={favoriteModels}
1177 modelOrder={modelOrder}
1178 onChange={updateCustomModels}
1179 onHiddenModelsChange={onHiddenModelsChange}
1180 onFavoriteModelsChange={onFavoriteModelsChange}
1181 onModelOrderChange={onModelOrderChange}
1182 />
1183 </div>
1184 </SettingsSection>
1185 ) : null}
1186 </>
1187 );
1188}