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