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

ProviderSettingsPanel.tsx

1,308 lines48.1 KB

1import { SettingsGroup } from "./SettingsGroup";
2import { RefreshIcon } from "~/components/ui/refresh-icon";
3import {
4 AuthSettingsWriteScope,
5 AuthProvidersManageScope,
6 AuthOrchestrationReadScope,
7} from "@t3tools/contracts";
8import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
9import { useAtomValue } from "@effect/atom-react";
10import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
11import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import {
17 defaultInstanceIdForDriver,
18 type EnvironmentId,
19 type AcpRegistryUrlAuthAction,
20 PROVIDER_DISPLAY_NAMES,
21 ProviderDriverKind,
22 type ProjectId,
23 type ProviderInstanceConfig,
24 type ProviderInstanceId,
25 resolveEnvironmentMachineKind,
26 resolveProjectProviderInstanceEnabled,
27 resolveProviderInstanceEnabled,
28} from "@t3tools/contracts";
29import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
30import {
31 getBackgroundActivityPresetSettings,
32 resolveServerBackgroundActivitySettings,
33} from "@t3tools/shared/backgroundActivitySettings";
34import * as Arr from "effect/Array";
35import * as Duration from "effect/Duration";
36import * as Result from "effect/Result";
37import { PlusIcon } from "lucide-react";
38import { useRef, useState, type ReactNode } from "react";
39​
40import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
41import {
42 useEnvironmentSettings,
43 usePersistEnvironmentProviderInstanceMutation,
44 useUpdateEnvironmentSettings,
45 useUpdateEnvironmentModelPreferences,
46 useToggleEnvironmentModelFavorite,
47} from "../../hooks/useSettings";
48import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
49import { cn } from "../../lib/utils";
50import { resolveAppModelSelectionState } from "../../modelSelection";
51import {
52 useEnvironments,
53 usePrimaryEnvironmentId,
54 type EnvironmentPresentation,
55} from "../../state/environments";
56import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
57import { useEnvironmentSessionState } from "../../state/session";
58import { useProjects, useServerConfigs } from "../../state/entities";
59import { useAtomCommand } from "../../state/use-atom-command";
60import { getRelativeTimeState } from "../../timestampFormat";
61import {
62 ConnectionStatusDot,
63 connectionPhaseDotClassName,
64 connectionPhasePingClassName,
65} from "../ConnectionStatusDot";
66import {
67 isProviderSettingsUpdateCandidate,
68 isProviderUpdateActive,
69 type ProviderSettingsUpdateCandidate,
70} from "../ProviderUpdateLaunchNotification.logic";
71import { ProviderUpdatesAction } from "../ProviderUpdatesAction";
72import { Button } from "../ui/button";
73import {
74 Empty,
75 EmptyContent,
76 EmptyDescription,
77 EmptyHeader,
78 EmptyMedia,
79 EmptyTitle,
80} from "../ui/empty";
81import {
82 NumberField,
83 NumberFieldDecrement,
84 NumberFieldGroup,
85 NumberFieldIncrement,
86 NumberFieldInput,
87} from "../ui/number-field";
88import { ScrollArea } from "../ui/scroll-area";
89import { Toggle, ToggleGroup } from "../ui/toggle-group";
90import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
91import { stackedThreadToast, toastManager } from "../ui/toast";
92import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
93import { ExpandableText } from "./ExpandableText";
94import { ProviderInstanceCard } from "./ProviderInstanceCard";
95import { UsageProviderSettings } from "./UsageProviderSettings";
96import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
97import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
98import { CodexSetupSection, CodexManagedRuntimeFields } from "./CodexSetupSection";
99import { readCodexSetupMode } from "./CodexSetupSection.logic";
100import { providerClients } from "./providerDriverMeta";
101import { searchableSetting } from "./settingsSearch";
102import {
103 backgroundActivityOverrideSettings,
104 buildProviderInstanceUpdatePatch,
105 durationToSeconds,
106 normalizeIntervalSeconds,
107 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
108} from "./SettingsPanels.logic";
109import {
110 PolicyTooltip,
111 SettingResetButton,
112 SettingsPageContainer,
113 SettingsRow,
114 SettingsSection,
115 useRelativeTimeTick,
116 useSettingsSearchTargetId,
117} from "./settingsLayout";
118import {
119 buildProviderEnvironmentOptions,
120 buildProviderInstanceOverridePatch,
121 classifyProviderEnvironmentAccess,
122 isProviderSettingsEnvironmentAvailable,
123 type ProviderEnvironmentAccess,
124 type ProviderOperateAccess,
125 resolveRemoteOperateAccess,
126 resolveSelectedProviderEnvironmentId,
127} from "./ProviderSettingsPanel.logic";
128​
129function modelListChanges(current: ReadonlyArray<string>, next: ReadonlyArray<string>) {
130 const currentSet = new Set(current);
131 const nextSet = new Set(next.map((model) => model.trim()).filter(Boolean));
132 return [...new Set([...currentSet, ...nextSet])]
133 .filter((model) => currentSet.has(model) !== nextSet.has(model))
134 .map((model) => ({ model, selected: nextSet.has(model) }));
136​
137function providerConfigString(config: unknown, key: string): string | null {
138 if (config === null || typeof config !== "object") return null;
139 const value = (config as Record<string, unknown>)[key];
140 return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
142​
143const PROVIDER_SETTINGS = providerClients.definitions.map((definition) => ({
144 provider: definition.driverKind,
145 hasDefaultInstance: definition.hasDefaultInstance !== false,
146}));
147​
148function configuredBinaryPath(config: unknown): string {
149 if (config === null || typeof config !== "object" || !("binaryPath" in config)) return "";
150 return typeof config.binaryPath === "string" ? config.binaryPath.trim() : "";
152​
153function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
154 useRelativeTimeTick();
155 const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
156​
157 if (lastCheckedRelative.status === "missing") {
158 return null;
159 }
160​
161 if (lastCheckedRelative.status === "invalid") {
162 return <span>Checked unavailable</span>;
163 }
164​
165 return (
166 <span>
167 {lastCheckedRelative.suffix ? (
168 <>
169 Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}
170 {lastCheckedRelative.suffix}
171 </>
172 ) : (
173 <>Checked {lastCheckedRelative.value}</>
174 )}
175 </span>
176 );
178​
179function providerEnvironmentDetail(environment: EnvironmentPresentation): string {
180 if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";
181 if (environment.relayManaged) return "T3 Connect";
182 if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";
183 if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";
184 return environment.displayUrl ?? "Remote device";
186​
187const providerCardHeightClassName =
188 "@min-[48rem]/providers:h-[min(44rem,calc(100dvh-11rem))] @min-[48rem]/providers:min-h-[32rem]";
189​
190function ProviderSettingsPlaceholder({
191 deviceTabs,
192 icon,
193 title,
194 description,
195 children,
196}: {
197 readonly deviceTabs?: ReactNode;
198 readonly icon: ReactNode;
199 readonly title: string;
200 readonly description: string;
201 readonly children?: ReactNode;
202}) {
203 return (
204 <SettingsSection {...searchableSetting("providers")} variant="plain">
205 {deviceTabs ? (
206 <div className="flex min-h-11 min-w-0 items-center px-3 sm:px-4">{deviceTabs}</div>
207 ) : null}
208 <SettingsGroup
209 divided={false}
210 className={cn(
211 providerCardHeightClassName,
212 "scrollbar-gutter-both flex overflow-x-hidden overflow-y-auto",
213 )}
214 >
215 <Empty>
216 <EmptyMedia variant="icon">{icon}</EmptyMedia>
217 <EmptyHeader>
218 <EmptyTitle>{title}</EmptyTitle>
219 <EmptyDescription>{description}</EmptyDescription>
220 </EmptyHeader>
221 {children ? <EmptyContent className="max-w-xl">{children}</EmptyContent> : null}
222 </Empty>
223 </SettingsGroup>
224 </SettingsSection>
225 );
227​
228function EnvironmentUnavailablePlaceholder({
229 environment,
230 access,
231 deviceTabs,
232}: {
233 readonly environment: EnvironmentPresentation;
234 readonly access: Exclude<ProviderEnvironmentAccess, { kind: "editable" | "read-only" }>;
235 readonly deviceTabs?: ReactNode;
236}) {
237 const isLoading = access.kind === "loading";
238 const title = isLoading
239 ? "Loading provider settings"
240 : access.kind === "error"
241 ? "Could not connect to this device"
242 : "Provider settings are unavailable";
243 const description = isLoading
244 ? access.reason === "permissions"
245 ? "Checking what this session is allowed to change."
246 : `Waiting for ${environment.label}'s configuration.`
247 : connectionStatusTitle(environment.connection);
248 const error = isLoading ? null : environment.connection.error;
249 // No spinner: this state can persist indefinitely for a wedged device, and a
250 // continuously repainting animation would run the whole time.
251 return (
252 <ProviderSettingsPlaceholder
253 deviceTabs={deviceTabs}
254 icon={
255 <EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(environment.serverConfig)} />
256 }
257 title={title}
258 description={description}
259 >
260 {error ? (
261 <ExpandableText
262 key={environment.environmentId}
263 text={error}
264 className="w-full text-left font-mono text-xs leading-relaxed text-muted-foreground"
265 />
266 ) : null}
267 </ProviderSettingsPlaceholder>
268 );
270​
271interface ProviderSettingsTarget {
272 readonly environmentId?: EnvironmentId;
273 readonly instanceId?: ProviderInstanceId;
274 readonly scoped?: boolean;
275 readonly environmentIds?: readonly EnvironmentId[];
276 readonly projectIds?: readonly ProjectId[];
278​
279export function ProviderSettingsPanel(target: ProviderSettingsTarget) {
280 return (
281 <SettingsPageContainer className="@container/providers gap-8">
282 <ProviderSettingsPanelContent
283 key={`${target.environmentId ?? ""}:${target.instanceId ?? ""}`}
284 {...target}
285 />
286 </SettingsPageContainer>
287 );
289​
290function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
291 const { environments, isReady } = useEnvironments();
292 const primaryEnvironmentId = usePrimaryEnvironmentId();
293 const searchTargetId = useSettingsSearchTargetId();
294 const options = buildProviderEnvironmentOptions(
295 environments,
296 primaryEnvironmentId,
297 target.environmentIds,
298 );
299 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
300 target.environmentId ?? primaryEnvironmentId,
301 );
302 const targetEnvironmentMissing =
303 target.environmentId !== undefined &&
304 selectedEnvironmentId === target.environmentId &&
305 !options.some((environment) => environment.environmentId === target.environmentId);
306 const effectiveEnvironmentId =
307 target.scoped || targetEnvironmentMissing
308 ? target.environmentId
309 : resolveSelectedProviderEnvironmentId(options, selectedEnvironmentId, primaryEnvironmentId);
310 const selectedEnvironment =
311 options.find((environment) => environment.environmentId === effectiveEnvironmentId) ?? null;
312 const selectedEnvironmentCanRenderSettings =
313 selectedEnvironment !== null &&
314 isProviderSettingsEnvironmentAvailable({
315 connectionPhase: selectedEnvironment.connection.phase,
316 hasServerConfig: selectedEnvironment.serverConfig !== null,
317 });
318 const searchableEnvironmentId = options.find((environment) =>
319 isProviderSettingsEnvironmentAvailable({
320 connectionPhase: environment.connection.phase,
321 hasServerConfig: environment.serverConfig !== null,
322 }),
323 )?.environmentId;
324 const searchableCursorEnvironmentId = options.find(
325 (environment) =>
326 environment.serverConfig?.environment.platform.os === "darwin" &&
327 isProviderSettingsEnvironmentAvailable({
328 connectionPhase: environment.connection.phase,
329 hasServerConfig: true,
330 }),
331 )?.environmentId;
332 // A search jump to a setting the selected device cannot show switches to one that can.
333 let searchRedirectEnvironmentId: EnvironmentId | undefined;
334 {
335 if (
336 !target.scoped &&
337 searchTargetId === searchableSetting("cursor-keychain-usage").id &&
338 (!selectedEnvironmentCanRenderSettings ||
339 selectedEnvironment?.serverConfig?.environment.platform.os !== "darwin") &&
340 searchableCursorEnvironmentId !== undefined
341 ) {
342 searchRedirectEnvironmentId = searchableCursorEnvironmentId;
343 } else if (
344 !target.scoped &&
345 (searchTargetId === searchableSetting("provider-health-check-interval").id ||
346 searchTargetId === searchableSetting("usage-providers").id) &&
347 !selectedEnvironmentCanRenderSettings &&
348 searchableEnvironmentId !== undefined
349 ) {
350 searchRedirectEnvironmentId = searchableEnvironmentId;
351 }
352 }
353 if (
354 searchRedirectEnvironmentId !== undefined &&
355 searchRedirectEnvironmentId !== selectedEnvironmentId
356 ) {
357 setSelectedEnvironmentId(searchRedirectEnvironmentId);
358 }
359 const onlyPrimaryDevice =
360 options.length === 1 && options[0]?.entry.target._tag === "PrimaryConnectionTarget";
361 const deviceTabs =
362 !target.scoped && !onlyPrimaryDevice && options.length > 0 ? (
363 <ScrollArea radius="none" hideScrollbars scrollFade className="h-11 min-w-0 flex-1">
364 <ToggleGroup
365 aria-label="Devices"
366 variant="segmented"
367 className="my-2"
368 value={effectiveEnvironmentId ? [effectiveEnvironmentId] : []}
369 onValueChange={(next) => {
370 const environment = options.find((option) => option.environmentId === next[0]);
371 if (environment) setSelectedEnvironmentId(environment.environmentId);
372 }}
373 >
374 {options.map((environment) => {
375 const machine = resolveEnvironmentMachineKind(environment.serverConfig);
376 const detail = providerEnvironmentDetail(environment);
377 const statusText = connectionStatusTitle(environment.connection);
378 return (
379 <Tooltip key={environment.environmentId}>
380 <TooltipTrigger
381 render={
382 <Toggle value={environment.environmentId}>
383 <EnvironmentMachineIcon
384 kind={machine}
385 className="size-3.5 shrink-0"
386 aria-hidden
387 />
388 <span className="max-w-40 truncate">{environment.label}</span>
389 {environment.connection.phase !== "connected" ? (
390 <ConnectionStatusDot
391 dotClassName={connectionPhaseDotClassName(environment.connection.phase)}
392 pingClassName={connectionPhasePingClassName(environment.connection.phase)}
393 />
394 ) : null}
395 <span className="sr-only">
396 {detail}, {statusText}
397 </span>
398 </Toggle>
399 }
400 />
401 <TooltipPopup side="top">
402 {detail} · {statusText}
403 </TooltipPopup>
404 </Tooltip>
405 );
406 })}
407 </ToggleGroup>
408 </ScrollArea>
409 ) : null;
410​
411 return (
412 <>
413 {targetEnvironmentMissing ? (
414 <ProviderSettingsPlaceholder
415 deviceTabs={deviceTabs}
416 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
417 title="Device unavailable"
418 description="Reconnect this device to set up its provider, or select another device."
419 />
420 ) : null}
421 {options.length === 0 && !targetEnvironmentMissing ? (
422 <ProviderSettingsPlaceholder
423 icon={<EnvironmentMachineIcon kind={resolveEnvironmentMachineKind(null)} />}
424 title={isReady ? "No connected devices" : "Loading devices"}
425 description={
426 isReady
427 ? "Connect an execution environment before configuring providers."
428 : "Reading connected execution environments."
429 }
430 />
431 ) : null}
432​
433 {selectedEnvironment ? (
434 <SelectedEnvironmentProviderSettings
435 key={selectedEnvironment.environmentId}
436 environment={selectedEnvironment}
437 deviceTabs={deviceTabs}
438 targetInstanceId={
439 target.environmentId === undefined ||
440 selectedEnvironment.environmentId === target.environmentId
441 ? target.instanceId
442 : undefined
443 }
444 projectIds={target.projectIds ?? []}
445 />
446 ) : null}
447 </>
448 );
450​
451function SelectedEnvironmentProviderSettings({
452 environment,
453 deviceTabs,
454 targetInstanceId,
455 projectIds,
456}: {
457 readonly environment: EnvironmentPresentation;
458 readonly deviceTabs?: ReactNode;
459 readonly targetInstanceId?: ProviderInstanceId | undefined;
460 readonly projectIds: readonly ProjectId[];
461}) {
462 return (
463 <RemoteSessionGatedProviderSettings
464 environment={environment}
465 deviceTabs={deviceTabs}
466 targetInstanceId={targetInstanceId}
467 projectIds={projectIds}
468 />
469 );
471​
472function RemoteSessionGatedProviderSettings({
473 environment,
474 deviceTabs,
475 targetInstanceId,
476 projectIds,
477}: {
478 readonly environment: EnvironmentPresentation;
479 readonly deviceTabs?: ReactNode;
480 readonly targetInstanceId?: ProviderInstanceId | undefined;
481 readonly projectIds: readonly ProjectId[];
482}) {
483 const sessionState = useEnvironmentSessionState(environment.environmentId);
484 const operateAccess = resolveRemoteOperateAccess({
485 session: sessionState.data,
486 isPending: sessionState.isPending,
487 hasError: sessionState.hasError,
488 });
489 return (
490 <AccessGatedProviderSettings
491 environment={environment}
492 operateAccess={operateAccess}
493 deviceTabs={deviceTabs}
494 targetInstanceId={targetInstanceId}
495 projectIds={projectIds}
496 />
497 );
499​
500function AccessGatedProviderSettings({
501 environment,
502 operateAccess,
503 deviceTabs,
504 targetInstanceId,
505 projectIds,
506}: {
507 readonly environment: EnvironmentPresentation;
508 readonly operateAccess: ProviderOperateAccess;
509 readonly deviceTabs?: ReactNode;
510 readonly targetInstanceId?: ProviderInstanceId | undefined;
511 readonly projectIds: readonly ProjectId[];
512}) {
513 const access = classifyProviderEnvironmentAccess({
514 connectionPhase: environment.connection.phase,
515 hasServerConfig: environment.serverConfig !== null,
516 operateAccess,
517 });
518 if (access.kind !== "editable" && access.kind !== "read-only") {
519 return (
520 <EnvironmentUnavailablePlaceholder
521 environment={environment}
522 access={access}
523 deviceTabs={deviceTabs}
524 />
525 );
526 }
527 return (
528 <EnvironmentProviderSettings
529 environmentId={environment.environmentId}
530 environmentLabel={environment.label}
531 readOnly={access.kind === "read-only"}
532 deviceTabs={deviceTabs}
533 targetInstanceId={targetInstanceId}
534 projectIds={projectIds}
535 />
536 );
538​
539const NO_PROJECT_IDS: readonly ProjectId[] = [];
540​
541export function EnvironmentProviderSettings({
542 environmentId,
543 environmentLabel,
544 readOnly = false,
545 deviceTabs,
546 targetInstanceId,
547 projectIds = NO_PROJECT_IDS,
548}: {
549 readonly environmentId: EnvironmentId;
550 readonly environmentLabel: string;
551 readonly deviceTabs?: ReactNode;
552 readonly targetInstanceId?: ProviderInstanceId | undefined;
553 readonly projectIds?: readonly ProjectId[];
554 readonly readOnly?: boolean;
555}) {
556 const settings = useEnvironmentSettings(environmentId);
557 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
558 const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
559 const updateSettings = useUpdateEnvironmentSettings(environmentId);
560 const updateModelPreferences = useUpdateEnvironmentModelPreferences(environmentId);
561 const toggleModelFavorite = useToggleEnvironmentModelFavorite(environmentId);
562 const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
563 const serverProviders =
564 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
565 const projects = useProjects().filter((project) => project.environmentId === environmentId);
566 // Older servers decode an unknown providerInstances key away, so sending
567 // a project override patch would silently do nothing. Hide the switch
568 // instead of offering a control that can never take effect.
569 const supportsProjectProviderOverrides =
570 useServerConfigs().get(environmentId)?.environment.capabilities
571 .projectProviderInstanceOverrides === true;
572 const refreshServerProviders = useAtomCommand(serverEnvironment.refreshProviders, {
573 reportFailure: false,
574 });
575 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
576 reportFailure: false,
577 });
578 const uninstallAcpRegistryManagedBinary = useAtomCommand(
579 serverEnvironment.uninstallAcpRegistryManagedBinary,
580 { reportFailure: false },
581 );
582 const acceptAcpRegistryUrlAuth = useAtomCommand(serverEnvironment.acceptAcpRegistryUrlAuth, {
583 reportFailure: false,
584 });
585 const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
586 const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
587 const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
588 targetInstanceId ?? null,
589 );
590 const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<
591 ReadonlySet<ProviderInstanceId>
592 >(() => new Set());
593 const refreshingRef = useRef(false);
594 const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());
595​
596 const acceptUrlAuthentication = (
597 instanceId: ProviderInstanceId,
598 action: AcpRegistryUrlAuthAction,
599 ) => {
600 void acceptAcpRegistryUrlAuth({
601 environmentId,
602 input: { instanceId, elicitationId: action.elicitationId },
603 }).then((result) => {
604 if (result._tag === "Success" && !result.value.accepted) {
605 toastManager.add({
606 type: "warning",
607 title: "Authentication request expired",
608 description: "Refresh the provider and start the authentication flow again.",
609 });
610 return;
611 }
612 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
613 const error = squashAtomCommandFailure(result);
614 toastManager.add({
615 type: "error",
616 title: "Could not continue authentication",
617 description:
618 error instanceof Error ? error.message : "The authentication request expired.",
619 });
620 }
621 });
622 };
623​
624 const providerUpdateCandidateByInstanceId = new Map(
625 serverProviders
626 .filter(isProviderSettingsUpdateCandidate)
627 .map((candidate) => [candidate.instanceId, candidate]),
628 );
629 const visibleProviderSettings = PROVIDER_SETTINGS.filter(
630 (providerSettings) =>
631 providerSettings.provider !== "cursor" ||
632 serverProviders.some(
633 (provider) =>
634 provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
635 ),
636 );
637 const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
638 const textGenInstanceId = textGenerationModelSelection.instanceId;
639 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
640 const providerHealthPreset = getBackgroundActivityPresetSettings(
641 resolvedBackgroundActivity.profile,
642 ).providerHealthRefreshInterval;
643 const providerHealthRefreshIntervalSeconds = durationToSeconds(
644 resolvedBackgroundActivity.providerHealthRefreshInterval,
645 );
646 const defaultProviderHealthRefreshIntervalSeconds = durationToSeconds(providerHealthPreset);
647 const lastCheckedAt =
648 serverProviders.length > 0
649 ? serverProviders.reduce(
650 (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
651 serverProviders[0]!.checkedAt,
652 )
653 : null;
654​
655 const refreshProviders = () => {
656 if (refreshingRef.current || !readEnvironmentScope(environmentId, AuthOrchestrationReadScope))
657 return;
658 refreshingRef.current = true;
659 setIsRefreshingProviders(true);
660 void (async () => {
661 const result = await refreshServerProviders({
662 environmentId,
663 input: { refreshModels: true },
664 });
665 refreshingRef.current = false;
666 setIsRefreshingProviders(false);
667 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
668 console.warn("Failed to refresh providers", {
669 operation: "refresh-providers",
670 environmentId,
671 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
672 });
673 }
674 })();
675 };
676​
677 const runProviderUpdate = async (
678 candidate: Pick<ProviderSettingsUpdateCandidate, "driver" | "instanceId">,
679 targetVersion?: string,
680 ) => {
681 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
682 // Ref-based re-entry guard, mirroring refreshProviders: a state updater
683 // may run after this function returns, so it cannot gate the dispatch.
684 if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
685 return;
686 }
687 updatingInstanceIdsRef.current.add(candidate.instanceId);
688 setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
689​
690 const result = await updateProvider({
691 environmentId,
692 input: {
693 provider: candidate.driver,
694 instanceId: candidate.instanceId,
695 ...(targetVersion ? { targetVersion } : {}),
696 },
697 });
698 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
699 const error = squashAtomCommandFailure(result);
700 toastManager.add(
701 stackedThreadToast({
702 type: "error",
703 title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
704 description:
705 error instanceof Error
706 ? error.message
707 : "The provider update command could not be started.",
708 }),
709 );
710 }
711 updatingInstanceIdsRef.current.delete(candidate.instanceId);
712 setUpdatingProviderInstanceIds((previous) => {
713 if (!previous.has(candidate.instanceId)) {
714 return previous;
715 }
716 const next = new Set(previous);
717 next.delete(candidate.instanceId);
718 return next;
719 });
720 };
721​
722 interface InstanceRow {
723 readonly instanceId: ProviderInstanceId;
724 readonly instance: ProviderInstanceConfig;
725 readonly driver: ProviderDriverKind;
726 readonly isDefault: boolean;
727 readonly isDirty?: boolean;
728 }
729​
730 const instancesByDriver = new Map<
731 ProviderDriverKind,
732 Array<[ProviderInstanceId, ProviderInstanceConfig]>
733 >();
734 for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
735 const driver = instance.driver;
736 const list = instancesByDriver.get(driver) ?? [];
737 list.push([rawId as ProviderInstanceId, instance]);
738 instancesByDriver.set(driver, list);
739 }
740​
741 const defaultSlotIdsBySource = new Set<string>(
742 visibleProviderSettings.map((providerSettings) =>
743 String(defaultInstanceIdForDriver(providerSettings.provider)),
744 ),
745 );
746​
747 const rows: InstanceRow[] = [];
748 const visibleDriverKinds = new Set<ProviderDriverKind>(
749 visibleProviderSettings.map((providerSettings) => providerSettings.provider),
750 );
751​
752 for (const providerSettings of visibleProviderSettings) {
753 const driver = providerSettings.provider;
754 const defaultInstanceId = defaultInstanceIdForDriver(driver);
755 const explicitInstance = settings.providerInstances?.[defaultInstanceId];
756 const effectiveInstance: ProviderInstanceConfig = explicitInstance ?? { driver };
757 const isDirty = explicitInstance !== undefined;
758 const hasDefaultSlot = providerSettings.hasDefaultInstance || explicitInstance !== undefined;
759 if (
760 hasDefaultSlot &&
761 (driver === "codex" ||
762 driver === "claudeAgent" ||
763 isDirty ||
764 resolveProviderInstanceEnabled(effectiveInstance) ||
765 defaultInstanceId === targetInstanceId)
766 ) {
767 rows.push({
768 instanceId: defaultInstanceId,
769 instance: effectiveInstance,
770 driver,
771 isDefault: true,
772 isDirty,
773 });
774 }
775 for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
776 if (id === defaultInstanceId) continue;
777 rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
778 }
779 }
780 for (const [driver, list] of instancesByDriver) {
781 if (visibleDriverKinds.has(driver)) continue;
782 for (const [id, instance] of list) {
783 rows.push({
784 instanceId: id,
785 instance,
786 driver: instance.driver,
787 isDefault: defaultSlotIdsBySource.has(String(id)),
788 });
789 }
790 }
791​
792 const targetInstanceMissing =
793 targetInstanceId !== undefined &&
794 selectedInstanceId === targetInstanceId &&
795 !rows.some((row) => row.instanceId === targetInstanceId);
796 const selectedRow =
797 rows.find((row) => row.instanceId === selectedInstanceId) ??
798 (targetInstanceMissing ? null : (rows[0] ?? null));
799​
800 const updateProviderInstance = async (
801 row: InstanceRow,
802 next: ProviderInstanceConfig,
803 options?: {
804 readonly textGenerationModelSelection?: Parameters<
805 typeof buildProviderInstanceUpdatePatch
806 >[0]["textGenerationModelSelection"];
807 },
808 ) => {
809 const { providerInstances: _providerInstances, ...patch } = buildProviderInstanceUpdatePatch({
810 settings,
811 instanceId: row.instanceId,
812 instance: next,
813 textGenerationModelSelection: options?.textGenerationModelSelection,
814 });
815 const result = await persistProviderInstance(
816 { operation: "upsert", instanceId: row.instanceId, instance: next },
817 patch,
818 );
819 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
820 const error = squashAtomCommandFailure(result);
821 toastManager.add({
822 type: "error",
823 title: "Could not update provider instance",
824 description: error instanceof Error ? error.message : "The settings update failed.",
825 });
826 }
827 };
828​
829 const deleteProviderInstance = async (row: InstanceRow) => {
830 const updateResult = await persistProviderInstance({
831 operation: "remove",
832 instanceId: row.instanceId,
833 });
834 if (updateResult._tag === "Failure") {
835 const error = squashAtomCommandFailure(updateResult);
836 toastManager.add({
837 type: "error",
838 title: "Could not delete provider instance",
839 description: error instanceof Error ? error.message : "The settings update failed.",
840 });
841 return;
842 }
843​
844 if (row.driver !== ProviderDriverKind.make("acpRegistry")) return;
845 if (providerConfigString(row.instance.config, "source") === "local") return;
846 const agentId = providerConfigString(row.instance.config, "agentId");
847 if (agentId === null) return;
848​
849 // The server decides from its latest settings whether this was the last
850 // instance using the managed agent. A client-side snapshot check can race
851 // two removals and make both callers skip cleanup.
852 const uninstallResult = await uninstallAcpRegistryManagedBinary({
853 environmentId,
854 input: { agentId },
855 });
856 if (uninstallResult._tag === "Failure" && !isAtomCommandInterrupted(uninstallResult)) {
857 const error = squashAtomCommandFailure(uninstallResult);
858 toastManager.add({
859 type: "warning",
860 title: "Provider deleted, but managed files remain",
861 description: error instanceof Error ? error.message : "Managed binary cleanup failed.",
862 });
863 }
864 };
865​
866 const resetDefaultInstance = async (driverKind: ProviderDriverKind) => {
867 const result = await persistProviderInstance({
868 operation: "remove",
869 instanceId: defaultInstanceIdForDriver(driverKind),
870 });
871 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
872 const error = squashAtomCommandFailure(result);
873 toastManager.add({
874 type: "error",
875 title: "Could not reset provider instance",
876 description: error instanceof Error ? error.message : "The settings update failed.",
877 });
878 }
879 };
880​
881 const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => {
882 const driverOption = providerClients.get(row.driver);
883 const liveProvider = serverProviders.find(
884 (candidate) => candidate.instanceId === row.instanceId,
885 );
886 const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
887 const isInstanceUpdateRunning =
888 updatingProviderInstanceIds.has(row.instanceId) ||
889 (liveProvider !== undefined && isProviderUpdateActive(liveProvider));
890 const showInlineUpdateButton = updateCandidate !== undefined;
891 const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
892 const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
893 hiddenModels: [],
894 modelOrder: [],
895 };
896 const favoriteModels = Arr.filterMap(settings.favorites ?? [], (favorite) =>
897 favorite.provider === row.instanceId ? Result.succeed(favorite.model) : Result.failVoid,
898 );
899 const resetLabel = driverOption?.label ?? String(row.driver);
900 const representativeProjectId = projectIds[0];
901 const writeProjectOverride = (next: boolean | undefined) => {
902 updateSettings({
903 projectSettingsOverrides: buildProviderInstanceOverridePatch(
904 settings,
905 projectIds,
906 row.instanceId,
907 next,
908 ),
909 });
910 };
911 const projectOverride =
912 representativeProjectId === undefined || !supportsProjectProviderOverrides
913 ? undefined
914 : {
915 value:
916 settings.projectSettingsOverrides[representativeProjectId]?.providerInstances?.[
917 row.instanceId
918 ]?.enabled,
919 effectiveEnabled: resolveProjectProviderInstanceEnabled(
920 settings,
921 representativeProjectId,
922 row.instanceId,
923 ),
924 onChange: (next: boolean) => writeProjectOverride(next),
925 onReset: () => writeProjectOverride(undefined),
926 };
927​
928 return (
929 <ProviderInstanceCard
930 key={row.instanceId}
931 environmentId={environmentId}
932 acpProjects={projects}
933 projectOverride={projectOverride}
934 onAcceptUrlAuth={
935 readOnly ? undefined : (action) => acceptUrlAuthentication(row.instanceId, action)
936 }
937 instanceId={row.instanceId}
938 instance={row.instance}
939 driverOption={driverOption}
940 liveProvider={liveProvider}
941 mode={mode}
942 selected={mode === "list" && selectedRow?.instanceId === row.instanceId}
943 onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined}
944 readOnly={readOnly}
945 runtime={
946 mode === "editor" &&
947 row.driver === "codex" &&
948 readCodexSetupMode(row.instance.config) === "managed" ? (
949 <CodexManagedRuntimeFields
950 environmentId={environmentId}
951 instanceId={row.instanceId}
952 provider={liveProvider}
953 />
954 ) : undefined
955 }
956 canWriteSettings={canWriteSettings}
957 setup={
958 mode === "editor" && row.driver === "antigravity" ? (
959 <ProviderSetupSection
960 environmentId={environmentId}
961 environmentLabel={environmentLabel}
962 instanceId={row.instanceId}
963 provider={liveProvider}
964 binaryPath={configuredBinaryPath(row.instance.config)}
965 authMethod={readAntigravityAuthMethod(row.instance.config)}
966 enabled={resolveProviderInstanceEnabled(row.instance)}
967 readOnly={readOnly}
968 onEnable={() => updateProviderInstance(row, { ...row.instance, enabled: true })}
969 />
970 ) : mode === "editor" &&
971 row.driver === "codex" &&
972 readCodexSetupMode(row.instance.config) === "managed" ? (
973 <CodexSetupSection
974 environmentId={environmentId}
975 instanceId={row.instanceId}
976 provider={liveProvider}
977 mode={readCodexSetupMode(row.instance.config)}
978 enabled={resolveProviderInstanceEnabled(row.instance)}
979 readOnly={readOnly}
980 onModeChange={(setupMode) =>
981 updateProviderInstance(row, {
982 ...row.instance,
983 enabled: true,
984 config: {
985 ...(row.instance.config !== null && typeof row.instance.config === "object"
986 ? row.instance.config
987 : {}),
988 enabled: true,
989 setupMode,
990 },
991 })
992 }
993 />
994 ) : mode === "editor" &&
995 !readOnly &&
996 liveProvider &&
997 (liveProvider.setup?.canAuthenticate ||
998 (liveProvider.driver === "acpRegistry" && liveProvider.installed)) ? (
999 <ProviderAuthenticationSection
1000 key={`${environmentId}:${row.instanceId}`}
1001 environmentId={environmentId}
1002 environmentLabel={environmentLabel}
1003 instanceId={row.instanceId}
1004 provider={liveProvider}
1005 readOnly={readOnly}
1006 />
1007 ) : mode === "editor" &&
1008 !readOnly &&
1009 row.driver === "cursor" &&
1010 liveProvider?.setup?.canAuthenticate === false ? (
1011 <SettingsRow
1012 title="Cursor account"
1013 description="Using CURSOR_API_KEY. Remove it from this provider's environment to use browser sign-in."
1014 />
1015 ) : null
1017 onUpdate={(next) => {
1018 const wasEnabled = resolveProviderInstanceEnabled(row.instance);
1019 const isDisabling = next.enabled === false && wasEnabled;
1020 const shouldClearTextGen =
1021 isDisabling &&
1022 textGenInstanceId === row.instanceId &&
1023 readEnvironmentScope(environmentId, AuthSettingsWriteScope);
1024 updateProviderInstance(
1025 row,
1026 next,
1027 shouldClearTextGen
1028 ? {
1029 textGenerationModelSelection:
1030 DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
1032 : undefined,
1033 );
1034 }}
1035 onDelete={
1036 mode === "editor" && !row.isDefault ? () => deleteProviderInstance(row) : undefined
1038 headerAction={
1039 mode === "editor" && row.isDefault && row.isDirty ? (
1040 <SettingResetButton
1041 label={`${resetLabel} provider settings`}
1042 onClick={() => resetDefaultInstance(row.driver)}
1043 />
1044 ) : null
1046 hiddenModels={modelPreferences.hiddenModels}
1047 favoriteModels={favoriteModels}
1048 modelOrder={modelPreferences.modelOrder}
1049 onHiddenModelsChange={(next, affectedModels) => {
1050 const hidden = new Set(next);
1051 const models =
1052 affectedModels ??
1053 modelListChanges(modelPreferences.hiddenModels, next).map((change) => change.model);
1054 void updateModelPreferences({
1055 setModelsHidden: models.map((model) => ({
1056 provider: row.instanceId,
1057 model,
1058 hidden: hidden.has(model),
1059 })),
1060 });
1061 }}
1062 onToggleFavorite={(model) => {
1063 void toggleModelFavorite(row.instanceId, model);
1064 }}
1065 onFavoriteModelsChange={(next) => {
1066 void updateModelPreferences({
1067 setModelFavorites: modelListChanges(favoriteModels, next).map(
1068 ({ model, selected }) => ({ provider: row.instanceId, model, favorite: selected }),
1069 ),
1070 });
1071 }}
1072 onModelOrderChange={(modelOrder) => {
1073 void updateModelPreferences({
1074 setProviderModelOrder: { provider: row.instanceId, modelOrder },
1075 });
1076 }}
1077 onInstallRecommended={
1078 !readOnly &&
1079 liveProvider?.compatibilityAdvisory?.message &&
1080 liveProvider.compatibilityAdvisory.recommendedVersion &&
1081 liveProvider.versionAdvisory?.canInstallVersion
1082 ? () => {
1083 void runProviderUpdate(
1084 liveProvider,
1085 liveProvider.compatibilityAdvisory?.recommendedVersion ?? undefined,
1086 );
1088 : undefined
1090 onRunUpdate={
1091 !readOnly && showInlineUpdateButton && updateCandidate
1092 ? () => {
1093 if (canRunInlineUpdate) void runProviderUpdate(updateCandidate);
1095 : undefined
1097 isUpdating={isInstanceUpdateRunning}
1098 />
1099 );
1100 };
1101​
1102 return (
1103 <>
1104 <SettingsSection
1105 {...searchableSetting("providers")}
1106 variant="plain"
1107 titleAction={
1108 !readOnly ? (
1109 <Tooltip>
1110 <TooltipTrigger
1111 render={
1112 <Button
1113 size="icon-xs"
1114 variant="ghost-muted"
1115 onClick={() => setIsAddInstanceDialogOpen(true)}
1116 aria-label="Add provider"
1118 <PlusIcon />
1119 </Button>
1121 />
1122 <TooltipPopup side="top">Add provider</TooltipPopup>
1123 </Tooltip>
1124 ) : null
1126 headerAction={
1127 <div className="flex min-w-0 items-center gap-2">
1128 <ProviderUpdatesAction />
1129 <Tooltip>
1130 <TooltipTrigger
1131 render={
1132 <Button
1133 size="xs"
1134 variant="ghost-muted"
1135 disabled={isRefreshingProviders || !canRefreshProviders}
1136 aria-busy={isRefreshingProviders}
1137 onClick={() => void refreshProviders()}
1139 <RefreshIcon refreshing={isRefreshingProviders} />
1140 <span className="sr-only">Refresh provider status</span>
1141 <span className="hidden min-w-0 truncate sm:inline">
1142 {isRefreshingProviders ? (
1143 "Refreshing providers"
1144 ) : (
1145 <ProviderLastChecked lastCheckedAt={lastCheckedAt} />
1146 )}
1147 </span>
1148 </Button>
1150 />
1151 <TooltipPopup side="top">Refresh provider status</TooltipPopup>
1152 </Tooltip>
1153 </div>
1156 {deviceTabs ? (
1157 <div className="flex min-h-11 min-w-0 items-center gap-2 px-3 sm:px-4">{deviceTabs}</div>
1158 ) : null}
1159 {readOnly ? (
1160 <SettingsGroup divided={false} className="overflow-hidden">
1161 <SettingsRow
1162 title="Limited permissions"
1163 description={`This session can view ${environmentLabel}'s providers but can't change their settings.`}
1164 />
1165 </SettingsGroup>
1166 ) : null}
1167 <SettingsGroup
1168 divided={false}
1169 className={cn(
1170 providerCardHeightClassName,
1171 "overflow-hidden @min-[48rem]/providers:grid @min-[48rem]/providers:grid-cols-[17rem_minmax(0,1fr)]",
1172 )}
1174 <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">
1175 <ScrollArea
1176 scrollFade
1177 chainVerticalScroll
1178 className="@min-[48rem]/providers:min-h-0 @min-[48rem]/providers:flex-1"
1180 <div className="divide-y divide-border/50">
1181 {rows.map((row) => renderProviderInstance(row, "list"))}
1182 {!readOnly ? (
1183 <button
1184 type="button"
1185 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"
1186 onClick={() => setIsAddInstanceDialogOpen(true)}
1188 <PlusIcon className="size-4 shrink-0" />
1189 Add provider
1190 </button>
1191 ) : null}
1192 </div>
1193 </ScrollArea>
1194 </div>
1195​
1196 <div className="min-w-0 @min-[48rem]/providers:min-h-0">
1197 {selectedRow ? (
1198 <ScrollArea scrollFade chainVerticalScroll className="@min-[48rem]/providers:h-full">
1199 <div className="space-y-6 p-4">{renderProviderInstance(selectedRow, "editor")}</div>
1200 </ScrollArea>
1201 ) : (
1202 <div className="p-6 text-sm text-muted-foreground">
1203 {targetInstanceMissing
1204 ? "This provider instance is no longer available on this device."
1205 : "No providers configured."}
1206 </div>
1207 )}
1208 </div>
1209 </SettingsGroup>
1210 </SettingsSection>
1211​
1212 <UsageProviderSettings
1213 key={environmentId}
1214 environmentId={environmentId}
1215 environmentLabel={environmentLabel}
1216 sources={settings.usageLimitSources}
1217 cursorKeychainUsageEnabled={settings.cursorKeychainUsageEnabled}
1218 readOnly={readOnly}
1219 />
1220​
1221 <SettingsSection title="Advanced">
1222 <SettingsRow
1223 id={searchableSetting("provider-health-check-interval").id}
1224 title={
1225 <span className="inline-flex items-center gap-1.5">
1226 {searchableSetting("provider-health-check-interval").title}
1227 <PolicyTooltip>
1228 This interval is configured here, then the shared Background activity policy decides
1229 whether provider probes may run when the timer fires. Custom intervals appear as
1230 Advanced in General settings.
1231 </PolicyTooltip>
1232 </span>
1234 description="Refresh provider status, versions, and models in the background. Set to 0 to disable."
1235 resetAction={
1236 providerHealthRefreshIntervalSeconds !== defaultProviderHealthRefreshIntervalSeconds ? (
1237 <span
1238 inert={!canWriteSettings}
1239 className={!canWriteSettings ? "opacity-50" : undefined}
1241 <SettingResetButton
1242 label="provider health check interval"
1243 onClick={() =>
1244 updateSettings(
1245 backgroundActivityOverrideSettings(
1246 settings.backgroundActivity,
1247 resolvedBackgroundActivity,
1248 { providerHealthRefreshInterval: undefined },
1249 ),
1252 />
1253 </span>
1254 ) : null
1256 control={
1257 <div
1258 inert={!canWriteSettings}
1259 aria-disabled={!canWriteSettings || undefined}
1260 className={cn(
1261 "flex shrink-0 items-center gap-2",
1262 !canWriteSettings && "opacity-50 select-none",
1263 )}
1265 <NumberField
1266 value={providerHealthRefreshIntervalSeconds}
1267 min={0}
1268 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
1269 size="sm"
1270 className="w-32"
1271 onValueChange={(value) =>
1272 updateSettings(
1273 backgroundActivityOverrideSettings(
1274 settings.backgroundActivity,
1275 resolvedBackgroundActivity,
1277 providerHealthRefreshInterval: Duration.seconds(
1278 normalizeIntervalSeconds(value),
1279 ),
1280 },
1281 ),
1285 <NumberFieldGroup>
1286 <NumberFieldDecrement aria-label="Decrease provider health check interval" />
1287 <NumberFieldInput aria-label="Provider health check interval in seconds" />
1288 <NumberFieldIncrement aria-label="Increase provider health check interval" />
1289 </NumberFieldGroup>
1290 </NumberField>
1291 <span className="text-xs text-muted-foreground">seconds</span>
1292 </div>
1294 />
1295 </SettingsSection>
1296​
1297 {isAddInstanceDialogOpen && !readOnly ? (
1298 <AddProviderInstanceDialog
1299 open
1300 environmentId={environmentId}
1301 environmentLabel={environmentLabel}
1302 onOpenChange={setIsAddInstanceDialogOpen}
1303 onCreated={setSelectedInstanceId}
1304 />
1305 ) : null}
1306 </>
1307 );