Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 ProviderDriverKind,
4 ProviderInstanceId,
5} from "@t3tools/contracts";
6import { DEFAULT_CLIENT_SETTINGS, type ClientSettings } from "@t3tools/contracts/settings";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
9const persistenceMocks = vi.hoisted(() => ({
10 getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
11 setClientSettings: vi.fn<(settings: ClientSettings) => Promise<void>>(),
12}));
13
14vi.mock("~/localApi", () => ({
15 ensureLocalApi: () => ({ persistence: persistenceMocks }),
16}));
17
18import {
19 __resetClientSettingsPersistenceForTests,
20 __setClientSettingsForTests,
21 ensureClientSettingsHydrated,
22 getClientSettings,
23 mergeEnvironmentSettings,
24 persistClientSettingsPatch,
25 persistClientSettingsUpdate,
26 resolveEnvironmentIdentificationMode,
27} from "./useSettings";
28
29beforeEach(() => {
30 persistenceMocks.getClientSettings.mockReset().mockResolvedValue(null);
31 persistenceMocks.setClientSettings.mockReset().mockResolvedValue(undefined);
32 __resetClientSettingsPersistenceForTests();
33});
34
35afterEach(() => {
36 vi.restoreAllMocks();
37});
38
39describe("client settings hydration", () => {
40 const savedSettings = {
41 ...DEFAULT_CLIENT_SETTINGS,
42 timestampFormat: "12-hour" as const,
43 favorites: [{ provider: ProviderInstanceId.make("codex_work"), model: "gpt-5.6" }],
44 };
45 const onboardingCompletedAt = "2026-09-05T12:00:00.000Z";
46 const complete = (current: ClientSettings) => ({ ...current, onboardingCompletedAt });
47
48 it("rejects completion after a failed read and preserves saved preferences on retry", async () => {
49 const failure = new Error("storage unavailable");
50 vi.spyOn(console, "error").mockImplementation(() => undefined);
51 persistenceMocks.getClientSettings
52 .mockRejectedValueOnce(failure)
53 .mockResolvedValue(savedSettings);
54
55 await expect(persistClientSettingsUpdate(complete)).rejects.toBe(failure);
56 expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
57 expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
58
59 const completedSettings = { ...savedSettings, onboardingCompletedAt };
60 await expect(persistClientSettingsUpdate(complete)).resolves.toEqual(completedSettings);
61 expect(persistenceMocks.setClientSettings).toHaveBeenCalledExactlyOnceWith(completedSettings);
62 expect(persistenceMocks.getClientSettings).toHaveBeenCalledTimes(2);
63 });
64
65 it("uses defaults only after storage confirms no saved settings exist", async () => {
66 const completedSettings = { ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt };
67
68 await expect(persistClientSettingsUpdate(complete)).resolves.toEqual(completedSettings);
69 expect(persistenceMocks.getClientSettings).toHaveBeenCalledOnce();
70 expect(persistenceMocks.setClientSettings).toHaveBeenCalledExactlyOnceWith(completedSettings);
71 });
72
73 it("holds patches until a pending read supplies the saved preferences", async () => {
74 let finishRead!: (settings: ClientSettings) => void;
75 persistenceMocks.getClientSettings.mockImplementationOnce(
76 () =>
77 new Promise((resolve) => {
78 finishRead = resolve;
79 }),
80 );
81 const persisted = new Promise<ClientSettings>((resolve) => {
82 persistenceMocks.setClientSettings.mockImplementationOnce(async (settings) => {
83 resolve(settings);
84 });
85 });
86
87 const hydration = ensureClientSettingsHydrated();
88 persistClientSettingsPatch({ wordWrap: false });
89 expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
90 expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
91
92 finishRead(savedSettings);
93 await hydration;
94 await expect(persisted).resolves.toEqual({ ...savedSettings, wordWrap: false });
95 expect(persistenceMocks.getClientSettings).toHaveBeenCalledOnce();
96 });
97
98 it("handles failed patch reads without writing and retries with the saved preferences", async () => {
99 const failure = new Error("storage unavailable");
100 vi.spyOn(console, "error").mockImplementation(() => undefined);
101 persistenceMocks.getClientSettings.mockRejectedValue(failure);
102
103 const hydration = ensureClientSettingsHydrated();
104 persistClientSettingsPatch({ wordWrap: false });
105 await expect(hydration).rejects.toBe(failure);
106 expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
107
108 persistenceMocks.getClientSettings.mockResolvedValue(savedSettings);
109 const persisted = new Promise<ClientSettings>((resolve) => {
110 persistenceMocks.setClientSettings.mockImplementationOnce(async (settings) => {
111 resolve(settings);
112 });
113 });
114 persistClientSettingsPatch({ wordWrap: false });
115
116 await expect(persisted).resolves.toEqual({ ...savedSettings, wordWrap: false });
117 });
118
119 it("preserves patch order across hydration and a blocked completion write", async () => {
120 let finishRead!: (settings: ClientSettings) => void;
121 const read = new Promise<ClientSettings>((resolve) => {
122 finishRead = resolve;
123 });
124 persistenceMocks.getClientSettings.mockReturnValue(read);
125 let finishCompletionWrite!: () => void;
126 const blockedWrite = new Promise<void>((resolve) => {
127 finishCompletionWrite = resolve;
128 });
129 let signalCompletionWrite!: () => void;
130 const completionWriteStarted = new Promise<void>((resolve) => {
131 signalCompletionWrite = resolve;
132 });
133 let durableSettings: ClientSettings = savedSettings;
134 const persist = vi
135 .fn<(settings: ClientSettings) => Promise<void>>()
136 .mockImplementationOnce(async (settings) => {
137 signalCompletionWrite();
138 await blockedWrite;
139 durableSettings = settings;
140 })
141 .mockImplementation(async (settings) => {
142 durableSettings = settings;
143 });
144
145 const completion = persistClientSettingsUpdate(complete, persist);
146 persistClientSettingsPatch({ wordWrap: false }, persist);
147 finishRead(savedSettings);
148 await completionWriteStarted;
149 persistClientSettingsPatch({ wordWrap: true }, persist);
150 const finalWrite = persistClientSettingsUpdate((current) => current, persist);
151
152 finishCompletionWrite();
153 await completion;
154 await finalWrite;
155
156 const expected = { ...savedSettings, onboardingCompletedAt, wordWrap: true };
157 expect(getClientSettings()).toEqual(expected);
158 expect(durableSettings).toEqual(expected);
159 });
160});
161
162describe("persistClientSettingsPatch", () => {
163 it("waits for settings writes in request order", async () => {
164 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
165 let finishFirst!: () => void;
166 let markFirstStarted!: () => void;
167 const firstStarted = new Promise<void>((resolve) => {
168 markFirstStarted = resolve;
169 });
170 persistenceMocks.setClientSettings.mockImplementationOnce(() => {
171 markFirstStarted();
172 return new Promise<void>((resolve) => {
173 finishFirst = resolve;
174 });
175 });
176
177 const firstSettings = { ...DEFAULT_CLIENT_SETTINGS, snapShotFlash: false };
178 const secondSettings = { ...firstSettings, snapShotPlaySound: false };
179 const first = persistClientSettingsPatch({ snapShotFlash: false });
180 await firstStarted;
181 const second = persistClientSettingsPatch({ snapShotPlaySound: false });
182
183 expect(persistenceMocks.setClientSettings).toHaveBeenCalledTimes(1);
184 expect(getClientSettings()).toEqual(secondSettings);
185 finishFirst();
186 await Promise.all([first, second]);
187
188 expect(persistenceMocks.setClientSettings).toHaveBeenNthCalledWith(1, firstSettings);
189 expect(persistenceMocks.setClientSettings).toHaveBeenNthCalledWith(2, secondSettings);
190 });
191});
192
193describe("persistClientSettingsUpdate", () => {
194 it("publishes the update only after persistence succeeds", async () => {
195 let finishPersistence!: () => void;
196 const persistence = new Promise<void>((resolve) => {
197 finishPersistence = resolve;
198 });
199 const setClientSettings = vi.fn(() => persistence);
200 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
201
202 const pending = persistClientSettingsUpdate(
203 (current) => ({
204 ...current,
205 timestampFormat: "12-hour",
206 }),
207 setClientSettings,
208 );
209
210 expect(getClientSettings().timestampFormat).toBe(DEFAULT_CLIENT_SETTINGS.timestampFormat);
211 finishPersistence();
212 await expect(pending).resolves.toMatchObject({ timestampFormat: "12-hour" });
213 expect(getClientSettings().timestampFormat).toBe("12-hour");
214 });
215
216 it("keeps the current snapshot and propagates persistence failure", async () => {
217 const failure = new Error("disk full");
218 const setClientSettings = vi.fn().mockRejectedValue(failure);
219 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
220
221 await expect(
222 persistClientSettingsUpdate(
223 (current) => ({ ...current, timestampFormat: "12-hour" }),
224 setClientSettings,
225 ),
226 ).rejects.toBe(failure);
227 expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
228 });
229
230 it("preserves an optimistic write made while an awaited update persists", async () => {
231 let finishFirstPersistence!: () => void;
232 let durableSettings = DEFAULT_CLIENT_SETTINGS;
233 const firstPersistence = new Promise<void>((resolve) => {
234 finishFirstPersistence = resolve;
235 });
236 const persist = vi
237 .fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
238 .mockImplementationOnce((settings) =>
239 firstPersistence.then(() => {
240 durableSettings = settings;
241 }),
242 )
243 .mockImplementation(async (settings) => {
244 durableSettings = settings;
245 });
246 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
247 const importedProfile = { id: "profile-import", name: "Imported", kind: "persistent" as const };
248
249 const pending = persistClientSettingsUpdate(
250 (current) => ({
251 ...current,
252 browserProfiles: [...current.browserProfiles, importedProfile],
253 }),
254 persist,
255 );
256 await Promise.resolve();
257 const patch = persistClientSettingsPatch({ wordWrap: false }, persist);
258 finishFirstPersistence();
259 await Promise.all([pending, patch]);
260
261 expect(persist).toHaveBeenCalledTimes(3);
262 expect(persist.mock.calls[1]?.[0]).toMatchObject({
263 wordWrap: false,
264 });
265 expect(persist.mock.calls[1]?.[0].browserProfiles).toContainEqual(importedProfile);
266 expect(durableSettings.wordWrap).toBe(false);
267 expect(durableSettings.browserProfiles).toContainEqual(importedProfile);
268 expect(getClientSettings().wordWrap).toBe(false);
269 expect(getClientSettings().browserProfiles).toContainEqual(importedProfile);
270 });
271
272 it("orders an awaited update after an older optimistic write", async () => {
273 let finishOldWrite!: () => void;
274 let durableSettings = DEFAULT_CLIENT_SETTINGS;
275 const oldWrite = new Promise<void>((resolve) => {
276 finishOldWrite = resolve;
277 });
278 const persist = vi
279 .fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
280 .mockImplementationOnce((settings) =>
281 oldWrite.then(() => {
282 durableSettings = settings;
283 }),
284 )
285 .mockImplementation(async (settings) => {
286 durableSettings = settings;
287 });
288 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
289
290 void persistClientSettingsPatch({ wordWrap: false }, persist);
291 const importedProfile = { id: "profile-import", name: "Imported", kind: "persistent" as const };
292 const registration = persistClientSettingsUpdate(
293 (current) => ({
294 ...current,
295 browserProfiles: [...current.browserProfiles, importedProfile],
296 }),
297 persist,
298 );
299 await Promise.resolve();
300 expect(persist).toHaveBeenCalledTimes(1);
301
302 finishOldWrite();
303 await registration;
304
305 expect(persist).toHaveBeenCalledTimes(2);
306 expect(durableSettings.wordWrap).toBe(false);
307 expect(durableSettings.browserProfiles).toContainEqual(importedProfile);
308 });
309
310 it("continues the queue after a rejected write", async () => {
311 const failure = new Error("disk full");
312 const persist = vi
313 .fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
314 .mockRejectedValueOnce(failure)
315 .mockResolvedValue(undefined);
316 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
317
318 await expect(
319 persistClientSettingsUpdate(
320 (current) => ({ ...current, timestampFormat: "12-hour" }),
321 persist,
322 ),
323 ).rejects.toBe(failure);
324 await expect(
325 persistClientSettingsUpdate((current) => ({ ...current, wordWrap: false }), persist),
326 ).resolves.toMatchObject({ wordWrap: false });
327 });
328});
329
330describe("resolveEnvironmentIdentificationMode", () => {
331 it("keeps identification hidden until client settings hydrate", () => {
332 expect(resolveEnvironmentIdentificationMode({ mode: "artwork", settingsHydrated: false })).toBe(
333 "none",
334 );
335 expect(resolveEnvironmentIdentificationMode({ mode: "pill", settingsHydrated: true })).toBe(
336 "pill",
337 );
338 });
339
340 it("uses a pill instead of artwork with a palette theme", () => {
341 expect(
342 resolveEnvironmentIdentificationMode({
343 mode: "artwork",
344 settingsHydrated: true,
345 paletteThemeActive: true,
346 }),
347 ).toBe("pill");
348 });
349
350 it("respects none with a palette theme", () => {
351 expect(
352 resolveEnvironmentIdentificationMode({
353 mode: "none",
354 settingsHydrated: true,
355 paletteThemeActive: true,
356 }),
357 ).toBe("none");
358 });
359
360 it("keeps artwork when the palette theme opts into it", () => {
361 expect(
362 resolveEnvironmentIdentificationMode({
363 mode: "artwork",
364 settingsHydrated: true,
365 paletteThemeActive: true,
366 paletteThemeAllowsArtwork: true,
367 }),
368 ).toBe("artwork");
369 });
370});
371
372describe("mergeEnvironmentSettings", () => {
373 it("combines the selected environment's server settings with client preferences", () => {
374 const serverSettings = {
375 ...DEFAULT_SERVER_SETTINGS,
376 providerInstances: {
377 [ProviderInstanceId.make("codex_remote")]: {
378 driver: ProviderDriverKind.make("codex"),
379 enabled: true,
380 },
381 },
382 };
383 const clientSettings = {
384 ...DEFAULT_CLIENT_SETTINGS,
385 favorites: [
386 {
387 provider: ProviderInstanceId.make("codex_remote"),
388 model: "gpt-5.4",
389 },
390 ],
391 };
392
393 const settings = mergeEnvironmentSettings(serverSettings, clientSettings);
394
395 expect(settings.providerInstances).toBe(serverSettings.providerInstances);
396 expect(settings.favorites).toBe(clientSettings.favorites);
397 });
398
399 it("keeps server settlement settings when legacy client data contains retired keys", () => {
400 const serverSettings = {
401 ...DEFAULT_SERVER_SETTINGS,
402 sidebarAutoSettleAfterDays: 14,
403 sidebarAutoSettleOnMerge: false,
404 };
405 const legacyClientSettings = {
406 ...DEFAULT_CLIENT_SETTINGS,
407 sidebarAutoSettleAfterDays: 1,
408 sidebarAutoSettleOnMerge: true,
409 };
410
411 const settings = mergeEnvironmentSettings(serverSettings, legacyClientSettings);
412
413 expect(settings.sidebarAutoSettleAfterDays).toBe(14);
414 expect(settings.sidebarAutoSettleOnMerge).toBe(false);
415 });
416});
417
418describe("onboarding completion persistence", () => {
419 it("keeps onboarding incomplete after a failed save and preserves preferences on retry", async () => {
420 const failure = new Error("disk full");
421 const persist = vi
422 .fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
423 .mockRejectedValueOnce(failure)
424 .mockResolvedValue(undefined);
425 const existingSettings = {
426 ...DEFAULT_CLIENT_SETTINGS,
427 timestampFormat: "12-hour" as const,
428 favorites: [
429 {
430 provider: ProviderInstanceId.make("codex_work"),
431 model: "gpt-5.6",
432 },
433 ],
434 };
435 __setClientSettingsForTests(existingSettings);
436 const onboardingCompletedAt = "2026-09-01T12:00:00.000Z";
437 const complete = (current: typeof DEFAULT_CLIENT_SETTINGS) => ({
438 ...current,
439 onboardingCompletedAt,
440 });
441
442 await expect(persistClientSettingsUpdate(complete, persist)).rejects.toBe(failure);
443 expect(getClientSettings()).toBe(existingSettings);
444 expect(getClientSettings().onboardingCompletedAt).toBeNull();
445
446 const completedSettings = { ...existingSettings, onboardingCompletedAt };
447 await expect(persistClientSettingsUpdate(complete, persist)).resolves.toEqual(
448 completedSettings,
449 );
450 expect(getClientSettings()).toEqual(completedSettings);
451 expect(persist).toHaveBeenLastCalledWith(completedSettings);
452 });
453});