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