@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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