@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,521 lines 55.1 KB
Raw
1 import { SettingsGroup } from "./SettingsGroup";
2 import { RefreshIcon } from "~/components/ui/refresh-icon";
3 import {
4 AuthSettingsWriteScope,
5 AuthProvidersManageScope,
6 AuthOrchestrationReadScope,
7 } from "@t3tools/contracts";
8 import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
9 import { useAtomValue } from "@effect/atom-react";
10 import { connectionErrorText, connectionStatusTitle } from "@t3tools/client-runtime/connection";
11 import {
12 errorDisplayMessage,
13 safeErrorLogAttributes,
14 thrownErrorMessage,
15 } from "@t3tools/client-runtime/errors";
16 import {
17 isAtomCommandInterrupted,
18 settlePromise,
19 squashAtomCommandFailure,
20 } from "@t3tools/client-runtime/state/runtime";
21 import {
22 defaultInstanceIdForDriver,
23 type EnvironmentId,
24 type AcpRegistryUrlAuthAction,
25 PROVIDER_DISPLAY_NAMES,
26 ProviderDriverKind,
27 type ProjectId,
28 type ProviderInstanceConfig,
29 type ProviderInstanceId,
30 type ServerProvider,
31 resolveEnvironmentMachineKind,
32 resolveProjectProviderInstanceEnabled,
33 resolveProviderInstanceEnabled,
34 } from "@t3tools/contracts";
35 import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts/settings";
36 import {
37 getBackgroundActivityPresetSettings,
38 resolveServerBackgroundActivitySettings,
39 } from "@t3tools/shared/backgroundActivitySettings";
40 import * as Arr from "effect/Array";
41 import * as Duration from "effect/Duration";
42 import * as Result from "effect/Result";
43 import { PlusIcon } from "lucide-react";
44 import { useRef, useState, type ReactNode } from "react";
45 import { msg, T, useGT, useMessages, Var } from "gt-react";
46 import { m as resolveNow, type MessageResolver } from "../../i18n/messages";
47
48 import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
49 import {
50 useEnvironmentSettings,
51 usePersistEnvironmentProviderInstanceMutation,
52 useUpdateEnvironmentSettings,
53 useUpdateEnvironmentModelPreferences,
54 useToggleEnvironmentModelFavorite,
55 } from "../../hooks/useSettings";
56 import { useStableCallback } from "../../hooks/useStableCallback";
57 import { ensureLocalApi } from "../../localApi";
58 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
59 import { cn } from "../../lib/utils";
60 import { resolveAppModelSelectionState } from "../../modelSelection";
61 import {
62 useEnvironments,
63 usePrimaryEnvironmentId,
64 type EnvironmentPresentation,
65 } from "../../state/environments";
66 import {
67 EMPTY_SERVER_PROVIDERS,
68 providersIgnoringCheckedAtAtom,
69 serverEnvironment,
70 } from "../../state/server";
71 import { useEnvironmentSessionState } from "../../state/session";
72 import { useProjects } from "../../state/entities";
73 import { useAtomCommand } from "../../state/use-atom-command";
74 import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
75 import {
76 ConnectionStatusDot,
77 connectionPhaseDotClassName,
78 connectionPhasePingClassName,
79 } from "../ConnectionStatusDot";
80 import {
81 isProviderSettingsUpdateCandidate,
82 isProviderUpdateActive,
83 type ProviderSettingsUpdateCandidate,
84 } from "../ProviderUpdateLaunchNotification.logic";
85 import { ProviderUpdatesAction } from "../ProviderUpdatesAction";
86 import { Button } from "../ui/button";
87 import {
88 Empty,
89 EmptyContent,
90 EmptyDescription,
91 EmptyHeader,
92 EmptyMedia,
93 EmptyTitle,
94 } from "../ui/empty";
95 import { ScrollArea } from "../ui/scroll-area";
96 import { Toggle, ToggleGroup } from "../ui/toggle-group";
97 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
98 import { stackedThreadToast, toastManager } from "../ui/toast";
99 import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
100 import { useManagedPolicy } from "~/state/managedPolicy";
101 import { ExpandableText } from "./ExpandableText";
102 import { IntervalSecondsField } from "./IntervalSecondsField";
103 import { ProviderInstanceCard } from "./ProviderInstanceCard";
104 import { useSecretSources } from "./SecretSourceInput";
105 import { TextGeneratorsSettings } from "./TextGeneratorsSettings";
106 import { UsageProviderSettings } from "./UsageProviderSettings";
107 import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
108 import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
109 import { CodexSetupSection, CodexManagedRuntimeFields } from "./CodexSetupSection";
110 import { readCodexSetupMode } from "./CodexSetupSection.logic";
111 import { providerClients } from "./providerDriverMeta";
112 import { useSearchableSetting } from "./settingsSearch";
113 import { CompactIdleThreadsRow } from "./SettingsPanels";
114 import {
115 backgroundActivityOverrideSettings,
116 buildProviderInstanceUpdatePatch,
117 durationToSeconds,
118 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
119 } from "./SettingsPanels.logic";
120 import {
121 PolicyTooltip,
122 SettingResetButton,
123 SettingsPageContainer,
124 SettingsRow,
125 SettingsSection,
126 useSettingsSearchTargetId,
127 } from "./settingsLayout";
128 import {
129 buildProviderEnvironmentOptions,
130 buildProviderInstanceOverridePatch,
131 classifyProviderEnvironmentAccess,
132 isProviderSettingsEnvironmentAvailable,
133 type ProviderEnvironmentAccess,
134 type ProviderOperateAccess,
135 resolveRemoteOperateAccess,
136 resolveSelectedProviderEnvironmentId,
137 } from "./ProviderSettingsPanel.logic";
138
139 function providerInstanceName(instance: ProviderInstanceConfig): string {
140 return (
141 instance.displayName?.trim() ||
142 providerClients.get(instance.driver)?.label ||
143 String(instance.driver)
144 );
145 }
146
147 async function confirmProviderInstanceRemoval(
148 question: string,
149 consequence = "",
150 ): Promise<boolean> {
151 const message = `${question}\n${resolveNow(msg("Its saved settings, including any custom binary path, will be removed."))}${consequence}`;
152 const confirmed = await settlePromise(() =>
153 ensureLocalApi().dialogs.confirm(message, { variant: "destructive" }),
154 );
155 return confirmed._tag === "Success" && confirmed.value;
156 }
157
158 function modelListChanges(current: ReadonlyArray<string>, next: ReadonlyArray<string>) {
159 const currentSet = new Set(current);
160 const nextSet = new Set(next.map((model) => model.trim()).filter(Boolean));
161 return [...new Set([...currentSet, ...nextSet])]
162 .filter((model) => currentSet.has(model) !== nextSet.has(model))
163 .map((model) => ({ model, selected: nextSet.has(model) }));
164 }
165
166 function providerConfigString(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 const PROVIDER_SETTINGS = providerClients.definitions.map((definition) => ({
173 provider: definition.driverKind,
174 hasDefaultInstance: definition.hasDefaultInstance !== false,
175 }));
176
177 function configuredBinaryPath(config: unknown): string {
178 if (config === null || typeof config !== "object" || !("binaryPath" in config)) return "";
179 return typeof config.binaryPath === "string" ? config.binaryPath.trim() : "";
180 }
181
182 // Subscribe only in the label because every status push restamps all providers' checkedAt.
183 function ProviderLastChecked({ environmentId }: { environmentId: EnvironmentId }) {
184 const serverProviders =
185 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
186 const lastCheckedAt =
187 serverProviders.length > 0
188 ? serverProviders.reduce(
189 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
190 serverProviders[0]!.checkedAt,
191 )
192 : null;
193 const lastCheckedRelative = useRelativeTimeState(lastCheckedAt);
194 const gt = useGT();
195
196 if (lastCheckedRelative.status === "missing") {
197 return null;
198 }
199
200 if (lastCheckedRelative.status === "invalid") {
201 return (
202 <span>
203 <T>Checked unavailable</T>
204 </span>
205 );
206 }
207
208 return (
209 <span>
210 {lastCheckedRelative.suffix ? (
211 <T context="the time is an elapsed time such as 5m">
212 Checked{" "}
213 <span className="font-mono tabular-nums">
214 <Var>{lastCheckedRelative.value}</Var>
215 </span>{" "}
216 ago
217 </T>
218 ) : (
219 gt("Checked {time}", { time: lastCheckedRelative.value })
220 )}
221 </span>
222 );
223 }
224
225 const T3_CONNECT_NAME = "T3 Connect";
226
227 function providerEnvironmentDetail(
228 environment: EnvironmentPresentation,
229 resolve: MessageResolver,
230 ): string {
231 if (environment.entry.target._tag === "PrimaryConnectionTarget")
232 return resolve(msg("Primary device"));
233 if (environment.relayManaged) return T3_CONNECT_NAME;
234 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
235 if (isDesktopLocalConnectionTarget(environment.entry.target)) return resolve(msg("Local device"));
236 return environment.displayUrl ?? resolve(msg("Remote device"));
237 }
238
239 const providerCardHeightClassName =
240 "@min-[48rem]/providers:h-[min(44rem,calc(100dvh-11rem))] @min-[48rem]/providers:min-h-[32rem]";
241
242 function ProviderSettingsPlaceholder({
243 deviceTabs,
244 icon,
245 title,
246 description,
247 children,
248 }: {
249 readonly deviceTabs?: ReactNode;
250 readonly icon: ReactNode;
251 readonly title: string;
252 readonly description: string;
253 readonly children?: ReactNode;
254 }) {
255 const searchableSetting = useSearchableSetting();
256 return (
257 <SettingsSection {...searchableSetting("providers")} variant="plain">
258 {deviceTabs ? (
259 <div className="flex min-h-11 min-w-0 items-center px-3 sm:px-4">{deviceTabs}</div>
260 ) : null}
261 <SettingsGroup
262 divided={false}
263 className={cn(
264 providerCardHeightClassName,
265 "scrollbar-gutter-both flex overflow-x-hidden overflow-y-auto",
266 )}
267 >
268 <Empty>
269 <EmptyMedia variant="icon">{icon}</EmptyMedia>
270 <EmptyHeader>
271 <EmptyTitle>{title}</EmptyTitle>
272 <EmptyDescription>{description}</EmptyDescription>
273 </EmptyHeader>
274 {children ? <EmptyContent className="max-w-xl">{children}</EmptyContent> : null}
275 </Empty>
276 </SettingsGroup>
277 </SettingsSection>
278 );
279 }
280
281 function EnvironmentUnavailablePlaceholder({
282 environment,
283 access,
284 deviceTabs,
285 }: {
286 readonly environment: EnvironmentPresentation;
287 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
288 readonly deviceTabs?: ReactNode;
289 }) {
290 const gt = useGT();
291 const m = useMessages();
292 const isLoading = access.kind === "loading";
293 const title = isLoading
294 ? gt("Loading provider settings")
295 : access.kind === "error"
296 ? gt("Could not connect to this device")
297 : gt("Provider settings are unavailable");
298 const description = isLoading
299 ? access.reason === "permissions"
300 ? gt("Checking what this session is allowed to change.")
301 : gt("Waiting for {environment}''s configuration.", { environment: environment.label })
302 : connectionStatusTitle(environment.connection, m);
303 const error = isLoading ? null : connectionErrorText(environment.connection, m);
304 // Wedged devices can remain here indefinitely; a spinner would continuously repaint.
305 return (
306 <ProviderSettingsPlaceholder
307 deviceTabs={deviceTabs}
308 icon={
309 <EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(environment.serverConfig)} />
310 }
311 title={title}
312 description={description}
313 >
314 {error ? (
315 <ExpandableText
316 key={environment.environmentId}
317 text={error}
318 className="w-full text-left font-mono text-xs leading-relaxed text-muted-foreground"
319 />
320 ) : null}
321 </ProviderSettingsPlaceholder>
322 );
323 }
324
325 interface ProviderSettingsTarget {
326 readonly environmentId?: EnvironmentId;
327 readonly instanceId?: ProviderInstanceId;
328 readonly scoped?: boolean;
329 readonly environmentIds?: readonly EnvironmentId[];
330 readonly projectIds?: readonly ProjectId[];
331 }
332
333 export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
334 return (
335 <SettingsPageContainer className="@container/providers gap-8">
336 <ProviderSettingsPanelContent
337 key={`${target.environmentId ?? ""}:${target.instanceId ?? ""}`}
338 {...target}
339 />
340 </SettingsPageContainer>
341 );
342 }
343
344 function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
345 const searchableSetting = useSearchableSetting();
346 const gt = useGT();
347 const m = useMessages();
348 const { environments, isReady } = useEnvironments();
349 const primaryEnvironmentId = usePrimaryEnvironmentId();
350 const searchTargetId = useSettingsSearchTargetId();
351 const options = buildProviderEnvironmentOptions(
352 environments,
353 primaryEnvironmentId,
354 target.environmentIds,
355 );
356 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
357 target.environmentId ?? primaryEnvironmentId,
358 );
359 const targetEnvironmentMissing =
360 target.environmentId !== undefined &&
361 selectedEnvironmentId === target.environmentId &&
362 !options.some((environment) => environment.environmentId === target.environmentId);
363 const effectiveEnvironmentId =
364 target.scoped || targetEnvironmentMissing
365 ? target.environmentId
366 : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
367 const selectedEnvironment =
368 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
369 const selectedEnvironmentCanRenderSettings =
370 selectedEnvironment !== null &&
371 isProviderSettingsEnvironmentAvailable({
372 connectionPhase: selectedEnvironment.connection.phase,
373 hasServerConfig: selectedEnvironment.serverConfig !== null,
374 });
375 const searchableEnvironmentId = options.find((environment) =>
376 isProviderSettingsEnvironmentAvailable({
377 connectionPhase: environment.connection.phase,
378 hasServerConfig: environment.serverConfig !== null,
379 }),
380 )?.environmentId;
381 let searchRedirectEnvironmentId: EnvironmentId | undefined;
382 {
383 if (
384 !target.scoped &&
385 (searchTargetId === searchableSetting("provider-health-check-interval").id ||
386 searchTargetId === searchableSetting("usage-providers").id) &&
387 !selectedEnvironmentCanRenderSettings &&
388 searchableEnvironmentId !== undefined
389 ) {
390 searchRedirectEnvironmentId = searchableEnvironmentId;
391 }
392 }
393 if (
394 searchRedirectEnvironmentId !== undefined &&
395 searchRedirectEnvironmentId !== selectedEnvironmentId
396 ) {
397 setSelectedEnvironmentId(searchRedirectEnvironmentId);
398 }
399 const onlyPrimaryDevice =
400 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
401 const deviceTabs =
402 !target.scoped && !onlyPrimaryDevice && options.length > 0 ? (
403 <ScrollArea radius="none" hideScrollbars scrollFade className="h-11 min-w-0 flex-1">
404 <ToggleGroup
405 aria-label={gt("Devices")}
406 variant="segmented"
407 className="my-2"
408 value={effectiveEnvironmentId ? [effectiveEnvironmentId] : []}
409 onValueChange={(next) => {
410 const environment = options.find((option) => option.environmentId === next[0]);
411 if (environment) setSelectedEnvironmentId(environment.environmentId);
412 }}
413 >
414 {options.map((environment) => {
415 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
416 const detail = providerEnvironmentDetail(environment, m);
417 const statusText = connectionStatusTitle(environment.connection, m);
418 return (
419 <Tooltip key={environment.environmentId}>
420 <TooltipTrigger
421 render={
422 <Toggle value={environment.environmentId}>
423 <EnvironmentMachineIcon
424 kind={machine}
425 className="size-3.5 shrink-0"
426 aria-hidden
427 />
428 <span className="max-w-40 truncate">{environment.label}</span>
429 {environment.connection.phase !== "connected" ? (
430 <ConnectionStatusDot
431 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
432 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
433 />
434 ) : null}
435 <span className="sr-only">
436 {detail}, {statusText}
437 </span>
438 </Toggle>
439 }
440 />
441 <TooltipPopup side="top">
442 {detail} · {statusText}
443 </TooltipPopup>
444 </Tooltip>
445 );
446 })}
447 </ToggleGroup>
448 </ScrollArea>
449 ) : null;
450
451 return (
452 <>
453 {targetEnvironmentMissing ? (
454 <ProviderSettingsPlaceholder
455 deviceTabs={deviceTabs}
456 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
457 title={gt("Device unavailable")}
458 description={gt(
459 "Reconnect this device to set up its provider, or select another device.",
460 )}
461 />
462 ) : null}
463 {options.length === 0 && !targetEnvironmentMissing ? (
464 <ProviderSettingsPlaceholder
465 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
466 title={isReady ? gt("No connected devices") : gt("Loading devices")}
467 description={
468 isReady
469 ? gt("Connect an execution environment before configuring providers.")
470 : gt("Reading connected execution environments.")
471 }
472 />
473 ) : null}
474
475 {selectedEnvironment ? (
476 <RemoteSessionGatedProviderSettings
477 key={selectedEnvironment.environmentId}
478 environment={selectedEnvironment}
479 deviceTabs={deviceTabs}
480 targetInstanceId={
481 target.environmentId === undefined ||
482 selectedEnvironment.environmentId === target.environmentId
483 ? target.instanceId
484 : undefined
485 }
486 projectIds={target.projectIds ?? []}
487 />
488 ) : null}
489 </>
490 );
491 }
492
493 function RemoteSessionGatedProviderSettings({
494 environment,
495 deviceTabs,
496 targetInstanceId,
497 projectIds,
498 }: {
499 readonly environment: EnvironmentPresentation;
500 readonly deviceTabs?: ReactNode;
501 readonly targetInstanceId?: ProviderInstanceId | undefined;
502 readonly projectIds: readonly ProjectId[];
503 }) {
504 const sessionState = useEnvironmentSessionState(environment.environmentId);
505 const operateAccess = resolveRemoteOperateAccess({
506 session: sessionState.data,
507 isPending: sessionState.isPending,
508 hasError: sessionState.hasError,
509 });
510 return (
511 <AccessGatedProviderSettings
512 environment={environment}
513 operateAccess={operateAccess}
514 deviceTabs={deviceTabs}
515 targetInstanceId={targetInstanceId}
516 projectIds={projectIds}
517 />
518 );
519 }
520
521 function AccessGatedProviderSettings({
522 environment,
523 operateAccess,
524 deviceTabs,
525 targetInstanceId,
526 projectIds,
527 }: {
528 readonly environment: EnvironmentPresentation;
529 readonly operateAccess: ProviderOperateAccess;
530 readonly deviceTabs?: ReactNode;
531 readonly targetInstanceId?: ProviderInstanceId | undefined;
532 readonly projectIds: readonly ProjectId[];
533 }) {
534 const access = classifyProviderEnvironmentAccess({
535 connectionPhase: environment.connection.phase,
536 hasServerConfig: environment.serverConfig !== null,
537 operateAccess,
538 });
539 if (access.kind !== "editable" && access.kind !== "read-only") {
540 return (
541 <EnvironmentUnavailablePlaceholder
542 environment={environment}
543 access={access}
544 deviceTabs={deviceTabs}
545 />
546 );
547 }
548 return (
549 <EnvironmentProviderSettings
550 environmentId={environment.environmentId}
551 environmentLabel={environment.label}
552 readOnly={access.kind === "read-only"}
553 deviceTabs={deviceTabs}
554 targetInstanceId={targetInstanceId}
555 projectIds={projectIds}
556 />
557 );
558 }
559
560 const NO_PROJECT_IDS: readonly ProjectId[] = [];
561 const NO_FAVORITES: UnifiedSettings["favorites"] = [];
562
563 export function EnvironmentProviderSettings({
564 environmentId,
565 environmentLabel,
566 readOnly = false,
567 deviceTabs,
568 targetInstanceId,
569 projectIds = NO_PROJECT_IDS,
570 }: {
571 readonly environmentId: EnvironmentId;
572 readonly environmentLabel: string;
573 readonly deviceTabs?: ReactNode;
574 readonly targetInstanceId?: ProviderInstanceId | undefined;
575 readonly projectIds?: readonly ProjectId[];
576 readonly readOnly?: boolean;
577 }) {
578 const searchableSetting = useSearchableSetting();
579 const gt = useGT();
580 const settings = useEnvironmentSettings(environmentId);
581 const managedPolicy = useManagedPolicy(environmentId);
582 // A policy that allows no provider leaves nothing to add.
583 const canAddProvider =
584 !readOnly && managedPolicy?.limits?.providers?.allowedDrivers?.length !== 0;
585 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
586 const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
587 const updateSettings = useUpdateEnvironmentSettings(environmentId);
588 const updateModelPreferences = useUpdateEnvironmentModelPreferences(environmentId);
589 const toggleModelFavorite = useToggleEnvironmentModelFavorite(environmentId);
590 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
591 const serverProviders = useAtomValue(providersIgnoringCheckedAtAtom(environmentId));
592 // Hide overrides on older servers that silently ignore providerInstances patches.
593 const supportsProjectProviderOverrides = useAtomValue(
594 serverEnvironment.configValueAtom(environmentId),
595 (config) => config?.environment.capabilities.projectProviderInstanceOverrides === true,
596 );
597 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
598 reportFailure: false,
599 });
600 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
601 reportFailure: false,
602 });
603 const uninstallAcpRegistryManagedBinary = useAtomCommand(
604 serverEnvironment.uninstallAcpRegistryManagedBinary,
605 { reportFailure: false },
606 );
607 const acceptAcpRegistryUrlAuth = useAtomCommand(serverEnvironment.acceptAcpRegistryUrlAuth, {
608 reportFailure: false,
609 });
610 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
611 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
612 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
613 targetInstanceId ?? null,
614 );
615 const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<
616 ReadonlySet<ProviderInstanceId>
617 >(() => new Set());
618 const refreshingRef = useRef(false);
619 const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());
620
621 const acceptUrlAuthentication = useStableCallback(
622 (instanceId: ProviderInstanceId, action: AcpRegistryUrlAuthAction) => {
623 void acceptAcpRegistryUrlAuth({
624 environmentId,
625 input: { instanceId, elicitationId: action.elicitationId },
626 }).then((result) => {
627 if (result._tag === "Success" && !result.value.accepted) {
628 toastManager.add({
629 type: "warning",
630 title: gt("Authentication request expired"),
631 description: gt("Refresh the provider and start the authentication flow again."),
632 });
633 return;
634 }
635 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
636 const error = squashAtomCommandFailure(result);
637 toastManager.add({
638 type: "error",
639 title: gt("Could not continue authentication"),
640 description:
641 error instanceof Error
642 ? (thrownErrorMessage(error, resolveNow) ?? error.message)
643 : gt("The authentication request expired."),
644 });
645 }
646 });
647 },
648 );
649
650 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
651 (providerSettings) =>
652 providerSettings.provider !== "cursor" ||
653 serverProviders.some(
654 (provider) =>
655 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
656 ),
657 );
658 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
659 const providerHealthPreset = getBackgroundActivityPresetSettings(
660 resolvedBackgroundActivity.profile,
661 ).providerHealthRefreshInterval;
662 const providerHealthRefreshIntervalSeconds = durationToSeconds(
663 resolvedBackgroundActivity.providerHealthRefreshInterval,
664 );
665 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
666
667 const refreshProviders = () => {
668 if (refreshingRef.current || !readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
669 return;
670 refreshingRef.current = true;
671 setIsRefreshingProviders(true);
672 void (async () => {
673 const result = await refreshServerProviders({
674 environmentId,
675 input: { refreshModels: true, reloadSecrets: true },
676 });
677 refreshingRef.current = false;
678 setIsRefreshingProviders(false);
679 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
680 console.warn("Failed to refresh providers", {
681 operation: "refresh-providers",
682 environmentId,
683 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
684 });
685 }
686 })();
687 };
688
689 const runProviderUpdate = useStableCallback(
690 async (
691 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
692 targetVersion?: string,
693 ) => {
694 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
695 // Guard re-entry with a ref; deferred state updates cannot gate dispatch.
696 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
697 return;
698 }
699 updatingInstanceIdsRef.current.add(candidate.instanceId);
700 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
701
702 const result = await updateProvider({
703 environmentId,
704 input: {
705 provider: candidate.driver,
706 instanceId: candidate.instanceId,
707 ...(targetVersion ? { targetVersion } : {}),
708 },
709 });
710 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
711 const error = squashAtomCommandFailure(result);
712 toastManager.add(
713 stackedThreadToast({
714 type: "error",
715 title: gt("Could not update {provider}", {
716 provider: PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
717 }),
718 description:
719 error instanceof Error
720 ? (errorDisplayMessage(error, resolveNow) ?? error.message)
721 : gt("The provider update command could not be started."),
722 }),
723 );
724 }
725 updatingInstanceIdsRef.current.delete(candidate.instanceId);
726 setUpdatingProviderInstanceIds((previous) => {
727 if (!previous.has(candidate.instanceId)) {
728 return previous;
729 }
730 const next = new Set(previous);
731 next.delete(candidate.instanceId);
732 return next;
733 });
734 },
735 );
736
737 interface InstanceRow {
738 readonly instanceId: ProviderInstanceId;
739 /** Undefined for a default slot the user never configured. */
740 readonly explicitInstance: ProviderInstanceConfig | undefined;
741 readonly driver: ProviderDriverKind;
742 readonly isDefault: boolean;
743 readonly isDirty?: boolean;
744 }
745
746 const instancesByDriver = new Map<
747 ProviderDriverKind,
748 Array<[ProviderInstanceId, ProviderInstanceConfig]>
749 >();
750 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
751 const driver = instance.driver;
752 const list = instancesByDriver.get(driver) ?? [];
753 list.push([rawId as ProviderInstanceId, instance]);
754 instancesByDriver.set(driver, list);
755 }
756
757 const defaultSlotIdsBySource = new Set<string>(
758 visibleProviderSettings.map((providerSettings) =>
759 String(defaultInstanceIdForDriver(providerSettings.provider)),
760 ),
761 );
762
763 const rows: InstanceRow[] = [];
764 const visibleDriverKinds = new Set<ProviderDriverKind>(
765 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
766 );
767
768 for (const providerSettings of visibleProviderSettings) {
769 const driver = providerSettings.provider;
770 const defaultInstanceId = defaultInstanceIdForDriver(driver);
771 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
772 const isDirty = explicitInstance !== undefined;
773 const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined;
774 if (
775 hasDefaultSlot &&
776 (driver === "codex" ||
777 driver === "claudeAgent" ||
778 isDirty ||
779 resolveProviderInstanceEnabled(explicitInstance ?? { driver }) ||
780 defaultInstanceId === targetInstanceId)
781 ) {
782 rows.push({
783 instanceId: defaultInstanceId,
784 explicitInstance,
785 driver,
786 isDefault: true,
787 isDirty,
788 });
789 }
790 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
791 if (id === defaultInstanceId) continue;
792 rows.push({
793 instanceId: id,
794 explicitInstance: instance,
795 driver: instance.driver,
796 isDefault: false,
797 });
798 }
799 }
800 for (const [driver, list] of instancesByDriver) {
801 if (visibleDriverKinds.has(driver)) continue;
802 for (const [id, instance] of list) {
803 rows.push({
804 instanceId: id,
805 explicitInstance: instance,
806 driver: instance.driver,
807 isDefault: defaultSlotIdsBySource.has(String(id)),
808 });
809 }
810 }
811
812 const targetInstanceMissing =
813 targetInstanceId !== undefined &&
814 selectedInstanceId === targetInstanceId &&
815 !rows.some((row) => row.instanceId === targetInstanceId);
816 const selectedRow =
817 rows.find((row) => row.instanceId === selectedInstanceId) ??
818 (targetInstanceMissing ? null : (rows[0] ?? null));
819
820 const persistInstance = async (
821 instanceId: ProviderInstanceId,
822 next: ProviderInstanceConfig,
823 textGenerationModelSelection?: Parameters<
824 typeof buildProviderInstanceUpdatePatch
825 >[0]["textGenerationModelSelection"],
826 ) => {
827 const { providerInstances: _providerInstances, ...patch } = buildProviderInstanceUpdatePatch({
828 settings,
829 instanceId,
830 instance: next,
831 textGenerationModelSelection,
832 });
833 const result = await persistProviderInstance(
834 { operation: "upsert", instanceId, instance: next },
835 patch,
836 );
837 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
838 const error = squashAtomCommandFailure(result);
839 toastManager.add({
840 type: "error",
841 title: gt("Could not update provider instance"),
842 description:
843 error instanceof Error
844 ? (thrownErrorMessage(error, resolveNow) ?? error.message)
845 : gt("The settings update failed."),
846 });
847 }
848 return result._tag !== "Failure";
849 };
850
851 const updateInstance = useStableCallback(
852 (
853 instanceId: ProviderInstanceId,
854 previous: ProviderInstanceConfig,
855 next: ProviderInstanceConfig,
856 ) => {
857 const isDisabling = next.enabled === false && resolveProviderInstanceEnabled(previous);
858 const shouldClearTextGen =
859 isDisabling &&
860 resolveAppModelSelectionState(settings, serverProviders).instanceId === instanceId &&
861 readEnvironmentScope(environmentId, AuthSettingsWriteScope);
862 return persistInstance(
863 instanceId,
864 next,
865 shouldClearTextGen ? DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection : undefined,
866 );
867 },
868 );
869
870 const enableInstance = useStableCallback(
871 (instanceId: ProviderInstanceId, next: ProviderInstanceConfig) =>
872 persistInstance(instanceId, next),
873 );
874
875 const deleteInstance = useStableCallback(
876 async (instanceId: ProviderInstanceId, instance: ProviderInstanceConfig) => {
877 const confirmed = await confirmProviderInstanceRemoval(
878 gt("Remove the {provider} provider instance?", {
879 provider: providerInstanceName(instance),
880 }),
881 );
882 if (!confirmed) return;
883 const updateResult = await persistProviderInstance({
884 operation: "remove",
885 instanceId,
886 });
887 if (updateResult._tag === "Failure") {
888 const error = squashAtomCommandFailure(updateResult);
889 toastManager.add({
890 type: "error",
891 title: gt("Could not delete provider instance"),
892 description:
893 error instanceof Error
894 ? (thrownErrorMessage(error, resolveNow) ?? error.message)
895 : gt("The settings update failed."),
896 });
897 return;
898 }
899
900 if (instance.driver !== ProviderDriverKind.make("acpRegistry")) return;
901 if (providerConfigString(instance.config, "source") === "local") return;
902 const agentId = providerConfigString(instance.config, "agentId");
903 if (agentId === null) return;
904
905 // Concurrent removals race client snapshots; let the server decide whether the agent remains in use.
906 const uninstallResult = await uninstallAcpRegistryManagedBinary({
907 environmentId,
908 input: { agentId },
909 });
910 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
911 const error = squashAtomCommandFailure(uninstallResult);
912 toastManager.add({
913 type: "warning",
914 title: gt("Provider deleted, but managed files remain"),
915 description:
916 error instanceof Error
917 ? (thrownErrorMessage(error, resolveNow) ?? error.message)
918 : gt("Managed binary cleanup failed."),
919 });
920 }
921 },
922 );
923
924 const resetDefaultInstance = useStableCallback(async (driverKind: ProviderDriverKind) => {
925 const instanceId = defaultInstanceIdForDriver(driverKind);
926 const instance = settings.providerInstances?.[instanceId] ?? { driver: driverKind };
927 const turnsOff =
928 resolveProviderInstanceEnabled(instance) &&
929 !resolveProviderInstanceEnabled({ driver: driverKind });
930 const confirmed = await confirmProviderInstanceRemoval(
931 gt("Reset the {provider} provider to its defaults?", {
932 provider: providerInstanceName(instance),
933 }),
934 turnsOff ? ` ${gt("It will also be turned off.")}` : "",
935 );
936 if (!confirmed) return;
937 const result = await persistProviderInstance({ operation: "remove", instanceId });
938 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
939 const error = squashAtomCommandFailure(result);
940 toastManager.add({
941 type: "error",
942 title: gt("Could not reset provider instance"),
943 description:
944 error instanceof Error
945 ? (thrownErrorMessage(error, resolveNow) ?? error.message)
946 : gt("The settings update failed."),
947 });
948 }
949 });
950
951 const writeProjectOverride = useStableCallback(
952 (instanceId: ProviderInstanceId, next: boolean | undefined) => {
953 updateSettings({
954 projectSettingsOverrides: buildProviderInstanceOverridePatch(
955 settings,
956 projectIds,
957 instanceId,
958 next,
959 ),
960 });
961 },
962 );
963
964 const stableUpdateModelPreferences = useStableCallback(updateModelPreferences);
965 const stableToggleModelFavorite = useStableCallback(toggleModelFavorite);
966 const actions: ProviderInstanceRowActions = {
967 acceptUrlAuthentication,
968 runProviderUpdate,
969 updateInstance,
970 enableInstance,
971 deleteInstance,
972 resetDefaultInstance,
973 writeProjectOverride,
974 updateModelPreferences: stableUpdateModelPreferences,
975 toggleModelFavorite: stableToggleModelFavorite,
976 selectInstance: setSelectedInstanceId,
977 };
978 // resolveModelPreferences falls back to a fresh `[]`; keep it stable for the rows.
979 const favorites = settings.favorites.length > 0 ? settings.favorites : NO_FAVORITES;
980
981 const representativeProjectId = projectIds[0];
982 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
983 const showProjectOverride =
984 representativeProjectId !== undefined && supportsProjectProviderOverrides;
985 return (
986 <ProviderInstanceRow
987 key={row.instanceId}
988 environmentId={environmentId}
989 environmentLabel={environmentLabel}
990 instanceId={row.instanceId}
991 driver={row.driver}
992 explicitInstance={row.explicitInstance}
993 isDefault={row.isDefault}
994 isDirty={row.isDirty === true}
995 mode={mode}
996 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
997 readOnly={readOnly}
998 canWriteSettings={canWriteSettings}
999 liveProvider={serverProviders.find((candidate) => candidate.instanceId === row.instanceId)}
1000 isUpdateDispatching={updatingProviderInstanceIds.has(row.instanceId)}
1001 showProjectOverride={showProjectOverride}
1002 projectOverrideValue={
1003 showProjectOverride
1004 ? settings.projectSettingsOverrides[representativeProjectId]?.providerInstances?.[
1005 row.instanceId
1006 ]?.enabled
1007 : undefined
1008 }
1009 projectOverrideEffectiveEnabled={
1010 showProjectOverride
1011 ? resolveProjectProviderInstanceEnabled(
1012 settings,
1013 representativeProjectId,
1014 row.instanceId,
1015 )
1016 : false
1017 }
1018 modelPreferences={settings.providerModelPreferences?.[row.instanceId]}
1019 favorites={favorites}
1020 actions={actions}
1021 />
1022 );
1023 };
1024
1025 return (
1026 <>
1027 <SettingsSection
1028 {...searchableSetting("providers")}
1029 variant="plain"
1030 titleAction={
1031 canAddProvider ? (
1032 <Tooltip>
1033 <TooltipTrigger
1034 render={
1035 <Button
1036 size="icon-xs"
1037 variant="ghost-muted"
1038 onClick={() => setIsAddInstanceDialogOpen(true)}
1039 aria-label={gt("Add provider")}
1040 >
1041 <PlusIcon />
1042 </Button>
1043 }
1044 />
1045 <TooltipPopup side="top">
1046 <T>Add provider</T>
1047 </TooltipPopup>
1048 </Tooltip>
1049 ) : null
1050 }
1051 headerAction={
1052 // The ghost button's padding would inset its label, so pull the text to the card edge.
1053 <div className="-me-2 flex min-w-0 items-center gap-2">
1054 <ProviderUpdatesAction />
1055 <Tooltip>
1056 <TooltipTrigger
1057 render={
1058 <Button
1059 size="xs"
1060 variant="ghost-muted"
1061 disabled={isRefreshingProviders || !canRefreshProviders}
1062 aria-busy={isRefreshingProviders}
1063 onClick={() => void refreshProviders()}
1064 >
1065 <RefreshIcon refreshing={isRefreshingProviders} />
1066 <span className="sr-only">
1067 <T>Refresh provider status</T>
1068 </span>
1069 <span className="hidden min-w-0 truncate sm:inline">
1070 {isRefreshingProviders ? (
1071 gt("Refreshing providers")
1072 ) : (
1073 <ProviderLastChecked environmentId={environmentId} />
1074 )}
1075 </span>
1076 </Button>
1077 }
1078 />
1079 <TooltipPopup side="top">
1080 <T>Refresh provider status</T>
1081 </TooltipPopup>
1082 </Tooltip>
1083 </div>
1084 }
1085 >
1086 {deviceTabs ? (
1087 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1088 ) : null}
1089 {readOnly ? (
1090 <SettingsGroup divided={false} className="overflow-hidden">
1091 <SettingsRow
1092 title={gt("Limited permissions")}
1093 description={gt(
1094 "This session can view {environment}''s providers but can't change their settings.",
1095 { environment: environmentLabel },
1096 )}
1097 />
1098 </SettingsGroup>
1099 ) : null}
1100 <SettingsGroup
1101 divided={false}
1102 className={cn(
1103 providerCardHeightClassName,
1104 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1105 )}
1106 >
1107 <div className="border-b border-border/60 bg-muted/10 @min-[48rem]/providers:flex @min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-col @min-[48rem]/providers:border-r @min-[48rem]/providers:border-b-0">
1108 <ScrollArea
1109 scrollFade
1110 chainVerticalScroll
1111 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1112 >
1113 <div className="divide-y divide-border/50">
1114 {rows.map((row) => renderProviderInstance(row, "list"))}
1115 {canAddProvider ? (
1116 <button
1117 type="button"
1118 className="flex w-full cursor-pointer items-center gap-3 px-3 py-3 text-left text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/25 hover:text-foreground focus-visible:bg-muted/25 focus-visible:text-foreground sm:px-4"
1119 onClick={() => setIsAddInstanceDialogOpen(true)}
1120 >
1121 <PlusIcon className="size-4 shrink-0" />
1122 <T>Add provider</T>
1123 </button>
1124 ) : null}
1125 </div>
1126 </ScrollArea>
1127 </div>
1128
1129 <div data-provider-detail className="min-w-0 @min-[48rem]/providers:min-h-0">
1130 {selectedRow ? (
1131 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1132 {/* Flat sections run dividers edge to edge and inset text like the list beside them. */}
1133 <div className="space-y-6 py-4">
1134 {renderProviderInstance(selectedRow, "editor")}
1135 </div>
1136 </ScrollArea>
1137 ) : (
1138 <div className="p-6 text-sm text-muted-foreground">
1139 {targetInstanceMissing
1140 ? gt("This provider instance is no longer available on this device.")
1141 : gt("No providers configured.")}
1142 </div>
1143 )}
1144 </div>
1145 </SettingsGroup>
1146 </SettingsSection>
1147
1148 <UsageProviderSettings
1149 key={environmentId}
1150 environmentId={environmentId}
1151 environmentLabel={environmentLabel}
1152 sources={settings.usageLimitSources}
1153 readOnly={readOnly}
1154 />
1155
1156 {/* The server drops text generators under a provider allow-list. */}
1157 {managedPolicy?.limits?.providers?.allowedDrivers === undefined ? (
1158 <TextGeneratorsSettings
1159 key={`text-generators:${environmentId}`}
1160 environmentId={environmentId}
1161 environmentLabel={environmentLabel}
1162 providers={serverProviders}
1163 readOnly={readOnly}
1164 />
1165 ) : null}
1166
1167 <SettingsSection title={gt("Advanced")}>
1168 <SettingsRow
1169 id={searchableSetting("provider-health-check-interval").id}
1170 title={
1171 <span className="inline-flex items-center gap-1.5">
1172 {searchableSetting("provider-health-check-interval").title}
1173 <PolicyTooltip>
1174 {gt(
1175 "This interval is configured here, then the shared Background activity policy decides whether provider probes may run when the timer fires. Custom intervals appear as Advanced in Maintenance settings.",
1176 )}
1177 </PolicyTooltip>
1178 </span>
1179 }
1180 description={gt(
1181 "Refresh provider status, versions, and models in the background. Set to 0 to disable.",
1182 )}
1183 resetAction={
1184 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1185 <span
1186 inert={!canWriteSettings}
1187 className={!canWriteSettings ? "opacity-50" : undefined}
1188 >
1189 <SettingResetButton
1190 ariaLabel={gt("Reset provider health check interval to default")}
1191 onClick={() =>
1192 updateSettings(
1193 backgroundActivityOverrideSettings(
1194 settings.backgroundActivity,
1195 resolvedBackgroundActivity,
1196 { providerHealthRefreshInterval: undefined },
1197 ),
1198 )
1199 }
1200 />
1201 </span>
1202 ) : null
1203 }
1204 control={
1205 <div
1206 inert={!canWriteSettings}
1207 aria-disabled={!canWriteSettings || undefined}
1208 className={cn(
1209 "flex shrink-0 items-center gap-2",
1210 !canWriteSettings && "opacity-50 select-none",
1211 )}
1212 >
1213 <IntervalSecondsField
1214 labels={{
1215 decrease: gt("Decrease provider health check interval"),
1216 input: gt("Provider health check interval in seconds"),
1217 increase: gt("Increase provider health check interval"),
1218 }}
1219 value={providerHealthRefreshIntervalSeconds}
1220 min={0}
1221 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1222 onCommit={(seconds, options) =>
1223 updateSettings(
1224 backgroundActivityOverrideSettings(
1225 settings.backgroundActivity,
1226 resolvedBackgroundActivity,
1227 { providerHealthRefreshInterval: Duration.seconds(seconds) },
1228 ),
1229 options,
1230 )
1231 }
1232 />
1233 <span className="text-xs text-muted-foreground">
1234 <T>seconds</T>
1235 </span>
1236 </div>
1237 }
1238 />
1239 <CompactIdleThreadsRow />
1240 </SettingsSection>
1241
1242 {isAddInstanceDialogOpen && !readOnly ? (
1243 <AddProviderInstanceDialog
1244 open
1245 environmentId={environmentId}
1246 environmentLabel={environmentLabel}
1247 onOpenChange={setIsAddInstanceDialogOpen}
1248 onCreated={setSelectedInstanceId}
1249 />
1250 ) : null}
1251 </>
1252 );
1253 }
1254
1255 interface ProviderInstanceRowActions {
1256 readonly acceptUrlAuthentication: (
1257 instanceId: ProviderInstanceId,
1258 action: AcpRegistryUrlAuthAction,
1259 ) => void;
1260 readonly runProviderUpdate: (
1261 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
1262 targetVersion?: string,
1263 ) => Promise<void>;
1264 readonly updateInstance: (
1265 instanceId: ProviderInstanceId,
1266 previous: ProviderInstanceConfig,
1267 next: ProviderInstanceConfig,
1268 ) => Promise<boolean>;
1269 readonly enableInstance: (
1270 instanceId: ProviderInstanceId,
1271 next: ProviderInstanceConfig,
1272 ) => Promise<boolean>;
1273 readonly deleteInstance: (
1274 instanceId: ProviderInstanceId,
1275 instance: ProviderInstanceConfig,
1276 ) => Promise<void>;
1277 readonly resetDefaultInstance: (driverKind: ProviderDriverKind) => Promise<void>;
1278 readonly writeProjectOverride: (
1279 instanceId: ProviderInstanceId,
1280 next: boolean | undefined,
1281 ) => void;
1282 readonly updateModelPreferences: ReturnType<typeof useUpdateEnvironmentModelPreferences>;
1283 readonly toggleModelFavorite: ReturnType<typeof useToggleEnvironmentModelFavorite>;
1284 readonly selectInstance: (instanceId: ProviderInstanceId) => void;
1285 }
1286
1287 const NO_MODELS: ReadonlyArray<string> = [];
1288
1289 /** Stable props let this boundary return cached cards even when settings rebuild parent row elements. */
1290 function ProviderInstanceRow({
1291 environmentId,
1292 environmentLabel,
1293 instanceId,
1294 driver,
1295 explicitInstance,
1296 isDefault,
1297 isDirty,
1298 mode,
1299 selected,
1300 readOnly,
1301 canWriteSettings,
1302 liveProvider,
1303 isUpdateDispatching,
1304 showProjectOverride,
1305 projectOverrideValue,
1306 projectOverrideEffectiveEnabled,
1307 modelPreferences,
1308 favorites,
1309 actions,
1310 }: {
1311 readonly environmentId: EnvironmentId;
1312 readonly environmentLabel: string;
1313 readonly instanceId: ProviderInstanceId;
1314 readonly driver: ProviderDriverKind;
1315 readonly explicitInstance: ProviderInstanceConfig | undefined;
1316 readonly isDefault: boolean;
1317 readonly isDirty: boolean;
1318 readonly mode: "list" | "editor";
1319 readonly selected: boolean;
1320 readonly readOnly: boolean;
1321 readonly canWriteSettings: boolean;
1322 readonly liveProvider: ServerProvider | undefined;
1323 readonly isUpdateDispatching: boolean;
1324 readonly showProjectOverride: boolean;
1325 readonly projectOverrideValue: boolean | undefined;
1326 readonly projectOverrideEffectiveEnabled: boolean;
1327 readonly modelPreferences:
1328 | { readonly hiddenModels: ReadonlyArray<string>; readonly modelOrder: ReadonlyArray<string> }
1329 | undefined;
1330 readonly favorites: UnifiedSettings["favorites"];
1331 readonly actions: ProviderInstanceRowActions;
1332 }) {
1333 const gt = useGT();
1334 const allProjects = useProjects();
1335 const secretSources = useSecretSources(environmentId);
1336 const acpProjects =
1337 mode === "editor" && liveProvider?.driver === "acpRegistry"
1338 ? allProjects.filter((project) => project.environmentId === environmentId)
1339 : undefined;
1340 const instance = explicitInstance ?? { driver };
1341 const driverOption = providerClients.get(driver);
1342 const updateCandidate =
1343 liveProvider !== undefined && isProviderSettingsUpdateCandidate(liveProvider)
1344 ? liveProvider
1345 : undefined;
1346 const isInstanceUpdateRunning =
1347 isUpdateDispatching || (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
1348 const hiddenModels = modelPreferences?.hiddenModels ?? NO_MODELS;
1349 const modelOrder = modelPreferences?.modelOrder ?? NO_MODELS;
1350 const favoriteModels = Arr.filterMap(favorites, (favorite) =>
1351 favorite.provider === instanceId ? Result.succeed(favorite.model) : Result.failVoid,
1352 );
1353 const resetLabel = driverOption?.label ?? String(driver);
1354 const projectOverride = showProjectOverride
1355 ? {
1356 value: projectOverrideValue,
1357 effectiveEnabled: projectOverrideEffectiveEnabled,
1358 onChange: (next: boolean) => actions.writeProjectOverride(instanceId, next),
1359 onReset: () => actions.writeProjectOverride(instanceId, undefined),
1360 }
1361 : undefined;
1362 const codexSetupMode = driver === "codex" ? readCodexSetupMode(instance.config) : null;
1363 const recommendedVersion = liveProvider?.compatibilityAdvisory?.recommendedVersion;
1364 const canInstallRecommended =
1365 !readOnly &&
1366 liveProvider !== undefined &&
1367 Boolean(liveProvider.compatibilityAdvisory?.message) &&
1368 Boolean(recommendedVersion) &&
1369 liveProvider.versionAdvisory?.canInstallVersion === true;
1370
1371 return (
1372 <ProviderInstanceCard
1373 environmentId={environmentId}
1374 secretSources={secretSources}
1375 acpProjects={acpProjects}
1376 projectOverride={projectOverride}
1377 onAcceptUrlAuth={
1378 readOnly ? undefined : (action) => actions.acceptUrlAuthentication(instanceId, action)
1379 }
1380 instanceId={instanceId}
1381 instance={instance}
1382 driverOption={driverOption}
1383 liveProvider={liveProvider}
1384 mode={mode}
1385 selected={selected}
1386 onSelect={mode === "list" ? () => actions.selectInstance(instanceId) : undefined}
1387 readOnly={readOnly}
1388 runtime={
1389 mode === "editor" && codexSetupMode === "managed" ? (
1390 <CodexManagedRuntimeFields
1391 environmentId={environmentId}
1392 instanceId={instanceId}
1393 provider={liveProvider}
1394 />
1395 ) : undefined
1396 }
1397 canWriteSettings={canWriteSettings}
1398 setup={
1399 mode === "editor" && driver === "antigravity" ? (
1400 <ProviderSetupSection
1401 environmentId={environmentId}
1402 environmentLabel={environmentLabel}
1403 instanceId={instanceId}
1404 provider={liveProvider}
1405 binaryPath={configuredBinaryPath(instance.config)}
1406 authMethod={readAntigravityAuthMethod(instance.config)}
1407 enabled={resolveProviderInstanceEnabled(instance)}
1408 readOnly={readOnly}
1409 onEnable={() => actions.enableInstance(instanceId, { ...instance, enabled: true })}
1410 />
1411 ) : mode === "editor" && codexSetupMode === "managed" ? (
1412 <CodexSetupSection
1413 environmentId={environmentId}
1414 instanceId={instanceId}
1415 provider={liveProvider}
1416 mode={codexSetupMode}
1417 enabled={resolveProviderInstanceEnabled(instance)}
1418 readOnly={readOnly}
1419 onModeChange={(setupMode) =>
1420 actions.enableInstance(instanceId, {
1421 ...instance,
1422 enabled: true,
1423 config: {
1424 ...(instance.config !== null && typeof instance.config === "object"
1425 ? instance.config
1426 : {}),
1427 enabled: true,
1428 setupMode,
1429 },
1430 })
1431 }
1432 />
1433 ) : mode === "editor" &&
1434 !readOnly &&
1435 liveProvider &&
1436 (liveProvider.setup?.canAuthenticate ||
1437 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
1438 <ProviderAuthenticationSection
1439 key={`${environmentId}:${instanceId}`}
1440 environmentId={environmentId}
1441 environmentLabel={environmentLabel}
1442 instanceId={instanceId}
1443 provider={liveProvider}
1444 readOnly={readOnly}
1445 />
1446 ) : mode === "editor" &&
1447 !readOnly &&
1448 driver === "cursor" &&
1449 liveProvider?.setup?.canAuthenticate === false ? (
1450 <SettingsRow
1451 title={gt("Cursor account")}
1452 description={gt(
1453 "Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in.",
1454 )}
1455 />
1456 ) : null
1457 }
1458 onUpdate={(next) => actions.updateInstance(instanceId, instance, next)}
1459 onDelete={
1460 mode === "editor" && !isDefault
1461 ? () => actions.deleteInstance(instanceId, instance)
1462 : undefined
1463 }
1464 headerAction={
1465 mode === "editor" && isDefault && isDirty ? (
1466 <SettingResetButton
1467 ariaLabel={gt("Reset {provider} provider settings to default", {
1468 provider: resetLabel,
1469 })}
1470 onClick={() => actions.resetDefaultInstance(driver)}
1471 />
1472 ) : null
1473 }
1474 hiddenModels={hiddenModels}
1475 favoriteModels={favoriteModels}
1476 modelOrder={modelOrder}
1477 onHiddenModelsChange={(next, affectedModels) => {
1478 const hidden = new Set(next);
1479 void actions.updateModelPreferences({
1480 setModelsHidden: affectedModels.map((model) => ({
1481 provider: instanceId,
1482 model,
1483 hidden: hidden.has(model),
1484 })),
1485 });
1486 }}
1487 onToggleFavorite={(model) => {
1488 void actions.toggleModelFavorite(instanceId, model);
1489 }}
1490 onFavoriteModelsChange={(next) => {
1491 void actions.updateModelPreferences({
1492 setModelFavorites: modelListChanges(favoriteModels, next).map(({ model, selected }) => ({
1493 provider: instanceId,
1494 model,
1495 favorite: selected,
1496 })),
1497 });
1498 }}
1499 onModelOrderChange={(nextOrder) => {
1500 void actions.updateModelPreferences({
1501 setProviderModelOrder: { provider: instanceId, modelOrder: nextOrder },
1502 });
1503 }}
1504 onInstallRecommended={
1505 canInstallRecommended
1506 ? () => {
1507 void actions.runProviderUpdate(liveProvider, recommendedVersion ?? undefined);
1508 }
1509 : undefined
1510 }
1511 onRunUpdate={
1512 !readOnly && updateCandidate
1513 ? () => {
1514 if (!isInstanceUpdateRunning) void actions.runProviderUpdate(updateCandidate);
1515 }
1516 : undefined
1517 }
1518 isUpdating={isInstanceUpdateRunning}
1519 />
1520 );
1521 }