Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3
4const mocks = vi.hoisted(() => {
5 const values = new Map<string, string>();
6 let preferencesJson: string | null = null;
7 let preferencesUpdatedAt = 0;
8 let loadPreferencesFails = false;
9 let savePreferencesFails = false;
10 return {
11 clear: () => {
12 values.clear();
13 preferencesJson = null;
14 preferencesUpdatedAt = 0;
15 loadPreferencesFails = false;
16 savePreferencesFails = false;
17 },
18 getStoredValue: (key: string) => values.get(key) ?? null,
19 getPreferencesJson: () => preferencesJson,
20 setPreferencesJson: (value: string, updatedAt: number) => {
21 preferencesJson = value;
22 preferencesUpdatedAt = updatedAt;
23 },
24 setDatabaseFailures: (load: boolean, save: boolean) => {
25 loadPreferencesFails = load;
26 savePreferencesFails = save;
27 },
28 getItemAsync: vi.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
29 setItemAsync: vi.fn((key: string, value: string) => {
30 values.set(key, value);
31 return Promise.resolve();
32 }),
33 deleteItemAsync: vi.fn((key: string) => {
34 values.delete(key);
35 return Promise.resolve();
36 }),
37 database: {
38 closeAsync: vi.fn(() => Promise.resolve()),
39 execAsync: vi.fn(() => Promise.resolve()),
40 withExclusiveTransactionAsync: vi.fn(
41 (run: (transaction: { execAsync: () => Promise<void> }) => Promise<void>) =>
42 run({ execAsync: () => Promise.resolve() }),
43 ),
44 getFirstAsync: vi.fn((sql: string) => {
45 if (sql.includes("PRAGMA user_version")) {
46 return Promise.resolve({ user_version: 1 });
47 }
48 if (loadPreferencesFails) {
49 return Promise.reject(new Error("database unavailable"));
50 }
51 return Promise.resolve(
52 preferencesJson === null
53 ? null
54 : { payload: preferencesJson, updatedAt: preferencesUpdatedAt },
55 );
56 }),
57 runAsync: vi.fn((_sql: string, payload?: unknown, updatedAt?: unknown) => {
58 if (savePreferencesFails) {
59 return Promise.reject(new Error("database unavailable"));
60 }
61 if (typeof payload === "string") {
62 preferencesJson = payload;
63 }
64 if (typeof updatedAt === "number") {
65 preferencesUpdatedAt = updatedAt;
66 }
67 return Promise.resolve();
68 }),
69 },
70 };
71});
72
73vi.mock("expo", () => ({
74 requireOptionalNativeModule: () => null,
75}));
76
77vi.mock("expo-secure-store", () => ({
78 deleteItemAsync: mocks.deleteItemAsync,
79 getItemAsync: mocks.getItemAsync,
80 setItemAsync: mocks.setItemAsync,
81}));
82
83vi.mock("expo-sqlite", () => ({
84 openDatabaseAsync: vi.fn(() => Promise.resolve(mocks.database)),
85}));
86
87vi.mock("expo-crypto", () => ({
88 getRandomBytes: vi.fn(() => new Uint8Array(16)),
89}));
90
91vi.mock("expo-constants", () => ({
92 default: { expoConfig: { extra: {} } },
93}));
94
95vi.mock("react-native", () => ({
96 AppState: { currentState: "active" },
97 Platform: {
98 OS: "ios",
99 },
100}));
101
102import {
103 loadPreferences,
104 loadSavedConnections,
105 saveConnection,
106 savePreferencesPatch,
107} from "../persistence/imperative";
108import { toStableSavedRemoteConnection } from "./connection";
109
110const managedConnection = {
111 environmentId: EnvironmentId.make("environment-1"),
112 environmentLabel: "Desktop",
113 pairingUrl: "https://desktop.example/",
114 displayUrl: "https://desktop.example/",
115 httpBaseUrl: "https://desktop.example/",
116 wsBaseUrl: "wss://desktop.example/",
117 bearerToken: null,
118 authenticationMethod: "dpop",
119 dpopAccessToken: "short-lived-token",
120 relayManaged: true,
121} as const;
122
123describe("mobile connection storage", () => {
124 beforeEach(() => {
125 mocks.clear();
126 vi.clearAllMocks();
127 });
128
129 it("persists relay-managed connections without their ephemeral access token", async () => {
130 await saveConnection(managedConnection);
131
132 const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];
133 expect(savedValue).toBeDefined();
134 expect(JSON.parse(savedValue ?? "")).toEqual({
135 connections: [toStableSavedRemoteConnection(managedConnection)],
136 });
137 });
138
139 it("loads relay-managed connection metadata without a cached access token", async () => {
140 await saveConnection(managedConnection);
141
142 await expect(loadSavedConnections()).resolves.toEqual([
143 toStableSavedRemoteConnection(managedConnection),
144 ]);
145 });
146
147 it("preserves secure-storage read failures with operation and key context", async () => {
148 const cause = new Error("keychain unavailable");
149 mocks.getItemAsync.mockRejectedValueOnce(cause);
150
151 await expect(loadSavedConnections()).rejects.toMatchObject({
152 _tag: "MobileSecureStorageError",
153 operation: "read",
154 key: "t3code.connections",
155 cause,
156 message: "Mobile secure storage operation read failed for key t3code.connections.",
157 });
158 });
159
160 it("logs structured decode failures before using the empty fallback", async () => {
161 await mocks.setItemAsync("t3code.connections", "{");
162 const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
163
164 await expect(loadSavedConnections()).resolves.toEqual([]);
165 expect(warn).toHaveBeenCalledWith(
166 "[mobile-storage] ignored invalid JSON",
167 expect.objectContaining({
168 _tag: "MobileStorageDecodeError",
169 key: "t3code.connections",
170 cause: expect.any(SyntaxError),
171 message: "Failed to decode mobile storage value for key t3code.connections.",
172 }),
173 );
174
175 warn.mockRestore();
176 });
177
178 it("loads legacy preferences when SQLite is unavailable", async () => {
179 mocks.setDatabaseFailures(true, true);
180 await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 17 }));
181
182 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 17 });
183 });
184
185 it("persists independent light and dark theme choices", async () => {
186 mocks.setPreferencesJson(
187 JSON.stringify({
188 themeId: "grove",
189 lightThemeId: "iris",
190 darkThemeId: "ocean",
191 themeMode: "system",
192 }),
193 10,
194 );
195
196 await expect(loadPreferences()).resolves.toEqual({
197 themeId: "grove",
198 lightThemeId: "iris",
199 darkThemeId: "ocean",
200 themeMode: "system",
201 });
202 });
203
204 it("persists Material You independently for each appearance", async () => {
205 const themes = { lightThemeId: "material-you", darkThemeId: "ocean" } as const;
206 await savePreferencesPatch(themes);
207 await expect(loadPreferences()).resolves.toEqual(themes);
208 await savePreferencesPatch({ lightThemeId: "t3-chat" });
209 await expect(loadPreferences()).resolves.toEqual({ ...themes, lightThemeId: "t3-chat" });
210 });
211
212 it.each([true, false])("drops the removed Android layout preference (%s)", async (enabled) => {
213 mocks.setPreferencesJson(
214 JSON.stringify({
215 materialYouStyleLayoutEnabled: enabled,
216 lightThemeId: "t3-chat",
217 }),
218 10,
219 );
220 await expect(loadPreferences()).resolves.toEqual({ lightThemeId: "t3-chat" });
221 });
222
223 it("drops the removed theme transition preference", async () => {
224 mocks.setPreferencesJson(JSON.stringify({ themeTransition: "circle-bottom-left" }), 10);
225
226 await expect(loadPreferences()).resolves.toEqual({});
227 });
228
229 it("falls back to secure storage when SQLite cannot save preferences", async () => {
230 mocks.setDatabaseFailures(true, true);
231 await expect(savePreferencesPatch({ baseFontSize: 19 })).resolves.toEqual({ baseFontSize: 19 });
232 const fallback = JSON.parse(mocks.getStoredValue("t3code.preferences.fallback") ?? "") as {
233 readonly payload: string;
234 readonly updatedAt: number;
235 };
236 expect(JSON.parse(fallback.payload)).toEqual({ baseFontSize: 19 });
237 expect(fallback.updatedAt).toEqual(expect.any(Number));
238 });
239
240 it("persists thread list shelf preferences", async () => {
241 await expect(
242 savePreferencesPatch({
243 threadListSettledShelfExpanded: false,
244 threadListSnoozedShelfExpanded: true,
245 threadListWorkingShelfExpanded: true,
246 workingShelfEnabled: true,
247 }),
248 ).resolves.toEqual({
249 threadListSettledShelfExpanded: false,
250 threadListSnoozedShelfExpanded: true,
251 threadListWorkingShelfExpanded: true,
252 workingShelfEnabled: true,
253 });
254
255 await expect(loadPreferences()).resolves.toEqual({
256 threadListSettledShelfExpanded: false,
257 threadListSnoozedShelfExpanded: true,
258 threadListWorkingShelfExpanded: true,
259 workingShelfEnabled: true,
260 });
261 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({
262 threadListSettledShelfExpanded: false,
263 threadListSnoozedShelfExpanded: true,
264 threadListWorkingShelfExpanded: true,
265 workingShelfEnabled: true,
266 });
267 });
268
269 it("drops legacy and invalid thread list shelf expansion preferences", async () => {
270 mocks.setPreferencesJson(
271 JSON.stringify({
272 baseFontSize: 17,
273 threadListV2SettledShelfExpanded: true,
274 threadListV2SnoozedShelfExpanded: true,
275 threadListSettledShelfExpanded: "false",
276 threadListSnoozedShelfExpanded: 1,
277 }),
278 10,
279 );
280
281 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 17 });
282 });
283
284 it("keeps valid list filters and drops malformed ones", async () => {
285 const threadListFilters = { environmentId: "environment-1", projectKey: null };
286 const pullRequestListFilters = {
287 environmentId: null,
288 controls: {
289 "": {
290 state: "all",
291 involvement: "reviewing",
292 filters: { labels: [["size:S"]] },
293 sort: "oldest",
294 },
295 },
296 };
297 mocks.setPreferencesJson(JSON.stringify({ threadListFilters, pullRequestListFilters }), 10);
298 await expect(loadPreferences()).resolves.toEqual({ threadListFilters, pullRequestListFilters });
299
300 mocks.setPreferencesJson(
301 JSON.stringify({
302 threadListFilters: { environmentId: 1, projectKey: null },
303 pullRequestListFilters: { environmentId: null, controls: { "": { sort: "newest" } } },
304 }),
305 11,
306 );
307 await expect(loadPreferences()).resolves.toEqual({});
308 });
309
310 it("reconciles fallback preferences after SQLite recovers", async () => {
311 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 15 }), 10);
312 await mocks.setItemAsync(
313 "t3code.preferences.fallback",
314 JSON.stringify({
315 payload: JSON.stringify({ baseFontSize: 19 }),
316 updatedAt: 20,
317 }),
318 );
319
320 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 19 });
321 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 19 });
322 expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
323 });
324
325 it("ignores a stale fallback when its previous deletion failed", async () => {
326 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
327 await mocks.setItemAsync(
328 "t3code.preferences.fallback",
329 JSON.stringify({
330 payload: JSON.stringify({ baseFontSize: 19 }),
331 updatedAt: 20,
332 }),
333 );
334
335 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
336 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
337 expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
338 });
339
340 it("ignores an invalid fallback even when it has a newer timestamp", async () => {
341 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
342 await mocks.setItemAsync(
343 "t3code.preferences.fallback",
344 JSON.stringify({ payload: "{", updatedAt: 40 }),
345 );
346 const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
347
348 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
349 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
350 expect(mocks.getStoredValue("t3code.preferences.fallback")).toBeNull();
351
352 warn.mockRestore();
353 });
354
355 it("keeps SQLite authoritative when stale legacy preferences remain", async () => {
356 mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 21 }), 30);
357 await mocks.setItemAsync("t3code.preferences", JSON.stringify({ baseFontSize: 19 }));
358
359 await expect(loadPreferences()).resolves.toEqual({ baseFontSize: 21 });
360 expect(JSON.parse(mocks.getPreferencesJson() ?? "")).toEqual({ baseFontSize: 21 });
361 });
362});