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

mobile-preferences.ts

395 lines14.4 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 { ProviderInstanceId, SidebarProjectGroupingMode } from "@t3tools/contracts";
9import type { ComposerEnterBehavior } from "../lib/composerEnterBehavior";
10import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
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 /** What the Return key does in the composer on a hardware keyboard. iOS only. */
32 readonly composerEnterBehavior?: ComposerEnterBehavior;
33 /** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
34 readonly projectGroupingEnabled?: boolean;
35 readonly projectGroupingMode?: SidebarProjectGroupingMode;
36 /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
37 readonly planModeEnabled?: boolean;
38 /** Model favorites belong to this device, like the web client setting. */
39 readonly modelFavorites?: ReadonlyArray<{
40 readonly provider: ProviderInstanceId;
41 readonly model: string;
42 }>;
43 /** Fresh keys reset both shelves to collapsed when users update. */
44 readonly threadListSettledShelfExpanded?: boolean;
45 readonly threadListSnoozedShelfExpanded?: boolean;
47​
48export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
49 "MobilePreferencesLoadError",
50 { cause: Schema.Defect() },
51) {
52 override get message(): string {
53 return "Failed to load mobile preferences.";
54 }
56​
57export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
58 "MobilePreferencesSaveError",
59 { cause: Schema.Defect() },
60) {
61 override get message(): string {
62 return "Failed to save mobile preferences.";
63 }
65​
66interface PreferencesFallback {
67 readonly payload: string;
68 readonly updatedAt: number;
69 readonly preferences: Preferences;
71​
72export class MobilePreferencesStore extends Context.Service<
73 MobilePreferencesStore,
74 {
75 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
76 readonly savePatch: (
77 patch: Partial<Preferences>,
78 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
79 readonly update: (
80 transform: (current: Preferences) => Partial<Preferences>,
81 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
82 }
83>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
84​
85function sanitizePreferences(parsed: Preferences): Preferences {
86 const preferences: {
87 liveActivitiesEnabled?: boolean;
88 themeId?: MobileThemeId;
89 lightThemeId?: MobileThemeId;
90 darkThemeId?: MobileThemeId;
91 themeMode?: MobileThemeMode;
92 baseFontSize?: number;
93 terminalFontSize?: number | null;
94 markdownFontSize?: number;
95 codeFontSize?: number | null;
96 codeWordBreak?: boolean;
97 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
98 collapsedProjectGroups?: readonly string[];
99 composerEnterBehavior?: ComposerEnterBehavior;
100 projectGroupingEnabled?: boolean;
101 projectGroupingMode?: SidebarProjectGroupingMode;
102 planModeEnabled?: boolean;
103 modelFavorites?: Preferences["modelFavorites"];
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 (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
158 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
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.planModeEnabled === "boolean") {
171 preferences.planModeEnabled = parsed.planModeEnabled;
172 }
173 if (Array.isArray(parsed.modelFavorites)) {
174 preferences.modelFavorites = parsed.modelFavorites.filter(
175 (favorite) =>
176 typeof favorite === "object" &&
177 favorite !== null &&
178 typeof favorite.provider === "string" &&
179 favorite.provider.length > 0 &&
180 typeof favorite.model === "string" &&
181 favorite.model.trim().length > 0,
182 );
183 }
184 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
185 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
186 }
187 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
188 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
189 }
190 return preferences;
192​
193export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
194 const database = yield* MobileDatabase.MobileDatabase;
195 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
196 const lock = yield* Semaphore.make(1);
197 const lastUpdatedAt = yield* Ref.make(0);
198​
199 const parsePayload = (raw: string | null): Preferences | 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_KEY, cause }),
208 );
209 return null;
210 }
211 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
212 ? (parsed as Preferences)
213 : null;
214 };
215​
216 const parseFallback = (raw: string | null): PreferencesFallback | null => {
217 if (raw === null || !raw.trim()) return null;
218 let parsed: unknown;
219 try {
220 parsed = JSON.parse(raw);
221 } catch (cause) {
222 console.warn(
223 "[mobile-storage] ignored invalid JSON",
224 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
225 );
226 return null;
227 }
228 if (
229 typeof parsed !== "object" ||
230 parsed === null ||
231 !("payload" in parsed) ||
232 typeof parsed.payload !== "string" ||
233 !("updatedAt" in parsed) ||
234 typeof parsed.updatedAt !== "number"
235 ) {
236 return null;
237 }
238 const preferences = parsePayload(parsed.payload);
239 return preferences === null
240 ? null
241 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
242 };
243​
244 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
245 key: string,
246 value: unknown,
247 ) {
248 return yield* Effect.try({
249 try: () => JSON.stringify(value),
250 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
251 });
252 });
253​
254 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
255 const next = Math.max(Date.now(), last + 1);
256 return [next, next] as const;
257 });
258​
259 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
260 payload: string,
261 updatedAt?: number,
262 ) {
263 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
264 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
265 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
266 if (databaseResult._tag === "Failure") {
267 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
268 Effect.annotateLogs({ cause: databaseResult.failure }),
269 );
270 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
271 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
272 return;
273 }
274 yield* secureStorage
275 .removeItem(PREFERENCES_FALLBACK_KEY)
276 .pipe(
277 Effect.catch((error) =>
278 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
279 Effect.annotateLogs({ error }),
280 ),
281 ),
282 );
283 });
284​
285 const loadUnlocked = Effect.gen(function* () {
286 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
287 const databaseAvailable = databaseResult._tag === "Success";
288 const storedJson = databaseAvailable
289 ? databaseResult.success
290 : Option.none<MobileDatabase.StoredPreferencesJson>();
291 if (databaseResult._tag === "Failure") {
292 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
293 Effect.annotateLogs({ cause: databaseResult.failure }),
294 );
295 }
296​
297 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
298 let fallbackJson: string | null = null;
299 if (fallbackResult._tag === "Success") {
300 fallbackJson = fallbackResult.success;
301 } else if (Option.isNone(storedJson)) {
302 return yield* fallbackResult.failure;
303 } else {
304 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
305 Effect.annotateLogs({ error: fallbackResult.failure }),
306 );
307 }
308​
309 const fallback = parseFallback(fallbackJson);
310 const storedPreferences = Option.isSome(storedJson)
311 ? parsePayload(storedJson.value.payload)
312 : null;
313 const fallbackIsNewer =
314 fallback !== null &&
315 (storedPreferences === null ||
316 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
317​
318 let parsed: Preferences | null = null;
319 if (fallbackIsNewer) {
320 parsed = fallback.preferences;
321 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
322 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
323 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
324 parsed = storedPreferences;
325 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
326 if (fallbackJson !== null) {
327 yield* secureStorage
328 .removeItem(PREFERENCES_FALLBACK_KEY)
329 .pipe(
330 Effect.catch((error) =>
331 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
332 Effect.annotateLogs({ error }),
333 ),
334 ),
335 );
336 }
337 }
338​
339 if (parsed === null) {
340 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
341 const legacyPreferences = parsePayload(legacyJson);
342 parsed = legacyPreferences;
343 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
344 yield* saveJson(legacyJson);
345 yield* secureStorage
346 .removeItem(PREFERENCES_KEY)
347 .pipe(
348 Effect.catch((error) =>
349 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
350 Effect.annotateLogs({ error }),
351 ),
352 ),
353 );
354 }
355 }
356​
357 return parsed === null ? {} : sanitizePreferences(parsed);
358 });
359​
360 const load = lock
361 .withPermits(1)(loadUnlocked)
362 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
363​
364 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
365 lock
366 .withPermits(1)(
367 Effect.gen(function* () {
368 const current = yield* loadUnlocked;
369 const patch = yield* Effect.try({
370 try: () => transform(current),
371 catch: (cause) => new MobilePreferencesSaveError({ cause }),
372 });
373 const next: Preferences = { ...current, ...patch };
374 const payload = yield* encode(PREFERENCES_KEY, next);
375 yield* saveJson(payload);
376 return next;
377 }),
378 )
379 .pipe(
380 Effect.mapError((cause) =>
381 cause instanceof MobilePreferencesSaveError
382 ? cause
383 : new MobilePreferencesSaveError({ cause }),
384 ),
385 ),
386 );
387​
388 return MobilePreferencesStore.of({
389 load,
390 update,
391 savePatch: (patch) => update(() => patch),
392 });
393});
394​
395export const layer = Layer.effect(MobilePreferencesStore, make());