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

ProviderInstanceCard.tsx

1,113 lines40.4 KB

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