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

ProviderInstanceCard.tsx

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