Skip to content
TypeScript

refactor(web): provider settings and Codex setup run as explicit flows (#25524)

Julius Marminge374e57d90bf9
diff --git a/apps/web/src/components/settings/AcpRegistryIcon.tsx b/apps/web/src/components/settings/AcpRegistryIcon.tsx
index 22277d55d4c..b7a5938ee89 100644
--- a/apps/web/src/components/settings/AcpRegistryIcon.tsx
+++ b/apps/web/src/components/settings/AcpRegistryIcon.tsx
@@ -1,4 +1,8 @@
-import { useEffect, useId, useState } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { useId, useState } from "react";
import {
resolveOfficialAcpRegistryIconUrl,
officialAcpRegistryIconUrlForAgentId,
@@ -66,6 +70,33 @@ export function loadCachedAcpRegistryIcon(iconUrl: string): Promise<Blob> {
return load;
}
+// Falls back to the raw allowlisted CDN URL when the validating fetch fails: the
+// CDN serves no CORS headers, so the fetch is often blocked cross-origin while
+// native <img> loading still works. The object URL is shared per agent and
+// revoked when the last icon unmounts.
+const acpRegistryIconSourceAtom = Atom.family((iconUrl: string) =>
+ Atom.make((get) => {
+ let disposed = false;
+ let objectUrl: string | null = null;
+ get.addFinalizer(() => {
+ disposed = true;
+ if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
+ });
+ return Effect.promise(() =>
+ loadCachedAcpRegistryIcon(iconUrl).then(
+ (blob) => {
+ if (disposed) return iconUrl;
+ objectUrl = URL.createObjectURL(blob);
+ return objectUrl;
+ },
+ () => iconUrl,
+ ),
+ );
+ }).pipe(Atom.withLabel(`acp-registry-icon:${iconUrl}`)),
+);
+
+const NO_ICON_SOURCE_ATOM = Atom.make(AsyncResult.initial<string>());
+
export function AcpRegistryAgentIcon({
icon,
className,
@@ -77,37 +108,18 @@ export function AcpRegistryAgentIcon({
}) {
const colorFilterId = useId();
const iconUrl = resolveOfficialAcpRegistryIconUrl(icon);
+ // Render only after the load pipeline resolves, so the fallback icon does
+ // not flash a broken image.
+ const source = Option.getOrNull(
+ AsyncResult.value(
+ useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)),
+ ),
+ );
const [image, setImage] = useState<{
- readonly iconUrl: string;
readonly source: string;
- readonly status: "loading" | "loaded" | "failed";
+ readonly status: "loaded" | "failed";
} | null>(null);
- const currentImage = image?.iconUrl === iconUrl ? image : null;
- // The CDN lacks CORS headers; native img loading can succeed after a validating fetch fails.
- const source = currentImage?.source ?? null;
- const status = currentImage?.status ?? "loading";
-
- useEffect(() => {
- if (iconUrl === null) return;
- let active = true;
- let objectUrl: string | null = null;
- void loadCachedAcpRegistryIcon(iconUrl)
- .then((blob) => {
- if (!active) return;
- objectUrl = URL.createObjectURL(blob);
- setImage({ iconUrl, source: objectUrl, status: "loading" });
- })
- .catch(() => {
- if (!active) return;
- setImage((current) =>
- current?.iconUrl === iconUrl ? current : { iconUrl, source: iconUrl, status: "loading" },
- );
- });
- return () => {
- active = false;
- if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
- };
- }, [iconUrl]);
+ const status = source !== null && image?.source === source ? image.status : "loading";
return (
<span
@@ -144,17 +156,8 @@ export function AcpRegistryAgentIcon({
decoding="async"
referrerPolicy="no-referrer"
src={source}
- onError={() => {
- if (iconUrl === null) return;
- setImage((current) =>
- current?.iconUrl === iconUrl && current.source !== source
- ? current
- : { iconUrl, source, status: "failed" },
- );
- }}
- onLoad={() => {
- if (iconUrl !== null) setImage({ iconUrl, source, status: "loaded" });
- }}
+ onError={() => setImage({ source, status: "failed" })}
+ onLoad={() => setImage({ source, status: "loaded" })}
/>
) : null}
</span>
diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
index dd3b74027c6..c6f48b8380a 100644
--- a/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
+++ b/apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
@@ -2,7 +2,7 @@ import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "
import { expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
-import { act, render } from "../../../test/render";
+import { render } from "../../../test/render";
const state = vi.hoisted(() => ({
result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
@@ -46,7 +46,7 @@ vi.mock(import("../../state/use-atom-command"), async (original) => ({
useAtomCommand: (() => state.prepare) as never,
}));
-import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
+import { AcpRegistrySearchStep, useAcpRegistrySearch } from "./AcpRegistrySearchStep";
const environmentId = EnvironmentId.make("remote-device");
const gemini: AcpRegistrySearchAgent = {
@@ -63,15 +63,20 @@ const gemini: AcpRegistrySearchAgent = {
integrity: "registry",
};
-function step(options?: {
+function Step({
+ configured = false,
+ onPrepared = vi.fn(),
+}: {
readonly configured?: boolean;
readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
}) {
+ const registry = useAcpRegistrySearch(environmentId, true);
return (
<AcpRegistrySearchStep
environmentId={environmentId}
+ registry={registry}
providerInstances={
- options?.configured
+ configured
? {
acpRegistry_gemini: {
driver: ProviderDriverKind.make("acpRegistry"),
@@ -80,20 +85,12 @@ function step(options?: {
}
: {}
}
- onPrepared={options?.onPrepared ?? vi.fn()}
+ onPrepared={onPrepared}
onManualConfiguration={vi.fn()}
/>
);
}
-function deferred<T>() {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>((done) => {
- resolve = done;
- });
- return { promise, resolve };
-}
-
function setup() {
state.canManage = true;
state.result = null;
@@ -111,7 +108,7 @@ it("rechecks the grant before preparing an agent", async () => {
setup();
state.result = { agents: [gemini] };
const onPrepared = vi.fn();
- await using _screen = await render(step({ onPrepared }));
+ await using _screen = await render(<Step onPrepared={onPrepared} />);
state.canManage = false;
await page.getByRole("button", { name: "Add Gemini CLI" }).click();
@@ -119,23 +116,3 @@ it("rechecks the grant before preparing an agent", async () => {
expect(state.prepare).not.toHaveBeenCalled();
expect(onPrepared).not.toHaveBeenCalled();
});
-
-it("ignores prepare completion after unmount", async () => {
- setup();
- const pending = deferred<unknown>();
- state.prepare.mockReturnValueOnce(pending.promise);
- state.result = { agents: [gemini] };
- const onPrepared = vi.fn();
- await using screen = await render(step({ onPrepared }));
-
- await page.getByRole("button", { name: "Add Gemini CLI" }).click();
- await screen.unmount();
- await act(async () =>
- pending.resolve({
- _tag: "Success",
- value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
- }),
- );
-
- expect(onPrepared).not.toHaveBeenCalled();
-});
diff --git a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx
index 9449ceba627..19b9a0f61f2 100644
--- a/apps/web/src/components/settings/AcpRegistrySearchStep.tsx
+++ b/apps/web/src/components/settings/AcpRegistrySearchStep.tsx
@@ -11,8 +11,9 @@ import type {
ProviderInstanceConfig,
} from "@t3tools/contracts";
import { ExternalLinkIcon, SearchIcon } from "lucide-react";
-import { type FormEvent, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { type FormEvent, useState } from "react";
+import { useDeadlinePassed } from "../../hooks/useDeadline";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -31,15 +32,7 @@ function errorMessage(error: unknown): string {
: "The ACP could not be prepared.";
}
-interface AcpRegistrySearchStepProps {
- readonly environmentId: EnvironmentId;
- readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
- readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
- readonly onManualConfiguration: () => void;
- readonly onLocalConfiguration?: () => void;
- readonly onLoadingChange?: (loading: boolean) => void;
- readonly onPreparingChange?: (preparing: boolean) => void;
-}
+const ACP_REGISTRY_SEARCH_DEBOUNCE_MS = 300;
function applyAcpRegistryPrepareResult(
agent: AcpRegistrySearchAgent,
@@ -53,77 +46,102 @@ function applyAcpRegistryPrepareResult(
};
}
-export function AcpRegistrySearchStep({
- environmentId,
- providerInstances,
- onPrepared,
- onManualConfiguration,
- onLocalConfiguration,
- onLoadingChange,
- onPreparingChange,
-}: AcpRegistrySearchStepProps) {
- const [query, setQuery] = useState("");
- const [submittedQuery, setSubmittedQuery] = useState("");
- const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
+/**
+ * Registry search and agent preparation. Owned by the dialog, which needs the
+ * loading and preparing state for its layout and navigation, and rendered by
+ * AcpRegistrySearchStep. Pass `enabled: false` while the step is hidden so the
+ * search is not kept subscribed.
+ */
+export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: boolean) {
+ const [input, setInput] = useState<{
+ readonly text: string;
+ readonly submitted: string;
+ readonly typedAt: number | null;
+ }>({ text: "", submitted: "", typedAt: null });
+ const typingSettled = useDeadlinePassed(
+ input.typedAt === null ? null : input.typedAt + ACP_REGISTRY_SEARCH_DEBOUNCE_MS,
+ );
+ const submittedQuery = typingSettled ? input.text.trim() : input.submitted;
const [preparingId, setPreparingId] = useState<string | null>(null);
const [prepareError, setPrepareError] = useState<string | null>(null);
- const prepareGeneration = useRef(0);
- const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const search = useEnvironmentQuery(
- serverEnvironment.searchAcpRegistry({
- environmentId,
- input: submittedQuery
- ? { query: submittedQuery }
- : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
- }),
+ enabled
+ ? serverEnvironment.searchAcpRegistry({
+ environmentId,
+ input: submittedQuery
+ ? { query: submittedQuery }
+ : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
+ })
+ : null,
);
const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, {
reportFailure: false,
});
- useEffect(
- () => () => {
- prepareGeneration.current += 1;
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
- onPreparingChange?.(false);
+ return {
+ query: input.text,
+ search,
+ preparingId,
+ prepareError,
+ type: (text: string) => {
+ setPrepareError(null);
+ setInput({ text, submitted: submittedQuery, typedAt: Date.now() });
+ },
+ submit: () => {
+ const trimmed = input.text.trim();
+ setPrepareError(null);
+ setInput({ text: trimmed, submitted: trimmed, typedAt: null });
+ if (trimmed === submittedQuery) search.refresh();
+ },
+ prepare: async (
+ agent: AcpRegistrySearchAgent,
+ onPrepared: (agent: AcpRegistrySearchAgent) => void,
+ ) => {
+ if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
+ setPrepareError(null);
+ setPreparingId(agent.id);
+ const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
+ setPreparingId(null);
+ if (result._tag === "Success") {
+ onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
+ return;
+ }
+ if (!isAtomCommandInterrupted(result)) {
+ setPrepareError(errorMessage(squashAtomCommandFailure(result)));
+ }
},
- [onPreparingChange],
- );
-
- const submitSearch = (nextQuery: string) => {
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
- const trimmed = nextQuery.trim();
- setQuery(trimmed);
- setPrepareError(null);
- if (trimmed === submittedQuery) {
- search.refresh();
- } else {
- setSubmittedQuery(trimmed);
- }
};
+}
+
+export type AcpRegistrySearch = ReturnType<typeof useAcpRegistrySearch>;
+
+interface AcpRegistrySearchStepProps {
+ readonly environmentId: EnvironmentId;
+ readonly registry: AcpRegistrySearch;
+ readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
+ readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
+ readonly onManualConfiguration: () => void;
+ readonly onLocalConfiguration?: () => void;
+}
+
+export function AcpRegistrySearchStep({
+ environmentId,
+ registry,
+ providerInstances,
+ onPrepared,
+ onManualConfiguration,
+ onLocalConfiguration,
+}: AcpRegistrySearchStepProps) {
+ const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
+ const { query, search, preparingId, prepareError } = registry;
const handleSearch = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
- submitSearch(query);
+ registry.submit();
};
- const handlePrepare = async (agent: AcpRegistrySearchAgent) => {
- if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
- const generation = ++prepareGeneration.current;
- setPrepareError(null);
- setPreparingId(agent.id);
- onPreparingChange?.(true);
- const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
- if (prepareGeneration.current !== generation) return;
- setPreparingId(null);
- onPreparingChange?.(false);
- if (result._tag === "Success") {
- onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
- return;
- }
- if (!isAtomCommandInterrupted(result)) {
- setPrepareError(errorMessage(squashAtomCommandFailure(result)));
- }
+ const handlePrepare = (agent: AcpRegistrySearchAgent) => {
+ void registry.prepare(agent, onPrepared);
};
const results = search.data?.agents ?? null;
@@ -131,11 +149,6 @@ export function AcpRegistrySearchStep({
const isRefreshing = search.isPending && results !== null;
const resultCount = results?.length ?? 0;
- useLayoutEffect(() => {
- onLoadingChange?.(search.isPending);
- return () => onLoadingChange?.(false);
- }, [onLoadingChange, search.isPending]);
-
return (
<section className="grid gap-3" aria-labelledby="acp-registry-search-heading">
<h3 className="sr-only" id="acp-registry-search-heading">
@@ -150,16 +163,7 @@ export function AcpRegistrySearchStep({
<InputGroupInput
aria-label="Search ACP Registry"
disabled={preparingId !== null}
- onChange={(event) => {
- const nextQuery = event.currentTarget.value;
- setQuery(nextQuery);
- setPrepareError(null);
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
- searchTimer.current = setTimeout(() => {
- searchTimer.current = null;
- setSubmittedQuery(nextQuery.trim());
- }, 300);
- }}
+ onChange={(event) => registry.type(event.currentTarget.value)}
placeholder="Search agents…"
size="sm"
type="search"
diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
index 127ec4ccac3..85ea937ebaa 100644
--- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
@@ -47,7 +47,7 @@ import {
type WizardNavigation,
} from "./AddProviderInstanceDialog.logic";
import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
-import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
+import { AcpRegistrySearchStep, useAcpRegistrySearch } from "./AcpRegistrySearchStep";
import { ProviderWizardAuthenticationStep } from "./ProviderWizardAuthenticationStep";
import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon";
import { AddManagedCodexAccountDialog } from "./CodexSetupSection";
@@ -113,8 +113,6 @@ export function AddProviderInstanceDialog({
ReadonlyArray<ProviderInstanceEnvironmentVariable>
>([]);
const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false);
- const [isRegistryLoading, setIsRegistryLoading] = useState(false);
- const [isPreparingRegistryAgent, setIsPreparingRegistryAgent] = useState(false);
const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
const [isSaving, setIsSaving] = useState(false);
@@ -130,6 +128,13 @@ export function AddProviderInstanceDialog({
const driverOption = providerClients.get(driver) ?? DEFAULT_DRIVER_OPTION;
const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND;
+ const showRegistrySearch =
+ !createdInstanceId &&
+ !addingChatGptAccount &&
+ wizardStep === 0 &&
+ !(isAcpRegistry && isManualAcpConfiguration);
+ const registry = useAcpRegistrySearch(environmentId, showRegistrySearch);
+ const isPreparingRegistryAgent = registry.preparingId !== null;
const defaultIdentity: ProviderIdentityDraft = {
label: driverOption.label,
accentColor: "",
@@ -388,7 +393,7 @@ export function AddProviderInstanceDialog({
<>
<WizardPanel
className={cn(isAcpRegistry && wizardStep === identityStep && "min-h-72")}
- holdHeight={wizardStep === 0 && !isManualAcpConfiguration && isRegistryLoading}
+ holdHeight={showRegistrySearch && registry.search.isPending}
>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
@@ -493,12 +498,11 @@ export function AddProviderInstanceDialog({
<>
<AcpRegistrySearchStep
environmentId={environmentId}
+ registry={registry}
providerInstances={settings.providerInstances}
onPrepared={handleAcpPrepared}
onManualConfiguration={handleManualAcpConfiguration}
onLocalConfiguration={handleLocalAcpConfiguration}
- onLoadingChange={setIsRegistryLoading}
- onPreparingChange={setIsPreparingRegistryAgent}
/>
{isAcpRegistry && hasAttemptedSubmit && acpSelectionError ? (
<p className="mt-2 text-2xs text-destructive">{acpSelectionError}</p>
diff --git a/apps/web/src/components/settings/CliCommandSettingsRow.tsx b/apps/web/src/components/settings/CliCommandSettingsRow.tsx
index b7d98628591..47b4d7b837c 100644
--- a/apps/web/src/components/settings/CliCommandSettingsRow.tsx
+++ b/apps/web/src/components/settings/CliCommandSettingsRow.tsx
@@ -1,35 +1,27 @@
-import type { DesktopCliCommandState } from "@t3tools/contracts";
-import { useEffect, useState } from "react";
+import { useState } from "react";
+import {
+ desktopCliCommandStateAtom,
+ getDesktopCliCommandBridge,
+ refreshDesktopCliCommandState,
+} from "~/state/desktopCliCommand";
+import { useEnvironmentQuery } from "~/state/query";
import { Button } from "../ui/button";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { SettingsRow } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
export function CliCommandSettingsRow() {
- const bridge = typeof window === "undefined" ? undefined : window.desktopBridge?.cliCommand;
- const [state, setState] = useState<DesktopCliCommandState | null>(null);
+ const bridge = getDesktopCliCommandBridge();
+ const query = useEnvironmentQuery(bridge ? desktopCliCommandStateAtom : null);
+ const state = query.data;
const [pending, setPending] = useState(false);
- useEffect(() => {
- if (!bridge) return;
- let cancelled = false;
- void bridge
- .getState()
- .then((next) => {
- if (!cancelled) setState(next);
- })
- .catch(() => undefined);
- return () => {
- cancelled = true;
- };
- }, [bridge]);
-
const change = (action: "install" | "uninstall") => {
if (!bridge || pending) return;
setPending(true);
void bridge[action]()
- .then(setState)
+ .then(refreshDesktopCliCommandState)
.catch((error: unknown) => {
toastManager.add(
stackedThreadToast({
@@ -60,7 +52,7 @@ export function CliCommandSettingsRow() {
<Button
size="sm"
variant="outline"
- disabled={pending}
+ disabled={pending || query.isPending}
onClick={() => change(installed ? "uninstall" : "install")}
>
{installed ? "Remove" : "Install"}
diff --git a/apps/web/src/components/settings/CodexSetupSection.logic.test.ts b/apps/web/src/components/settings/CodexSetupSection.logic.test.ts
new file mode 100644
index 00000000000..5297d6e4fbb
--- /dev/null
+++ b/apps/web/src/components/settings/CodexSetupSection.logic.test.ts
@@ -0,0 +1,121 @@
+import type { ProviderAuthState, ProviderInstallState } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ settleAuthorizationPage,
+ settleHandoffAuthorizationPage,
+ settleProviderInstall,
+} from "./CodexSetupSection.logic";
+
+const install = (overrides: Partial<ProviderInstallState>) =>
+ ({
+ driver: "codex",
+ operationId: "op-1",
+ phase: "downloading",
+ downloadedBytes: 0,
+ totalBytes: null,
+ version: "0.2.0",
+ installedVersion: "0.1.0",
+ canRemove: true,
+ message: null,
+ ...overrides,
+ }) as ProviderInstallState;
+
+const auth = (overrides: Partial<ProviderAuthState>) =>
+ ({
+ instanceId: "codex",
+ phase: "starting",
+ flowId: "flow-1",
+ authorizationUrl: null,
+ expiresAt: null,
+ message: null,
+ ...overrides,
+ }) as ProviderAuthState;
+
+describe("settleProviderInstall", () => {
+ it("ignores the previous runtime while the update it started has not been pushed yet", () => {
+ const started = install({ operationId: "op-2", phase: "downloading" });
+ const previous = install({ operationId: "op-1", phase: "succeeded" });
+ expect(settleProviderInstall(started, previous)).toBeUndefined();
+ expect(settleProviderInstall(started, null)).toBeUndefined();
+ expect(settleProviderInstall(started, { ...started, phase: "extracting" })).toBeUndefined();
+ });
+
+ it("settles on the started operation's terminal phase", () => {
+ const started = install({ operationId: "op-2" });
+ expect(
+ settleProviderInstall(
+ started,
+ install({ operationId: "op-2", phase: "succeeded", installedVersion: "0.2.0" }),
+ ),
+ ).toBe(true);
+ expect(settleProviderInstall(started, install({ operationId: "op-2", phase: "failed" }))).toBe(
+ false,
+ );
+ expect(
+ settleProviderInstall(started, install({ operationId: "op-2", phase: "cancelled" })),
+ ).toBe(false);
+ });
+
+ it("settles immediately when start reused an existing runtime", () => {
+ expect(settleProviderInstall(install({ operationId: null, phase: "succeeded" }), null)).toBe(
+ true,
+ );
+ expect(
+ settleProviderInstall(
+ install({ operationId: null, phase: "idle", installedVersion: null }),
+ null,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("settleAuthorizationPage", () => {
+ it("waits for its own flow to reach the browser step", () => {
+ expect(settleAuthorizationPage(null, "flow-1")).toBeUndefined();
+ expect(settleAuthorizationPage(auth({ phase: "starting" }), "flow-1")).toBeUndefined();
+ expect(
+ settleAuthorizationPage(auth({ phase: "waiting", authorizationUrl: "https://a" }), "flow-1"),
+ ).toBe("https://a");
+ expect(
+ settleAuthorizationPage(
+ auth({
+ phase: "waiting",
+ authorizationUrl: "https://a",
+ interaction: {
+ type: "browser",
+ id: "interaction-1",
+ url: "https://b",
+ requiresConsent: false,
+ } as ProviderAuthState["interaction"],
+ }),
+ "flow-1",
+ ),
+ ).toBe("https://b");
+ });
+
+ it("ignores a flow another client started", () => {
+ expect(
+ settleAuthorizationPage(
+ auth({ flowId: "flow-2", phase: "waiting", authorizationUrl: "https://a" }),
+ "flow-1",
+ ),
+ ).toBeUndefined();
+ });
+
+ it("gives up when its flow ends before a page is available", () => {
+ expect(settleAuthorizationPage(auth({ phase: "failed" }), "flow-1")).toBeNull();
+ expect(settleAuthorizationPage(auth({ phase: "cancelled" }), "flow-1")).toBeNull();
+ expect(settleAuthorizationPage(auth({ phase: "succeeded" }), "flow-1")).toBeNull();
+ });
+
+ it("follows a handoff until the primary environment finishes", () => {
+ expect(
+ settleHandoffAuthorizationPage({
+ phase: "auth",
+ state: auth({ flowId: "primary-flow", phase: "waiting", authorizationUrl: "https://a" }),
+ }),
+ ).toBe("https://a");
+ expect(settleHandoffAuthorizationPage({ phase: "finished", profile: {} as never })).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/settings/CodexSetupSection.logic.ts b/apps/web/src/components/settings/CodexSetupSection.logic.ts
index 46868d513db..71e935a8e68 100644
--- a/apps/web/src/components/settings/CodexSetupSection.logic.ts
+++ b/apps/web/src/components/settings/CodexSetupSection.logic.ts
@@ -1,3 +1,9 @@
+import type {
+ ChatGptHandoffState,
+ ProviderAuthState,
+ ProviderInstallState,
+} from "@t3tools/contracts";
+
export function readCodexSetupMode(config: unknown): "managed" | "existing" {
return config !== null &&
typeof config === "object" &&
@@ -6,3 +12,50 @@ export function readCodexSetupMode(config: unknown): "managed" | "existing" {
? "managed"
: "existing";
}
+
+const RUNNING_INSTALL_PHASES = new Set(["downloading", "extracting", "verifying"]);
+
+/**
+ * Whether the `started` install left a usable runtime; `undefined` until settled.
+ * The subscription can still carry the previous operation's state when start
+ * returns, so only a state with the same operation id settles a running install.
+ */
+export function settleProviderInstall(
+ started: ProviderInstallState,
+ current: ProviderInstallState | null,
+): boolean | undefined {
+ const state = RUNNING_INSTALL_PHASES.has(started.phase)
+ ? current?.operationId === started.operationId
+ ? current
+ : null
+ : started;
+ if (state === null || RUNNING_INSTALL_PHASES.has(state.phase)) return undefined;
+ return state.phase !== "failed" && state.phase !== "cancelled" && state.installedVersion !== null;
+}
+
+/**
+ * The authorization page for a sign-in flow: a URL once the flow waits on the
+ * browser, `null` once it ends without one, `undefined` while it is still
+ * starting. A `flowId` limits this to one flow, because auth state is shared
+ * per instance and another client can start a flow of its own.
+ */
+export function settleAuthorizationPage(
+ state: ProviderAuthState | null,
+ flowId: string | null,
+): string | null | undefined {
+ if (state === null || state.flowId === null) return undefined;
+ if (flowId !== null && state.flowId !== flowId) return undefined;
+ if (state.phase === "succeeded" || state.phase === "failed" || state.phase === "cancelled")
+ return null;
+ if (state.phase !== "waiting") return undefined;
+ const url =
+ state.interaction?.type === "browser" ? state.interaction.url : state.authorizationUrl;
+ return url ?? undefined;
+}
+
+export function settleHandoffAuthorizationPage(
+ state: ChatGptHandoffState | null,
+): string | null | undefined {
+ if (state === null) return undefined;
+ return state.phase === "finished" ? null : settleAuthorizationPage(state.state, null);
+}
diff --git a/apps/web/src/components/settings/CodexSetupSection.tsx b/apps/web/src/components/settings/CodexSetupSection.tsx
index 9feafee33be..afdde3f13a6 100644
--- a/apps/web/src/components/settings/CodexSetupSection.tsx
+++ b/apps/web/src/components/settings/CodexSetupSection.tsx
@@ -1,5 +1,5 @@
import { AuthProvidersManageScope } from "@t3tools/contracts";
-import { useEnvironmentScope } from "../../state/session";
+import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -27,14 +27,14 @@ import {
} from "react";
import { ensureLocalApi } from "../../localApi";
-import {
- useEnvironmentHttpBaseUrl,
- usePrimaryEnvironmentId,
- useEnvironment,
-} from "../../state/environments";
+import { useEnvironmentHttpBaseUrl } from "../../state/environments";
+import { environmentPresentations } from "../../state/presentation";
+import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
+import { appAtomRegistry } from "../../rpc/atomRegistry";
+import { waitForQuerySettled } from "../../state/waitForQuerySettled";
import { Button } from "../ui/button";
import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
import { ChatGptUsageButton } from "./ChatGptUsageButton";
@@ -46,9 +46,46 @@ import { SettingsRow } from "./settingsLayout";
import { AddCodexAccountDialog } from "./AddCodexAccountDialog";
import { getOnboardingProviderState } from "../../onboarding/providerReadiness.logic";
import { getProviderSummary } from "./providerStatus";
+import {
+ settleAuthorizationPage,
+ settleHandoffAuthorizationPage,
+ settleProviderInstall,
+} from "./CodexSetupSection.logic";
const noop = () => undefined;
+const isLoopbackUrl = (url: string | null) => url !== null && isLoopbackHost(new URL(url).hostname);
+
+// A loopback server can receive the provider's callback itself, unless the
+// desktop shell offers to catch it on the client.
+const prefersClientCallback = (local: boolean) =>
+ !local || window.desktopBridge?.receiveProviderAuthCallback !== undefined;
+
+/**
+ * How a sign-in started now reaches the provider. Read at use time, because a
+ * sign-in can start minutes after the click that asked for it (once an install
+ * finishes), and the primary environment may have connected in between.
+ */
+function readSignInRouting(environmentId: EnvironmentId) {
+ const local = isLoopbackUrl(readPreparedConnection(environmentId)?.httpBaseUrl ?? null);
+ const clientCallback = prefersClientCallback(local);
+ const primaryEnvironmentId = appAtomRegistry.get(primaryEnvironmentIdAtom);
+ const primaryAuthEnvironmentId =
+ !local &&
+ primaryEnvironmentId !== null &&
+ appAtomRegistry.get(environmentPresentations.presentationAtom(primaryEnvironmentId))?.connection
+ .phase === "connected" &&
+ isLoopbackUrl(readPreparedConnection(primaryEnvironmentId)?.httpBaseUrl ?? null) &&
+ (window.desktopBridge !== undefined || isLoopbackHost(window.location.hostname))
+ ? primaryEnvironmentId
+ : null;
+ return {
+ clientCallback,
+ remoteWeb: clientCallback && !window.desktopBridge?.receiveProviderAuthCallback,
+ primaryAuthEnvironmentId,
+ };
+}
+
interface CodexSetupSectionProps {
readonly environmentId: EnvironmentId;
readonly instanceId: ProviderInstanceId;
@@ -240,7 +277,7 @@ function ManagedCodexSetup({
const url = auth?.interaction?.type === "browser" ? auth.interaction.url : auth?.authorizationUrl;
const installation = installQuery.data;
const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
- const local = httpBaseUrl !== null && isLoopbackHost(new URL(httpBaseUrl).hostname);
+ const local = isLoopbackUrl(httpBaseUrl);
const options = { reportFailure: false, reportDefect: false };
const startAuth = useAtomCommand(serverEnvironment.startProviderAuth, options);
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, options);
@@ -251,21 +288,8 @@ function ManagedCodexSetup({
const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, options);
const reconnectProfile = useAtomCommand(serverEnvironment.chatGptReconnectProfile, options);
const importProfile = useAtomCommand(serverEnvironment.chatGptImportProfile, options);
- const clientCallback =
- !handoff && (!local || window.desktopBridge?.receiveProviderAuthCallback !== undefined);
+ const clientCallback = !handoff && prefersClientCallback(local);
const remoteWeb = clientCallback && !window.desktopBridge?.receiveProviderAuthCallback;
- const primaryEnvironmentId = usePrimaryEnvironmentId();
- const primaryEnvironment = useEnvironment(primaryEnvironmentId);
- const primaryHttpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironmentId);
- const primaryAuthEnvironmentId =
- !local &&
- primaryEnvironmentId &&
- primaryEnvironment?.connection.phase === "connected" &&
- primaryHttpBaseUrl &&
- isLoopbackHost(new URL(primaryHttpBaseUrl).hostname) &&
- (window.desktopBridge !== undefined || isLoopbackHost(window.location.hostname))
- ? primaryEnvironmentId
- : null;
const returnUrl = new URL(window.location.href);
if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
if (returnUrl.pathname === "/settings/providers")
@@ -279,9 +303,19 @@ function ManagedCodexSetup({
const [awaitingProvider, setAwaitingProvider] = useState<"sign-in" | "handoff" | null>(null);
const pendingRef = useRef(false);
const [error, setError] = useState<string | null>(null);
- const continueWithSignIn = useRef<string | null>(null);
- const openRequested = useRef(false);
- const openedFlow = useRef<string | null>(null);
+ // The setup or sign-in this client started. Its follow-up steps (sign in
+ // once the install lands, open the page once the flow waits) belong to it
+ // alone, so Cancel, a new attempt, or unmounting abort them.
+ const operation = useRef<AbortController | null>(null);
+ const beginOperation = () => {
+ operation.current?.abort();
+ const controller = new AbortController();
+ operation.current = controller;
+ return controller.signal;
+ };
+ const abortOperation = () => operation.current?.abort();
+ // Once the card unmounts, nothing may start a sign-in or open a page on its behalf.
+ useEffect(() => () => operation.current?.abort(), []);
const [autoStartHandled, setAutoStartHandled] = useState(false);
const installed = installation?.installedVersion != null;
const authenticated = provider?.auth.status === "authenticated";
@@ -300,6 +334,8 @@ function ManagedCodexSetup({
) {
setAwaitingProvider(null);
}
+ // The server does not refresh the provider snapshot when a sign-in flow
+ // succeeds, and the flow can finish elsewhere (callback, pasted redirect URL).
useEffect(() => {
if (awaitingProvider && auth?.phase === "succeeded") {
void refreshProviders({ environmentId, input: { instanceId } });
@@ -398,21 +434,52 @@ function ManagedCodexSetup({
return run(() => cancelAuth({ environmentId, input: { instanceId, flowId: auth!.flowId! } }));
};
- const signIn = async (methodId = "chatgpt") => {
+ const receivingCallback = useRef<string | null>(null);
+ const openPage = async (
+ authorizationUrl: string,
+ flowId: string | null,
+ viaClientCallback: boolean,
+ ) => {
+ try {
+ const receive = window.desktopBridge?.receiveProviderAuthCallback;
+ if (receive && viaClientCallback && flowId) {
+ if (receivingCallback.current === authorizationUrl) {
+ await ensureLocalApi().shell.openExternal(authorizationUrl);
+ return;
+ }
+ receivingCallback.current = authorizationUrl;
+ const callbackUrl = await receive(authorizationUrl);
+ if (receivingCallback.current !== authorizationUrl) return;
+ receivingCallback.current = null;
+ await run(() =>
+ completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
+ );
+ } else {
+ await ensureLocalApi().shell.openExternal(authorizationUrl);
+ }
+ } catch {
+ setError(
+ "Could not finish sign-in on this computer. Try again or paste the redirect URL below.",
+ );
+ }
+ };
+
+ const signIn = async (methodId: string, signal: AbortSignal) => {
if (pendingRef.current) return;
- openRequested.current = true;
setTransferFailed(false);
setRequestedMethodId(methodId);
const returnUrl = new URL(window.location.href);
if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
if (returnUrl.pathname === "/settings/providers")
returnUrl.searchParams.set("instanceId", instanceId);
+ const { clientCallback, remoteWeb, primaryAuthEnvironmentId } =
+ readSignInRouting(environmentId);
if (primaryAuthEnvironmentId) {
const attemptId = `${handoffId}:${++handoffSequence.current}`;
- const succeeded = await run(
+ await run(
() => reconnectProfile({ environmentId, input: { instanceId, methodId } }),
- (profile) =>
- setHandoff({
+ (profile) => {
+ const nextHandoff = {
environmentId: primaryAuthEnvironmentId,
input: {
instanceId,
@@ -421,40 +488,73 @@ function ManagedCodexSetup({
returnUrl: returnUrl.toString(),
profile,
},
- }),
+ };
+ setHandoff(nextHandoff);
+ void waitForQuerySettled({
+ registry: appAtomRegistry,
+ atom: serverEnvironment.chatGptHandoffState(nextHandoff),
+ settle: settleHandoffAuthorizationPage,
+ signal,
+ }).then((page) => {
+ if (page && !signal.aborted) void openPage(page, null, false);
+ });
+ },
);
- if (!succeeded) openRequested.current = false;
return;
}
- if (
- !(await run(
- () =>
- startAuth({
- environmentId,
- input: {
- instanceId,
- methodId,
- returnUrl: returnUrl.toString(),
- callbackMode: clientCallback ? "client" : "server",
- },
- }),
- () => setAwaitingProvider("sign-in"),
- ))
- ) {
- openRequested.current = false;
- }
+ await run(
+ () =>
+ startAuth({
+ environmentId,
+ input: {
+ instanceId,
+ methodId,
+ returnUrl: returnUrl.toString(),
+ callbackMode: clientCallback ? "client" : "server",
+ },
+ }),
+ (started) => {
+ setAwaitingProvider("sign-in");
+ const startedFlowId = started.flowId;
+ // A remote browser cannot receive the callback, so the user opens the page from the card.
+ if (remoteWeb || startedFlowId === null) return;
+ const startedPage = settleAuthorizationPage(started, startedFlowId);
+ void (
+ startedPage !== undefined
+ ? Promise.resolve(startedPage)
+ : waitForQuerySettled({
+ registry: appAtomRegistry,
+ atom: serverEnvironment.providerAuthState(target),
+ settle: (state) => settleAuthorizationPage(state, startedFlowId),
+ signal,
+ })
+ ).then((page) => {
+ if (page && !signal.aborted) void openPage(page, startedFlowId, clientCallback);
+ });
+ },
+ );
};
const setup = async (methodId = "chatgpt") => {
if (unavailable || busy) return;
+ const signal = beginOperation();
if (installed && !updateAvailable) {
- await signIn(methodId);
- } else {
- continueWithSignIn.current = methodId;
- if (!(await run(() => startInstall({ environmentId, input: { instanceId } })))) {
- continueWithSignIn.current = null;
- }
+ await signIn(methodId, signal);
+ return;
}
+ await run(
+ () => startInstall({ environmentId, input: { instanceId } }),
+ (started) => {
+ void waitForQuerySettled({
+ registry: appAtomRegistry,
+ atom: serverEnvironment.providerInstallState(target),
+ settle: (current) => settleProviderInstall(started, current),
+ signal,
+ }).then((ready) => {
+ if (ready && !signal.aborted) void signIn(methodId, signal);
+ });
+ },
+ );
};
if (
@@ -476,48 +576,6 @@ function ManagedCodexSetup({
if (autoStartHandled) startAutomatically();
}, [autoStartHandled]);
- const signInAfterInstall = useEffectEvent((methodId: string) => signIn(methodId));
- useEffect(() => {
- if (!continueWithSignIn.current || pending || installActive) return;
- if (installation?.phase === "failed" || installation?.phase === "cancelled") {
- continueWithSignIn.current = null;
- } else if (installed) {
- const methodId = continueWithSignIn.current;
- continueWithSignIn.current = null;
- void signInAfterInstall(methodId);
- }
- }, [pending, installActive, installation?.phase, installed]);
-
- const receivingCallback = useRef<string | null>(null);
- const flowId = auth?.flowId;
- const openPage = async (authorizationUrl: string) => {
- try {
- const receive = window.desktopBridge?.receiveProviderAuthCallback;
- if (receive && clientCallback && flowId) {
- if (receivingCallback.current === authorizationUrl) {
- await ensureLocalApi().shell.openExternal(authorizationUrl);
- return;
- }
- receivingCallback.current = authorizationUrl;
- const callbackUrl = await receive(authorizationUrl);
- if (receivingCallback.current !== authorizationUrl) return;
- receivingCallback.current = null;
- await run(() =>
- completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
- );
- } else {
- await ensureLocalApi().shell.openExternal(authorizationUrl);
- }
- } catch {
- setError(
- "Could not finish sign-in on this computer. Try again or paste the redirect URL below.",
- );
- }
- };
- const openPageForFlow = useEffectEvent((authorizationUrl: string) => {
- void openPage(authorizationUrl);
- });
-
useEffect(() => {
if (!clientCallback || !url || !window.desktopBridge?.cancelProviderAuthCallback) return;
return () => {
@@ -526,21 +584,6 @@ function ManagedCodexSetup({
};
}, [clientCallback, url]);
- useEffect(() => {
- if (
- !openRequested.current ||
- auth?.phase !== "waiting" ||
- !auth.flowId ||
- !url ||
- openedFlow.current === auth.flowId
- )
- return;
- openedFlow.current = auth.flowId;
- openRequested.current = false;
- // oxlint-disable-next-line react/set-state-in-effect -- Opening the page may complete the flow through a server command, which marks itself pending.
- if (!remoteWeb) openPageForFlow(url);
- }, [auth?.phase, auth?.flowId, url, remoteWeb]);
-
const runtimeDescription =
installation?.phase === "downloading"
? `Downloading ${(installation.downloadedBytes / 1_000_000).toFixed(1)}${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)}`} MB.`
@@ -606,7 +649,7 @@ function ManagedCodexSetup({
onClick={() => {
if (handoffQuery.data?.phase === "finished")
void transferProfile(handoffQuery.data.profile);
- else if (url) void openPage(url);
+ else if (url) void openPage(url, auth?.flowId ?? null, clientCallback);
}}
>
{finishingSignIn
@@ -815,8 +858,7 @@ function ManagedCodexSetup({
variant="ghost-muted"
disabled={pending || readOnly}
onClick={() => {
- openRequested.current = false;
- continueWithSignIn.current = null;
+ abortOperation();
if (handoff || (authActive && auth?.flowId)) void cancelSignIn();
else if (installation?.operationId)
void run(() =>
@@ -879,7 +921,7 @@ function ManagedCodexSetup({
disabled={pending || readOnly}
onClick={() => {
if (!handoff && !auth?.flowId) return;
- openRequested.current = false;
+ abortOperation();
void cancelSignIn();
onSignInCancelled?.();
}}
@@ -895,7 +937,7 @@ function ManagedCodexSetup({
disabled={pending || readOnly}
onClick={() => {
if (!installation?.operationId) return;
- continueWithSignIn.current = null;
+ abortOperation();
void run(() =>
cancelInstall({
environmentId,
diff --git a/apps/web/src/components/settings/ProviderAccentColorPicker.tsx b/apps/web/src/components/settings/ProviderAccentColorPicker.tsx
index 00759dad856..3914935a76c 100644
--- a/apps/web/src/components/settings/ProviderAccentColorPicker.tsx
+++ b/apps/web/src/components/settings/ProviderAccentColorPicker.tsx
@@ -1,5 +1,5 @@
import { PlusIcon, XIcon } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState, type PointerEvent } from "react";
import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";
import { ColorHueSlider, ColorSaturationValuePlane } from "../ui/color-picker";
@@ -12,32 +12,58 @@ const FALLBACK_ACCENT_COLOR = "#2563eb";
function ProviderCustomColorPanel(props: {
readonly value: string;
+ readonly onPreview: (value: string) => void;
readonly onCommit: (value: string) => void;
}) {
- const { onCommit } = props;
+ const { onCommit, onPreview } = props;
const [hsv, setHsv] = useState(() => hexToHsv(props.value));
const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v);
const [hexDraft, setHexDraft] = useState<string | null>(null);
+ // Pointer drags only preview and commit once on release, so a drag writes
+ // settings once instead of on every pointer move. Keyboard steps commit
+ // immediately because they have no release to wait for. Holds the latest
+ // dragged color, or null when no drag is in progress.
+ const drag = useRef<string | null>(null);
+ const startDrag = (event: PointerEvent<HTMLDivElement>) => {
+ if (event.button === 0) drag.current = currentColor;
+ };
- const commitHsv = (nextHsv: HsvColor) => {
+ const changeHsv = (nextHsv: HsvColor) => {
setHsv(nextHsv);
- onCommit(hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v));
+ const color = hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
+ if (drag.current === null) {
+ onCommit(color);
+ return;
+ }
+ drag.current = color;
+ onPreview(color);
+ };
+ const endDrag = () => {
+ const color = drag.current;
+ drag.current = null;
+ if (color !== null) onCommit(color);
};
return (
<div className="w-56 bg-popover">
- <ColorSaturationValuePlane
- label="Accent color"
- value={hsv}
- onChange={commitHsv}
- variant="edge"
- />
- <div className="grid gap-3 p-3">
- <ColorHueSlider
- label="Accent color hue"
- value={hsv.h}
- onChange={(h) => commitHsv({ ...hsv, h })}
+ <div onPointerDownCapture={startDrag}>
+ <ColorSaturationValuePlane
+ label="Accent color"
+ value={hsv}
+ onChange={changeHsv}
+ onInteractionEnd={endDrag}
+ variant="edge"
/>
+ </div>
+ <div className="grid gap-3 p-3">
+ <div onPointerDownCapture={startDrag}>
+ <ColorHueSlider
+ label="Accent color hue"
+ value={hsv.h}
+ onChange={(h) => changeHsv({ ...hsv, h })}
+ onInteractionEnd={endDrag}
+ />
+ </div>
<Input
nativeInput
size="compact"
@@ -47,7 +73,7 @@ function ProviderCustomColorPanel(props: {
setHexDraft(nextColor);
if (!/^#[\da-f]{6}$/i.test(nextColor)) return;
setHsv(hexToHsv(nextColor));
- props.onCommit(nextColor);
+ onCommit(nextColor);
}}
onBlur={() => setHexDraft(null)}
font="mono"
@@ -62,13 +88,19 @@ function ProviderCustomColorPanel(props: {
function ProviderCustomColorPicker(props: {
readonly displayName: string;
readonly value: string | undefined;
+ readonly onPreview: (value: string) => void;
readonly onCommit: (value: string) => void;
readonly onClear: () => void;
+ readonly onClose: () => void;
}) {
const normalized = normalizeProviderAccentColor(props.value);
return (
- <Popover>
+ <Popover
+ onOpenChange={(open) => {
+ if (!open) props.onClose();
+ }}
+ >
<PopoverTrigger
render={
<Button
@@ -89,6 +121,7 @@ function ProviderCustomColorPicker(props: {
<PopoverPopup side="bottom" align="start" sideOffset={6} padding="none">
<ProviderCustomColorPanel
value={normalized ?? FALLBACK_ACCENT_COLOR}
+ onPreview={props.onPreview}
onCommit={props.onCommit}
/>
{normalized ? (
@@ -119,78 +152,45 @@ export function ProviderAccentColorPicker(props: {
readonly value: string | undefined;
readonly onCommit: (value: string) => void;
readonly description?: string;
- readonly commitDelayMs?: number;
readonly layout?: "stacked" | "inline";
}) {
- const {
- commitDelayMs = 0,
- description,
- displayName,
- layout = "stacked",
- onCommit,
- value,
- } = props;
- const [optimisticValue, setOptimisticValue] = useState(() => value ?? "");
- const commitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const pendingCommitRef = useRef<string | null>(null);
- const onCommitRef = useRef(onCommit);
-
- useEffect(() => {
- onCommitRef.current = onCommit;
- }, [onCommit]);
-
- useEffect(() => {
- if (pendingCommitRef.current !== null) return;
- setOptimisticValue(value ?? "");
- }, [value]);
-
- useEffect(() => {
- return () => {
- if (commitTimeoutRef.current !== null) {
- clearTimeout(commitTimeoutRef.current);
- }
- const pendingCommit = pendingCommitRef.current;
- if (pendingCommit !== null) {
- onCommitRef.current(pendingCommit);
- }
- };
- }, []);
-
- const commitAccentColor = (value: string) => {
- const normalizedValue = normalizeProviderAccentColor(value) ?? "";
- setOptimisticValue(normalizedValue);
-
- if (commitDelayMs <= 0) {
- pendingCommitRef.current = null;
- if (commitTimeoutRef.current !== null) {
- clearTimeout(commitTimeoutRef.current);
- commitTimeoutRef.current = null;
- }
- onCommit(normalizedValue);
- return;
- }
-
- pendingCommitRef.current = normalizedValue;
- if (commitTimeoutRef.current !== null) {
- clearTimeout(commitTimeoutRef.current);
- }
- commitTimeoutRef.current = setTimeout(() => {
- commitTimeoutRef.current = null;
- const pendingCommit = pendingCommitRef.current;
- pendingCommitRef.current = null;
- if (pendingCommit !== null) {
- onCommitRef.current(pendingCommit);
- }
- }, commitDelayMs);
+ const { description, displayName, layout = "stacked", onCommit } = props;
+ const value = props.value ?? "";
+ // The draft shows a dragged or just-committed color only while `value` is
+ // still the one it was picked against, so the persisted value (or any outside
+ // change) takes over as soon as it lands. `previewing` marks a drag that has
+ // not been committed yet, which closing the popover commits.
+ const [draft, setDraft] = useState<{
+ readonly color: string;
+ readonly base: string;
+ readonly previewing: boolean;
+ } | null>(null);
+ if (draft !== null && draft.base !== value) setDraft(null);
+ const shownValue = draft !== null && draft.base === value ? draft.color : value;
+ const commit = (color: string) => {
+ const normalized = normalizeProviderAccentColor(color) ?? "";
+ setDraft({ color: normalized, base: value, previewing: false });
+ // Not deduplicated against `value`: it is stale while an earlier commit is
+ // in flight, so returning to it must still be submitted.
+ onCommit(normalized);
};
- const normalized = normalizeProviderAccentColor(optimisticValue);
const picker = (
<ProviderCustomColorPicker
displayName={displayName}
- value={normalized}
- onCommit={commitAccentColor}
- onClear={() => commitAccentColor("")}
+ value={normalizeProviderAccentColor(shownValue)}
+ onPreview={(color) =>
+ setDraft({
+ color: normalizeProviderAccentColor(color) ?? "",
+ base: value,
+ previewing: true,
+ })
+ }
+ onCommit={commit}
+ onClear={() => commit("")}
+ onClose={() => {
+ if (draft?.previewing && draft.base === value) commit(draft.color);
+ }}
/>
);
diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx
index ab825090e73..d190007399f 100644
--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx
+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx
@@ -15,7 +15,7 @@ import {
import { Lock as LockGlyph, LockOpen } from "lucide";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";
-import { useEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
+import { useState, type ReactElement, type ReactNode } from "react";
import {
isProviderDriverKind,
resolveProviderInstanceEnabled,
@@ -53,7 +53,12 @@ import type {
ProviderClientDefinition,
ProviderEnvironmentField,
} from "@t3tools/provider-core/client";
-import { deriveProviderSettingsFields, ProviderSettingsForm } from "./ProviderSettingsForm";
+import {
+ deriveProviderSettingsFields,
+ ProviderSettingsForm,
+ reconcileRowsDraft,
+ seedRowsDraft,
+} from "./ProviderSettingsForm";
import { ProviderModelsSection } from "./ProviderModelsSection";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
@@ -112,6 +117,9 @@ function makeEnvironmentDraftRow(
};
}
+const toEnvironmentDraftRows = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) =>
+ environment.map(makeEnvironmentDraftRow);
+
function providerEnvironmentsEqual(
left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
@@ -300,29 +308,19 @@ export function ProviderEnvironmentSection(props: {
readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
}) {
- const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
- props.environment.map(makeEnvironmentDraftRow),
+ const [storedDraft, setDraft] = useState(() =>
+ seedRowsDraft(props.environment, toEnvironmentDraftRows),
);
- const previousEnvironmentRef = useRef(props.environment);
- const lastPublishedEnvironmentRef = useRef<
- ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
- >(undefined);
-
- useEffect(() => {
- const previousEnvironment = previousEnvironmentRef.current;
- const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
- previousEnvironmentRef.current = props.environment;
- lastPublishedEnvironmentRef.current = undefined;
- if (
- previousEnvironment === props.environment ||
- providerEnvironmentsEqual(previousEnvironment, props.environment) ||
- (lastPublishedEnvironment !== undefined &&
- providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
- ) {
- return;
- }
- setRows(props.environment.map(makeEnvironmentDraftRow));
- }, [props.environment]);
+ const draft = reconcileRowsDraft(
+ storedDraft,
+ props.environment,
+ providerEnvironmentsEqual,
+ toEnvironmentDraftRows,
+ );
+ if (draft !== storedDraft) setDraft(draft);
+ const rows = draft.rows;
+ const setRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) =>
+ setDraft({ ...draft, rows: nextRows });
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
const published: ProviderInstanceEnvironmentVariable[] = [];
@@ -342,7 +340,7 @@ export function ProviderEnvironmentSection(props: {
const { id: _id, ...rest } = row;
published.push({ ...rest, name });
}
- lastPublishedEnvironmentRef.current = published;
+ setDraft({ rows: nextRows, seen: draft.seen, lastPublished: published });
props.onChange(published);
};
@@ -1156,7 +1154,6 @@ export function ProviderInstanceCard({
displayName={displayName}
value={accentColor}
onCommit={updateAccentColor}
- commitDelayMs={120}
/>
<DraftInput
id={`provider-instance-${instanceId}-display-name`}
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
index 1d989bcdf66..0d408e59fee 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts
+++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
@@ -6,6 +6,8 @@ import { providerClients } from "./providerDriverMeta";
import {
deriveProviderSettingsFields,
nextProviderConfigWithFieldValue,
+ reconcileRowsDraft,
+ seedRowsDraft,
} from "./ProviderSettingsForm";
describe("ProviderSettingsForm helpers", () => {
@@ -55,3 +57,33 @@ describe("ProviderSettingsForm helpers", () => {
expect(next).toEqual({ experimental: false });
});
});
+
+describe("reconcileRowsDraft", () => {
+ let nextId = 0;
+ const toRows = (values: ReadonlyArray<string>) =>
+ values.map((value) => ({ id: nextId++, value }));
+ const equal = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
+ left.length === right.length && left.every((value, index) => value === right[index]);
+
+ it("keeps rows when an equal value arrives with a new identity", () => {
+ const draft = seedRowsDraft(["a"], toRows);
+ expect(reconcileRowsDraft(draft, ["a"], equal, toRows)).toBe(draft);
+ });
+
+ it("keeps row ids when the published value echoes back", () => {
+ const seeded = seedRowsDraft(["a"], toRows);
+ const edited = { rows: [...seeded.rows, { id: 99, value: "" }], seen: seeded.seen };
+ const draft = { ...edited, lastPublished: ["a", ""] };
+ const next = reconcileRowsDraft(draft, ["a", ""], equal, toRows);
+ expect(next.rows).toBe(draft.rows);
+ expect(next.seen).toEqual(["a", ""]);
+ expect(next.lastPublished).toBeUndefined();
+ });
+
+ it("reseeds rows when the value changes from outside", () => {
+ const draft = { ...seedRowsDraft(["a"], toRows), lastPublished: ["b"] };
+ const next = reconcileRowsDraft(draft, ["c"], equal, toRows);
+ expect(next.rows.map((row) => row.value)).toEqual(["c"]);
+ expect(next.lastPublished).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx
index e1f41a5568a..a36f93fec7c 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, type ReactNode } from "react";
+import { useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
@@ -143,11 +143,44 @@ export function deriveProviderSettingsFields(
}
let commandArgumentDraftId = 0;
+/**
+ * Editable rows seeded from a configured value. `seen` is the value the rows
+ * were last reconciled against; `lastPublished` is what the rows last sent to
+ * the owner, so its echo does not reseed rows (and drop their ids) mid-edit.
+ */
+export interface RowsDraft<V, R> {
+ readonly rows: ReadonlyArray<R>;
+ readonly seen: V;
+ readonly lastPublished: V | undefined;
+}
+
+export function seedRowsDraft<V, R>(
+ value: V,
+ toRows: (value: V) => ReadonlyArray<R>,
+): RowsDraft<V, R> {
+ return { rows: toRows(value), seen: value, lastPublished: undefined };
+}
+
+/** Reseeds the rows when the configured value changes from outside this editor. */
+export function reconcileRowsDraft<V, R>(
+ draft: RowsDraft<V, R>,
+ incoming: V,
+ equal: (left: V, right: V) => boolean,
+ toRows: (value: V) => ReadonlyArray<R>,
+): RowsDraft<V, R> {
+ if (draft.seen === incoming || equal(draft.seen, incoming)) return draft;
+ const echo = draft.lastPublished !== undefined && equal(draft.lastPublished, incoming);
+ return { rows: echo ? draft.rows : toRows(incoming), seen: incoming, lastPublished: undefined };
+}
+
const makeCommandArgumentDraftRow = (value: string) => ({
id: `provider-argument-${commandArgumentDraftId++}`,
value,
});
+const toCommandArgumentRows = (args: ReadonlyArray<string>) =>
+ args.map(makeCommandArgumentDraftRow);
+
function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
return left.length === right.length && left.every((argument, index) => argument === right[index]);
}
@@ -167,31 +200,14 @@ function ProviderCommandArguments({
onChange,
}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
const args = configuredCommandArgs(value);
- const [rows, setRows] = useState(() => args.map(makeCommandArgumentDraftRow));
- const rowsRef = useRef(rows);
- const previousArgsRef = useRef(args);
- const lastPublishedArgsRef = useRef<ReadonlyArray<string> | undefined>(undefined);
-
- useEffect(() => {
- const previousArgs = previousArgsRef.current;
- const lastPublishedArgs = lastPublishedArgsRef.current;
- previousArgsRef.current = args;
- lastPublishedArgsRef.current = undefined;
- if (
- commandArgumentsEqual(previousArgs, args) ||
- (lastPublishedArgs !== undefined && commandArgumentsEqual(lastPublishedArgs, args))
- )
- return;
- const nextRows = args.map(makeCommandArgumentDraftRow);
- rowsRef.current = nextRows;
- setRows(nextRows);
- }, [args]);
+ const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
+ const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
+ if (draft !== storedDraft) setDraft(draft);
+ const rows = draft.rows;
const updateArguments = (nextRows: typeof rows) => {
- rowsRef.current = nextRows;
- setRows(nextRows);
const next = nextRows.map((row) => row.value);
- lastPublishedArgsRef.current = next;
+ setDraft({ rows: nextRows, seen: draft.seen, lastPublished: next });
const config =
value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
onChange({ ...config, commandArgs: next });
@@ -206,7 +222,7 @@ function ProviderCommandArguments({
type="button"
size="sm"
variant="outline"
- onClick={() => updateArguments([...rowsRef.current, makeCommandArgumentDraftRow("")])}
+ onClick={() => updateArguments([...rows, makeCommandArgumentDraftRow("")])}
>
<PlusIcon />
Add argument
@@ -223,7 +239,7 @@ function ProviderCommandArguments({
value={argument.value}
onCommit={(next) =>
updateArguments(
- rowsRef.current.map((current) =>
+ rows.map((current) =>
current.id === argument.id ? { ...current, value: next } : current,
),
)
@@ -236,7 +252,7 @@ function ProviderCommandArguments({
size="icon-micro"
variant="ghost-destructive"
onClick={() =>
- updateArguments(rowsRef.current.filter((current) => current.id !== argument.id))
+ updateArguments(rows.filter((current) => current.id !== argument.id))
}
aria-label={`Remove argument ${index + 1}`}
>
diff --git a/apps/web/src/components/settings/colorPickers.browser.test.tsx b/apps/web/src/components/settings/colorPickers.browser.test.tsx
index 1f4915bd9ca..e468830ff3e 100644
--- a/apps/web/src/components/settings/colorPickers.browser.test.tsx
+++ b/apps/web/src/components/settings/colorPickers.browser.test.tsx
@@ -4,6 +4,7 @@ import { userEvent } from "vite-plus/test/browser";
import type { ReactNode } from "react";
import { act, render } from "../../../test/render";
+import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
import { ThemeColorField } from "./ThemeColorPicker";
const HUE = "Accent color hue";
@@ -58,8 +59,10 @@ async function renderThemeField(value: string) {
const field = (current: string) => (
<ThemeColorField role="accent" value={current} onChange={onChange} />
);
- const screen = await renderPicker(field(value));
+ await using stack = new AsyncDisposableStack();
+ const screen = stack.use(await renderPicker(field(value)));
await open("Choose Accent color color");
+ stack.move();
return Object.assign(screen, {
onChange,
echo: (current: string) => screen.rerender(field(current)),
@@ -82,3 +85,54 @@ describe("theme color field", () => {
expect(slider(HUE).getAttribute("aria-valuenow")).toBe("10");
});
});
+
+async function renderAccentPicker(value: string) {
+ const onCommit = vi.fn();
+ const picker = (current: string) => (
+ <ProviderAccentColorPicker displayName="Codex" value={current} onCommit={onCommit} />
+ );
+ await using stack = new AsyncDisposableStack();
+ const screen = stack.use(await renderPicker(picker(value)));
+ await open("Change accent color for Codex");
+ stack.move();
+ return Object.assign(screen, {
+ onCommit,
+ echo: (current: string) => screen.rerender(picker(current)),
+ });
+}
+
+describe("provider accent color picker", () => {
+ it("commits a drag that is still in progress when the popover closes", async () => {
+ await using screen = await renderAccentPicker("#ff0000");
+
+ await act(async () => {
+ pointer(HUE, "pointerdown", 0.5);
+ pointer(HUE, "pointermove", 0.5);
+ });
+ expect(screen.onCommit).not.toHaveBeenCalled();
+
+ await userEvent.keyboard("{Escape}");
+ expect(screen.onCommit).toHaveBeenCalledTimes(1);
+ expect(screen.onCommit.mock.calls[0]?.[0]).not.toBe("#ff0000");
+ });
+
+ it("saves a change back to the saved color while the first change is still saving", async () => {
+ await using screen = await renderAccentPicker("#ff0000");
+
+ await userEvent.fill(byLabel("Custom hex accent color"), "#00ff00");
+ await userEvent.fill(byLabel("Custom hex accent color"), "#ff0000");
+
+ expect(screen.onCommit).toHaveBeenLastCalledWith("#ff0000");
+ });
+
+ it("shows the saved color again when it is reverted outside the picker", async () => {
+ await using screen = await renderAccentPicker("#ff0000");
+
+ await userEvent.fill(byLabel("Custom hex accent color"), "#00ff00");
+ expect(screen.onCommit).toHaveBeenLastCalledWith("#00ff00");
+ await screen.echo("#00ff00");
+ await screen.echo("#ff0000");
+
+ expect(byLabel("Change accent color for Codex").style.backgroundColor).toBe("rgb(255, 0, 0)");
+ });
+});
diff --git a/apps/web/src/state/desktopCliCommand.test.ts b/apps/web/src/state/desktopCliCommand.test.ts
new file mode 100644
index 00000000000..3240c8b0632
--- /dev/null
+++ b/apps/web/src/state/desktopCliCommand.test.ts
@@ -0,0 +1,40 @@
+import type { DesktopCliCommandState } from "@t3tools/contracts";
+import { AtomRegistry } from "effect/reactivity";
+import * as AsyncResult from "effect/reactivity/AsyncResult";
+import { afterAll, describe, expect, it, vi } from "vite-plus/test";
+
+import { desktopCliCommandStateAtom } from "./desktopCliCommand";
+
+const getState = vi.fn<() => Promise<DesktopCliCommandState>>();
+vi.stubGlobal("window", { desktopBridge: { cliCommand: { getState } } });
+
+describe("desktopCliCommandStateAtom", () => {
+ afterAll(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("reloads stale state when Settings mounts it again", async () => {
+ getState.mockResolvedValue({
+ supported: true,
+ installedPath: null,
+ onPath: false,
+ launcherPath: null,
+ });
+ using now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);
+ const registry = AtomRegistry.make();
+
+ const unmountFirst = registry.mount(desktopCliCommandStateAtom);
+ await vi.waitFor(() => {
+ const result = registry.get(desktopCliCommandStateAtom);
+ expect(AsyncResult.isInitial(result) || result.waiting).toBe(false);
+ });
+ unmountFirst();
+ await vi.waitFor(() => expect(registry.getNodes().size).toBe(1));
+
+ now.mockReturnValue(1_060_000);
+ const unmountSecond = registry.mount(desktopCliCommandStateAtom);
+ await vi.waitFor(() => expect(getState).toHaveBeenCalledTimes(2));
+ unmountSecond();
+ registry.dispose();
+ });
+});
diff --git a/apps/web/src/state/desktopCliCommand.ts b/apps/web/src/state/desktopCliCommand.ts
new file mode 100644
index 00000000000..d30838d4045
--- /dev/null
+++ b/apps/web/src/state/desktopCliCommand.ts
@@ -0,0 +1,52 @@
+import type { DesktopBridge, DesktopCliCommandState } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import { Atom } from "effect/reactivity";
+
+import { appAtomRegistry } from "~/rpc/atomRegistry";
+
+type DesktopCliCommandBridge = NonNullable<DesktopBridge["cliCommand"]>;
+
+class DesktopCliCommandUnavailableError extends Schema.TaggedError<DesktopCliCommandUnavailableError>()(
+ "DesktopCliCommandUnavailableError",
+ {},
+) {
+ override get message(): string {
+ return "The t3 command is unavailable.";
+ }
+}
+
+class DesktopCliCommandLoadError extends Schema.TaggedError<DesktopCliCommandLoadError>()(
+ "DesktopCliCommandLoadError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Failed to load the t3 command state.";
+ }
+}
+
+export function getDesktopCliCommandBridge(): DesktopCliCommandBridge | undefined {
+ return typeof window === "undefined" ? undefined : window.desktopBridge?.cliCommand;
+}
+
+const loadDesktopCliCommandState = Effect.fn("loadDesktopCliCommandState")(function* () {
+ const bridge = getDesktopCliCommandBridge();
+ if (!bridge) {
+ return yield* new DesktopCliCommandUnavailableError();
+ }
+ return yield* Effect.tryPromise({
+ try: (): Promise<DesktopCliCommandState> => bridge.getState(),
+ catch: (cause) => new DesktopCliCommandLoadError({ cause }),
+ });
+});
+
+export const desktopCliCommandStateAtom = Atom.make(loadDesktopCliCommandState()).pipe(
+ // Keep the loaded state, but let the SWR wrapper revalidate when Settings remounts.
+ Atom.keepAlive,
+ Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
+ Atom.withLabel("desktop:cli-command:load"),
+);
+
+export function refreshDesktopCliCommandState(): void {
+ appAtomRegistry.refresh(desktopCliCommandStateAtom);
+}
diff --git a/apps/web/src/state/waitForQuerySettled.test.ts b/apps/web/src/state/waitForQuerySettled.test.ts
new file mode 100644
index 00000000000..846f15e37cc
--- /dev/null
+++ b/apps/web/src/state/waitForQuerySettled.test.ts
@@ -0,0 +1,56 @@
+import * as Cause from "effect/Cause";
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
+import { describe, expect, it } from "vite-plus/test";
+
+import { waitForQuerySettled } from "./waitForQuerySettled";
+
+const settle = (value: number | null) =>
+ value !== null && value >= 2 ? `settled:${value}` : undefined;
+
+describe("waitForQuerySettled", () => {
+ it("resolves with the first settled value", async () => {
+ const registry = AtomRegistry.make();
+ const atom = Atom.make(AsyncResult.success<number, string>(1));
+ const result = waitForQuerySettled({
+ registry,
+ atom,
+ settle,
+ signal: new AbortController().signal,
+ });
+ registry.set(atom, AsyncResult.success(2));
+ registry.set(atom, AsyncResult.success(3));
+ expect(await result).toBe("settled:2");
+ });
+
+ it("resolves at once when the current value already settles", async () => {
+ const registry = AtomRegistry.make();
+ const atom = Atom.make(AsyncResult.success<number, string>(5));
+ expect(
+ await waitForQuerySettled({ registry, atom, settle, signal: new AbortController().signal }),
+ ).toBe("settled:5");
+ });
+
+ it("resolves undefined when aborted", async () => {
+ const registry = AtomRegistry.make();
+ const atom = Atom.make(AsyncResult.success<number, string>(1));
+ const controller = new AbortController();
+ const result = waitForQuerySettled({ registry, atom, settle, signal: controller.signal });
+ controller.abort();
+ registry.set(atom, AsyncResult.success(2));
+ expect(await result).toBeUndefined();
+ });
+
+ it("resolves undefined when the query fails, even before any success", async () => {
+ const registry = AtomRegistry.make();
+ const atom = Atom.make<AsyncResult.AsyncResult<number, string>>(AsyncResult.initial());
+ const result = waitForQuerySettled({
+ registry,
+ atom,
+ settle,
+ signal: new AbortController().signal,
+ });
+ registry.set(atom, AsyncResult.failure(Cause.fail("stream closed")));
+ registry.set(atom, AsyncResult.success(2));
+ expect(await result).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/state/waitForQuerySettled.ts b/apps/web/src/state/waitForQuerySettled.ts
new file mode 100644
index 00000000000..159aed2efdc
--- /dev/null
+++ b/apps/web/src/state/waitForQuerySettled.ts
@@ -0,0 +1,38 @@
+import * as Option from "effect/Option";
+import { AsyncResult, type Atom, type AtomRegistry } from "effect/reactivity";
+
+/**
+ * Resolves with the first defined `settle` result for a query atom's value.
+ * Resolves `undefined` once `signal` aborts or the query fails, because a
+ * failed query can no longer report the state the caller is waiting for.
+ * Subscribing keeps the atom mounted, so the subscription ends on every exit.
+ */
+export function waitForQuerySettled<A, E, R>(input: {
+ readonly registry: AtomRegistry.AtomRegistry;
+ readonly atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
+ readonly settle: (value: A | null) => R | undefined;
+ readonly signal: AbortSignal;
+}): Promise<R | undefined> {
+ const { registry, atom, settle, signal } = input;
+ return new Promise((resolve) => {
+ let done = false;
+ let unsubscribe: (() => void) | undefined;
+ const finish = (result: R | undefined) => {
+ if (done) return;
+ done = true;
+ unsubscribe?.();
+ signal.removeEventListener("abort", onAbort);
+ resolve(result);
+ };
+ const onAbort = () => finish(undefined);
+ const check = (result: AsyncResult.AsyncResult<A, E>) => {
+ if (AsyncResult.isFailure(result)) return finish(undefined);
+ const settled = settle(Option.getOrNull(AsyncResult.value(result)));
+ if (settled !== undefined) finish(settled);
+ };
+ if (signal.aborted) return finish(undefined);
+ signal.addEventListener("abort", onAbort);
+ unsubscribe = registry.subscribe(atom, check, { immediate: true });
+ if (done) unsubscribe();
+ });
+}