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

ProviderInstanceCard.tsx

1,160 lines41.1 KB

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