The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): provider settings and Codex setup run as explicit flows (#25524)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 10:29 UTC
374e57d90bf9a646c16df654abbbdff1c988bfa4
17 files changed
+913
-432
apps/web/src/components/settings/AcpRegistryIcon.tsx
+43
-40
@@ -1,4 +1,8 @@
1
-import { useEffect, useId, useState } from "react";
1
+import { useAtomValue } from "@effect/atom-react";
2
+import * as Effect from "effect/Effect";
3
+import * as Option from "effect/Option";
4
+import { AsyncResult, Atom } from "effect/reactivity";
5
+import { useId, useState } from "react";
6
import {
7
resolveOfficialAcpRegistryIconUrl,
8
officialAcpRegistryIconUrlForAgentId,
@@ -66,6 +70,33 @@ export function loadCachedAcpRegistryIcon(iconUrl: string): Promise<Blob> {
70
return load;
71
}
72
73
+// Falls back to the raw allowlisted CDN URL when the validating fetch fails: the
74
+// CDN serves no CORS headers, so the fetch is often blocked cross-origin while
75
+// native <img> loading still works. The object URL is shared per agent and
76
+// revoked when the last icon unmounts.
77
+const acpRegistryIconSourceAtom = Atom.family((iconUrl: string) =>
78
+ Atom.make((get) => {
79
+ let disposed = false;
80
+ let objectUrl: string | null = null;
81
+ get.addFinalizer(() => {
82
+ disposed = true;
83
+ if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
84
+ });
85
+ return Effect.promise(() =>
86
+ loadCachedAcpRegistryIcon(iconUrl).then(
87
+ (blob) => {
88
+ if (disposed) return iconUrl;
89
+ objectUrl = URL.createObjectURL(blob);
90
+ return objectUrl;
91
+ },
92
+ () => iconUrl,
93
+ ),
94
+ );
95
+ }).pipe(Atom.withLabel(`acp-registry-icon:${iconUrl}`)),
96
+);
97
+
98
+const NO_ICON_SOURCE_ATOM = Atom.make(AsyncResult.initial<string>());
99
+
100
export function AcpRegistryAgentIcon({
101
icon,
102
className,
@@ -77,37 +108,18 @@ export function AcpRegistryAgentIcon({
108
}) {
109
const colorFilterId = useId();
110
const iconUrl = resolveOfficialAcpRegistryIconUrl(icon);
111
+ // Render only after the load pipeline resolves, so the fallback icon does
112
+ // not flash a broken image.
113
+ const source = Option.getOrNull(
114
+ AsyncResult.value(
115
+ useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)),
116
+ ),
117
+ );
118
const [image, setImage] = useState<{
81
- readonly iconUrl: string;
119
readonly source: string;
83
- readonly status: "loading" | "loaded" | "failed";
120
+ readonly status: "loaded" | "failed";
121
} | null>(null);
85
- const currentImage = image?.iconUrl === iconUrl ? image : null;
86
- // The CDN lacks CORS headers; native img loading can succeed after a validating fetch fails.
87
- const source = currentImage?.source ?? null;
88
- const status = currentImage?.status ?? "loading";
89
-
90
- useEffect(() => {
91
- if (iconUrl === null) return;
92
- let active = true;
93
- let objectUrl: string | null = null;
94
- void loadCachedAcpRegistryIcon(iconUrl)
95
- .then((blob) => {
96
- if (!active) return;
97
- objectUrl = URL.createObjectURL(blob);
98
- setImage({ iconUrl, source: objectUrl, status: "loading" });
99
- })
100
- .catch(() => {
101
- if (!active) return;
102
- setImage((current) =>
103
- current?.iconUrl === iconUrl ? current : { iconUrl, source: iconUrl, status: "loading" },
104
- );
105
- });
106
- return () => {
107
- active = false;
108
- if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
109
- };
110
- }, [iconUrl]);
122
+ const status = source !== null && image?.source === source ? image.status : "loading";
123
124
return (
125
<span
@@ -144,17 +156,8 @@ export function AcpRegistryAgentIcon({
156
decoding="async"
157
referrerPolicy="no-referrer"
158
src={source}
147
- onError={() => {
148
- if (iconUrl === null) return;
149
- setImage((current) =>
150
- current?.iconUrl === iconUrl && current.source !== source
151
- ? current
152
- : { iconUrl, source, status: "failed" },
153
- );
154
- }}
155
- onLoad={() => {
156
- if (iconUrl !== null) setImage({ iconUrl, source, status: "loaded" });
157
- }}
159
+ onError={() => setImage({ source, status: "failed" })}
160
+ onLoad={() => setImage({ source, status: "loaded" })}
161
/>
162
) : null}
163
</span>
apps/web/src/components/settings/AcpRegistrySearchStep.browser.test.tsx
+11
-34
@@ -2,7 +2,7 @@ import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "
2
import { expect, it, vi } from "vite-plus/test";
3
import { page } from "vite-plus/test/browser";
4
5
-import { act, render } from "../../../test/render";
5
+import { render } from "../../../test/render";
6
7
const state = vi.hoisted(() => ({
8
result: null as { readonly agents: ReadonlyArray<AcpRegistrySearchAgent> } | null,
@@ -46,7 +46,7 @@ vi.mock(import("../../state/use-atom-command"), async (original) => ({
46
useAtomCommand: (() => state.prepare) as never,
47
}));
48
49
-import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
49
+import { AcpRegistrySearchStep, useAcpRegistrySearch } from "./AcpRegistrySearchStep";
50
51
const environmentId = EnvironmentId.make("remote-device");
52
const gemini: AcpRegistrySearchAgent = {
@@ -63,15 +63,20 @@ const gemini: AcpRegistrySearchAgent = {
63
integrity: "registry",
64
};
65
66
-function step(options?: {
66
+function Step({
67
+ configured = false,
68
+ onPrepared = vi.fn(),
69
+}: {
70
readonly configured?: boolean;
71
readonly onPrepared?: (agent: AcpRegistrySearchAgent) => void;
72
}) {
73
+ const registry = useAcpRegistrySearch(environmentId, true);
74
return (
75
<AcpRegistrySearchStep
76
environmentId={environmentId}
77
+ registry={registry}
78
providerInstances={
74
- options?.configured
79
+ configured
80
? {
81
acpRegistry_gemini: {
82
driver: ProviderDriverKind.make("acpRegistry"),
@@ -80,20 +85,12 @@ function step(options?: {
85
}
86
: {}
87
}
83
- onPrepared={options?.onPrepared ?? vi.fn()}
88
+ onPrepared={onPrepared}
89
onManualConfiguration={vi.fn()}
90
/>
91
);
92
}
93
89
-function deferred<T>() {
90
- let resolve!: (value: T) => void;
91
- const promise = new Promise<T>((done) => {
92
- resolve = done;
93
- });
94
- return { promise, resolve };
95
-}
96
-
94
function setup() {
95
state.canManage = true;
96
state.result = null;
@@ -111,7 +108,7 @@ it("rechecks the grant before preparing an agent", async () => {
108
setup();
109
state.result = { agents: [gemini] };
110
const onPrepared = vi.fn();
114
- await using _screen = await render(step({ onPrepared }));
111
+ await using _screen = await render(<Step onPrepared={onPrepared} />);
112
state.canManage = false;
113
114
await page.getByRole("button", { name: "Add Gemini CLI" }).click();
@@ -119,23 +116,3 @@ it("rechecks the grant before preparing an agent", async () => {
116
expect(state.prepare).not.toHaveBeenCalled();
117
expect(onPrepared).not.toHaveBeenCalled();
118
});
122
-
123
-it("ignores prepare completion after unmount", async () => {
124
- setup();
125
- const pending = deferred<unknown>();
126
- state.prepare.mockReturnValueOnce(pending.promise);
127
- state.result = { agents: [gemini] };
128
- const onPrepared = vi.fn();
129
- await using screen = await render(step({ onPrepared }));
130
-
131
- await page.getByRole("button", { name: "Add Gemini CLI" }).click();
132
- await screen.unmount();
133
- await act(async () =>
134
- pending.resolve({
135
- _tag: "Success",
136
- value: { agentId: "gemini", version: "1.2.3", distribution: "npx", prepared: true },
137
- }),
138
- );
139
-
140
- expect(onPrepared).not.toHaveBeenCalled();
141
-});
apps/web/src/components/settings/AcpRegistrySearchStep.tsx
+85
-81
@@ -11,8 +11,9 @@ import type {
11
ProviderInstanceConfig,
12
} from "@t3tools/contracts";
13
import { ExternalLinkIcon, SearchIcon } from "lucide-react";
14
-import { type FormEvent, useEffect, useLayoutEffect, useRef, useState } from "react";
14
+import { type FormEvent, useState } from "react";
15
16
+import { useDeadlinePassed } from "../../hooks/useDeadline";
17
import { serverEnvironment } from "../../state/server";
18
import { useEnvironmentQuery } from "../../state/query";
19
import { useAtomCommand } from "../../state/use-atom-command";
@@ -31,15 +32,7 @@ function errorMessage(error: unknown): string {
32
: "The ACP could not be prepared.";
33
}
34
34
-interface AcpRegistrySearchStepProps {
35
- readonly environmentId: EnvironmentId;
36
- readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
37
- readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
38
- readonly onManualConfiguration: () => void;
39
- readonly onLocalConfiguration?: () => void;
40
- readonly onLoadingChange?: (loading: boolean) => void;
41
- readonly onPreparingChange?: (preparing: boolean) => void;
42
-}
35
+const ACP_REGISTRY_SEARCH_DEBOUNCE_MS = 300;
36
37
function applyAcpRegistryPrepareResult(
38
agent: AcpRegistrySearchAgent,
@@ -53,77 +46,102 @@ function applyAcpRegistryPrepareResult(
46
};
47
}
48
56
-export function AcpRegistrySearchStep({
57
- environmentId,
58
- providerInstances,
59
- onPrepared,
60
- onManualConfiguration,
61
- onLocalConfiguration,
62
- onLoadingChange,
63
- onPreparingChange,
64
-}: AcpRegistrySearchStepProps) {
65
- const [query, setQuery] = useState("");
66
- const [submittedQuery, setSubmittedQuery] = useState("");
67
- const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
49
+/**
50
+ * Registry search and agent preparation. Owned by the dialog, which needs the
51
+ * loading and preparing state for its layout and navigation, and rendered by
52
+ * AcpRegistrySearchStep. Pass `enabled: false` while the step is hidden so the
53
+ * search is not kept subscribed.
54
+ */
55
+export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: boolean) {
56
+ const [input, setInput] = useState<{
57
+ readonly text: string;
58
+ readonly submitted: string;
59
+ readonly typedAt: number | null;
60
+ }>({ text: "", submitted: "", typedAt: null });
61
+ const typingSettled = useDeadlinePassed(
62
+ input.typedAt === null ? null : input.typedAt + ACP_REGISTRY_SEARCH_DEBOUNCE_MS,
63
+ );
64
+ const submittedQuery = typingSettled ? input.text.trim() : input.submitted;
65
const [preparingId, setPreparingId] = useState<string | null>(null);
66
const [prepareError, setPrepareError] = useState<string | null>(null);
70
- const prepareGeneration = useRef(0);
71
- const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
67
const search = useEnvironmentQuery(
73
- serverEnvironment.searchAcpRegistry({
74
- environmentId,
75
- input: submittedQuery
76
- ? { query: submittedQuery }
77
- : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
78
- }),
68
+ enabled
69
+ ? serverEnvironment.searchAcpRegistry({
70
+ environmentId,
71
+ input: submittedQuery
72
+ ? { query: submittedQuery }
73
+ : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
74
+ })
75
+ : null,
76
);
77
const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, {
78
reportFailure: false,
79
});
80
84
- useEffect(
85
- () => () => {
86
- prepareGeneration.current += 1;
87
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
88
- onPreparingChange?.(false);
81
+ return {
82
+ query: input.text,
83
+ search,
84
+ preparingId,
85
+ prepareError,
86
+ type: (text: string) => {
87
+ setPrepareError(null);
88
+ setInput({ text, submitted: submittedQuery, typedAt: Date.now() });
89
+ },
90
+ submit: () => {
91
+ const trimmed = input.text.trim();
92
+ setPrepareError(null);
93
+ setInput({ text: trimmed, submitted: trimmed, typedAt: null });
94
+ if (trimmed === submittedQuery) search.refresh();
95
+ },
96
+ prepare: async (
97
+ agent: AcpRegistrySearchAgent,
98
+ onPrepared: (agent: AcpRegistrySearchAgent) => void,
99
+ ) => {
100
+ if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
101
+ setPrepareError(null);
102
+ setPreparingId(agent.id);
103
+ const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
104
+ setPreparingId(null);
105
+ if (result._tag === "Success") {
106
+ onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
107
+ return;
108
+ }
109
+ if (!isAtomCommandInterrupted(result)) {
110
+ setPrepareError(errorMessage(squashAtomCommandFailure(result)));
111
+ }
112
},
90
- [onPreparingChange],
91
- );
92
-
93
- const submitSearch = (nextQuery: string) => {
94
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
95
- const trimmed = nextQuery.trim();
96
- setQuery(trimmed);
97
- setPrepareError(null);
98
- if (trimmed === submittedQuery) {
99
- search.refresh();
100
- } else {
101
- setSubmittedQuery(trimmed);
102
- }
113
};
114
+}
115
+
116
+export type AcpRegistrySearch = ReturnType<typeof useAcpRegistrySearch>;
117
+
118
+interface AcpRegistrySearchStepProps {
119
+ readonly environmentId: EnvironmentId;
120
+ readonly registry: AcpRegistrySearch;
121
+ readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
122
+ readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
123
+ readonly onManualConfiguration: () => void;
124
+ readonly onLocalConfiguration?: () => void;
125
+}
126
+
127
+export function AcpRegistrySearchStep({
128
+ environmentId,
129
+ registry,
130
+ providerInstances,
131
+ onPrepared,
132
+ onManualConfiguration,
133
+ onLocalConfiguration,
134
+}: AcpRegistrySearchStepProps) {
135
+ const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
136
+ const { query, search, preparingId, prepareError } = registry;
137
138
const handleSearch = (event: FormEvent<HTMLFormElement>) => {
139
event.preventDefault();
107
- submitSearch(query);
140
+ registry.submit();
141
};
142
110
- const handlePrepare = async (agent: AcpRegistrySearchAgent) => {
111
- if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
112
- const generation = ++prepareGeneration.current;
113
- setPrepareError(null);
114
- setPreparingId(agent.id);
115
- onPreparingChange?.(true);
116
- const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
117
- if (prepareGeneration.current !== generation) return;
118
- setPreparingId(null);
119
- onPreparingChange?.(false);
120
- if (result._tag === "Success") {
121
- onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
122
- return;
123
- }
124
- if (!isAtomCommandInterrupted(result)) {
125
- setPrepareError(errorMessage(squashAtomCommandFailure(result)));
126
- }
143
+ const handlePrepare = (agent: AcpRegistrySearchAgent) => {
144
+ void registry.prepare(agent, onPrepared);
145
};
146
147
const results = search.data?.agents ?? null;
@@ -131,11 +149,6 @@ export function AcpRegistrySearchStep({
149
const isRefreshing = search.isPending && results !== null;
150
const resultCount = results?.length ?? 0;
151
134
- useLayoutEffect(() => {
135
- onLoadingChange?.(search.isPending);
136
- return () => onLoadingChange?.(false);
137
- }, [onLoadingChange, search.isPending]);
138
-
152
return (
153
<section className="grid gap-3" aria-labelledby="acp-registry-search-heading">
154
<h3 className="sr-only" id="acp-registry-search-heading">
@@ -150,16 +163,7 @@ export function AcpRegistrySearchStep({
163
<InputGroupInput
164
aria-label="Search ACP Registry"
165
disabled={preparingId !== null}
153
- onChange={(event) => {
154
- const nextQuery = event.currentTarget.value;
155
- setQuery(nextQuery);
156
- setPrepareError(null);
157
- if (searchTimer.current !== null) clearTimeout(searchTimer.current);
158
- searchTimer.current = setTimeout(() => {
159
- searchTimer.current = null;
160
- setSubmittedQuery(nextQuery.trim());
161
- }, 300);
162
- }}
166
+ onChange={(event) => registry.type(event.currentTarget.value)}
167
placeholder="Search agents…"
168
size="sm"
169
type="search"
apps/web/src/components/settings/AddProviderInstanceDialog.tsx
+10
-6
@@ -47,7 +47,7 @@ import {
47
type WizardNavigation,
48
} from "./AddProviderInstanceDialog.logic";
49
import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";
50
-import { AcpRegistrySearchStep } from "./AcpRegistrySearchStep";
50
+import { AcpRegistrySearchStep, useAcpRegistrySearch } from "./AcpRegistrySearchStep";
51
import { ProviderWizardAuthenticationStep } from "./ProviderWizardAuthenticationStep";
52
import { resolveOfficialAcpRegistryIconUrl } from "./AcpRegistryIcon";
53
import { AddManagedCodexAccountDialog } from "./CodexSetupSection";
@@ -113,8 +113,6 @@ export function AddProviderInstanceDialog({
113
ReadonlyArray<ProviderInstanceEnvironmentVariable>
114
>([]);
115
const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false);
116
- const [isRegistryLoading, setIsRegistryLoading] = useState(false);
117
- const [isPreparingRegistryAgent, setIsPreparingRegistryAgent] = useState(false);
116
const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
117
const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
118
const [isSaving, setIsSaving] = useState(false);
@@ -130,6 +128,13 @@ export function AddProviderInstanceDialog({
128
129
const driverOption = providerClients.get(driver) ?? DEFAULT_DRIVER_OPTION;
130
const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND;
131
+ const showRegistrySearch =
132
+ !createdInstanceId &&
133
+ !addingChatGptAccount &&
134
+ wizardStep === 0 &&
135
+ !(isAcpRegistry && isManualAcpConfiguration);
136
+ const registry = useAcpRegistrySearch(environmentId, showRegistrySearch);
137
+ const isPreparingRegistryAgent = registry.preparingId !== null;
138
const defaultIdentity: ProviderIdentityDraft = {
139
label: driverOption.label,
140
accentColor: "",
@@ -388,7 +393,7 @@ export function AddProviderInstanceDialog({
393
<>
394
<WizardPanel
395
className={cn(isAcpRegistry && wizardStep === identityStep && "min-h-72")}
391
- holdHeight={wizardStep === 0 && !isManualAcpConfiguration && isRegistryLoading}
396
+ holdHeight={showRegistrySearch && registry.search.isPending}
397
>
398
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
399
<div id="add-instance-driver-label" className="text-sm font-medium text-foreground">
@@ -493,12 +498,11 @@ export function AddProviderInstanceDialog({
498
<>
499
<AcpRegistrySearchStep
500
environmentId={environmentId}
501
+ registry={registry}
502
providerInstances={settings.providerInstances}
503
onPrepared={handleAcpPrepared}
504
onManualConfiguration={handleManualAcpConfiguration}
505
onLocalConfiguration={handleLocalAcpConfiguration}
500
- onLoadingChange={setIsRegistryLoading}
501
- onPreparingChange={setIsPreparingRegistryAgent}
506
/>
507
{isAcpRegistry && hasAttemptedSubmit && acpSelectionError ? (
508
<p className="mt-2 text-2xs text-destructive">{acpSelectionError}</p>
apps/web/src/components/settings/CliCommandSettingsRow.tsx
+12
-20
@@ -1,35 +1,27 @@
1
-import type { DesktopCliCommandState } from "@t3tools/contracts";
2
-import { useEffect, useState } from "react";
1
+import { useState } from "react";
2
3
+import {
4
+ desktopCliCommandStateAtom,
5
+ getDesktopCliCommandBridge,
6
+ refreshDesktopCliCommandState,
7
+} from "~/state/desktopCliCommand";
8
+import { useEnvironmentQuery } from "~/state/query";
9
import { Button } from "../ui/button";
10
import { stackedThreadToast, toastManager } from "../ui/toast";
11
import { SettingsRow } from "./settingsLayout";
12
import { searchableSetting } from "./settingsSearch";
13
14
export function CliCommandSettingsRow() {
10
- const bridge = typeof window === "undefined" ? undefined : window.desktopBridge?.cliCommand;
11
- const [state, setState] = useState<DesktopCliCommandState | null>(null);
15
+ const bridge = getDesktopCliCommandBridge();
16
+ const query = useEnvironmentQuery(bridge ? desktopCliCommandStateAtom : null);
17
+ const state = query.data;
18
const [pending, setPending] = useState(false);
19
14
- useEffect(() => {
15
- if (!bridge) return;
16
- let cancelled = false;
17
- void bridge
18
- .getState()
19
- .then((next) => {
20
- if (!cancelled) setState(next);
21
- })
22
- .catch(() => undefined);
23
- return () => {
24
- cancelled = true;
25
- };
26
- }, [bridge]);
27
-
20
const change = (action: "install" | "uninstall") => {
21
if (!bridge || pending) return;
22
setPending(true);
23
void bridge[action]()
32
- .then(setState)
24
+ .then(refreshDesktopCliCommandState)
25
.catch((error: unknown) => {
26
toastManager.add(
27
stackedThreadToast({
@@ -60,7 +52,7 @@ export function CliCommandSettingsRow() {
52
<Button
53
size="sm"
54
variant="outline"
63
- disabled={pending}
55
+ disabled={pending || query.isPending}
56
onClick={() => change(installed ? "uninstall" : "install")}
57
>
58
{installed ? "Remove" : "Install"}
apps/web/src/components/settings/CodexSetupSection.logic.test.ts
new
+121
@@ -0,0 +1,121 @@
1
+import type { ProviderAuthState, ProviderInstallState } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import {
5
+ settleAuthorizationPage,
6
+ settleHandoffAuthorizationPage,
7
+ settleProviderInstall,
8
+} from "./CodexSetupSection.logic";
9
+
10
+const install = (overrides: Partial<ProviderInstallState>) =>
11
+ ({
12
+ driver: "codex",
13
+ operationId: "op-1",
14
+ phase: "downloading",
15
+ downloadedBytes: 0,
16
+ totalBytes: null,
17
+ version: "0.2.0",
18
+ installedVersion: "0.1.0",
19
+ canRemove: true,
20
+ message: null,
21
+ ...overrides,
22
+ }) as ProviderInstallState;
23
+
24
+const auth = (overrides: Partial<ProviderAuthState>) =>
25
+ ({
26
+ instanceId: "codex",
27
+ phase: "starting",
28
+ flowId: "flow-1",
29
+ authorizationUrl: null,
30
+ expiresAt: null,
31
+ message: null,
32
+ ...overrides,
33
+ }) as ProviderAuthState;
34
+
35
+describe("settleProviderInstall", () => {
36
+ it("ignores the previous runtime while the update it started has not been pushed yet", () => {
37
+ const started = install({ operationId: "op-2", phase: "downloading" });
38
+ const previous = install({ operationId: "op-1", phase: "succeeded" });
39
+ expect(settleProviderInstall(started, previous)).toBeUndefined();
40
+ expect(settleProviderInstall(started, null)).toBeUndefined();
41
+ expect(settleProviderInstall(started, { ...started, phase: "extracting" })).toBeUndefined();
42
+ });
43
+
44
+ it("settles on the started operation's terminal phase", () => {
45
+ const started = install({ operationId: "op-2" });
46
+ expect(
47
+ settleProviderInstall(
48
+ started,
49
+ install({ operationId: "op-2", phase: "succeeded", installedVersion: "0.2.0" }),
50
+ ),
51
+ ).toBe(true);
52
+ expect(settleProviderInstall(started, install({ operationId: "op-2", phase: "failed" }))).toBe(
53
+ false,
54
+ );
55
+ expect(
56
+ settleProviderInstall(started, install({ operationId: "op-2", phase: "cancelled" })),
57
+ ).toBe(false);
58
+ });
59
+
60
+ it("settles immediately when start reused an existing runtime", () => {
61
+ expect(settleProviderInstall(install({ operationId: null, phase: "succeeded" }), null)).toBe(
62
+ true,
63
+ );
64
+ expect(
65
+ settleProviderInstall(
66
+ install({ operationId: null, phase: "idle", installedVersion: null }),
67
+ null,
68
+ ),
69
+ ).toBe(false);
70
+ });
71
+});
72
+
73
+describe("settleAuthorizationPage", () => {
74
+ it("waits for its own flow to reach the browser step", () => {
75
+ expect(settleAuthorizationPage(null, "flow-1")).toBeUndefined();
76
+ expect(settleAuthorizationPage(auth({ phase: "starting" }), "flow-1")).toBeUndefined();
77
+ expect(
78
+ settleAuthorizationPage(auth({ phase: "waiting", authorizationUrl: "https://a" }), "flow-1"),
79
+ ).toBe("https://a");
80
+ expect(
81
+ settleAuthorizationPage(
82
+ auth({
83
+ phase: "waiting",
84
+ authorizationUrl: "https://a",
85
+ interaction: {
86
+ type: "browser",
87
+ id: "interaction-1",
88
+ url: "https://b",
89
+ requiresConsent: false,
90
+ } as ProviderAuthState["interaction"],
91
+ }),
92
+ "flow-1",
93
+ ),
94
+ ).toBe("https://b");
95
+ });
96
+
97
+ it("ignores a flow another client started", () => {
98
+ expect(
99
+ settleAuthorizationPage(
100
+ auth({ flowId: "flow-2", phase: "waiting", authorizationUrl: "https://a" }),
101
+ "flow-1",
102
+ ),
103
+ ).toBeUndefined();
104
+ });
105
+
106
+ it("gives up when its flow ends before a page is available", () => {
107
+ expect(settleAuthorizationPage(auth({ phase: "failed" }), "flow-1")).toBeNull();
108
+ expect(settleAuthorizationPage(auth({ phase: "cancelled" }), "flow-1")).toBeNull();
109
+ expect(settleAuthorizationPage(auth({ phase: "succeeded" }), "flow-1")).toBeNull();
110
+ });
111
+
112
+ it("follows a handoff until the primary environment finishes", () => {
113
+ expect(
114
+ settleHandoffAuthorizationPage({
115
+ phase: "auth",
116
+ state: auth({ flowId: "primary-flow", phase: "waiting", authorizationUrl: "https://a" }),
117
+ }),
118
+ ).toBe("https://a");
119
+ expect(settleHandoffAuthorizationPage({ phase: "finished", profile: {} as never })).toBeNull();
120
+ });
121
+});
apps/web/src/components/settings/CodexSetupSection.logic.ts
+53
@@ -1,3 +1,9 @@
1
+import type {
2
+ ChatGptHandoffState,
3
+ ProviderAuthState,
4
+ ProviderInstallState,
5
+} from "@t3tools/contracts";
6
+
7
export function readCodexSetupMode(config: unknown): "managed" | "existing" {
8
return config !== null &&
9
typeof config === "object" &&
@@ -6,3 +12,50 @@ export function readCodexSetupMode(config: unknown): "managed" | "existing" {
12
? "managed"
13
: "existing";
14
}
15
+
16
+const RUNNING_INSTALL_PHASES = new Set(["downloading", "extracting", "verifying"]);
17
+
18
+/**
19
+ * Whether the `started` install left a usable runtime; `undefined` until settled.
20
+ * The subscription can still carry the previous operation's state when start
21
+ * returns, so only a state with the same operation id settles a running install.
22
+ */
23
+export function settleProviderInstall(
24
+ started: ProviderInstallState,
25
+ current: ProviderInstallState | null,
26
+): boolean | undefined {
27
+ const state = RUNNING_INSTALL_PHASES.has(started.phase)
28
+ ? current?.operationId === started.operationId
29
+ ? current
30
+ : null
31
+ : started;
32
+ if (state === null || RUNNING_INSTALL_PHASES.has(state.phase)) return undefined;
33
+ return state.phase !== "failed" && state.phase !== "cancelled" && state.installedVersion !== null;
34
+}
35
+
36
+/**
37
+ * The authorization page for a sign-in flow: a URL once the flow waits on the
38
+ * browser, `null` once it ends without one, `undefined` while it is still
39
+ * starting. A `flowId` limits this to one flow, because auth state is shared
40
+ * per instance and another client can start a flow of its own.
41
+ */
42
+export function settleAuthorizationPage(
43
+ state: ProviderAuthState | null,
44
+ flowId: string | null,
45
+): string | null | undefined {
46
+ if (state === null || state.flowId === null) return undefined;
47
+ if (flowId !== null && state.flowId !== flowId) return undefined;
48
+ if (state.phase === "succeeded" || state.phase === "failed" || state.phase === "cancelled")
49
+ return null;
50
+ if (state.phase !== "waiting") return undefined;
51
+ const url =
52
+ state.interaction?.type === "browser" ? state.interaction.url : state.authorizationUrl;
53
+ return url ?? undefined;
54
+}
55
+
56
+export function settleHandoffAuthorizationPage(
57
+ state: ChatGptHandoffState | null,
58
+): string | null | undefined {
59
+ if (state === null) return undefined;
60
+ return state.phase === "finished" ? null : settleAuthorizationPage(state.state, null);
61
+}
apps/web/src/components/settings/CodexSetupSection.tsx
+158
-116
@@ -1,5 +1,5 @@
1
import { AuthProvidersManageScope } from "@t3tools/contracts";
2
-import { useEnvironmentScope } from "../../state/session";
2
+import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
3
import {
4
isAtomCommandInterrupted,
5
squashAtomCommandFailure,
@@ -27,14 +27,14 @@ import {
27
} from "react";
28
29
import { ensureLocalApi } from "../../localApi";
30
-import {
31
- useEnvironmentHttpBaseUrl,
32
- usePrimaryEnvironmentId,
33
- useEnvironment,
34
-} from "../../state/environments";
30
+import { useEnvironmentHttpBaseUrl } from "../../state/environments";
31
+import { environmentPresentations } from "../../state/presentation";
32
+import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment";
33
import { useEnvironmentQuery } from "../../state/query";
34
import { serverEnvironment } from "../../state/server";
35
import { useAtomCommand } from "../../state/use-atom-command";
36
+import { appAtomRegistry } from "../../rpc/atomRegistry";
37
+import { waitForQuerySettled } from "../../state/waitForQuerySettled";
38
import { Button } from "../ui/button";
39
import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
40
import { ChatGptUsageButton } from "./ChatGptUsageButton";
@@ -46,9 +46,46 @@ import { SettingsRow } from "./settingsLayout";
46
import { AddCodexAccountDialog } from "./AddCodexAccountDialog";
47
import { getOnboardingProviderState } from "../../onboarding/providerReadiness.logic";
48
import { getProviderSummary } from "./providerStatus";
49
+import {
50
+ settleAuthorizationPage,
51
+ settleHandoffAuthorizationPage,
52
+ settleProviderInstall,
53
+} from "./CodexSetupSection.logic";
54
55
const noop = () => undefined;
56
57
+const isLoopbackUrl = (url: string | null) => url !== null && isLoopbackHost(new URL(url).hostname);
58
+
59
+// A loopback server can receive the provider's callback itself, unless the
60
+// desktop shell offers to catch it on the client.
61
+const prefersClientCallback = (local: boolean) =>
62
+ !local || window.desktopBridge?.receiveProviderAuthCallback !== undefined;
63
+
64
+/**
65
+ * How a sign-in started now reaches the provider. Read at use time, because a
66
+ * sign-in can start minutes after the click that asked for it (once an install
67
+ * finishes), and the primary environment may have connected in between.
68
+ */
69
+function readSignInRouting(environmentId: EnvironmentId) {
70
+ const local = isLoopbackUrl(readPreparedConnection(environmentId)?.httpBaseUrl ?? null);
71
+ const clientCallback = prefersClientCallback(local);
72
+ const primaryEnvironmentId = appAtomRegistry.get(primaryEnvironmentIdAtom);
73
+ const primaryAuthEnvironmentId =
74
+ !local &&
75
+ primaryEnvironmentId !== null &&
76
+ appAtomRegistry.get(environmentPresentations.presentationAtom(primaryEnvironmentId))?.connection
77
+ .phase === "connected" &&
78
+ isLoopbackUrl(readPreparedConnection(primaryEnvironmentId)?.httpBaseUrl ?? null) &&
79
+ (window.desktopBridge !== undefined || isLoopbackHost(window.location.hostname))
80
+ ? primaryEnvironmentId
81
+ : null;
82
+ return {
83
+ clientCallback,
84
+ remoteWeb: clientCallback && !window.desktopBridge?.receiveProviderAuthCallback,
85
+ primaryAuthEnvironmentId,
86
+ };
87
+}
88
+
89
interface CodexSetupSectionProps {
90
readonly environmentId: EnvironmentId;
91
readonly instanceId: ProviderInstanceId;
@@ -240,7 +277,7 @@ function ManagedCodexSetup({
277
const url = auth?.interaction?.type === "browser" ? auth.interaction.url : auth?.authorizationUrl;
278
const installation = installQuery.data;
279
const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
243
- const local = httpBaseUrl !== null && isLoopbackHost(new URL(httpBaseUrl).hostname);
280
+ const local = isLoopbackUrl(httpBaseUrl);
281
const options = { reportFailure: false, reportDefect: false };
282
const startAuth = useAtomCommand(serverEnvironment.startProviderAuth, options);
283
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, options);
@@ -251,21 +288,8 @@ function ManagedCodexSetup({
288
const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, options);
289
const reconnectProfile = useAtomCommand(serverEnvironment.chatGptReconnectProfile, options);
290
const importProfile = useAtomCommand(serverEnvironment.chatGptImportProfile, options);
254
- const clientCallback =
255
- !handoff && (!local || window.desktopBridge?.receiveProviderAuthCallback !== undefined);
291
+ const clientCallback = !handoff && prefersClientCallback(local);
292
const remoteWeb = clientCallback && !window.desktopBridge?.receiveProviderAuthCallback;
257
- const primaryEnvironmentId = usePrimaryEnvironmentId();
258
- const primaryEnvironment = useEnvironment(primaryEnvironmentId);
259
- const primaryHttpBaseUrl = useEnvironmentHttpBaseUrl(primaryEnvironmentId);
260
- const primaryAuthEnvironmentId =
261
- !local &&
262
- primaryEnvironmentId &&
263
- primaryEnvironment?.connection.phase === "connected" &&
264
- primaryHttpBaseUrl &&
265
- isLoopbackHost(new URL(primaryHttpBaseUrl).hostname) &&
266
- (window.desktopBridge !== undefined || isLoopbackHost(window.location.hostname))
267
- ? primaryEnvironmentId
268
- : null;
293
const returnUrl = new URL(window.location.href);
294
if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
295
if (returnUrl.pathname === "/settings/providers")
@@ -279,9 +303,19 @@ function ManagedCodexSetup({
303
const [awaitingProvider, setAwaitingProvider] = useState<"sign-in" | "handoff" | null>(null);
304
const pendingRef = useRef(false);
305
const [error, setError] = useState<string | null>(null);
282
- const continueWithSignIn = useRef<string | null>(null);
283
- const openRequested = useRef(false);
284
- const openedFlow = useRef<string | null>(null);
306
+ // The setup or sign-in this client started. Its follow-up steps (sign in
307
+ // once the install lands, open the page once the flow waits) belong to it
308
+ // alone, so Cancel, a new attempt, or unmounting abort them.
309
+ const operation = useRef<AbortController | null>(null);
310
+ const beginOperation = () => {
311
+ operation.current?.abort();
312
+ const controller = new AbortController();
313
+ operation.current = controller;
314
+ return controller.signal;
315
+ };
316
+ const abortOperation = () => operation.current?.abort();
317
+ // Once the card unmounts, nothing may start a sign-in or open a page on its behalf.
318
+ useEffect(() => () => operation.current?.abort(), []);
319
const [autoStartHandled, setAutoStartHandled] = useState(false);
320
const installed = installation?.installedVersion != null;
321
const authenticated = provider?.auth.status === "authenticated";
@@ -300,6 +334,8 @@ function ManagedCodexSetup({
334
) {
335
setAwaitingProvider(null);
336
}
337
+ // The server does not refresh the provider snapshot when a sign-in flow
338
+ // succeeds, and the flow can finish elsewhere (callback, pasted redirect URL).
339
useEffect(() => {
340
if (awaitingProvider && auth?.phase === "succeeded") {
341
void refreshProviders({ environmentId, input: { instanceId } });
@@ -398,21 +434,52 @@ function ManagedCodexSetup({
434
return run(() => cancelAuth({ environmentId, input: { instanceId, flowId: auth!.flowId! } }));
435
};
436
401
- const signIn = async (methodId = "chatgpt") => {
437
+ const receivingCallback = useRef<string | null>(null);
438
+ const openPage = async (
439
+ authorizationUrl: string,
440
+ flowId: string | null,
441
+ viaClientCallback: boolean,
442
+ ) => {
443
+ try {
444
+ const receive = window.desktopBridge?.receiveProviderAuthCallback;
445
+ if (receive && viaClientCallback && flowId) {
446
+ if (receivingCallback.current === authorizationUrl) {
447
+ await ensureLocalApi().shell.openExternal(authorizationUrl);
448
+ return;
449
+ }
450
+ receivingCallback.current = authorizationUrl;
451
+ const callbackUrl = await receive(authorizationUrl);
452
+ if (receivingCallback.current !== authorizationUrl) return;
453
+ receivingCallback.current = null;
454
+ await run(() =>
455
+ completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
456
+ );
457
+ } else {
458
+ await ensureLocalApi().shell.openExternal(authorizationUrl);
459
+ }
460
+ } catch {
461
+ setError(
462
+ "Could not finish sign-in on this computer. Try again or paste the redirect URL below.",
463
+ );
464
+ }
465
+ };
466
+
467
+ const signIn = async (methodId: string, signal: AbortSignal) => {
468
if (pendingRef.current) return;
403
- openRequested.current = true;
469
setTransferFailed(false);
470
setRequestedMethodId(methodId);
471
const returnUrl = new URL(window.location.href);
472
if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
473
if (returnUrl.pathname === "/settings/providers")
474
returnUrl.searchParams.set("instanceId", instanceId);
475
+ const { clientCallback, remoteWeb, primaryAuthEnvironmentId } =
476
+ readSignInRouting(environmentId);
477
if (primaryAuthEnvironmentId) {
478
const attemptId = `${handoffId}:${++handoffSequence.current}`;
412
- const succeeded = await run(
479
+ await run(
480
() => reconnectProfile({ environmentId, input: { instanceId, methodId } }),
414
- (profile) =>
415
- setHandoff({
481
+ (profile) => {
482
+ const nextHandoff = {
483
environmentId: primaryAuthEnvironmentId,
484
input: {
485
instanceId,
@@ -421,40 +488,73 @@ function ManagedCodexSetup({
488
returnUrl: returnUrl.toString(),
489
profile,
490
},
424
- }),
491
+ };
492
+ setHandoff(nextHandoff);
493
+ void waitForQuerySettled({
494
+ registry: appAtomRegistry,
495
+ atom: serverEnvironment.chatGptHandoffState(nextHandoff),
496
+ settle: settleHandoffAuthorizationPage,
497
+ signal,
498
+ }).then((page) => {
499
+ if (page && !signal.aborted) void openPage(page, null, false);
500
+ });
501
+ },
502
);
426
- if (!succeeded) openRequested.current = false;
503
return;
504
}
429
- if (
430
- !(await run(
431
- () =>
432
- startAuth({
433
- environmentId,
434
- input: {
435
- instanceId,
436
- methodId,
437
- returnUrl: returnUrl.toString(),
438
- callbackMode: clientCallback ? "client" : "server",
439
- },
440
- }),
441
- () => setAwaitingProvider("sign-in"),
442
- ))
443
- ) {
444
- openRequested.current = false;
445
- }
505
+ await run(
506
+ () =>
507
+ startAuth({
508
+ environmentId,
509
+ input: {
510
+ instanceId,
511
+ methodId,
512
+ returnUrl: returnUrl.toString(),
513
+ callbackMode: clientCallback ? "client" : "server",
514
+ },
515
+ }),
516
+ (started) => {
517
+ setAwaitingProvider("sign-in");
518
+ const startedFlowId = started.flowId;
519
+ // A remote browser cannot receive the callback, so the user opens the page from the card.
520
+ if (remoteWeb || startedFlowId === null) return;
521
+ const startedPage = settleAuthorizationPage(started, startedFlowId);
522
+ void (
523
+ startedPage !== undefined
524
+ ? Promise.resolve(startedPage)
525
+ : waitForQuerySettled({
526
+ registry: appAtomRegistry,
527
+ atom: serverEnvironment.providerAuthState(target),
528
+ settle: (state) => settleAuthorizationPage(state, startedFlowId),
529
+ signal,
530
+ })
531
+ ).then((page) => {
532
+ if (page && !signal.aborted) void openPage(page, startedFlowId, clientCallback);
533
+ });
534
+ },
535
+ );
536
};
537
538
const setup = async (methodId = "chatgpt") => {
539
if (unavailable || busy) return;
540
+ const signal = beginOperation();
541
if (installed && !updateAvailable) {
451
- await signIn(methodId);
452
- } else {
453
- continueWithSignIn.current = methodId;
454
- if (!(await run(() => startInstall({ environmentId, input: { instanceId } })))) {
455
- continueWithSignIn.current = null;
456
- }
542
+ await signIn(methodId, signal);
543
+ return;
544
}
545
+ await run(
546
+ () => startInstall({ environmentId, input: { instanceId } }),
547
+ (started) => {
548
+ void waitForQuerySettled({
549
+ registry: appAtomRegistry,
550
+ atom: serverEnvironment.providerInstallState(target),
551
+ settle: (current) => settleProviderInstall(started, current),
552
+ signal,
553
+ }).then((ready) => {
554
+ if (ready && !signal.aborted) void signIn(methodId, signal);
555
+ });
556
+ },
557
+ );
558
};
559
560
if (
@@ -476,48 +576,6 @@ function ManagedCodexSetup({
576
if (autoStartHandled) startAutomatically();
577
}, [autoStartHandled]);
578
479
- const signInAfterInstall = useEffectEvent((methodId: string) => signIn(methodId));
480
- useEffect(() => {
481
- if (!continueWithSignIn.current || pending || installActive) return;
482
- if (installation?.phase === "failed" || installation?.phase === "cancelled") {
483
- continueWithSignIn.current = null;
484
- } else if (installed) {
485
- const methodId = continueWithSignIn.current;
486
- continueWithSignIn.current = null;
487
- void signInAfterInstall(methodId);
488
- }
489
- }, [pending, installActive, installation?.phase, installed]);
490
-
491
- const receivingCallback = useRef<string | null>(null);
492
- const flowId = auth?.flowId;
493
- const openPage = async (authorizationUrl: string) => {
494
- try {
495
- const receive = window.desktopBridge?.receiveProviderAuthCallback;
496
- if (receive && clientCallback && flowId) {
497
- if (receivingCallback.current === authorizationUrl) {
498
- await ensureLocalApi().shell.openExternal(authorizationUrl);
499
- return;
500
- }
501
- receivingCallback.current = authorizationUrl;
502
- const callbackUrl = await receive(authorizationUrl);
503
- if (receivingCallback.current !== authorizationUrl) return;
504
- receivingCallback.current = null;
505
- await run(() =>
506
- completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
507
- );
508
- } else {
509
- await ensureLocalApi().shell.openExternal(authorizationUrl);
510
- }
511
- } catch {
512
- setError(
513
- "Could not finish sign-in on this computer. Try again or paste the redirect URL below.",
514
- );
515
- }
516
- };
517
- const openPageForFlow = useEffectEvent((authorizationUrl: string) => {
518
- void openPage(authorizationUrl);
519
- });
520
-
579
useEffect(() => {
580
if (!clientCallback || !url || !window.desktopBridge?.cancelProviderAuthCallback) return;
581
return () => {
@@ -526,21 +584,6 @@ function ManagedCodexSetup({
584
};
585
}, [clientCallback, url]);
586
529
- useEffect(() => {
530
- if (
531
- !openRequested.current ||
532
- auth?.phase !== "waiting" ||
533
- !auth.flowId ||
534
- !url ||
535
- openedFlow.current === auth.flowId
536
- )
537
- return;
538
- openedFlow.current = auth.flowId;
539
- openRequested.current = false;
540
- // oxlint-disable-next-line react/set-state-in-effect -- Opening the page may complete the flow through a server command, which marks itself pending.
541
- if (!remoteWeb) openPageForFlow(url);
542
- }, [auth?.phase, auth?.flowId, url, remoteWeb]);
543
-
587
const runtimeDescription =
588
installation?.phase === "downloading"
589
? `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({
649
onClick={() => {
650
if (handoffQuery.data?.phase === "finished")
651
void transferProfile(handoffQuery.data.profile);
609
- else if (url) void openPage(url);
652
+ else if (url) void openPage(url, auth?.flowId ?? null, clientCallback);
653
}}
654
>
655
{finishingSignIn
@@ -815,8 +858,7 @@ function ManagedCodexSetup({
858
variant="ghost-muted"
859
disabled={pending || readOnly}
860
onClick={() => {
818
- openRequested.current = false;
819
- continueWithSignIn.current = null;
861
+ abortOperation();
862
if (handoff || (authActive && auth?.flowId)) void cancelSignIn();
863
else if (installation?.operationId)
864
void run(() =>
@@ -879,7 +921,7 @@ function ManagedCodexSetup({
921
disabled={pending || readOnly}
922
onClick={() => {
923
if (!handoff && !auth?.flowId) return;
882
- openRequested.current = false;
924
+ abortOperation();
925
void cancelSignIn();
926
onSignInCancelled?.();
927
}}
@@ -895,7 +937,7 @@ function ManagedCodexSetup({
937
disabled={pending || readOnly}
938
onClick={() => {
939
if (!installation?.operationId) return;
898
- continueWithSignIn.current = null;
940
+ abortOperation();
941
void run(() =>
942
cancelInstall({
943
environmentId,
apps/web/src/components/settings/ProviderAccentColorPicker.tsx
+82
-82
@@ -1,5 +1,5 @@
1
import { PlusIcon, XIcon } from "lucide-react";
2
-import { useEffect, useRef, useState } from "react";
2
+import { useRef, useState, type PointerEvent } from "react";
3
4
import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";
5
import { ColorHueSlider, ColorSaturationValuePlane } from "../ui/color-picker";
@@ -12,32 +12,58 @@ const FALLBACK_ACCENT_COLOR = "#2563eb";
12
13
function ProviderCustomColorPanel(props: {
14
readonly value: string;
15
+ readonly onPreview: (value: string) => void;
16
readonly onCommit: (value: string) => void;
17
}) {
17
- const { onCommit } = props;
18
+ const { onCommit, onPreview } = props;
19
const [hsv, setHsv] = useState(() => hexToHsv(props.value));
20
const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v);
21
const [hexDraft, setHexDraft] = useState<string | null>(null);
22
+ // Pointer drags only preview and commit once on release, so a drag writes
23
+ // settings once instead of on every pointer move. Keyboard steps commit
24
+ // immediately because they have no release to wait for. Holds the latest
25
+ // dragged color, or null when no drag is in progress.
26
+ const drag = useRef<string | null>(null);
27
+ const startDrag = (event: PointerEvent<HTMLDivElement>) => {
28
+ if (event.button === 0) drag.current = currentColor;
29
+ };
30
22
- const commitHsv = (nextHsv: HsvColor) => {
31
+ const changeHsv = (nextHsv: HsvColor) => {
32
setHsv(nextHsv);
24
- onCommit(hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v));
33
+ const color = hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
34
+ if (drag.current === null) {
35
+ onCommit(color);
36
+ return;
37
+ }
38
+ drag.current = color;
39
+ onPreview(color);
40
+ };
41
+ const endDrag = () => {
42
+ const color = drag.current;
43
+ drag.current = null;
44
+ if (color !== null) onCommit(color);
45
};
46
47
return (
48
<div className="w-56 bg-popover">
29
- <ColorSaturationValuePlane
30
- label="Accent color"
31
- value={hsv}
32
- onChange={commitHsv}
33
- variant="edge"
34
- />
35
- <div className="grid gap-3 p-3">
36
- <ColorHueSlider
37
- label="Accent color hue"
38
- value={hsv.h}
39
- onChange={(h) => commitHsv({ ...hsv, h })}
49
+ <div onPointerDownCapture={startDrag}>
50
+ <ColorSaturationValuePlane
51
+ label="Accent color"
52
+ value={hsv}
53
+ onChange={changeHsv}
54
+ onInteractionEnd={endDrag}
55
+ variant="edge"
56
/>
57
+ </div>
58
+ <div className="grid gap-3 p-3">
59
+ <div onPointerDownCapture={startDrag}>
60
+ <ColorHueSlider
61
+ label="Accent color hue"
62
+ value={hsv.h}
63
+ onChange={(h) => changeHsv({ ...hsv, h })}
64
+ onInteractionEnd={endDrag}
65
+ />
66
+ </div>
67
<Input
68
nativeInput
69
size="compact"
@@ -47,7 +73,7 @@ function ProviderCustomColorPanel(props: {
73
setHexDraft(nextColor);
74
if (!/^#[\da-f]{6}$/i.test(nextColor)) return;
75
setHsv(hexToHsv(nextColor));
50
- props.onCommit(nextColor);
76
+ onCommit(nextColor);
77
}}
78
onBlur={() => setHexDraft(null)}
79
font="mono"
@@ -62,13 +88,19 @@ function ProviderCustomColorPanel(props: {
88
function ProviderCustomColorPicker(props: {
89
readonly displayName: string;
90
readonly value: string | undefined;
91
+ readonly onPreview: (value: string) => void;
92
readonly onCommit: (value: string) => void;
93
readonly onClear: () => void;
94
+ readonly onClose: () => void;
95
}) {
96
const normalized = normalizeProviderAccentColor(props.value);
97
98
return (
71
- <Popover>
99
+ <Popover
100
+ onOpenChange={(open) => {
101
+ if (!open) props.onClose();
102
+ }}
103
+ >
104
<PopoverTrigger
105
render={
106
<Button
@@ -89,6 +121,7 @@ function ProviderCustomColorPicker(props: {
121
<PopoverPopup side="bottom" align="start" sideOffset={6} padding="none">
122
<ProviderCustomColorPanel
123
value={normalized ?? FALLBACK_ACCENT_COLOR}
124
+ onPreview={props.onPreview}
125
onCommit={props.onCommit}
126
/>
127
{normalized ? (
@@ -119,78 +152,45 @@ export function ProviderAccentColorPicker(props: {
152
readonly value: string | undefined;
153
readonly onCommit: (value: string) => void;
154
readonly description?: string;
122
- readonly commitDelayMs?: number;
155
readonly layout?: "stacked" | "inline";
156
}) {
125
- const {
126
- commitDelayMs = 0,
127
- description,
128
- displayName,
129
- layout = "stacked",
130
- onCommit,
131
- value,
132
- } = props;
133
- const [optimisticValue, setOptimisticValue] = useState(() => value ?? "");
134
- const commitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
135
- const pendingCommitRef = useRef<string | null>(null);
136
- const onCommitRef = useRef(onCommit);
137
-
138
- useEffect(() => {
139
- onCommitRef.current = onCommit;
140
- }, [onCommit]);
141
-
142
- useEffect(() => {
143
- if (pendingCommitRef.current !== null) return;
144
- setOptimisticValue(value ?? "");
145
- }, [value]);
146
-
147
- useEffect(() => {
148
- return () => {
149
- if (commitTimeoutRef.current !== null) {
150
- clearTimeout(commitTimeoutRef.current);
151
- }
152
- const pendingCommit = pendingCommitRef.current;
153
- if (pendingCommit !== null) {
154
- onCommitRef.current(pendingCommit);
155
- }
156
- };
157
- }, []);
158
-
159
- const commitAccentColor = (value: string) => {
160
- const normalizedValue = normalizeProviderAccentColor(value) ?? "";
161
- setOptimisticValue(normalizedValue);
162
-
163
- if (commitDelayMs <= 0) {
164
- pendingCommitRef.current = null;
165
- if (commitTimeoutRef.current !== null) {
166
- clearTimeout(commitTimeoutRef.current);
167
- commitTimeoutRef.current = null;
168
- }
169
- onCommit(normalizedValue);
170
- return;
171
- }
172
-
173
- pendingCommitRef.current = normalizedValue;
174
- if (commitTimeoutRef.current !== null) {
175
- clearTimeout(commitTimeoutRef.current);
176
- }
177
- commitTimeoutRef.current = setTimeout(() => {
178
- commitTimeoutRef.current = null;
179
- const pendingCommit = pendingCommitRef.current;
180
- pendingCommitRef.current = null;
181
- if (pendingCommit !== null) {
182
- onCommitRef.current(pendingCommit);
183
- }
184
- }, commitDelayMs);
157
+ const { description, displayName, layout = "stacked", onCommit } = props;
158
+ const value = props.value ?? "";
159
+ // The draft shows a dragged or just-committed color only while `value` is
160
+ // still the one it was picked against, so the persisted value (or any outside
161
+ // change) takes over as soon as it lands. `previewing` marks a drag that has
162
+ // not been committed yet, which closing the popover commits.
163
+ const [draft, setDraft] = useState<{
164
+ readonly color: string;
165
+ readonly base: string;
166
+ readonly previewing: boolean;
167
+ } | null>(null);
168
+ if (draft !== null && draft.base !== value) setDraft(null);
169
+ const shownValue = draft !== null && draft.base === value ? draft.color : value;
170
+ const commit = (color: string) => {
171
+ const normalized = normalizeProviderAccentColor(color) ?? "";
172
+ setDraft({ color: normalized, base: value, previewing: false });
173
+ // Not deduplicated against `value`: it is stale while an earlier commit is
174
+ // in flight, so returning to it must still be submitted.
175
+ onCommit(normalized);
176
};
177
187
- const normalized = normalizeProviderAccentColor(optimisticValue);
178
const picker = (
179
<ProviderCustomColorPicker
180
displayName={displayName}
191
- value={normalized}
192
- onCommit={commitAccentColor}
193
- onClear={() => commitAccentColor("")}
181
+ value={normalizeProviderAccentColor(shownValue)}
182
+ onPreview={(color) =>
183
+ setDraft({
184
+ color: normalizeProviderAccentColor(color) ?? "",
185
+ base: value,
186
+ previewing: true,
187
+ })
188
+ }
189
+ onCommit={commit}
190
+ onClear={() => commit("")}
191
+ onClose={() => {
192
+ if (draft?.previewing && draft.base === value) commit(draft.color);
193
+ }}
194
/>
195
);
196
apps/web/src/components/settings/ProviderInstanceCard.tsx
+23
-26
@@ -15,7 +15,7 @@ import {
15
import { Lock as LockGlyph, LockOpen } from "lucide";
16
import * as Arr from "effect/Array";
17
import * as Result from "effect/Result";
18
-import { useEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
18
+import { useState, type ReactElement, type ReactNode } from "react";
19
import {
20
isProviderDriverKind,
21
resolveProviderInstanceEnabled,
@@ -53,7 +53,12 @@ import type {
53
ProviderClientDefinition,
54
ProviderEnvironmentField,
55
} from "@t3tools/provider-core/client";
56
-import { deriveProviderSettingsFields, ProviderSettingsForm } from "./ProviderSettingsForm";
56
+import {
57
+ deriveProviderSettingsFields,
58
+ ProviderSettingsForm,
59
+ reconcileRowsDraft,
60
+ seedRowsDraft,
61
+} from "./ProviderSettingsForm";
62
import { ProviderModelsSection } from "./ProviderModelsSection";
63
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
64
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
@@ -112,6 +117,9 @@ function makeEnvironmentDraftRow(
117
};
118
}
119
120
+const toEnvironmentDraftRows = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) =>
121
+ environment.map(makeEnvironmentDraftRow);
122
+
123
function providerEnvironmentsEqual(
124
left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
125
right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
@@ -300,29 +308,19 @@ export function ProviderEnvironmentSection(props: {
308
readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
309
readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
310
}) {
303
- const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
304
- props.environment.map(makeEnvironmentDraftRow),
311
+ const [storedDraft, setDraft] = useState(() =>
312
+ seedRowsDraft(props.environment, toEnvironmentDraftRows),
313
);
306
- const previousEnvironmentRef = useRef(props.environment);
307
- const lastPublishedEnvironmentRef = useRef<
308
- ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
309
- >(undefined);
310
-
311
- useEffect(() => {
312
- const previousEnvironment = previousEnvironmentRef.current;
313
- const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
314
- previousEnvironmentRef.current = props.environment;
315
- lastPublishedEnvironmentRef.current = undefined;
316
- if (
317
- previousEnvironment === props.environment ||
318
- providerEnvironmentsEqual(previousEnvironment, props.environment) ||
319
- (lastPublishedEnvironment !== undefined &&
320
- providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
321
- ) {
322
- return;
323
- }
324
- setRows(props.environment.map(makeEnvironmentDraftRow));
325
- }, [props.environment]);
314
+ const draft = reconcileRowsDraft(
315
+ storedDraft,
316
+ props.environment,
317
+ providerEnvironmentsEqual,
318
+ toEnvironmentDraftRows,
319
+ );
320
+ if (draft !== storedDraft) setDraft(draft);
321
+ const rows = draft.rows;
322
+ const setRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) =>
323
+ setDraft({ ...draft, rows: nextRows });
324
325
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
326
const published: ProviderInstanceEnvironmentVariable[] = [];
@@ -342,7 +340,7 @@ export function ProviderEnvironmentSection(props: {
340
const { id: _id, ...rest } = row;
341
published.push({ ...rest, name });
342
}
345
- lastPublishedEnvironmentRef.current = published;
343
+ setDraft({ rows: nextRows, seen: draft.seen, lastPublished: published });
344
props.onChange(published);
345
};
346
@@ -1156,7 +1154,6 @@ export function ProviderInstanceCard({
1154
displayName={displayName}
1155
value={accentColor}
1156
onCommit={updateAccentColor}
1159
- commitDelayMs={120}
1157
/>
1158
<DraftInput
1159
id={`provider-instance-${instanceId}-display-name`}
apps/web/src/components/settings/ProviderSettingsForm.test.ts
+32
@@ -6,6 +6,8 @@ import { providerClients } from "./providerDriverMeta";
6
import {
7
deriveProviderSettingsFields,
8
nextProviderConfigWithFieldValue,
9
+ reconcileRowsDraft,
10
+ seedRowsDraft,
11
} from "./ProviderSettingsForm";
12
13
describe("ProviderSettingsForm helpers", () => {
@@ -55,3 +57,33 @@ describe("ProviderSettingsForm helpers", () => {
57
expect(next).toEqual({ experimental: false });
58
});
59
});
60
+
61
+describe("reconcileRowsDraft", () => {
62
+ let nextId = 0;
63
+ const toRows = (values: ReadonlyArray<string>) =>
64
+ values.map((value) => ({ id: nextId++, value }));
65
+ const equal = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
66
+ left.length === right.length && left.every((value, index) => value === right[index]);
67
+
68
+ it("keeps rows when an equal value arrives with a new identity", () => {
69
+ const draft = seedRowsDraft(["a"], toRows);
70
+ expect(reconcileRowsDraft(draft, ["a"], equal, toRows)).toBe(draft);
71
+ });
72
+
73
+ it("keeps row ids when the published value echoes back", () => {
74
+ const seeded = seedRowsDraft(["a"], toRows);
75
+ const edited = { rows: [...seeded.rows, { id: 99, value: "" }], seen: seeded.seen };
76
+ const draft = { ...edited, lastPublished: ["a", ""] };
77
+ const next = reconcileRowsDraft(draft, ["a", ""], equal, toRows);
78
+ expect(next.rows).toBe(draft.rows);
79
+ expect(next.seen).toEqual(["a", ""]);
80
+ expect(next.lastPublished).toBeUndefined();
81
+ });
82
+
83
+ it("reseeds rows when the value changes from outside", () => {
84
+ const draft = { ...seedRowsDraft(["a"], toRows), lastPublished: ["b"] };
85
+ const next = reconcileRowsDraft(draft, ["c"], equal, toRows);
86
+ expect(next.rows.map((row) => row.value)).toEqual(["c"]);
87
+ expect(next.lastPublished).toBeUndefined();
88
+ });
89
+});
apps/web/src/components/settings/ProviderSettingsForm.tsx
+42
-26
@@ -1,4 +1,4 @@
1
-import { useEffect, useRef, useState, type ReactNode } from "react";
1
+import { useState, type ReactNode } from "react";
2
import * as Option from "effect/Option";
3
import * as Schema from "effect/Schema";
4
import {
@@ -143,11 +143,44 @@ export function deriveProviderSettingsFields(
143
}
144
145
let commandArgumentDraftId = 0;
146
+/**
147
+ * Editable rows seeded from a configured value. `seen` is the value the rows
148
+ * were last reconciled against; `lastPublished` is what the rows last sent to
149
+ * the owner, so its echo does not reseed rows (and drop their ids) mid-edit.
150
+ */
151
+export interface RowsDraft<V, R> {
152
+ readonly rows: ReadonlyArray<R>;
153
+ readonly seen: V;
154
+ readonly lastPublished: V | undefined;
155
+}
156
+
157
+export function seedRowsDraft<V, R>(
158
+ value: V,
159
+ toRows: (value: V) => ReadonlyArray<R>,
160
+): RowsDraft<V, R> {
161
+ return { rows: toRows(value), seen: value, lastPublished: undefined };
162
+}
163
+
164
+/** Reseeds the rows when the configured value changes from outside this editor. */
165
+export function reconcileRowsDraft<V, R>(
166
+ draft: RowsDraft<V, R>,
167
+ incoming: V,
168
+ equal: (left: V, right: V) => boolean,
169
+ toRows: (value: V) => ReadonlyArray<R>,
170
+): RowsDraft<V, R> {
171
+ if (draft.seen === incoming || equal(draft.seen, incoming)) return draft;
172
+ const echo = draft.lastPublished !== undefined && equal(draft.lastPublished, incoming);
173
+ return { rows: echo ? draft.rows : toRows(incoming), seen: incoming, lastPublished: undefined };
174
+}
175
+
176
const makeCommandArgumentDraftRow = (value: string) => ({
177
id: `provider-argument-${commandArgumentDraftId++}`,
178
value,
179
});
180
181
+const toCommandArgumentRows = (args: ReadonlyArray<string>) =>
182
+ args.map(makeCommandArgumentDraftRow);
183
+
184
function commandArgumentsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>) {
185
return left.length === right.length && left.every((argument, index) => argument === right[index]);
186
}
@@ -167,31 +200,14 @@ function ProviderCommandArguments({
200
onChange,
201
}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
202
const args = configuredCommandArgs(value);
170
- const [rows, setRows] = useState(() => args.map(makeCommandArgumentDraftRow));
171
- const rowsRef = useRef(rows);
172
- const previousArgsRef = useRef(args);
173
- const lastPublishedArgsRef = useRef<ReadonlyArray<string> | undefined>(undefined);
174
-
175
- useEffect(() => {
176
- const previousArgs = previousArgsRef.current;
177
- const lastPublishedArgs = lastPublishedArgsRef.current;
178
- previousArgsRef.current = args;
179
- lastPublishedArgsRef.current = undefined;
180
- if (
181
- commandArgumentsEqual(previousArgs, args) ||
182
- (lastPublishedArgs !== undefined && commandArgumentsEqual(lastPublishedArgs, args))
183
- )
184
- return;
185
- const nextRows = args.map(makeCommandArgumentDraftRow);
186
- rowsRef.current = nextRows;
187
- setRows(nextRows);
188
- }, [args]);
203
+ const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
204
+ const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
205
+ if (draft !== storedDraft) setDraft(draft);
206
+ const rows = draft.rows;
207
208
const updateArguments = (nextRows: typeof rows) => {
191
- rowsRef.current = nextRows;
192
- setRows(nextRows);
209
const next = nextRows.map((row) => row.value);
194
- lastPublishedArgsRef.current = next;
210
+ setDraft({ rows: nextRows, seen: draft.seen, lastPublished: next });
211
const config =
212
value !== null && typeof value === "object" ? { ...(value as Record<string, unknown>) } : {};
213
onChange({ ...config, commandArgs: next });
@@ -206,7 +222,7 @@ function ProviderCommandArguments({
222
type="button"
223
size="sm"
224
variant="outline"
209
- onClick={() => updateArguments([...rowsRef.current, makeCommandArgumentDraftRow("")])}
225
+ onClick={() => updateArguments([...rows, makeCommandArgumentDraftRow("")])}
226
>
227
<PlusIcon />
228
Add argument
@@ -223,7 +239,7 @@ function ProviderCommandArguments({
239
value={argument.value}
240
onCommit={(next) =>
241
updateArguments(
226
- rowsRef.current.map((current) =>
242
+ rows.map((current) =>
243
current.id === argument.id ? { ...current, value: next } : current,
244
),
245
)
@@ -236,7 +252,7 @@ function ProviderCommandArguments({
252
size="icon-micro"
253
variant="ghost-destructive"
254
onClick={() =>
239
- updateArguments(rowsRef.current.filter((current) => current.id !== argument.id))
255
+ updateArguments(rows.filter((current) => current.id !== argument.id))
256
}
257
aria-label={`Remove argument ${index + 1}`}
258
>
apps/web/src/components/settings/colorPickers.browser.test.tsx
+55
-1
@@ -4,6 +4,7 @@ import { userEvent } from "vite-plus/test/browser";
4
import type { ReactNode } from "react";
5
6
import { act, render } from "../../../test/render";
7
+import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
8
import { ThemeColorField } from "./ThemeColorPicker";
9
10
const HUE = "Accent color hue";
@@ -58,8 +59,10 @@ async function renderThemeField(value: string) {
59
const field = (current: string) => (
60
<ThemeColorField role="accent" value={current} onChange={onChange} />
61
);
61
- const screen = await renderPicker(field(value));
62
+ await using stack = new AsyncDisposableStack();
63
+ const screen = stack.use(await renderPicker(field(value)));
64
await open("Choose Accent color color");
65
+ stack.move();
66
return Object.assign(screen, {
67
onChange,
68
echo: (current: string) => screen.rerender(field(current)),
@@ -82,3 +85,54 @@ describe("theme color field", () => {
85
expect(slider(HUE).getAttribute("aria-valuenow")).toBe("10");
86
});
87
});
88
+
89
+async function renderAccentPicker(value: string) {
90
+ const onCommit = vi.fn();
91
+ const picker = (current: string) => (
92
+ <ProviderAccentColorPicker displayName="Codex" value={current} onCommit={onCommit} />
93
+ );
94
+ await using stack = new AsyncDisposableStack();
95
+ const screen = stack.use(await renderPicker(picker(value)));
96
+ await open("Change accent color for Codex");
97
+ stack.move();
98
+ return Object.assign(screen, {
99
+ onCommit,
100
+ echo: (current: string) => screen.rerender(picker(current)),
101
+ });
102
+}
103
+
104
+describe("provider accent color picker", () => {
105
+ it("commits a drag that is still in progress when the popover closes", async () => {
106
+ await using screen = await renderAccentPicker("#ff0000");
107
+
108
+ await act(async () => {
109
+ pointer(HUE, "pointerdown", 0.5);
110
+ pointer(HUE, "pointermove", 0.5);
111
+ });
112
+ expect(screen.onCommit).not.toHaveBeenCalled();
113
+
114
+ await userEvent.keyboard("{Escape}");
115
+ expect(screen.onCommit).toHaveBeenCalledTimes(1);
116
+ expect(screen.onCommit.mock.calls[0]?.[0]).not.toBe("#ff0000");
117
+ });
118
+
119
+ it("saves a change back to the saved color while the first change is still saving", async () => {
120
+ await using screen = await renderAccentPicker("#ff0000");
121
+
122
+ await userEvent.fill(byLabel("Custom hex accent color"), "#00ff00");
123
+ await userEvent.fill(byLabel("Custom hex accent color"), "#ff0000");
124
+
125
+ expect(screen.onCommit).toHaveBeenLastCalledWith("#ff0000");
126
+ });
127
+
128
+ it("shows the saved color again when it is reverted outside the picker", async () => {
129
+ await using screen = await renderAccentPicker("#ff0000");
130
+
131
+ await userEvent.fill(byLabel("Custom hex accent color"), "#00ff00");
132
+ expect(screen.onCommit).toHaveBeenLastCalledWith("#00ff00");
133
+ await screen.echo("#00ff00");
134
+ await screen.echo("#ff0000");
135
+
136
+ expect(byLabel("Change accent color for Codex").style.backgroundColor).toBe("rgb(255, 0, 0)");
137
+ });
138
+});
apps/web/src/state/desktopCliCommand.test.ts
new
+40
@@ -0,0 +1,40 @@
1
+import type { DesktopCliCommandState } from "@t3tools/contracts";
2
+import { AtomRegistry } from "effect/reactivity";
3
+import * as AsyncResult from "effect/reactivity/AsyncResult";
4
+import { afterAll, describe, expect, it, vi } from "vite-plus/test";
5
+
6
+import { desktopCliCommandStateAtom } from "./desktopCliCommand";
7
+
8
+const getState = vi.fn<() => Promise<DesktopCliCommandState>>();
9
+vi.stubGlobal("window", { desktopBridge: { cliCommand: { getState } } });
10
+
11
+describe("desktopCliCommandStateAtom", () => {
12
+ afterAll(() => {
13
+ vi.unstubAllGlobals();
14
+ });
15
+
16
+ it("reloads stale state when Settings mounts it again", async () => {
17
+ getState.mockResolvedValue({
18
+ supported: true,
19
+ installedPath: null,
20
+ onPath: false,
21
+ launcherPath: null,
22
+ });
23
+ using now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);
24
+ const registry = AtomRegistry.make();
25
+
26
+ const unmountFirst = registry.mount(desktopCliCommandStateAtom);
27
+ await vi.waitFor(() => {
28
+ const result = registry.get(desktopCliCommandStateAtom);
29
+ expect(AsyncResult.isInitial(result) || result.waiting).toBe(false);
30
+ });
31
+ unmountFirst();
32
+ await vi.waitFor(() => expect(registry.getNodes().size).toBe(1));
33
+
34
+ now.mockReturnValue(1_060_000);
35
+ const unmountSecond = registry.mount(desktopCliCommandStateAtom);
36
+ await vi.waitFor(() => expect(getState).toHaveBeenCalledTimes(2));
37
+ unmountSecond();
38
+ registry.dispose();
39
+ });
40
+});
apps/web/src/state/desktopCliCommand.ts
new
+52
@@ -0,0 +1,52 @@
1
+import type { DesktopBridge, DesktopCliCommandState } from "@t3tools/contracts";
2
+import * as Effect from "effect/Effect";
3
+import * as Schema from "effect/Schema";
4
+import { Atom } from "effect/reactivity";
5
+
6
+import { appAtomRegistry } from "~/rpc/atomRegistry";
7
+
8
+type DesktopCliCommandBridge = NonNullable<DesktopBridge["cliCommand"]>;
9
+
10
+class DesktopCliCommandUnavailableError extends Schema.TaggedError<DesktopCliCommandUnavailableError>()(
11
+ "DesktopCliCommandUnavailableError",
12
+ {},
13
+) {
14
+ override get message(): string {
15
+ return "The t3 command is unavailable.";
16
+ }
17
+}
18
+
19
+class DesktopCliCommandLoadError extends Schema.TaggedError<DesktopCliCommandLoadError>()(
20
+ "DesktopCliCommandLoadError",
21
+ { cause: Schema.Defect() },
22
+) {
23
+ override get message(): string {
24
+ return "Failed to load the t3 command state.";
25
+ }
26
+}
27
+
28
+export function getDesktopCliCommandBridge(): DesktopCliCommandBridge | undefined {
29
+ return typeof window === "undefined" ? undefined : window.desktopBridge?.cliCommand;
30
+}
31
+
32
+const loadDesktopCliCommandState = Effect.fn("loadDesktopCliCommandState")(function* () {
33
+ const bridge = getDesktopCliCommandBridge();
34
+ if (!bridge) {
35
+ return yield* new DesktopCliCommandUnavailableError();
36
+ }
37
+ return yield* Effect.tryPromise({
38
+ try: (): Promise<DesktopCliCommandState> => bridge.getState(),
39
+ catch: (cause) => new DesktopCliCommandLoadError({ cause }),
40
+ });
41
+});
42
+
43
+export const desktopCliCommandStateAtom = Atom.make(loadDesktopCliCommandState()).pipe(
44
+ // Keep the loaded state, but let the SWR wrapper revalidate when Settings remounts.
45
+ Atom.keepAlive,
46
+ Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
47
+ Atom.withLabel("desktop:cli-command:load"),
48
+);
49
+
50
+export function refreshDesktopCliCommandState(): void {
51
+ appAtomRegistry.refresh(desktopCliCommandStateAtom);
52
+}
apps/web/src/state/waitForQuerySettled.test.ts
new
+56
@@ -0,0 +1,56 @@
1
+import * as Cause from "effect/Cause";
2
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import { waitForQuerySettled } from "./waitForQuerySettled";
6
+
7
+const settle = (value: number | null) =>
8
+ value !== null && value >= 2 ? `settled:${value}` : undefined;
9
+
10
+describe("waitForQuerySettled", () => {
11
+ it("resolves with the first settled value", async () => {
12
+ const registry = AtomRegistry.make();
13
+ const atom = Atom.make(AsyncResult.success<number, string>(1));
14
+ const result = waitForQuerySettled({
15
+ registry,
16
+ atom,
17
+ settle,
18
+ signal: new AbortController().signal,
19
+ });
20
+ registry.set(atom, AsyncResult.success(2));
21
+ registry.set(atom, AsyncResult.success(3));
22
+ expect(await result).toBe("settled:2");
23
+ });
24
+
25
+ it("resolves at once when the current value already settles", async () => {
26
+ const registry = AtomRegistry.make();
27
+ const atom = Atom.make(AsyncResult.success<number, string>(5));
28
+ expect(
29
+ await waitForQuerySettled({ registry, atom, settle, signal: new AbortController().signal }),
30
+ ).toBe("settled:5");
31
+ });
32
+
33
+ it("resolves undefined when aborted", async () => {
34
+ const registry = AtomRegistry.make();
35
+ const atom = Atom.make(AsyncResult.success<number, string>(1));
36
+ const controller = new AbortController();
37
+ const result = waitForQuerySettled({ registry, atom, settle, signal: controller.signal });
38
+ controller.abort();
39
+ registry.set(atom, AsyncResult.success(2));
40
+ expect(await result).toBeUndefined();
41
+ });
42
+
43
+ it("resolves undefined when the query fails, even before any success", async () => {
44
+ const registry = AtomRegistry.make();
45
+ const atom = Atom.make<AsyncResult.AsyncResult<number, string>>(AsyncResult.initial());
46
+ const result = waitForQuerySettled({
47
+ registry,
48
+ atom,
49
+ settle,
50
+ signal: new AbortController().signal,
51
+ });
52
+ registry.set(atom, AsyncResult.failure(Cause.fail("stream closed")));
53
+ registry.set(atom, AsyncResult.success(2));
54
+ expect(await result).toBeUndefined();
55
+ });
56
+});
apps/web/src/state/waitForQuerySettled.ts
new
+38
@@ -0,0 +1,38 @@
1
+import * as Option from "effect/Option";
2
+import { AsyncResult, type Atom, type AtomRegistry } from "effect/reactivity";
3
+
4
+/**
5
+ * Resolves with the first defined `settle` result for a query atom's value.
6
+ * Resolves `undefined` once `signal` aborts or the query fails, because a
7
+ * failed query can no longer report the state the caller is waiting for.
8
+ * Subscribing keeps the atom mounted, so the subscription ends on every exit.
9
+ */
10
+export function waitForQuerySettled<A, E, R>(input: {
11
+ readonly registry: AtomRegistry.AtomRegistry;
12
+ readonly atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
13
+ readonly settle: (value: A | null) => R | undefined;
14
+ readonly signal: AbortSignal;
15
+}): Promise<R | undefined> {
16
+ const { registry, atom, settle, signal } = input;
17
+ return new Promise((resolve) => {
18
+ let done = false;
19
+ let unsubscribe: (() => void) | undefined;
20
+ const finish = (result: R | undefined) => {
21
+ if (done) return;
22
+ done = true;
23
+ unsubscribe?.();
24
+ signal.removeEventListener("abort", onAbort);
25
+ resolve(result);
26
+ };
27
+ const onAbort = () => finish(undefined);
28
+ const check = (result: AsyncResult.AsyncResult<A, E>) => {
29
+ if (AsyncResult.isFailure(result)) return finish(undefined);
30
+ const settled = settle(Option.getOrNull(AsyncResult.value(result)));
31
+ if (settled !== undefined) finish(settled);
32
+ };
33
+ if (signal.aborted) return finish(undefined);
34
+ signal.addEventListener("abort", onAbort);
35
+ unsubscribe = registry.subscribe(atom, check, { immediate: true });
36
+ if (done) unsubscribe();
37
+ });
38
+}