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

ProviderInstanceCard.tsx

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