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

ProviderInstanceCard.tsx

1,340 lines47.5 KB

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