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