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

mobile-preferences.ts

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