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

preferences.test.ts

349 lines11.4 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
6import { vi } from "vite-plus/test";
7import { ProviderInstanceId } from "@t3tools/contracts";
8import { RegistryContext, useAtomSet } from "@effect/atom-react";
9import { createElement } from "react";
10import { renderToString } from "react-dom/server";
11​
12vi.mock("expo-secure-store", () => ({
13 getItemAsync: vi.fn(),
14 setItemAsync: vi.fn(),
15}));
16​
17vi.mock("react-native", () => ({
18 Platform: { OS: "ios" },
19}));
20​
21vi.mock("../lib/runtime", async () => {
22 const Layer = await import("effect/Layer");
23 return {
24 runtime: { runPromise: vi.fn() },
25 runtimeContextLayer: Layer.empty,
26 };
27});
28​
29import type { Preferences } from "../persistence/mobile-preferences";
30import {
31 createMobilePreferencesState,
32 MobilePreferencesLoadError,
33 MobilePreferencesSaveError,
34 MobilePreferencesStore,
35} from "./preferences";
36​
37function deferred<A>() {
38 let resolve!: (value: A) => void;
39 const promise = new Promise<A>((resume) => {
40 resolve = resume;
41 });
42 return { promise, resolve } as const;
44​
45function makePreferencesState(
46 service: Omit<MobilePreferencesStore["Service"], "update"> &
47 Partial<Pick<MobilePreferencesStore["Service"], "update">>,
48) {
49 const completeService = MobilePreferencesStore.of({
50 ...service,
51 update:
52 service.update ??
53 ((transform) =>
54 service.load.pipe(
55 Effect.flatMap((current) => service.savePatch(transform(current))),
56 Effect.mapError((cause) =>
57 cause._tag === "MobilePreferencesSaveError"
58 ? cause
59 : new MobilePreferencesSaveError({ cause }),
60 ),
61 )),
62 });
63 return createMobilePreferencesState(
64 Atom.runtime(Layer.succeed(MobilePreferencesStore, completeService)),
65 );
67​
68describe("mobile preferences state", () => {
69 it.effect("shares one preference load across consumers", () =>
70 Effect.gen(function* () {
71 const load = vi.fn(() => Promise.resolve<Preferences>({ baseFontSize: 17 }));
72 const state = makePreferencesState({
73 load: Effect.promise(load),
74 savePatch: (patch) => Effect.succeed(patch),
75 });
76 const registry = AtomRegistry.make();
77 const unmountFirst = registry.mount(state.preferencesAtom);
78 const unmountSecond = registry.mount(state.preferencesAtom);
79​
80 expect(
81 yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
82 suspendOnWaiting: true,
83 }),
84 ).toEqual({ baseFontSize: 17 });
85 expect(load).toHaveBeenCalledTimes(1);
86​
87 unmountSecond();
88 unmountFirst();
89 registry.dispose();
90 }),
91 );
92​
93 it.effect("preserves an optimistic patch when the initial load finishes later", () =>
94 Effect.gen(function* () {
95 const pendingLoad = deferred<Preferences>();
96 const savePatch = vi.fn((patch: Partial<Preferences>) => Effect.succeed(patch));
97 const state = makePreferencesState({
98 load: Effect.promise(() => pendingLoad.promise),
99 savePatch,
100 });
101 const registry = AtomRegistry.make();
102 const unmountPreferences = registry.mount(state.preferencesAtom);
103 const unmountUpdate = registry.mount(state.updatePreferencesAtom);
104​
105 registry.set(state.updatePreferencesAtom, {
106 collapsedProjectGroups: ["project:new"],
107 });
108 pendingLoad.resolve({
109 baseFontSize: 18,
110 collapsedProjectGroups: ["project:old"],
111 });
112​
113 const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
114 suspendOnWaiting: true,
115 });
116 expect(preferences).toEqual({
117 baseFontSize: 18,
118 collapsedProjectGroups: ["project:new"],
119 });
120 expect(savePatch).toHaveBeenCalledWith({
121 collapsedProjectGroups: ["project:new"],
122 });
123 expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false);
124​
125 unmountUpdate();
126 unmountPreferences();
127 registry.dispose();
128 }),
129 );
130​
131 it.effect("keeps both favorites when the React setter sends updates before a render", () =>
132 Effect.gen(function* () {
133 let persisted: Preferences = { modelFavorites: [] };
134 const state = makePreferencesState({
135 load: Effect.succeed(persisted),
136 savePatch: (patch) =>
137 Effect.sync(() => {
138 persisted = { ...persisted, ...patch };
139 return persisted;
140 }),
141 update: (transform) =>
142 Effect.sync(() => {
143 persisted = { ...persisted, ...transform(persisted) };
144 return persisted;
145 }),
146 });
147 const registry = AtomRegistry.make();
148 const unmountPreferences = registry.mount(state.preferencesAtom);
149 const unmountUpdate = registry.mount(state.updatePreferencesAtom);
150 yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true });
151​
152 function useSavePreferences() {
153 return useAtomSet(state.updatePreferencesAtom);
154 }
155 const setters: Array<ReturnType<typeof useSavePreferences>> = [];
156 function CaptureSetter() {
157 setters.push(useSavePreferences());
158 return null;
159 }
160 // Exercise the real React setter, which treats bare functions as updates
161 // to the atom's read value. Direct registry.set calls bypass that behavior.
162 renderToString(
163 createElement(RegistryContext.Provider, { value: registry }, createElement(CaptureSetter)),
164 );
165 const savePreferences = setters[0]!;
166 const provider = ProviderInstanceId.make("codex");
167 savePreferences({
168 transform: (current) => ({
169 modelFavorites: [...(current.modelFavorites ?? []), { provider, model: "astra" }],
170 }),
171 });
172 savePreferences({
173 transform: (current) => ({
174 modelFavorites: [...(current.modelFavorites ?? []), { provider, model: "sol" }],
175 }),
176 });
177 yield* AtomRegistry.getResult(registry, state.updatePreferencesAtom, {
178 suspendOnWaiting: true,
179 });
180​
181 expect(persisted.modelFavorites).toEqual([
182 { provider, model: "astra" },
183 { provider, model: "sol" },
184 ]);
185​
186 savePreferences({
187 transform: (current) => ({
188 modelFavorites: (current.modelFavorites ?? []).filter(
189 (favorite) => favorite.model !== "astra",
190 ),
191 }),
192 });
193 yield* AtomRegistry.getResult(registry, state.updatePreferencesAtom, {
194 suspendOnWaiting: true,
195 });
196 expect(persisted.modelFavorites).toEqual([{ provider, model: "sol" }]);
197​
198 unmountUpdate();
199 unmountPreferences();
200 registry.dispose();
201 }),
202 );
203​
204 it.effect("falls back to empty preferences when secure storage cannot be read", () =>
205 Effect.gen(function* () {
206 const state = makePreferencesState({
207 load: Effect.fail(
208 new MobilePreferencesLoadError({
209 cause: new Error("secure storage unavailable"),
210 }),
211 ),
212 savePatch: (patch) => Effect.succeed(patch),
213 });
214 const registry = AtomRegistry.make();
215 const unmount = registry.mount(state.preferencesAtom);
216​
217 expect(
218 yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
219 suspendOnWaiting: true,
220 }),
221 ).toEqual({});
222​
223 unmount();
224 registry.dispose();
225 }),
226 );
227​
228 it.effect("does not roll back a newer optimistic write with the same value", () =>
229 Effect.gen(function* () {
230 let saveCount = 0;
231 const state = makePreferencesState({
232 load: Effect.succeed({ baseFontSize: 16, codeFontSize: 13 }),
233 savePatch: (patch) => {
234 saveCount += 1;
235 return saveCount === 1
236 ? Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") }))
237 : Effect.succeed(patch);
238 },
239 });
240 const registry = AtomRegistry.make();
241 const unmountPreferences = registry.mount(state.preferencesAtom);
242 const unmountUpdate = registry.mount(state.updatePreferencesAtom);
243​
244 yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
245 suspendOnWaiting: true,
246 });
247 registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
248 registry.set(state.updatePreferencesAtom, { baseFontSize: 18, codeFontSize: 15 });
249​
250 yield* Effect.promise(() =>
251 vi.waitFor(() => {
252 expect(AsyncResult.isFailure(registry.get(state.updatePreferencesAtom))).toBe(false);
253 expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
254 {
255 baseFontSize: 18,
256 codeFontSize: 15,
257 },
258 );
259 }),
260 );
261​
262 unmountUpdate();
263 unmountPreferences();
264 registry.dispose();
265 }),
266 );
267​
268 it.effect("rolls back an optimistic field when its save fails", () =>
269 Effect.gen(function* () {
270 const state = makePreferencesState({
271 load: Effect.succeed({ baseFontSize: 16 }),
272 savePatch: () =>
273 Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") })),
274 });
275 const registry = AtomRegistry.make();
276 const unmountPreferences = registry.mount(state.preferencesAtom);
277 const unmountUpdate = registry.mount(state.updatePreferencesAtom);
278​
279 yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
280 suspendOnWaiting: true,
281 });
282 registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
283​
284 yield* Effect.promise(() =>
285 vi.waitFor(() => {
286 expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
287 {
288 baseFontSize: 16,
289 },
290 );
291 }),
292 );
293​
294 unmountUpdate();
295 unmountPreferences();
296 registry.dispose();
297 }),
298 );
299​
300 it.effect("rolls back to the last confirmed value after a later save fails", () =>
301 Effect.gen(function* () {
302 let saveCount = 0;
303 const state = makePreferencesState({
304 load: Effect.succeed({ baseFontSize: 16 }),
305 savePatch: () => {
306 saveCount += 1;
307 return saveCount === 1
308 ? Effect.succeed({ baseFontSize: 14 })
309 : Effect.fail(new MobilePreferencesSaveError({ cause: new Error("write failed") }));
310 },
311 });
312 const registry = AtomRegistry.make();
313 const unmountPreferences = registry.mount(state.preferencesAtom);
314 const unmountUpdate = registry.mount(state.updatePreferencesAtom);
315​
316 yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
317 suspendOnWaiting: true,
318 });
319 registry.set(state.updatePreferencesAtom, { baseFontSize: 14 });
320 yield* Effect.promise(() =>
321 vi.waitFor(() => {
322 expect(saveCount).toBe(1);
323 expect(registry.get(state.updatePreferencesAtom).waiting).toBe(false);
324 expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
325 {
326 baseFontSize: 14,
327 },
328 );
329 }),
330 );
331​
332 registry.set(state.updatePreferencesAtom, { baseFontSize: 18 });
333 yield* Effect.promise(() =>
334 vi.waitFor(() => {
335 expect(saveCount).toBe(2);
336 expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual(
337 {
338 baseFontSize: 14,
339 },
340 );
341 }),
342 );
343​
344 unmountUpdate();
345 unmountPreferences();
346 registry.dispose();
347 }),
348 );
349});