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