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

ProviderInstanceCard.tsx

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