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

mobile-preferences.ts

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