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

ProviderInstanceCard.tsx

1,350 lines46.7 KB

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