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

mobile-preferences.ts

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