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