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

mobile-preferences.ts

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