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

ProviderInstanceCard.tsx

1,106 lines40.5 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 } 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 <SettingsRow
363 title="Variables"
364 description="API keys, base URLs, and other per-instance CLI settings."
365 control={
366 <Button type="button" size="sm" variant="outline" onClick={addVariable}>
367 <PlusIcon className="size-3" />
368 Add variable
369 </Button>
370 }
371 >
372 {rows.length > 0 ? (
373 <div className="mt-3 min-w-0 space-y-2 pb-2">
374 {rows.map((variable, index) => (
375 <div key={variable.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
376 <DraftInput
377 size="sm"
378 className="w-full min-w-0 font-mono sm:w-44 sm:shrink-0"
379 value={variable.name}
380 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
381 placeholder="VARIABLE_NAME"
382 spellCheck={false}
383 aria-label={`Environment variable name ${index + 1}`}
384 />
385 <span className="hidden text-xs text-muted-foreground sm:inline" aria-hidden>
386 =
387 </span>
388 <DraftInput
389 size="sm"
390 className="min-w-0 flex-1 font-mono"
391 value={variable.valueRedacted ? "" : variable.value}
392 onCommit={(value) => updateVariable(variable.id, { value })}
393 type={variable.sensitive ? "password" : undefined}
394 autoComplete="off"
395 placeholder={
396 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
397 }
398 spellCheck={false}
399 aria-label={`Environment variable value ${index + 1}`}
400 />
401 <Tooltip>
402 <TooltipTrigger
403 render={
404 <Button
405 type="button"
406 size="icon-micro"
407 variant="ghost-muted"
408 className={cn(
409 "[--control-icon-color:currentColor]",
410 variable.sensitive && "text-foreground",
411 )}
412 onClick={() => {
413 const sensitive = !variable.sensitive;
414 updateVariable(variable.id, {
415 sensitive,
416 ...(sensitive && variable.valueRedacted === undefined
417 ? {}
418 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
419 });
420 }}
421 aria-pressed={variable.sensitive}
422 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
423 >
424 {variable.sensitive ? (
425 <LockIcon className="size-3" />
426 ) : (
427 <LockOpenIcon className="size-3" />
428 )}
429 </Button>
430 }
431 />
432 <TooltipPopup side="top">
433 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
434 </TooltipPopup>
435 </Tooltip>
436 <Button
437 type="button"
438 size="icon-micro"
439 variant="ghost-muted"
440 className="[--control-icon-color:currentColor] hover:text-destructive"
441 onClick={() => removeVariable(variable.id)}
442 aria-label={`Remove environment variable ${variable.name || index + 1}`}
443 >
444 <XIcon className="size-3" />
445 </Button>
446 </div>
447 ))}
448 <p className="text-xs text-muted-foreground">
449 Sensitive values are stored separately and never returned to the app.
450 </p>
451 </div>
452 ) : null}
453 </SettingsRow>
454 );
456​
457interface ProviderInstanceCardProps {
458 readonly instanceId: ProviderInstanceId;
459 readonly instance: ProviderInstanceConfig;
460 readonly driverOption: DriverOption | undefined;
461 readonly liveProvider: ServerProvider | undefined;
462 readonly mode: "list" | "editor";
463 readonly selected?: boolean | undefined;
464 readonly onSelect?: (() => void) | undefined;
465 readonly readOnly?: boolean | undefined;
466 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
467 /**
468 * Pass `undefined` to hide the delete footer entirely. Built-in default
469 * instance slots use `undefined` — they can't be deleted without losing
470 * the slot, and their "reset to defaults" affordance lives on an outer
471 * reset button instead. Explicit `| undefined` in the type accommodates
472 * `exactOptionalPropertyTypes: true`, where an absent key and
473 * `{ onDelete: undefined }` are treated as distinct shapes.
474 */
475 readonly onDelete?: (() => void) | undefined;
476 /**
477 * Optional outer reset button rendered next to the driver icon. Built-in
478 * default slots supply a reset-to-factory control here; custom instances
479 * omit it.
480 */
481 readonly headerAction?: ReactNode | undefined;
482 readonly setup?: ReactNode;
483 readonly hiddenModels: ReadonlyArray<string>;
484 readonly favoriteModels: ReadonlyArray<string>;
485 readonly modelOrder: ReadonlyArray<string>;
486 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
487 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
488 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
489 readonly onRunUpdate?: (() => void) | undefined;
490 readonly isUpdating?: boolean | undefined;
491 readonly onAcceptUrlAuth?: ((action: AcpRegistryUrlAuthAction) => void) | undefined;
492 readonly environmentId?: EnvironmentId | undefined;
493 readonly acpProjects?:
494 | ReadonlyArray<{
495 readonly id: ProjectId;
496 readonly title: string;
497 readonly workspaceRoot: string;
498 }>
499 | undefined;
501​
502const EMPTY_ACP_PROJECTS: NonNullable<ProviderInstanceCardProps["acpProjects"]> = [];
503​
504/**
505 * Renders one provider instance as either a compact selectable list row or
506 * the full editor shown beside that list. Both modes use the same enabled
507 * state and provider metadata.
508 *
509 * Behavior notes:
510 * - `liveProvider` is matched by the caller via `instanceId`; when no
511 * match is available (e.g. the server hasn't checked it yet, or the
512 * driver is not shipped by the current build) the card still renders
513 * with a neutral "checking" summary.
514 * - Unknown drivers (`driverOption === undefined`) get a read-only
515 * notice instead of editable fields, so fork instances round-trip
516 * without accidentally destroying their config.
517 * - The enabled Switch writes to the envelope's `instance.enabled`
518 * field, which is the single enabled flag: the server folds any legacy
519 * driver-specific `config.enabled` into the envelope on load and both
520 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
521 * false wins, then envelope, then config, then the driver default).
522 */
523export function ProviderInstanceCard({
524 instanceId,
525 instance,
526 driverOption,
527 liveProvider,
528 mode,
529 selected = false,
530 onSelect,
531 readOnly = false,
532 onUpdate,
533 onDelete,
534 headerAction,
535 setup,
536 hiddenModels,
537 favoriteModels,
538 modelOrder,
539 onHiddenModelsChange,
540 onFavoriteModelsChange,
541 onModelOrderChange,
542 onRunUpdate,
543 isUpdating = false,
544 onAcceptUrlAuth,
545 environmentId,
546 acpProjects = EMPTY_ACP_PROJECTS,
547}: ProviderInstanceCardProps) {
548 const enabled = resolveProviderInstanceEnabled(instance);
549 // A locally disabled provider reads "Disabled" with a muted dot even if its
550 // last server status is stale. Enabled providers use the server status.
551 const statusKey: ProviderStatusKey = enabled
552 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
553 : "disabled";
554 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
555 const summary = enabled
556 ? getProviderSummary(liveProvider)
557 : { headline: "Disabled", detail: null };
558 const authEmail = liveProvider?.auth.email?.trim();
559 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
560 const authLabel =
561 enabled && liveProvider?.auth.status === "authenticated"
562 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
563 : null;
564 const versionLabel = getProviderVersionLabel(liveProvider?.version);
565 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
566 const urlAuthAction = liveProvider?.auth.action;
567 const updateCommand = versionAdvisory?.updateCommand ?? null;
568 const displayName =
569 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
570 const accentColor = normalizeProviderAccentColor(instance.accentColor);
571 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
572 onCopy: ({ providerName }) => {
573 toastManager.add({
574 type: "success",
575 title: `${providerName} update command copied`,
576 description: "Run it in a terminal when you are ready to update.",
577 });
578 },
579 onError: (error, { providerName }) => {
580 toastManager.add(
581 stackedThreadToast({
582 type: "error",
583 title: `Could not copy ${providerName} update command`,
584 description: error.message,
585 }),
586 );
587 },
588 });
589​
590 // Narrow `instance.driver` for callers that key on the closed
591 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
592 // fork drivers pass through as `null` and those callers fall back to
593 // verbatim behaviour.
594 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
595 ? instance.driver
596 : null;
597 const customModels =
598 instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
599 // Server-returned models may lag behind settings writes. Treat server
600 // models as the source for built-ins only; custom rows come directly
601 // from the current instance config so add/remove reflects immediately.
602 const modelsForDisplay = deriveProviderModelsForDisplay({
603 liveModels: liveProvider?.models,
604 customModels,
605 });
606 const updateDisplayName = (value: string) => {
607 const trimmed = value.trim();
608 const { displayName: _omit, ...rest } = instance;
609 onUpdate(
610 trimmed.length > 0
611 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
612 : (rest as ProviderInstanceConfig),
613 );
614 };
615​
616 const updateEnabled = (value: boolean) => {
617 onUpdate({ ...instance, enabled: value });
618 };
619​
620 const updateAccentColor = (value: string) => {
621 const normalized = normalizeProviderAccentColor(value);
622 const { accentColor: _omit, ...rest } = instance;
623 onUpdate(
624 normalized
625 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
626 : (rest as ProviderInstanceConfig),
627 );
628 };
629​
630 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
631 const { config: _omit, ...rest } = instance;
632 onUpdate(
633 nextConfig !== undefined
634 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
635 : (rest as ProviderInstanceConfig),
636 );
637 };
638​
639 const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
640 const nextConfig = nextConfigBlobWithValue(
641 instance.config,
642 "customModels",
643 next.map(toCustomModelSetting),
644 );
645 const { config: _omit, ...rest } = instance;
646 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
647 };
648​
649 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
650 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
651 const { environment: _omit, ...rest } = instance;
652 onUpdate(
653 cleaned.length > 0
654 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
655 : (rest as ProviderInstanceConfig),
656 );
657 };
658 // Drivers that need a named secret (Cursor's API key) get a dedicated field;
659 // the generic editor only shows the remaining variables.
660 const environmentFields = driverOption?.environmentFields ?? [];
661 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
662 const genericEnvironment = providerEnvironmentWithoutNames(
663 instance.environment,
664 environmentFieldNames,
665 );
666 const updateGenericEnvironment = (
667 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
668 ) => {
669 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
670 environmentFieldNames.has(variable.name),
671 );
672 updateEnvironment([...dedicatedEnvironment, ...environment]);
673 };
674 const updateEnvironmentField = (field: ProviderEnvironmentFieldDefinition, value: string) => {
675 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
676 };
677 const removeEnvironmentField = (field: ProviderEnvironmentFieldDefinition) => {
678 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
679 };
680​
681 const titleIconNode = (
682 <ProviderInstanceIcon
683 driverKind={driverKind ?? instance.driver}
684 displayName={displayName}
685 accentColor={accentColor}
686 acpRegistryAgentId={readConfigString(instance.config, "agentId") ?? undefined}
687 acpRegistryIconUrl={readConfigString(instance.config, "registryIconUrl") ?? undefined}
688 showBadge={Boolean(accentColor)}
689 className="size-5"
690 iconClassName="size-4 text-foreground/80"
691 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
692 />
693 );
694​
695 const titleTailNode = headerAction ? (
696 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
697 ) : null;
698​
699 const versionCodeNode = versionLabel ? (
700 <code className="text-xs text-muted-foreground">{versionLabel}</code>
701 ) : null;
702​
703 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
704 const statusDotNode =
705 statusKey === "warning" || statusKey === "error" ? (
706 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
707 ) : null;
708 // Trouble states carry the server's explanation (a failed probe, a shadow
709 // home entry that is not a symlink, a missing binary). Show it wherever the
710 // headline shows so the user can act without opening the editor.
711 const needsAttention = statusKey === "warning" || statusKey === "error";
712 const editorStatusNode =
713 isAuthenticated && authEmail ? (
714 <>
715 {needsAttention ? statusDotNode : null}
716 <span>Authenticated as</span>
717 <ProviderAuthEmail email={authEmail} />
718 {authLabel ? <span>· {authLabel}</span> : null}
719 {summary.detail ? (
720 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
721 ) : null}
722 </>
723 ) : (
724 <>
725 {statusDotNode}
726 <span>{summary.headline}</span>
727 {summary.detail ? (
728 <span className="min-w-0 [overflow-wrap:anywhere]">· {summary.detail}</span>
729 ) : null}
730 </>
731 );
732 if (mode === "list") {
733 return (
734 <div
735 data-slot="settings-row"
736 className={cn(
737 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
738 selected ? "bg-muted/45" : "hover:bg-muted/25",
739 )}
740 >
741 <div
742 className={cn(
743 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
744 !enabled && !selected && "opacity-60 group-hover:opacity-100",
745 )}
746 >
747 <button
748 type="button"
749 className="pointer-events-auto absolute inset-0 cursor-pointer rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
750 onClick={onSelect}
751 aria-label={`Select ${displayName}`}
752 aria-pressed={selected}
753 />
754 {titleIconNode}
755 <span className="min-w-0 flex-1">
756 <span className="flex min-w-0 items-center gap-2">
757 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
758 {String(instanceId) !== String(instance.driver) ? (
759 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
760 {instanceId}
761 </code>
762 ) : null}
763 {versionLabel ? (
764 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
765 {versionLabel}
766 </code>
767 ) : null}
768 {versionAdvisory ? (
769 updateCommand ? (
770 <Tooltip>
771 <TooltipTrigger
772 render={
773 <Button
774 type="button"
775 size="icon-micro"
776 variant="ghost-muted"
777 className="pointer-events-auto relative shrink-0"
778 aria-label={`Copy ${displayName} update command`}
779 onClick={() =>
780 copyToClipboard(updateCommand, { providerName: displayName })
781 }
782 >
783 <ArrowUpCircleIcon className="size-3.5" />
784 </Button>
785 }
786 />
787 <TooltipPopup side="top">Copy update command</TooltipPopup>
788 </Tooltip>
789 ) : (
790 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
791 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
792 </span>
793 )
794 ) : null}
795 </span>
796 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
797 {statusDotNode ? (
798 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
799 ) : null}
800 <span className="line-clamp-2 [overflow-wrap:anywhere]">
801 {summary.headline}
802 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
803 </span>
804 </span>
805 </span>
806 </div>
807 <span className="flex h-5 shrink-0 items-center">
808 <Switch
809 checked={enabled}
810 disabled={readOnly}
811 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
812 aria-label={`Enable ${displayName}`}
813 />
814 </span>
815 </div>
816 );
817 }
818​
819 const editorHeaderAction = (
820 <div className="flex shrink-0 items-center gap-1.5">
821 {driverOption?.badgeLabel ? (
822 <Badge variant="warning" size="sm" className="shrink-0">
823 {driverOption.badgeLabel}
824 </Badge>
825 ) : null}
826 {versionCodeNode}
827 <span
828 inert={readOnly}
829 aria-disabled={readOnly || undefined}
830 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
831 >
832 {versionAdvisory ? (
833 <Popover>
834 <PopoverTrigger
835 render={
836 <Button
837 type="button"
838 size="icon-xs"
839 variant="ghost"
840 className={cn(
841 "[--control-icon-color:currentColor]",
842 versionAdvisory.emphasis === "strong"
843 ? "text-warning hover:text-warning"
844 : "text-muted-foreground hover:text-foreground",
845 )}
846 aria-label="Update available — view details"
847 >
848 <ArrowUpCircleIcon />
849 </Button>
850 }
851 />
852 <PopoverPopup
853 side="bottom"
854 align="end"
855 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
856 >
857 <div className="grid min-w-0 gap-3">
858 <div className="grid gap-0.5">
859 <p className="text-[13px] font-semibold leading-tight text-foreground">
860 Update available
861 </p>
862 <p
863 className={cn(
864 "text-xs leading-snug",
865 versionAdvisory.emphasis === "strong"
866 ? "text-warning"
867 : "text-muted-foreground",
868 )}
869 >
870 {versionAdvisory.detail}
871 </p>
872 </div>
873 {onRunUpdate ? (
874 <Button
875 type="button"
876 size="xs"
877 variant="outline"
878 className="w-full"
879 disabled={isUpdating}
880 onClick={onRunUpdate}
881 >
882 {isUpdating ? <Spinner /> : <DownloadIcon />}
883 {isUpdating ? "Updating" : "Update now"}
884 </Button>
885 ) : null}
886 {onRunUpdate && updateCommand ? (
887 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
888 <span aria-hidden className="h-px flex-1 bg-border" />
889 or, update manually using
890 <span aria-hidden className="h-px flex-1 bg-border" />
891 </div>
892 ) : null}
893 {updateCommand ? (
894 <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">
895 <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground">
896 {updateCommand}
897 </code>
898 <Tooltip>
899 <TooltipTrigger
900 render={
901 <Button
902 type="button"
903 size="icon-xs"
904 variant="ghost"
905 className="shrink-0 text-muted-foreground hover:text-foreground"
906 onClick={() =>
907 copyToClipboard(updateCommand, { providerName: displayName })
908 }
909 aria-label="Copy update command"
910 >
911 <CopyIcon className="size-3" />
912 </Button>
913 }
914 />
915 <TooltipPopup side="top">Copy command</TooltipPopup>
916 </Tooltip>
917 </div>
918 ) : null}
919 </div>
920 </PopoverPopup>
921 </Popover>
922 ) : null}
923 {titleTailNode}
924 {onDelete ? (
925 <Button
926 type="button"
927 size="icon-xs"
928 variant="ghost-muted"
929 disabled={readOnly}
930 className="[--control-icon-color:currentColor] hover:text-destructive"
931 onClick={onDelete}
932 aria-label={`Delete instance ${instanceId}`}
933 >
934 <Trash2Icon />
935 </Button>
936 ) : null}
937 </span>
938 </div>
939 );
940​
941 return (
942 <>
943 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
944 <SettingsRow
945 title="Display name"
946 status={
947 <>
948 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5">
949 {editorStatusNode}
950 </div>
951 {urlAuthAction && onAcceptUrlAuth ? (
952 <div className="grid max-w-xl gap-1.5 pt-1 text-xs">
953 <p>{urlAuthAction.message}</p>
954 <code className="break-all text-[11px]">{urlAuthAction.url}</code>
955 <Button
956 render={
957 <a
958 href={urlAuthAction.url}
959 target="_blank"
960 rel="noopener noreferrer"
961 onClick={() => onAcceptUrlAuth(urlAuthAction)}
962 />
963 }
964 size="xs"
965 variant="outline"
966 className="w-fit"
967 disabled={readOnly}
968 >
969 <ExternalLinkIcon />
970 Continue authentication
971 </Button>
972 </div>
973 ) : null}
974 </>
975 }
976 control={
977 <div
978 inert={readOnly}
979 aria-disabled={readOnly || undefined}
980 className={cn(
981 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
982 readOnly && "opacity-50 select-none",
983 )}
984 >
985 <ProviderAccentColorPicker
986 layout="inline"
987 displayName={displayName}
988 value={accentColor}
989 onCommit={updateAccentColor}
990 commitDelayMs={120}
991 />
992 <DraftInput
993 id={`provider-instance-${instanceId}-display-name`}
994 size="sm"
995 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
996 value={instance.displayName ?? ""}
997 onCommit={updateDisplayName}
998 placeholder={driverOption?.label ?? "Instance label"}
999 spellCheck={false}
1000 />
1001 </div>
1003 />
1004 </SettingsSection>
1005​
1006 {setup ? <SettingsSection title="Setup">{setup}</SettingsSection> : null}
1007​
1008 <SettingsSection
1009 title="Runtime"
1010 inert={readOnly}
1011 aria-disabled={readOnly || undefined}
1012 className={readOnly ? "opacity-50 select-none" : undefined}
1014 {driverOption ? (
1015 <ProviderSettingsForm
1016 definition={driverOption}
1017 value={instance.config}
1018 idPrefix={`provider-instance-${instanceId}`}
1019 variant="settings"
1020 onChange={updateConfig}
1021 />
1022 ) : (
1023 <SettingsRow
1024 title="Driver"
1025 description={
1026 <span>
1027 This instance uses{" "}
1028 <code className="text-foreground">{String(instance.driver)}</code>, which is not
1029 available in this build. Its configuration is preserved.
1030 </span>
1032 />
1033 )}
1034 </SettingsSection>
1035​
1036 <SettingsSection
1037 title="Environment"
1038 inert={readOnly}
1039 aria-disabled={readOnly || undefined}
1040 className={readOnly ? "opacity-50 select-none" : undefined}
1042 {environmentFields.length > 0 ? (
1043 <div className="grid gap-3 px-3 py-3 sm:px-4">
1044 {environmentFields.map((field) => (
1045 <ProviderEnvironmentFieldRow
1046 key={field.name}
1047 field={field}
1048 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
1049 idPrefix={`provider-instance-${instanceId}`}
1050 onCommit={updateEnvironmentField}
1051 onRemove={removeEnvironmentField}
1052 />
1053 ))}
1054 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1055 <AcpSessionManagementSection
1056 environmentId={environmentId}
1057 instanceId={instanceId}
1058 provider={liveProvider}
1059 projects={acpProjects}
1060 readOnly={readOnly}
1061 />
1062 ) : null}
1063 </div>
1064 ) : null}
1065 <SettingsRow
1066 title="Variables"
1067 description="API keys, base URLs, and other per-instance CLI settings."
1069 <ProviderEnvironmentSection
1070 environment={genericEnvironment}
1071 onChange={updateGenericEnvironment}
1072 />
1073 </SettingsRow>
1074 </SettingsSection>
1075​
1076 {driverOption !== undefined ? (
1077 <SettingsSection
1078 title="Models"
1079 inert={readOnly}
1080 aria-disabled={readOnly || undefined}
1081 className={readOnly ? "opacity-50 select-none" : undefined}
1083 <div className="px-3 py-3 sm:px-4">
1084 <p className="mb-3 text-xs text-muted-foreground">
1085 Favorites, visibility, and ordering are saved on this device. Custom models are saved
1086 on the selected environment.
1087 </p>
1088 <ProviderModelsSection
1089 instanceId={instanceId}
1090 driverKind={driverKind}
1091 models={modelsForDisplay}
1092 customModels={customModels}
1093 hiddenModels={hiddenModels}
1094 favoriteModels={favoriteModels}
1095 modelOrder={modelOrder}
1096 onChange={updateCustomModels}
1097 onHiddenModelsChange={onHiddenModelsChange}
1098 onFavoriteModelsChange={onFavoriteModelsChange}
1099 onModelOrderChange={onModelOrderChange}
1100 />
1101 </div>
1102 </SettingsSection>
1103 ) : null}
1104 </>
1105 );