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

ProviderInstanceCard.tsx

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