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

mobile-preferences.ts

389 lines14.1 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
9import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
10​
11import * as MobileDatabase from "./mobile-database";
12import * as MobileSecureStorage from "./mobile-secure-storage";
13import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
14​
15const PREFERENCES_KEY = "t3code.preferences";
16const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
17​
18export interface Preferences {
19 readonly liveActivitiesEnabled?: boolean;
20 readonly themeId?: MobileThemeId;
21 readonly lightThemeId?: MobileThemeId;
22 readonly darkThemeId?: MobileThemeId;
23 readonly themeMode?: MobileThemeMode;
24 readonly materialYouStyleLayoutEnabled?: boolean;
25 readonly baseFontSize?: number;
26 readonly terminalFontSize?: number | null;
27 readonly markdownFontSize?: number;
28 readonly codeFontSize?: number | null;
29 readonly codeWordBreak?: boolean;
30 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
31 readonly collapsedProjectGroups?: readonly string[];
32 /** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
33 readonly projectGroupingEnabled?: boolean;
34 readonly projectGroupingMode?: SidebarProjectGroupingMode;
35 /**
36 * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
37 * no client-settings sync, so the legacy grouped thread list is opted into
38 * per device. Deliberately a fresh key (was `threadListV2Enabled`, an
39 * opt-out): sanitizing drops the old key, so every device resets to the
40 * default flat list — see `resolveThreadListV2Enabled`.
41 */
42 readonly legacyThreadListEnabled?: boolean;
43 /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
44 readonly planModeEnabled?: boolean;
45 /** Fresh keys reset both shelves to collapsed when users update. */
46 readonly threadListSettledShelfExpanded?: boolean;
47 readonly threadListSnoozedShelfExpanded?: boolean;
49​
50export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
51 "MobilePreferencesLoadError",
52 { cause: Schema.Defect() },
53) {
54 override get message(): string {
55 return "Failed to load mobile preferences.";
56 }
58​
59export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
60 "MobilePreferencesSaveError",
61 { cause: Schema.Defect() },
62) {
63 override get message(): string {
64 return "Failed to save mobile preferences.";
65 }
67​
68interface PreferencesFallback {
69 readonly payload: string;
70 readonly updatedAt: number;
71 readonly preferences: Preferences;
73​
74export class MobilePreferencesStore extends Context.Service<
75 MobilePreferencesStore,
76 {
77 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
78 readonly savePatch: (
79 patch: Partial<Preferences>,
80 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
81 readonly update: (
82 transform: (current: Preferences) => Partial<Preferences>,
83 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
84 }
85>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
86​
87function sanitizePreferences(parsed: Preferences): Preferences {
88 const preferences: {
89 liveActivitiesEnabled?: boolean;
90 themeId?: MobileThemeId;
91 lightThemeId?: MobileThemeId;
92 darkThemeId?: MobileThemeId;
93 themeMode?: MobileThemeMode;
94 materialYouStyleLayoutEnabled?: boolean;
95 baseFontSize?: number;
96 terminalFontSize?: number | null;
97 markdownFontSize?: number;
98 codeFontSize?: number | null;
99 codeWordBreak?: boolean;
100 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
101 collapsedProjectGroups?: readonly string[];
102 projectGroupingEnabled?: boolean;
103 projectGroupingMode?: SidebarProjectGroupingMode;
104 legacyThreadListEnabled?: boolean;
105 planModeEnabled?: boolean;
106 threadListSettledShelfExpanded?: boolean;
107 threadListSnoozedShelfExpanded?: boolean;
108 } = {};
109​
110 if (typeof parsed.liveActivitiesEnabled === "boolean") {
111 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
112 }
113 if (
114 typeof parsed.themeId === "string" &&
115 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
116 ) {
117 preferences.themeId = parsed.themeId as MobileThemeId;
118 }
119 if (
120 typeof parsed.lightThemeId === "string" &&
121 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
122 ) {
123 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
124 }
125 if (
126 typeof parsed.darkThemeId === "string" &&
127 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
128 ) {
129 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
130 }
131 if (
132 parsed.themeMode === "system" ||
133 parsed.themeMode === "light" ||
134 parsed.themeMode === "dark"
135 ) {
136 preferences.themeMode = parsed.themeMode;
137 }
138 if (typeof parsed.materialYouStyleLayoutEnabled === "boolean") {
139 preferences.materialYouStyleLayoutEnabled = parsed.materialYouStyleLayoutEnabled;
140 }
141 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
142 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
143 preferences.terminalFontSize = parsed.terminalFontSize;
144 }
145 if (typeof parsed.markdownFontSize === "number") {
146 preferences.markdownFontSize = parsed.markdownFontSize;
147 }
148 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
149 preferences.codeFontSize = parsed.codeFontSize;
150 }
151 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
152 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
153 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
154 (account): account is string => typeof account === "string",
155 );
156 }
157 if (Array.isArray(parsed.collapsedProjectGroups)) {
158 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
159 (key): key is string => typeof key === "string",
160 );
161 }
162 if (typeof parsed.projectGroupingEnabled === "boolean") {
163 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
164 }
165 if (
166 parsed.projectGroupingMode === "repository" ||
167 parsed.projectGroupingMode === "repository_path" ||
168 parsed.projectGroupingMode === "separate"
169 ) {
170 preferences.projectGroupingMode = parsed.projectGroupingMode;
171 }
172 if (typeof parsed.legacyThreadListEnabled === "boolean") {
173 preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
174 }
175 if (typeof parsed.planModeEnabled === "boolean") {
176 preferences.planModeEnabled = parsed.planModeEnabled;
177 }
178 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
179 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
180 }
181 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
182 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
183 }
184 return preferences;
186​
187export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
188 const database = yield* MobileDatabase.MobileDatabase;
189 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
190 const lock = yield* Semaphore.make(1);
191 const lastUpdatedAt = yield* Ref.make(0);
192​
193 const parsePayload = (raw: string | null): Preferences | null => {
194 if (raw === null || !raw.trim()) return null;
195 let parsed: unknown;
196 try {
197 parsed = JSON.parse(raw);
198 } catch (cause) {
199 console.warn(
200 "[mobile-storage] ignored invalid JSON",
201 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
202 );
203 return null;
204 }
205 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
206 ? (parsed as Preferences)
207 : null;
208 };
209​
210 const parseFallback = (raw: string | null): PreferencesFallback | null => {
211 if (raw === null || !raw.trim()) return null;
212 let parsed: unknown;
213 try {
214 parsed = JSON.parse(raw);
215 } catch (cause) {
216 console.warn(
217 "[mobile-storage] ignored invalid JSON",
218 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
219 );
220 return null;
221 }
222 if (
223 typeof parsed !== "object" ||
224 parsed === null ||
225 !("payload" in parsed) ||
226 typeof parsed.payload !== "string" ||
227 !("updatedAt" in parsed) ||
228 typeof parsed.updatedAt !== "number"
229 ) {
230 return null;
231 }
232 const preferences = parsePayload(parsed.payload);
233 return preferences === null
234 ? null
235 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
236 };
237​
238 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
239 key: string,
240 value: unknown,
241 ) {
242 return yield* Effect.try({
243 try: () => JSON.stringify(value),
244 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
245 });
246 });
247​
248 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
249 const next = Math.max(Date.now(), last + 1);
250 return [next, next] as const;
251 });
252​
253 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
254 payload: string,
255 updatedAt?: number,
256 ) {
257 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
258 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
259 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
260 if (databaseResult._tag === "Failure") {
261 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
262 Effect.annotateLogs({ cause: databaseResult.failure }),
263 );
264 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
265 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
266 return;
267 }
268 yield* secureStorage
269 .removeItem(PREFERENCES_FALLBACK_KEY)
270 .pipe(
271 Effect.catch((error) =>
272 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
273 Effect.annotateLogs({ error }),
274 ),
275 ),
276 );
277 });
278​
279 const loadUnlocked = Effect.gen(function* () {
280 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
281 const databaseAvailable = databaseResult._tag === "Success";
282 const storedJson = databaseAvailable
283 ? databaseResult.success
284 : Option.none<MobileDatabase.StoredPreferencesJson>();
285 if (databaseResult._tag === "Failure") {
286 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
287 Effect.annotateLogs({ cause: databaseResult.failure }),
288 );
289 }
290​
291 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
292 let fallbackJson: string | null = null;
293 if (fallbackResult._tag === "Success") {
294 fallbackJson = fallbackResult.success;
295 } else if (Option.isNone(storedJson)) {
296 return yield* fallbackResult.failure;
297 } else {
298 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
299 Effect.annotateLogs({ error: fallbackResult.failure }),
300 );
301 }
302​
303 const fallback = parseFallback(fallbackJson);
304 const storedPreferences = Option.isSome(storedJson)
305 ? parsePayload(storedJson.value.payload)
306 : null;
307 const fallbackIsNewer =
308 fallback !== null &&
309 (storedPreferences === null ||
310 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
311​
312 let parsed: Preferences | null = null;
313 if (fallbackIsNewer) {
314 parsed = fallback.preferences;
315 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
316 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
317 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
318 parsed = storedPreferences;
319 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
320 if (fallbackJson !== null) {
321 yield* secureStorage
322 .removeItem(PREFERENCES_FALLBACK_KEY)
323 .pipe(
324 Effect.catch((error) =>
325 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
326 Effect.annotateLogs({ error }),
327 ),
328 ),
329 );
330 }
331 }
332​
333 if (parsed === null) {
334 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
335 const legacyPreferences = parsePayload(legacyJson);
336 parsed = legacyPreferences;
337 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
338 yield* saveJson(legacyJson);
339 yield* secureStorage
340 .removeItem(PREFERENCES_KEY)
341 .pipe(
342 Effect.catch((error) =>
343 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
344 Effect.annotateLogs({ error }),
345 ),
346 ),
347 );
348 }
349 }
350​
351 return parsed === null ? {} : sanitizePreferences(parsed);
352 });
353​
354 const load = lock
355 .withPermits(1)(loadUnlocked)
356 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
357​
358 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
359 lock
360 .withPermits(1)(
361 Effect.gen(function* () {
362 const current = yield* loadUnlocked;
363 const patch = yield* Effect.try({
364 try: () => transform(current),
365 catch: (cause) => new MobilePreferencesSaveError({ cause }),
366 });
367 const next: Preferences = { ...current, ...patch };
368 const payload = yield* encode(PREFERENCES_KEY, next);
369 yield* saveJson(payload);
370 return next;
371 }),
372 )
373 .pipe(
374 Effect.mapError((cause) =>
375 cause instanceof MobilePreferencesSaveError
376 ? cause
377 : new MobilePreferencesSaveError({ cause }),
378 ),
379 ),
380 );
381​
382 return MobilePreferencesStore.of({
383 load,
384 update,
385 savePatch: (patch) => update(() => patch),
386 });
387});
388​
389export const layer = Layer.effect(MobilePreferencesStore, make());