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

mobile-preferences.ts

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