Open History to see the last commit
1import { Spinner } from "~/components/ui/spinner";
2
3import {
4 AlertTriangleIcon,
5 CheckIcon,
6 ArrowUpCircleIcon,
7 CopyIcon,
8 DownloadIcon,
9 ExternalLinkIcon,
10 LayersIcon,
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 { useClientSettings } from "../../hooks/useSettings";
41import { useStableCallback } from "../../hooks/useStableCallback";
42import { normalizeProviderAccentColor } from "../../providerInstances";
43import { Badge } from "../ui/badge";
44import { Button } from "../ui/button";
45import { MorphIcon } from "~/components/MorphIcon";
46import { DraftInput } from "../ui/draft-input";
47import { SecretInput } from "./SecretInput";
48import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
49import { Switch } from "../ui/switch";
50import { stackedThreadToast, toastManager } from "../ui/toast";
51import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
52import type {
53 ProviderClientDefinition,
54 ProviderEnvironmentField,
55} from "@t3tools/provider-core/client";
56import { deriveProviderSettingsFields, ProviderSettingsForm } from "./ProviderSettingsForm";
57import { ProviderModelsSection } from "./ProviderModelsSection";
58import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
59import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
60import { RedactedSensitiveText } from "./RedactedSensitiveText";
61import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
62import { AcpSessionManagementSection } from "./AcpSessionManagementSection";
63import { FoldedSettingsSection } from "./FoldedSettingsSection";
64import { readCodexSetupMode } from "./CodexSetupSection.logic";
65import {
66 getProviderVersionAdvisoryPresentation,
67 PROVIDER_STATUS_STYLES,
68 getProviderStatusKey,
69 getProviderSummary,
70 getProviderVersionLabel,
71} from "./providerStatus";
72
73const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
74
75function ProviderStatusDiagnostic({
76 detail,
77 children,
78}: {
79 detail: string | null;
80 children: ReactElement;
81}) {
82 if (!detail) return children;
83 return (
84 <Tooltip>
85 <TooltipTrigger render={children} />
86 <TooltipPopup side="top">{detail}</TooltipPopup>
87 </Tooltip>
88 );
89}
90
91let environmentVariableDraftId = 0;
92const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;
93
94type EnvironmentDraftRow = {
95 readonly id: string;
96 readonly name: string;
97 readonly value: string;
98 readonly sensitive: boolean;
99 readonly valueRedacted?: boolean;
100};
101
102function makeEnvironmentDraftRow(
103 variable: ProviderInstanceEnvironmentVariable,
104 index: number,
105): EnvironmentDraftRow {
106 return {
107 id: `${index}:${variable.name}`,
108 name: variable.name,
109 value: variable.value,
110 sensitive: variable.sensitive,
111 ...(variable.valueRedacted !== undefined ? { valueRedacted: variable.valueRedacted } : {}),
112 };
113}
114
115function providerEnvironmentsEqual(
116 left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
117 right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
118): boolean {
119 return (
120 left.length === right.length &&
121 left.every((variable, index) => {
122 const other = right[index];
123 return (
124 other !== undefined &&
125 variable.name === other.name &&
126 variable.value === other.value &&
127 variable.sensitive === other.sensitive &&
128 variable.valueRedacted === other.valueRedacted
129 );
130 })
131 );
132}
133
134function readConfigString(config: unknown, key: string): string | null {
135 if (config === null || typeof config !== "object") return null;
136 const value = (config as Record<string, unknown>)[key];
137 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
138}
139
140/** Preserve explicit empty arrays/objects; clearing a custom list differs from selecting driver defaults. */
141function nextConfigBlobWithValue(
142 config: unknown,
143 key: string,
144 value: unknown,
145): Record<string, unknown> {
146 const base: Record<string, unknown> =
147 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
148 base[key] = value;
149 return base;
150}
151
152export function deriveProviderModelsForDisplay(input: {
153 readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
154 readonly customModels: ReadonlyArray<CustomModelDefinition>;
155}): ReadonlyArray<ServerProviderModel> {
156 const liveCustomModelsBySlug = new Map(
157 Arr.filterMap(input.liveModels ?? [], (model) =>
158 model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
159 ),
160 );
161 const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
162 const serverSlugs = new Set(serverModels.map((model) => model.slug));
163 const customModels = input.customModels.flatMap((entry) =>
164 serverSlugs.has(entry.slug)
165 ? []
166 : [
167 {
168 slug: entry.slug,
169 name: entry.name,
170 isCustom: true,
171 capabilities:
172 entry.capabilities ?? liveCustomModelsBySlug.get(entry.slug)?.capabilities ?? null,
173 },
174 ],
175 );
176 return [...serverModels, ...customModels];
177}
178
179function ProviderAuthEmail(props: { readonly email: string | undefined }) {
180 const email = props.email?.trim();
181 if (!email) return null;
182
183 return (
184 <RedactedSensitiveText
185 value={email}
186 ariaLabel="Toggle account email visibility"
187 revealTooltip="Click to reveal email"
188 hideTooltip="Click to hide email"
189 className="max-w-full truncate"
190 />
191 );
192}
193
194function readProviderEnvironmentVariable(
195 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
196 name: string,
197): ProviderInstanceEnvironmentVariable | undefined {
198 return environment?.find((variable) => variable.name === name);
199}
200
201function providerEnvironmentWithoutNames(
202 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
203 names: ReadonlySet<string>,
204): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
205 return (environment ?? []).filter((variable) => !names.has(variable.name));
206}
207
208export function nextProviderEnvironmentWithFieldValue(
209 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined,
210 field: ProviderEnvironmentField,
211 value: string,
212): ReadonlyArray<ProviderInstanceEnvironmentVariable> {
213 const trimmed = value.trim();
214 const next: ProviderInstanceEnvironmentVariable[] = [];
215 let found = false;
216
217 for (const variable of environment ?? []) {
218 if (variable.name !== field.name) {
219 next.push(variable);
220 continue;
221 }
222 found = true;
223 if (trimmed.length > 0) {
224 next.push({
225 name: variable.name,
226 value: trimmed,
227 sensitive: field.sensitive ?? true,
228 });
229 }
230 }
231
232 if (!found && trimmed.length > 0) {
233 next.push({
234 name: field.name,
235 value: trimmed,
236 sensitive: field.sensitive ?? true,
237 });
238 }
239
240 return next;
241}
242
243function ProviderEnvironmentFieldRow(props: {
244 readonly field: ProviderEnvironmentField;
245 readonly variable: ProviderInstanceEnvironmentVariable | undefined;
246 readonly idPrefix: string;
247 readonly onCommit: (field: ProviderEnvironmentField, value: string) => void;
248 readonly onRemove: (field: ProviderEnvironmentField) => void;
249}) {
250 const inputId = `${props.idPrefix}-environment-${props.field.name}`;
251 const value = props.variable?.valueRedacted ? "" : (props.variable?.value ?? "");
252
253 return (
254 <SettingsRow
255 title={<label htmlFor={inputId}>{props.field.label}</label>}
256 description={props.field.description}
257 control={
258 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
259 {props.field.sensitive === false ? (
260 <DraftInput
261 id={inputId}
262 size="sm"
263 className="min-w-0 flex-1"
264 autoComplete="off"
265 value={value}
266 onCommit={(next) => props.onCommit(props.field, next)}
267 placeholder={props.field.placeholder}
268 spellCheck={false}
269 />
270 ) : (
271 <SecretInput
272 id={inputId}
273 size="sm"
274 className="min-w-0 flex-1"
275 value={value}
276 onCommit={(next) => props.onCommit(props.field, next)}
277 placeholder={props.field.placeholder}
278 configured={props.variable?.valueRedacted === true}
279 spellCheck={false}
280 />
281 )}
282 {props.variable ? (
283 <Button
284 type="button"
285 size="icon-sm"
286 variant="ghost-destructive"
287 onClick={() => props.onRemove(props.field)}
288 aria-label={`Clear ${props.field.label}`}
289 >
290 <XIcon className="size-3.5" />
291 </Button>
292 ) : null}
293 </div>
294 }
295 />
296 );
297}
298
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 {variable.sensitive ? (
409 <SecretInput
410 size="sm"
411 font="mono"
412 className="min-w-0 flex-1"
413 value={variable.valueRedacted ? "" : variable.value}
414 onCommit={(value) => updateVariable(variable.id, { value })}
415 placeholder="value"
416 configured={variable.valueRedacted === true}
417 spellCheck={false}
418 aria-label={`Environment variable value ${index + 1}`}
419 />
420 ) : (
421 <DraftInput
422 size="sm"
423 font="mono"
424 className="min-w-0 flex-1"
425 value={variable.valueRedacted ? "" : variable.value}
426 onCommit={(value) => updateVariable(variable.id, { value })}
427 autoComplete="off"
428 placeholder="value"
429 spellCheck={false}
430 aria-label={`Environment variable value ${index + 1}`}
431 />
432 )}
433 <Tooltip>
434 <TooltipTrigger
435 render={
436 <Button
437 type="button"
438 size="icon-micro"
439 variant="ghost-muted"
440 onClick={() => {
441 const sensitive = !variable.sensitive;
442 updateVariable(variable.id, {
443 sensitive,
444 ...(sensitive && variable.valueRedacted === undefined
445 ? {}
446 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
447 });
448 }}
449 aria-pressed={variable.sensitive}
450 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
451 >
452 <MorphIcon
453 className="size-3"
454 icon={variable.sensitive ? LockGlyph : LockOpen}
455 />
456 </Button>
457 }
458 />
459 <TooltipPopup side="top">
460 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
461 </TooltipPopup>
462 </Tooltip>
463 <Button
464 type="button"
465 size="icon-micro"
466 variant="ghost-destructive"
467 onClick={() => removeVariable(variable.id)}
468 aria-label={`Remove environment variable ${variable.name || index + 1}`}
469 >
470 <XIcon className="size-3" />
471 </Button>
472 </div>
473 ))}
474 <p className="text-xs text-muted-foreground">
475 Sensitive values are stored separately and never returned to the app.
476 </p>
477 </div>
478 ) : null}
479 </SettingsRow>
480 );
481}
482
483function ProjectOverrideInheritance({
484 projectEnabled,
485 deviceEnabled,
486}: {
487 readonly projectEnabled: boolean;
488 readonly deviceEnabled: boolean;
489}) {
490 const layers = [
491 { key: "project", label: "Project", enabled: projectEnabled, effective: true },
492 { key: "device", label: "Device", enabled: deviceEnabled, effective: false },
493 ];
494 return (
495 <Popover>
496 <Tooltip>
497 <TooltipTrigger
498 render={
499 <PopoverTrigger
500 render={
501 <Button
502 size="icon-micro"
503 variant="ghost-muted"
504 aria-label="Overridden for this project. Show where this value comes from"
505 />
506 }
507 />
508 }
509 >
510 <LayersIcon className="size-3 text-primary" />
511 </TooltipTrigger>
512 <TooltipPopup side="top">Overridden for this project</TooltipPopup>
513 </Tooltip>
514 <PopoverPopup align="end" width="md" padding="none">
515 <ol role="list" className="px-3 py-2.5 text-sm">
516 {layers.map((layer) => (
517 <li
518 key={layer.key}
519 className={cn(
520 "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 rounded-md px-2 py-1",
521 layer.effective && "bg-foreground/[0.06]",
522 )}
523 >
524 <span
525 className={cn(
526 "min-w-0 truncate",
527 layer.effective ? "font-medium text-foreground" : "text-muted-foreground",
528 )}
529 >
530 {layer.label}
531 </span>
532 <span
533 className={cn(
534 "flex items-center gap-1.5",
535 layer.effective ? "text-foreground" : "text-muted-foreground",
536 )}
537 >
538 {layer.enabled ? "On" : "Off"}
539 {layer.effective ? (
540 <CheckIcon aria-hidden className="size-3.5 shrink-0 text-primary" />
541 ) : (
542 <span aria-hidden className="size-3.5 shrink-0" />
543 )}
544 </span>
545 </li>
546 ))}
547 </ol>
548 </PopoverPopup>
549 </Popover>
550 );
551}
552
553interface ProjectOverrideControl {
554 readonly value: boolean | undefined;
555 readonly effectiveEnabled: boolean;
556 readonly onChange: (next: boolean) => void;
557 readonly onReset: () => void;
558}
559
560interface ProviderInstanceCardProps {
561 readonly instanceId: ProviderInstanceId;
562 readonly instance: ProviderInstanceConfig;
563 readonly driverOption: ProviderClientDefinition | undefined;
564 readonly liveProvider: ServerProvider | undefined;
565 readonly mode: "list" | "editor";
566 readonly selected?: boolean | undefined;
567 readonly onSelect?: (() => void) | undefined;
568 readonly readOnly?: boolean | undefined;
569 readonly canWriteSettings?: boolean;
570 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
571 readonly onDelete?: (() => void) | undefined;
572 readonly headerAction?: ReactNode | undefined;
573 readonly setup?: ReactNode;
574 readonly runtime?: ReactNode;
575 readonly hiddenModels: ReadonlyArray<string>;
576 readonly favoriteModels: ReadonlyArray<string>;
577 readonly modelOrder: ReadonlyArray<string>;
578 readonly onHiddenModelsChange: (
579 next: ReadonlyArray<string>,
580 affectedModels?: ReadonlyArray<string>,
581 ) => void;
582 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
583 readonly onToggleFavorite: (model: string) => void;
584 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
585 readonly onRunUpdate?: (() => void) | undefined;
586 readonly onInstallRecommended?: (() => void) | undefined;
587 readonly isUpdating?: boolean | undefined;
588 readonly onAcceptUrlAuth?: ((action: AcpRegistryUrlAuthAction) => void) | undefined;
589 readonly environmentId?: EnvironmentId | undefined;
590 readonly projectOverride?: ProjectOverrideControl | undefined;
591 readonly acpProjects?:
592 | ReadonlyArray<{
593 readonly id: ProjectId;
594 readonly title: string;
595 readonly workspaceRoot: string;
596 }>
597 | undefined;
598}
599
600const EMPTY_ACP_PROJECTS: NonNullable<ProviderInstanceCardProps["acpProjects"]> = [];
601const NO_CUSTOM_MODELS: ReadonlyArray<CustomModelDefinition> = [];
602
603/** Unknown drivers stay read-only to preserve fork config. projectOverride switches affect only the
604 * project, not instance.enabled. */
605export function ProviderInstanceCard({
606 instanceId,
607 instance,
608 driverOption,
609 liveProvider,
610 mode,
611 selected = false,
612 onSelect,
613 readOnly = false,
614 canWriteSettings = true,
615 onUpdate,
616 onDelete,
617 headerAction,
618 setup,
619 runtime,
620 hiddenModels,
621 favoriteModels,
622 modelOrder,
623 onHiddenModelsChange,
624 onFavoriteModelsChange,
625 onToggleFavorite,
626 onModelOrderChange,
627 onRunUpdate,
628 onInstallRecommended,
629 isUpdating = false,
630 onAcceptUrlAuth,
631 environmentId,
632 acpProjects = EMPTY_ACP_PROJECTS,
633 projectOverride,
634}: ProviderInstanceCardProps) {
635 const enabled = projectOverride?.effectiveEnabled ?? resolveProviderInstanceEnabled(instance);
636 const effectiveProvider = liveProvider && { ...liveProvider, enabled };
637 const compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
638 const statusKey = enabled ? getProviderStatusKey(effectiveProvider) : "disabled";
639 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
640 const summary = enabled
641 ? getProviderSummary(effectiveProvider)
642 : { headline: "Disabled", detail: null };
643 const authEmail = liveProvider?.auth.email?.trim();
644 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
645 const authLabel =
646 enabled && liveProvider?.auth.status === "authenticated"
647 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
648 : null;
649 const versionLabel = getProviderVersionLabel(liveProvider?.version);
650 const versionAdvisory = getProviderVersionAdvisoryPresentation(
651 liveProvider?.versionAdvisory,
652 liveProvider?.compatibilityAdvisory,
653 enabled,
654 );
655 const updateCommand = versionAdvisory?.updateCommand ?? null;
656 const updateState = liveProvider?.updateState;
657 const updateProgress = isUpdating
658 ? ((updateState?.status === "queued" || updateState?.status === "running"
659 ? updateState.message
660 : null) ?? "Starting update")
661 : null;
662 const updateProblem =
663 !isUpdating && (updateState?.status === "failed" || updateState?.status === "unchanged")
664 ? updateState.message
665 : null;
666 const hasCompatibilityWarning =
667 compatibility !== undefined &&
668 compatibility.status !== "supported" &&
669 compatibility.status !== "unknown";
670 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
671 const onRunVersionAction = readOnly
672 ? undefined
673 : versionAdvisory?.targetVersion
674 ? onInstallRecommended
675 : onRunUpdate;
676 const urlAuthAction = liveProvider?.auth.action;
677 const displayName =
678 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
679 const accentColor = normalizeProviderAccentColor(instance.accentColor);
680 const redesign = useClientSettings((settings) => settings.redesignEnabled);
681 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
682 onCopy: ({ providerName }) => {
683 toastManager.add({
684 type: "success",
685 title: `${providerName} update command copied`,
686 description: "Run it in a terminal when you are ready to update.",
687 });
688 },
689 onError: (error, { providerName }) => {
690 toastManager.add(
691 stackedThreadToast({
692 type: "error",
693 title: `Could not copy ${providerName} update command`,
694 description: error.message,
695 }),
696 );
697 },
698 });
699
700 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
701 ? instance.driver
702 : null;
703 const storedCustomModels =
704 instance.config !== null && typeof instance.config === "object"
705 ? (instance.config as Record<string, unknown>).customModels
706 : undefined;
707 const customModels =
708 instance.driver === "antigravity"
709 ? NO_CUSTOM_MODELS
710 : readCustomModelEntries(storedCustomModels);
711 const modelsForDisplay = deriveProviderModelsForDisplay({
712 liveModels: liveProvider?.models,
713 customModels,
714 });
715 const updateDisplayName = (value: string) => {
716 const trimmed = value.trim();
717 const { displayName: _omit, ...rest } = instance;
718 onUpdate(
719 trimmed.length > 0
720 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
721 : (rest as ProviderInstanceConfig),
722 );
723 };
724
725 const updateEnabled = (value: boolean) => {
726 if (projectOverride) {
727 projectOverride.onChange(value);
728 return;
729 }
730 onUpdate({ ...instance, enabled: value });
731 };
732
733 const updateAccentColor = (value: string) => {
734 const normalized = normalizeProviderAccentColor(value);
735 const { accentColor: _omit, ...rest } = instance;
736 onUpdate(
737 normalized
738 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
739 : (rest as ProviderInstanceConfig),
740 );
741 };
742
743 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
744 const { config: _omit, ...rest } = instance;
745 onUpdate(
746 nextConfig !== undefined
747 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
748 : (rest as ProviderInstanceConfig),
749 );
750 };
751
752 const updateCustomModels = useStableCallback((next: ReadonlyArray<CustomModelDefinition>) => {
753 const nextConfig = nextConfigBlobWithValue(
754 instance.config,
755 "customModels",
756 next.map(toCustomModelSetting),
757 );
758 const { config: _omit, ...rest } = instance;
759 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
760 });
761
762 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
763 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
764 const { environment: _omit, ...rest } = instance;
765 onUpdate(
766 cleaned.length > 0
767 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
768 : (rest as ProviderInstanceConfig),
769 );
770 };
771 const environmentFields = driverOption?.environmentFields ?? [];
772 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
773 const genericEnvironment = providerEnvironmentWithoutNames(
774 instance.environment,
775 environmentFieldNames,
776 );
777 const updateGenericEnvironment = (
778 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
779 ) => {
780 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
781 environmentFieldNames.has(variable.name),
782 );
783 updateEnvironment([...dedicatedEnvironment, ...environment]);
784 };
785 const updateEnvironmentField = (field: ProviderEnvironmentField, value: string) => {
786 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
787 };
788 const removeEnvironmentField = (field: ProviderEnvironmentField) => {
789 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
790 };
791
792 const titleIconNode = (
793 <ProviderInstanceIcon
794 driverKind={driverKind ?? instance.driver}
795 displayName={displayName}
796 accentColor={accentColor}
797 acpRegistryAgentId={
798 readConfigString(instance.config, "source") === "local"
799 ? undefined
800 : (readConfigString(instance.config, "agentId") ?? undefined)
801 }
802 acpRegistryIconUrl={
803 readConfigString(instance.config, "source") === "local"
804 ? undefined
805 : (readConfigString(instance.config, "registryIconUrl") ?? undefined)
806 }
807 showBadge={Boolean(accentColor)}
808 className="size-5"
809 iconClassName="size-4 text-foreground/80"
810 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
811 />
812 );
813
814 const titleTailNode = headerAction ? (
815 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
816 ) : null;
817
818 const versionCodeNode = versionLabel ? (
819 <code className="text-xs text-muted-foreground">{versionLabel}</code>
820 ) : null;
821
822 const statusDotNode =
823 statusKey === "warning" || statusKey === "error" ? (
824 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
825 ) : null;
826 const needsAttention = statusKey === "warning" || statusKey === "error";
827 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
828 const inlineStatusDetail = hasCompatibilityWarning
829 ? compatibility?.status === "broken"
830 ? "Incompatible"
831 : compatibility?.status === "unsupported"
832 ? "Unsupported"
833 : "Limited support"
834 : summary.detail;
835 const editorStatusNode =
836 isAuthenticated && authEmail ? (
837 <>
838 {needsAttention ? statusDotNode : null}
839 <span>Authenticated as</span>
840 <ProviderAuthEmail email={authEmail} />
841 {authLabel ? <span>· {authLabel}</span> : null}
842 {inlineStatusDetail ? (
843 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
844 ) : null}
845 </>
846 ) : (
847 <>
848 {statusDotNode}
849 <span>{summary.headline}</span>
850 {inlineStatusDetail ? (
851 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
852 ) : null}
853 </>
854 );
855 const versionAdvisoryNode = versionAdvisory ? (
856 <Popover>
857 <Tooltip>
858 <TooltipTrigger
859 render={
860 <PopoverTrigger
861 render={
862 <Button
863 type="button"
864 size={mode === "list" ? "icon-micro" : "icon-xs"}
865 variant="ghost-muted"
866 className={mode === "list" ? "pointer-events-auto relative shrink-0" : undefined}
867 aria-label={`${updateProgress ? "Updating" : versionAdvisory.title}, view details`}
868 >
869 {updateProgress ? (
870 <Spinner tone="muted" {...(mode === "list" ? { size: "sm" as const } : {})} />
871 ) : (
872 <VersionAdvisoryIcon
873 className={cn(
874 mode === "list" && "size-3.5",
875 hasCompatibilityWarning && "text-warning",
876 )}
877 />
878 )}
879 </Button>
880 }
881 />
882 }
883 />
884 <TooltipPopup side="top">
885 {updateProgress ? "Updating" : versionAdvisory.title}
886 </TooltipPopup>
887 </Tooltip>
888 <PopoverPopup side="bottom" align="end" width="md" aria-label={versionAdvisory.title}>
889 <div className="grid min-w-0 gap-3">
890 <div className="grid gap-0.5">
891 <p className="text-sm font-semibold leading-tight text-foreground">
892 {versionAdvisory.title}
893 </p>
894 <p
895 className={cn(
896 "text-xs leading-snug [overflow-wrap:anywhere]",
897 versionAdvisory.emphasis === "strong" ? "text-warning" : "text-muted-foreground",
898 )}
899 >
900 {versionAdvisory.detail}
901 </p>
902 </div>
903 {onRunVersionAction ? (
904 <Button
905 type="button"
906 size="xs"
907 variant="outline"
908 className="w-full"
909 disabled={isUpdating}
910 onClick={onRunVersionAction}
911 >
912 {isUpdating ? <Spinner /> : <DownloadIcon />}
913 {isUpdating
914 ? "Updating"
915 : versionAdvisory.targetVersion
916 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
917 : "Update now"}
918 </Button>
919 ) : null}
920 {updateProgress || updateProblem ? (
921 <p
922 aria-live="polite"
923 className={cn(
924 "text-xs leading-snug [overflow-wrap:anywhere]",
925 updateProblem ? "text-warning" : "text-muted-foreground",
926 )}
927 >
928 {updateProgress ?? updateProblem}
929 </p>
930 ) : null}
931 {onRunVersionAction && updateCommand ? (
932 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
933 <span aria-hidden className="h-px flex-1 bg-border" />
934 or, update manually using
935 <span aria-hidden className="h-px flex-1 bg-border" />
936 </div>
937 ) : null}
938 {updateCommand ? (
939 <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">
940 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
941 {updateCommand}
942 </code>
943 <Tooltip>
944 <TooltipTrigger
945 render={
946 <Button
947 type="button"
948 size="icon-xs"
949 variant="ghost-muted"
950 className="shrink-0"
951 onClick={() => copyToClipboard(updateCommand, { providerName: displayName })}
952 aria-label="Copy update command"
953 >
954 <CopyIcon className="size-3" />
955 </Button>
956 }
957 />
958 <TooltipPopup side="top">Copy command</TooltipPopup>
959 </Tooltip>
960 </div>
961 ) : null}
962 </div>
963 </PopoverPopup>
964 </Popover>
965 ) : null;
966
967 if (mode === "list") {
968 return (
969 <div
970 data-slot="settings-row"
971 className={cn(
972 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
973 selected ? "bg-muted/45 redesign:bg-foreground/[0.06]" : "hover:bg-muted/25",
974 )}
975 >
976 <div
977 className={cn(
978 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
979 !enabled && !selected && "opacity-60 group-hover:opacity-100",
980 )}
981 >
982 <button
983 type="button"
984 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
985 onClick={onSelect}
986 aria-label={`Select ${displayName}`}
987 aria-pressed={selected}
988 />
989 {titleIconNode}
990 <span className="min-w-0 flex-1">
991 <span className="flex min-w-0 items-center gap-2">
992 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
993 {versionLabel ? (
994 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
995 {versionLabel}
996 </code>
997 ) : null}
998 {versionAdvisoryNode}
999 </span>
1000 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
1001 {statusDotNode && !updateProgress ? (
1002 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
1003 ) : null}
1004 <ProviderStatusDiagnostic detail={statusDiagnostic}>
1005 <span
1006 tabIndex={statusDiagnostic ? 0 : undefined}
1007 aria-live="polite"
1008 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
1009 >
1010 {updateProgress ? (
1011 `Updating · ${updateProgress}`
1012 ) : (
1013 <>
1014 {summary.headline}
1015 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
1016 </>
1017 )}
1018 </span>
1019 </ProviderStatusDiagnostic>
1020 </span>
1021 </span>
1022 </div>
1023 <span className="flex h-5 shrink-0 items-center gap-1">
1024 {projectOverride?.value !== undefined ? (
1025 <span className="flex items-center">
1026 <ProjectOverrideInheritance
1027 projectEnabled={projectOverride.value}
1028 deviceEnabled={resolveProviderInstanceEnabled(instance)}
1029 />
1030 <SettingResetButton
1031 label={`${displayName} enablement`}
1032 tooltip="Reset to the device setting"
1033 disabled={readOnly || !canWriteSettings}
1034 onClick={projectOverride.onReset}
1035 />
1036 </span>
1037 ) : null}
1038 <Switch
1039 checked={enabled}
1040 disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
1041 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
1042 aria-label={`Enable ${displayName}`}
1043 />
1044 </span>
1045 </div>
1046 );
1047 }
1048
1049 const editorHeaderAction = (
1050 <div className="flex shrink-0 items-center gap-1.5">
1051 {driverOption?.badgeLabel ? (
1052 <Badge variant="warning" size="sm" className="shrink-0">
1053 {driverOption.badgeLabel}
1054 </Badge>
1055 ) : null}
1056 {versionCodeNode}
1057 {versionAdvisoryNode}
1058 <span
1059 inert={readOnly}
1060 aria-disabled={readOnly || undefined}
1061 // Empty, it would still add a flex gap and pull the version off the column edge.
1062 className={cn("inline-flex items-center gap-1 empty:hidden", readOnly && "opacity-50")}
1063 >
1064 {titleTailNode}
1065 {onDelete ? (
1066 <Button
1067 type="button"
1068 size="icon-xs"
1069 variant="ghost-destructive"
1070 disabled={readOnly}
1071 onClick={onDelete}
1072 aria-label={`Delete instance ${instanceId}`}
1073 >
1074 <Trash2Icon />
1075 </Button>
1076 ) : null}
1077 </span>
1078 </div>
1079 );
1080
1081 // The New design gives provider status its own row instead of hanging it under the name field.
1082 const statusContent = (
1083 <>
1084 <ProviderStatusDiagnostic detail={statusDiagnostic}>
1085 <div
1086 tabIndex={statusDiagnostic ? 0 : undefined}
1087 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
1088 >
1089 {editorStatusNode}
1090 </div>
1091 </ProviderStatusDiagnostic>
1092 {urlAuthAction && onAcceptUrlAuth ? (
1093 <div className="grid max-w-xl gap-1.5 pt-1 text-xs">
1094 <p>{urlAuthAction.message}</p>
1095 <code className="break-all text-2xs">{urlAuthAction.url}</code>
1096 <Button
1097 render={
1098 <a
1099 href={urlAuthAction.url}
1100 target="_blank"
1101 rel="noopener noreferrer"
1102 onClick={() => onAcceptUrlAuth(urlAuthAction)}
1103 />
1104 }
1105 size="xs"
1106 variant="outline"
1107 className="w-fit"
1108 disabled={readOnly}
1109 >
1110 <ExternalLinkIcon />
1111 Continue authentication
1112 </Button>
1113 </div>
1114 ) : null}
1115 </>
1116 );
1117
1118 const runtimeFields = driverOption ? (
1119 <ProviderSettingsForm
1120 definition={driverOption}
1121 value={instance.config}
1122 idPrefix={`provider-instance-${instanceId}`}
1123 variant="settings"
1124 onChange={updateConfig}
1125 />
1126 ) : (
1127 <SettingsRow
1128 title="Driver"
1129 description={
1130 <span>
1131 This instance uses <code className="text-foreground">{String(instance.driver)}</code>,
1132 which is not available in this build. Its configuration is preserved.
1133 </span>
1134 }
1135 />
1136 );
1137
1138 return (
1139 <>
1140 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
1141 {redesign ? <SettingsRow title="Status" status={statusContent} /> : null}
1142 <SettingsRow
1143 title="Display name"
1144 {...(redesign ? {} : { status: statusContent })}
1145 control={
1146 <div
1147 inert={readOnly}
1148 aria-disabled={readOnly || undefined}
1149 className={cn(
1150 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
1151 readOnly && "opacity-50 select-none",
1152 )}
1153 >
1154 <ProviderAccentColorPicker
1155 layout="inline"
1156 displayName={displayName}
1157 value={accentColor}
1158 onCommit={updateAccentColor}
1159 commitDelayMs={120}
1160 />
1161 <DraftInput
1162 id={`provider-instance-${instanceId}-display-name`}
1163 size="sm"
1164 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
1165 value={instance.displayName ?? ""}
1166 onCommit={updateDisplayName}
1167 placeholder={driverOption?.label ?? "Instance label"}
1168 spellCheck={false}
1169 />
1170 </div>
1171 }
1172 />
1173 </SettingsSection>
1174
1175 {setup || environmentFields.length > 0 ? (
1176 <SettingsSection title="Setup">
1177 {setup}
1178 {environmentFields.length > 0 ? (
1179 <div
1180 inert={readOnly}
1181 aria-disabled={readOnly || undefined}
1182 className={readOnly ? "opacity-50 select-none" : undefined}
1183 >
1184 {environmentFields.map((field) => (
1185 <ProviderEnvironmentFieldRow
1186 key={field.name}
1187 field={field}
1188 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
1189 idPrefix={`provider-instance-${instanceId}`}
1190 onCommit={updateEnvironmentField}
1191 onRemove={removeEnvironmentField}
1192 />
1193 ))}
1194 </div>
1195 ) : null}
1196 </SettingsSection>
1197 ) : null}
1198
1199 {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? (
1200 <div
1201 inert={readOnly}
1202 aria-disabled={readOnly || undefined}
1203 className={readOnly ? "opacity-50 select-none" : undefined}
1204 >
1205 <FoldedSettingsSection
1206 key={instanceId}
1207 id={`provider-instance-${instanceId}-runtime`}
1208 title="Runtime"
1209 headerPlacement="outside"
1210 >
1211 {runtime ?? runtimeFields}
1212 </FoldedSettingsSection>
1213 </div>
1214 ) : !driverOption || deriveProviderSettingsFields(driverOption).length > 0 ? (
1215 <SettingsSection
1216 title="Runtime"
1217 inert={readOnly}
1218 aria-disabled={readOnly || undefined}
1219 className={readOnly ? "opacity-50 select-none" : undefined}
1220 >
1221 {runtimeFields}
1222 </SettingsSection>
1223 ) : null}
1224
1225 <SettingsSection
1226 title="Environment"
1227 inert={readOnly}
1228 aria-disabled={readOnly || undefined}
1229 className={readOnly ? "opacity-50 select-none" : undefined}
1230 >
1231 <ProviderEnvironmentSection
1232 environment={genericEnvironment}
1233 onChange={updateGenericEnvironment}
1234 />
1235 </SettingsSection>
1236 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1237 <AcpSessionManagementSection
1238 environmentId={environmentId}
1239 instanceId={instanceId}
1240 provider={liveProvider}
1241 projects={acpProjects}
1242 readOnly={readOnly}
1243 />
1244 ) : null}
1245
1246 {driverOption !== undefined ? (
1247 <SettingsSection title="Models">
1248 <div className="px-3 py-3 sm:px-4">
1249 <p className="mb-3 text-xs text-muted-foreground">
1250 Model preferences and custom models are saved on the selected environment and shared
1251 across connected devices.
1252 </p>
1253 <ProviderModelsSection
1254 canManageCustomModels={!readOnly}
1255 canWritePreferences={canWriteSettings}
1256 instanceId={instanceId}
1257 driverKind={driverKind}
1258 models={modelsForDisplay}
1259 customModels={customModels}
1260 hiddenModels={hiddenModels}
1261 favoriteModels={favoriteModels}
1262 modelOrder={modelOrder}
1263 onChange={updateCustomModels}
1264 onHiddenModelsChange={onHiddenModelsChange}
1265 onFavoriteModelsChange={onFavoriteModelsChange}
1266 onToggleFavorite={onToggleFavorite}
1267 onModelOrderChange={onModelOrderChange}
1268 />
1269 </div>
1270 </SettingsSection>
1271 ) : null}
1272 </>
1273 );
1274}