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

useSettings.sync.browser.test.tsx

252 lines8.6 KB

1import { RegistryContext } from "@effect/atom-react";
2import {
3 AuthSettingsWriteScope,
4 DEFAULT_SERVER_SETTINGS,
5 EnvironmentId,
6 type AuthEnvironmentScope,
7 type AuthSessionState,
8 type ServerSettingsPatch,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import { AsyncResult, Atom } from "effect/reactivity";
12import { act } from "react";
13import { createRoot, type Root } from "react-dom/client";
14import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
15​
16type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
17const state = vi.hoisted(() => ({
18 sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
19 environments: [] as Array<{
20 environmentId: EnvironmentId;
21 label: string;
22 connection: { phase: "connected" | "disconnected" };
23 serverConfig: {
24 environment: { capabilities: { threadAutoSettlement: boolean } };
25 settings: typeof DEFAULT_SERVER_SETTINGS;
26 };
27 }>,
28 persist: vi.fn(),
29 toast: vi.fn(),
30}));
31​
32vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => ({
33 ...(await original()),
34 createEnvironmentSessionAtoms: (() => ({
35 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
36 })) as never,
37}));
38vi.mock(import("~/state/environments"), async (original) => ({
39 ...(await original()),
40 useEnvironments: (() => ({ environments: state.environments })) as never,
41 usePrimaryEnvironment: (() =>
42 state.environments.find((environment) => environment.environmentId === primaryId) ??
43 null) as never,
44}));
45vi.mock(import("~/state/use-atom-command"), async (original) => ({
46 ...(await original()),
47 useAtomCommand: (() => state.persist) as never,
48}));
49vi.mock(import("~/components/ui/toast"), async (original) => {
50 const actual = await original();
51 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } };
52});
53​
54import { appAtomRegistry } from "~/rpc/atomRegistry";
55import { useUpdatePrimarySettings } from "./useSettings";
56​
57const primaryId = EnvironmentId.make("primary");
58const remoteId = EnvironmentId.make("remote");
59const patch = { sidebarAutoSettleOnMerge: false } satisfies ServerSettingsPatch;
60const session = (scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState => ({
61 authenticated: true,
62 scopes,
63 auth: {
64 policy: "remote-reachable",
65 bootstrapMethods: ["one-time-token"],
66 sessionMethods: ["bearer-access-token"],
67 sessionCookieName: "t3_session",
68 },
69});
70let root: Root;
71let container: HTMLDivElement;
72let handlers: Array<() => void> = [];
73​
74function SettingsEditor() {
75 const updateSettings = useUpdatePrimarySettings();
76 const save = () => void updateSettings(patch);
77 handlers.push(save);
78 return <button onClick={save}>Save shared setting</button>;
80​
81function saveSharedSettings() {
82 container.querySelector("button")!.click();
84​
85async function mountEditor() {
86 await act(() =>
87 root.render(
88 <RegistryContext.Provider value={appAtomRegistry}>
89 <SettingsEditor />
90 </RegistryContext.Provider>,
91 ),
92 );
94​
95beforeEach(() => {
96 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
97 handlers = [];
98 state.sessions.clear();
99 state.sessions.set(
100 primaryId,
101 Atom.make<SessionResult>(AsyncResult.success(session([AuthSettingsWriteScope]))),
102 );
103 state.sessions.set(remoteId, Atom.make<SessionResult>(AsyncResult.initial()));
104 state.environments = [primaryId, remoteId].map((environmentId) => ({
105 environmentId,
106 label: environmentId,
107 connection: { phase: "connected" },
108 serverConfig: {
109 environment: { capabilities: { threadAutoSettlement: true } },
110 settings: DEFAULT_SERVER_SETTINGS,
111 },
112 }));
113 state.persist.mockReset();
114 state.persist.mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
115 state.toast.mockReset();
116 container = document.createElement("div");
117 document.body.append(container);
118 root = createRoot(container);
119});
120​
121afterEach(async () => {
122 await act(() => root.unmount());
123 container.remove();
124 vi.unstubAllGlobals();
125});
126​
127describe("shared settings writes", () => {
128 it("waits for the remaining target before reporting a partial save", async () => {
129 let finishRemote = () => {};
130 const remote = new Promise((resolve) => {
131 finishRemote = () => resolve(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
132 });
133 state.persist.mockResolvedValueOnce(
134 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
135 );
136 state.persist.mockReturnValueOnce(remote);
137 await mountEditor();
138 await act(async () => saveSharedSettings());
139 expect(state.toast).not.toHaveBeenCalled();
140 await act(async () => finishRemote());
141 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
142 type: "error",
143 title: "Setting saved on some environments",
144 description: "Could not save on primary: Permission denied\nSaved on remote.",
145 });
146 });
147​
148 it("keeps a single-target failure specific to that environment", async () => {
149 appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
150 state.persist.mockResolvedValueOnce(
151 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
152 );
153 await mountEditor();
154 await act(async () => saveSharedSettings());
155 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
156 type: "error",
157 title: "Setting not saved",
158 description: "Could not save on primary: Permission denied",
159 });
160 });
161​
162 it("names the failed environment when a server rejects a save after the grant check", async () => {
163 state.persist.mockResolvedValueOnce(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
164 state.persist.mockResolvedValueOnce(
165 AsyncResult.failure(Cause.fail(new Error("Permission denied"))),
166 );
167 await mountEditor();
168 await act(async () => saveSharedSettings());
169 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
170 type: "error",
171 title: "Setting saved on some environments",
172 description: "Could not save on remote: Permission denied\nSaved on primary.",
173 });
174 });
175​
176 it("dispatches to the primary and connected remote before the remote grant finishes loading", async () => {
177 await mountEditor();
178 saveSharedSettings();
179​
180 expect(state.persist.mock.calls).toEqual([
181 [{ environmentId: primaryId, input: { patch } }],
182 [{ environmentId: remoteId, input: { patch } }],
183 ]);
184 expect(appAtomRegistry.get(state.sessions.get(remoteId)!)).toMatchObject({ _tag: "Initial" });
185 });
186​
187 it.each([
188 ["denied", () => AsyncResult.success(session([]))],
189 ["denied while refreshing", () => AsyncResult.waiting(AsyncResult.success(session([])))],
190 [
191 "failed",
192 () => AsyncResult.failure<AuthSessionState, Error>(Cause.fail(new Error("session rejected"))),
193 ],
194 ] as const)("skips a remote whose grant is %s", async (_label, result) => {
195 appAtomRegistry.set(state.sessions.get(remoteId)!, result());
196 await mountEditor();
197 saveSharedSettings();
198​
199 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
200 environmentId: primaryId,
201 input: { patch },
202 });
203 });
204​
205 it.each(["disconnected", "unsupported"] as const)(
206 "skips a %s remote even with a cold grant",
207 async (condition) => {
208 const remote = state.environments[1]!;
209 if (condition === "disconnected") remote.connection.phase = "disconnected";
210 else remote.serverConfig.environment.capabilities.threadAutoSettlement = false;
211 await mountEditor();
212 saveSharedSettings();
213​
214 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
215 environmentId: primaryId,
216 input: { patch },
217 });
218 },
219 );
220​
221 it.each(["primary", "hosted"] as const)(
222 "rechecks a cold remote grant that resolves to denied after the %s handler renders",
223 async (mode) => {
224 if (mode === "hosted") {
225 state.environments = state.environments.filter(
226 (environment) => environment.environmentId !== primaryId,
227 );
228 }
229 await mountEditor();
230 const previousUpdate = handlers.at(-1)!;
231 await act(() => {
232 appAtomRegistry.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));
233 });
234 previousUpdate();
235​
236 if (mode === "primary") {
237 expect(state.persist).toHaveBeenCalledExactlyOnceWith({
238 environmentId: primaryId,
239 input: { patch },
240 });
241 expect(state.toast).not.toHaveBeenCalled();
242 } else {
243 expect(state.persist).not.toHaveBeenCalled();
244 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
245 type: "warning",
246 title: "Setting not saved",
247 description: "This connection lacks permission to change settings on remote.",
248 });
249 }
250 },
251 );
252});