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