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

ProviderInstanceCard.tsx

1,285 lines44.4 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 getProviderSummary,
70 getProviderVersionLabel,
71 type ProviderStatusKey,
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 compatibility = enabled ? liveProvider?.compatibilityAdvisory : undefined;
649 const statusKey: ProviderStatusKey = enabled
650 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
651 : "disabled";
652 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
653 const summary = enabled
654 ? getProviderSummary(liveProvider && { ...liveProvider, enabled: true })
655 : { headline: "Disabled", detail: null };
656 const authEmail = liveProvider?.auth.email?.trim();
657 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
658 const authLabel =
659 enabled && liveProvider?.auth.status === "authenticated"
660 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
661 : null;
662 const versionLabel = getProviderVersionLabel(liveProvider?.version);
663 const versionAdvisory = getProviderVersionAdvisoryPresentation(
664 liveProvider?.versionAdvisory,
665 liveProvider?.compatibilityAdvisory,
666 enabled,
667 );
668 const updateCommand = versionAdvisory?.updateCommand ?? null;
669 const updateState = liveProvider?.updateState;
670 const updateProgress = isUpdating
671 ? ((updateState?.status === "queued" || updateState?.status === "running"
672 ? updateState.message
673 : null) ?? "Starting update")
674 : null;
675 const updateProblem =
676 !isUpdating && (updateState?.status === "failed" || updateState?.status === "unchanged")
677 ? updateState.message
678 : null;
679 const hasCompatibilityWarning =
680 compatibility !== undefined &&
681 compatibility.status !== "supported" &&
682 compatibility.status !== "unknown";
683 const VersionAdvisoryIcon = hasCompatibilityWarning ? AlertTriangleIcon : ArrowUpCircleIcon;
684 const onRunVersionAction = readOnly
685 ? undefined
686 : versionAdvisory?.targetVersion
687 ? onInstallRecommended
688 : onRunUpdate;
689 const urlAuthAction = liveProvider?.auth.action;
690 const displayName =
691 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
692 const accentColor = normalizeProviderAccentColor(instance.accentColor);
693 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
694 onCopy: ({ providerName }) => {
695 toastManager.add({
696 type: "success",
697 title: `${providerName} update command copied`,
698 description: "Run it in a terminal when you are ready to update.",
699 });
700 },
701 onError: (error, { providerName }) => {
702 toastManager.add(
703 stackedThreadToast({
704 type: "error",
705 title: `Could not copy ${providerName} update command`,
706 description: error.message,
707 }),
708 );
709 },
710 });
711​
712 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
713 ? instance.driver
714 : null;
715 // Keyed on the stored list, not the whole instance, so writing another field
716 // leaves the models list (often ~50 rows) with the same props.
717 const storedCustomModels =
718 instance.config !== null && typeof instance.config === "object"
719 ? (instance.config as Record<string, unknown>).customModels
720 : undefined;
721 const customModels =
722 instance.driver === "antigravity"
723 ? NO_CUSTOM_MODELS
724 : readCustomModelEntries(storedCustomModels);
725 const modelsForDisplay = deriveProviderModelsForDisplay({
726 liveModels: liveProvider?.models,
727 customModels,
728 });
729 const updateDisplayName = (value: string) => {
730 const trimmed = value.trim();
731 const { displayName: _omit, ...rest } = instance;
732 onUpdate(
733 trimmed.length > 0
734 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
735 : (rest as ProviderInstanceConfig),
736 );
737 };
738​
739 const updateEnabled = (value: boolean) => {
740 if (projectOverride) {
741 projectOverride.onChange(value);
742 return;
743 }
744 onUpdate({ ...instance, enabled: value });
745 };
746​
747 const updateAccentColor = (value: string) => {
748 const normalized = normalizeProviderAccentColor(value);
749 const { accentColor: _omit, ...rest } = instance;
750 onUpdate(
751 normalized
752 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
753 : (rest as ProviderInstanceConfig),
754 );
755 };
756​
757 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
758 const { config: _omit, ...rest } = instance;
759 onUpdate(
760 nextConfig !== undefined
761 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
762 : (rest as ProviderInstanceConfig),
763 );
764 };
765​
766 const updateCustomModels = useStableCallback((next: ReadonlyArray<CustomModelDefinition>) => {
767 const nextConfig = nextConfigBlobWithValue(
768 instance.config,
769 "customModels",
770 next.map(toCustomModelSetting),
771 );
772 const { config: _omit, ...rest } = instance;
773 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
774 });
775​
776 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
777 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
778 const { environment: _omit, ...rest } = instance;
779 onUpdate(
780 cleaned.length > 0
781 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
782 : (rest as ProviderInstanceConfig),
783 );
784 };
785 const environmentFields = driverOption?.environmentFields ?? [];
786 const environmentFieldNames = new Set(environmentFields.map((field) => field.name));
787 const genericEnvironment = providerEnvironmentWithoutNames(
788 instance.environment,
789 environmentFieldNames,
790 );
791 const updateGenericEnvironment = (
792 environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
793 ) => {
794 const dedicatedEnvironment = (instance.environment ?? []).filter((variable) =>
795 environmentFieldNames.has(variable.name),
796 );
797 updateEnvironment([...dedicatedEnvironment, ...environment]);
798 };
799 const updateEnvironmentField = (field: ProviderEnvironmentField, value: string) => {
800 updateEnvironment(nextProviderEnvironmentWithFieldValue(instance.environment, field, value));
801 };
802 const removeEnvironmentField = (field: ProviderEnvironmentField) => {
803 updateEnvironment(providerEnvironmentWithoutNames(instance.environment, new Set([field.name])));
804 };
805​
806 const titleIconNode = (
807 <ProviderInstanceIcon
808 driverKind={driverKind ?? instance.driver}
809 displayName={displayName}
810 accentColor={accentColor}
811 acpRegistryAgentId={
812 readConfigString(instance.config, "source") === "local"
813 ? undefined
814 : (readConfigString(instance.config, "agentId") ?? undefined)
815 }
816 acpRegistryIconUrl={
817 readConfigString(instance.config, "source") === "local"
818 ? undefined
819 : (readConfigString(instance.config, "registryIconUrl") ?? undefined)
820 }
821 showBadge={Boolean(accentColor)}
822 className="size-5"
823 iconClassName="size-4 text-foreground/80"
824 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs"
825 />
826 );
827​
828 const titleTailNode = headerAction ? (
829 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
830 ) : null;
831​
832 const versionCodeNode = versionLabel ? (
833 <code className="text-xs text-muted-foreground">{versionLabel}</code>
834 ) : null;
835​
836 const statusDotNode =
837 statusKey === "warning" || statusKey === "error" ? (
838 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
839 ) : null;
840 const needsAttention = statusKey === "warning" || statusKey === "error";
841 const statusDiagnostic = hasCompatibilityWarning && needsAttention ? summary.detail : null;
842 const inlineStatusDetail = hasCompatibilityWarning
843 ? compatibility?.status === "broken"
844 ? "Incompatible"
845 : compatibility?.status === "unsupported"
846 ? "Unsupported"
847 : "Limited support"
848 : summary.detail;
849 const editorStatusNode =
850 isAuthenticated && authEmail ? (
851 <>
852 {needsAttention ? statusDotNode : null}
853 <span>Authenticated as</span>
854 <ProviderAuthEmail email={authEmail} />
855 {authLabel ? <span>· {authLabel}</span> : null}
856 {inlineStatusDetail ? (
857 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
858 ) : null}
859 </>
860 ) : (
861 <>
862 {statusDotNode}
863 <span>{summary.headline}</span>
864 {inlineStatusDetail ? (
865 <span className="min-w-0 [overflow-wrap:anywhere]">· {inlineStatusDetail}</span>
866 ) : null}
867 </>
868 );
869 const versionAdvisoryNode = versionAdvisory ? (
870 <Popover>
871 <Tooltip>
872 <TooltipTrigger
873 render={
874 <PopoverTrigger
875 render={
876 <Button
877 type="button"
878 size={mode === "list" ? "icon-micro" : "icon-xs"}
879 variant="ghost-muted"
880 className={mode === "list" ? "pointer-events-auto relative shrink-0" : undefined}
881 aria-label={`${updateProgress ? "Updating" : versionAdvisory.title} — view details`}
882 >
883 {updateProgress ? (
884 <Spinner tone="muted" {...(mode === "list" ? { size: "sm" as const } : {})} />
885 ) : (
886 <VersionAdvisoryIcon
887 className={cn(
888 mode === "list" && "size-3.5",
889 hasCompatibilityWarning && "text-warning",
890 )}
891 />
892 )}
893 </Button>
894 }
895 />
896 }
897 />
898 <TooltipPopup side="top">
899 {updateProgress ? "Updating" : versionAdvisory.title}
900 </TooltipPopup>
901 </Tooltip>
902 <PopoverPopup side="bottom" align="end" width="md" aria-label={versionAdvisory.title}>
903 <div className="grid min-w-0 gap-3">
904 <div className="grid gap-0.5">
905 <p className="text-sm font-semibold leading-tight text-foreground">
906 {versionAdvisory.title}
907 </p>
908 <p
909 className={cn(
910 "text-xs leading-snug",
911 versionAdvisory.emphasis === "strong" ? "text-warning" : "text-muted-foreground",
912 )}
913 >
914 {versionAdvisory.detail}
915 </p>
916 </div>
917 {onRunVersionAction ? (
918 <Button
919 type="button"
920 size="xs"
921 variant="outline"
922 className="w-full"
923 disabled={isUpdating}
924 onClick={onRunVersionAction}
925 >
926 {isUpdating ? <Spinner /> : <DownloadIcon />}
927 {isUpdating
928 ? "Updating"
929 : versionAdvisory.targetVersion
930 ? `Install ${getProviderVersionLabel(versionAdvisory.targetVersion)}`
931 : "Update now"}
932 </Button>
933 ) : null}
934 {updateProgress || updateProblem ? (
935 <p
936 aria-live="polite"
937 className={cn(
938 "text-xs leading-snug [overflow-wrap:anywhere]",
939 updateProblem ? "text-warning" : "text-muted-foreground",
940 )}
941 >
942 {updateProgress ?? updateProblem}
943 </p>
944 ) : null}
945 {onRunVersionAction && updateCommand ? (
946 <div className="flex items-center gap-2 text-3xs font-medium uppercase tracking-wider text-muted-foreground">
947 <span aria-hidden className="h-px flex-1 bg-border" />
948 or, update manually using
949 <span aria-hidden className="h-px flex-1 bg-border" />
950 </div>
951 ) : null}
952 {updateCommand ? (
953 <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">
954 <code className="min-w-0 flex-1 truncate font-mono text-2xs text-foreground">
955 {updateCommand}
956 </code>
957 <Tooltip>
958 <TooltipTrigger
959 render={
960 <Button
961 type="button"
962 size="icon-xs"
963 variant="ghost-muted"
964 className="shrink-0"
965 onClick={() => copyToClipboard(updateCommand, { providerName: displayName })}
966 aria-label="Copy update command"
967 >
968 <CopyIcon className="size-3" />
969 </Button>
970 }
971 />
972 <TooltipPopup side="top">Copy command</TooltipPopup>
973 </Tooltip>
974 </div>
975 ) : null}
976 </div>
977 </PopoverPopup>
978 </Popover>
979 ) : null;
980​
981 if (mode === "list") {
982 return (
983 <div
984 data-slot="settings-row"
985 className={cn(
986 "group flex min-h-18 items-center gap-3 px-3 py-3 transition-colors sm:px-4",
987 selected ? "bg-muted/45" : "hover:bg-muted/25",
988 )}
989 >
990 <div
991 className={cn(
992 "pointer-events-none relative flex min-w-0 flex-1 items-start gap-3 rounded-md text-left transition-opacity",
993 !enabled && !selected && "opacity-60 group-hover:opacity-100",
994 )}
995 >
996 <button
997 type="button"
998 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"
999 onClick={onSelect}
1000 aria-label={`Select ${displayName}`}
1001 aria-pressed={selected}
1002 />
1003 {titleIconNode}
1004 <span className="min-w-0 flex-1">
1005 <span className="flex min-w-0 items-center gap-2">
1006 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
1007 {versionLabel ? (
1008 <code className="max-w-24 shrink-0 truncate text-xs text-muted-foreground">
1009 {versionLabel}
1010 </code>
1011 ) : null}
1012 {versionAdvisoryNode}
1013 </span>
1014 <span className="mt-0.5 flex items-start gap-1.5 text-xs leading-normal text-muted-foreground/80">
1015 {statusDotNode && !updateProgress ? (
1016 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
1017 ) : null}
1018 <ProviderStatusDiagnostic detail={statusDiagnostic}>
1019 <span
1020 tabIndex={statusDiagnostic ? 0 : undefined}
1021 aria-live="polite"
1022 className="pointer-events-auto line-clamp-2 [overflow-wrap:anywhere]"
1024 {updateProgress ? (
1025 `Updating · ${updateProgress}`
1026 ) : (
1027 <>
1028 {summary.headline}
1029 {needsAttention && inlineStatusDetail ? ` · ${inlineStatusDetail}` : null}
1030 </>
1031 )}
1032 </span>
1033 </ProviderStatusDiagnostic>
1034 </span>
1035 </span>
1036 </div>
1037 <span className="flex h-5 shrink-0 items-center gap-1">
1038 {projectOverride?.value !== undefined ? (
1039 <span className="flex items-center">
1040 <ProjectOverrideInheritance
1041 projectEnabled={projectOverride.value}
1042 deviceEnabled={resolveProviderInstanceEnabled(instance)}
1043 />
1044 <SettingResetButton
1045 label={`${displayName} enablement`}
1046 tooltip="Reset to the device setting"
1047 disabled={readOnly || !canWriteSettings}
1048 onClick={projectOverride.onReset}
1049 />
1050 </span>
1051 ) : null}
1052 <Switch
1053 checked={enabled}
1054 disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
1055 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
1056 aria-label={`Enable ${displayName}`}
1057 />
1058 </span>
1059 </div>
1060 );
1062​
1063 const editorHeaderAction = (
1064 <div className="flex shrink-0 items-center gap-1.5">
1065 {driverOption?.badgeLabel ? (
1066 <Badge variant="warning" size="sm" className="shrink-0">
1067 {driverOption.badgeLabel}
1068 </Badge>
1069 ) : null}
1070 {versionCodeNode}
1071 {versionAdvisoryNode}
1072 <span
1073 inert={readOnly}
1074 aria-disabled={readOnly || undefined}
1075 className={cn("inline-flex items-center gap-1", readOnly && "opacity-50")}
1077 {titleTailNode}
1078 {onDelete ? (
1079 <Button
1080 type="button"
1081 size="icon-xs"
1082 variant="ghost-destructive"
1083 disabled={readOnly}
1084 onClick={onDelete}
1085 aria-label={`Delete instance ${instanceId}`}
1087 <Trash2Icon />
1088 </Button>
1089 ) : null}
1090 </span>
1091 </div>
1092 );
1093​
1094 const runtimeFields = driverOption ? (
1095 <ProviderSettingsForm
1096 definition={driverOption}
1097 value={instance.config}
1098 idPrefix={`provider-instance-${instanceId}`}
1099 variant="settings"
1100 onChange={updateConfig}
1101 />
1102 ) : (
1103 <SettingsRow
1104 title="Driver"
1105 description={
1106 <span>
1107 This instance uses <code className="text-foreground">{String(instance.driver)}</code>,
1108 which is not available in this build. Its configuration is preserved.
1109 </span>
1111 />
1112 );
1113​
1114 return (
1115 <>
1116 <SettingsSection title={displayName} icon={titleIconNode} headerAction={editorHeaderAction}>
1117 <SettingsRow
1118 title="Display name"
1119 status={
1120 <>
1121 <ProviderStatusDiagnostic detail={statusDiagnostic}>
1122 <div
1123 tabIndex={statusDiagnostic ? 0 : undefined}
1124 className="flex min-w-0 flex-wrap items-baseline gap-x-1.5"
1126 {editorStatusNode}
1127 </div>
1128 </ProviderStatusDiagnostic>
1129 {urlAuthAction && onAcceptUrlAuth ? (
1130 <div className="grid max-w-xl gap-1.5 pt-1 text-xs">
1131 <p>{urlAuthAction.message}</p>
1132 <code className="break-all text-2xs">{urlAuthAction.url}</code>
1133 <Button
1134 render={
1135 <a
1136 href={urlAuthAction.url}
1137 target="_blank"
1138 rel="noopener noreferrer"
1139 onClick={() => onAcceptUrlAuth(urlAuthAction)}
1140 />
1142 size="xs"
1143 variant="outline"
1144 className="w-fit"
1145 disabled={readOnly}
1147 <ExternalLinkIcon />
1148 Continue authentication
1149 </Button>
1150 </div>
1151 ) : null}
1152 </>
1154 control={
1155 <div
1156 inert={readOnly}
1157 aria-disabled={readOnly || undefined}
1158 className={cn(
1159 "flex w-full min-w-0 items-center justify-end gap-2 @min-[32rem]/settings-row:w-auto",
1160 readOnly && "opacity-50 select-none",
1161 )}
1163 <ProviderAccentColorPicker
1164 layout="inline"
1165 displayName={displayName}
1166 value={accentColor}
1167 onCommit={updateAccentColor}
1168 commitDelayMs={120}
1169 />
1170 <DraftInput
1171 id={`provider-instance-${instanceId}-display-name`}
1172 size="sm"
1173 className="min-w-0 flex-1 @min-[32rem]/settings-row:w-56"
1174 value={instance.displayName ?? ""}
1175 onCommit={updateDisplayName}
1176 placeholder={driverOption?.label ?? "Instance label"}
1177 spellCheck={false}
1178 />
1179 </div>
1181 />
1182 </SettingsSection>
1183​
1184 {setup || environmentFields.length > 0 ? (
1185 <SettingsSection title="Setup">
1186 {setup}
1187 <div
1188 inert={readOnly}
1189 aria-disabled={readOnly || undefined}
1190 className={readOnly ? "opacity-50 select-none" : undefined}
1192 {environmentFields.length > 0 ? (
1193 <>
1194 {environmentFields.map((field) => (
1195 <ProviderEnvironmentFieldRow
1196 key={field.name}
1197 field={field}
1198 variable={readProviderEnvironmentVariable(instance.environment, field.name)}
1199 idPrefix={`provider-instance-${instanceId}`}
1200 onCommit={updateEnvironmentField}
1201 onRemove={removeEnvironmentField}
1202 />
1203 ))}
1204 </>
1205 ) : null}
1206 </div>
1207 </SettingsSection>
1208 ) : null}
1209​
1210 {instance.driver === "codex" && readCodexSetupMode(instance.config) === "managed" ? (
1211 <div
1212 inert={readOnly}
1213 aria-disabled={readOnly || undefined}
1214 className={readOnly ? "opacity-50 select-none" : undefined}
1216 <FoldedSettingsSection
1217 key={instanceId}
1218 id={`provider-instance-${instanceId}-runtime`}
1219 title="Runtime"
1220 headerPlacement="outside"
1222 {runtime ?? runtimeFields}
1223 </FoldedSettingsSection>
1224 </div>
1225 ) : !driverOption || deriveProviderSettingsFields(driverOption).length > 0 ? (
1226 <SettingsSection
1227 title="Runtime"
1228 inert={readOnly}
1229 aria-disabled={readOnly || undefined}
1230 className={readOnly ? "opacity-50 select-none" : undefined}
1232 {runtimeFields}
1233 </SettingsSection>
1234 ) : null}
1235​
1236 <SettingsSection
1237 title="Environment"
1238 inert={readOnly}
1239 aria-disabled={readOnly || undefined}
1240 className={readOnly ? "opacity-50 select-none" : undefined}
1242 <ProviderEnvironmentSection
1243 environment={genericEnvironment}
1244 onChange={updateGenericEnvironment}
1245 />
1246 </SettingsSection>
1247 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1248 <AcpSessionManagementSection
1249 environmentId={environmentId}
1250 instanceId={instanceId}
1251 provider={liveProvider}
1252 projects={acpProjects}
1253 readOnly={readOnly}
1254 />
1255 ) : null}
1256​
1257 {driverOption !== undefined ? (
1258 <SettingsSection title="Models">
1259 <div className="px-3 py-3 sm:px-4">
1260 <p className="mb-3 text-xs text-muted-foreground">
1261 Model preferences and custom models are saved on the selected environment and shared
1262 across connected devices.
1263 </p>
1264 <ProviderModelsSection
1265 canManageCustomModels={!readOnly}
1266 canWritePreferences={canWriteSettings}
1267 instanceId={instanceId}
1268 driverKind={driverKind}
1269 models={modelsForDisplay}
1270 customModels={customModels}
1271 hiddenModels={hiddenModels}
1272 favoriteModels={favoriteModels}
1273 modelOrder={modelOrder}
1274 onChange={updateCustomModels}
1275 onHiddenModelsChange={onHiddenModelsChange}
1276 onFavoriteModelsChange={onFavoriteModelsChange}
1277 onToggleFavorite={onToggleFavorite}
1278 onModelOrderChange={onModelOrderChange}
1279 />
1280 </div>
1281 </SettingsSection>
1282 ) : null}
1283 </>
1284 );