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

mobile-preferences.ts

407 lines15.0 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 /**
37 * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
38 * no client-settings sync, so the legacy grouped thread list is opted into
39 * per device. Deliberately a fresh key (was `threadListV2Enabled`, an
40 * opt-out): sanitizing drops the old key, so every device resets to the
41 * default flat list — see `resolveThreadListV2Enabled`.
42 */
43 readonly legacyThreadListEnabled?: boolean;
44 /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
45 readonly planModeEnabled?: boolean;
46 /** Model favorites belong to this device, like the web client setting. */
47 readonly modelFavorites?: ReadonlyArray<{
48 readonly provider: ProviderInstanceId;
49 readonly model: string;
50 }>;
51 /** Fresh keys reset both shelves to collapsed when users update. */
52 readonly threadListSettledShelfExpanded?: boolean;
53 readonly threadListSnoozedShelfExpanded?: boolean;
55​
56export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
57 "MobilePreferencesLoadError",
58 { cause: Schema.Defect() },
59) {
60 override get message(): string {
61 return "Failed to load mobile preferences.";
62 }
64​
65export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
66 "MobilePreferencesSaveError",
67 { cause: Schema.Defect() },
68) {
69 override get message(): string {
70 return "Failed to save mobile preferences.";
71 }
73​
74interface PreferencesFallback {
75 readonly payload: string;
76 readonly updatedAt: number;
77 readonly preferences: Preferences;
79​
80export class MobilePreferencesStore extends Context.Service<
81 MobilePreferencesStore,
82 {
83 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
84 readonly savePatch: (
85 patch: Partial<Preferences>,
86 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
87 readonly update: (
88 transform: (current: Preferences) => Partial<Preferences>,
89 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
90 }
91>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
92​
93function sanitizePreferences(parsed: Preferences): Preferences {
94 const preferences: {
95 liveActivitiesEnabled?: boolean;
96 themeId?: MobileThemeId;
97 lightThemeId?: MobileThemeId;
98 darkThemeId?: MobileThemeId;
99 themeMode?: MobileThemeMode;
100 baseFontSize?: number;
101 terminalFontSize?: number | null;
102 markdownFontSize?: number;
103 codeFontSize?: number | null;
104 codeWordBreak?: boolean;
105 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
106 collapsedProjectGroups?: readonly string[];
107 composerEnterBehavior?: ComposerEnterBehavior;
108 projectGroupingEnabled?: boolean;
109 projectGroupingMode?: SidebarProjectGroupingMode;
110 legacyThreadListEnabled?: boolean;
111 planModeEnabled?: boolean;
112 modelFavorites?: Preferences["modelFavorites"];
113 threadListSettledShelfExpanded?: boolean;
114 threadListSnoozedShelfExpanded?: boolean;
115 } = {};
116​
117 if (typeof parsed.liveActivitiesEnabled === "boolean") {
118 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
119 }
120 if (
121 typeof parsed.themeId === "string" &&
122 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
123 ) {
124 preferences.themeId = parsed.themeId as MobileThemeId;
125 }
126 if (
127 typeof parsed.lightThemeId === "string" &&
128 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
129 ) {
130 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
131 }
132 if (
133 typeof parsed.darkThemeId === "string" &&
134 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
135 ) {
136 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
137 }
138 if (
139 parsed.themeMode === "system" ||
140 parsed.themeMode === "light" ||
141 parsed.themeMode === "dark"
142 ) {
143 preferences.themeMode = parsed.themeMode;
144 }
145 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
146 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
147 preferences.terminalFontSize = parsed.terminalFontSize;
148 }
149 if (typeof parsed.markdownFontSize === "number") {
150 preferences.markdownFontSize = parsed.markdownFontSize;
151 }
152 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
153 preferences.codeFontSize = parsed.codeFontSize;
154 }
155 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
156 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
157 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
158 (account): account is string => typeof account === "string",
159 );
160 }
161 if (Array.isArray(parsed.collapsedProjectGroups)) {
162 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
163 (key): key is string => typeof key === "string",
164 );
165 }
166 if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
167 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
168 }
169 if (typeof parsed.projectGroupingEnabled === "boolean") {
170 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
171 }
172 if (
173 parsed.projectGroupingMode === "repository" ||
174 parsed.projectGroupingMode === "repository_path" ||
175 parsed.projectGroupingMode === "separate"
176 ) {
177 preferences.projectGroupingMode = parsed.projectGroupingMode;
178 }
179 if (typeof parsed.legacyThreadListEnabled === "boolean") {
180 preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
181 }
182 if (typeof parsed.planModeEnabled === "boolean") {
183 preferences.planModeEnabled = parsed.planModeEnabled;
184 }
185 if (Array.isArray(parsed.modelFavorites)) {
186 preferences.modelFavorites = parsed.modelFavorites.filter(
187 (favorite) =>
188 typeof favorite === "object" &&
189 favorite !== null &&
190 typeof favorite.provider === "string" &&
191 favorite.provider.length > 0 &&
192 typeof favorite.model === "string" &&
193 favorite.model.trim().length > 0,
194 );
195 }
196 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
197 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
198 }
199 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
200 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
201 }
202 return preferences;
204​
205export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
206 const database = yield* MobileDatabase.MobileDatabase;
207 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
208 const lock = yield* Semaphore.make(1);
209 const lastUpdatedAt = yield* Ref.make(0);
210​
211 const parsePayload = (raw: string | null): Preferences | 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_KEY, cause }),
220 );
221 return null;
222 }
223 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
224 ? (parsed as Preferences)
225 : null;
226 };
227​
228 const parseFallback = (raw: string | null): PreferencesFallback | null => {
229 if (raw === null || !raw.trim()) return null;
230 let parsed: unknown;
231 try {
232 parsed = JSON.parse(raw);
233 } catch (cause) {
234 console.warn(
235 "[mobile-storage] ignored invalid JSON",
236 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
237 );
238 return null;
239 }
240 if (
241 typeof parsed !== "object" ||
242 parsed === null ||
243 !("payload" in parsed) ||
244 typeof parsed.payload !== "string" ||
245 !("updatedAt" in parsed) ||
246 typeof parsed.updatedAt !== "number"
247 ) {
248 return null;
249 }
250 const preferences = parsePayload(parsed.payload);
251 return preferences === null
252 ? null
253 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
254 };
255​
256 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
257 key: string,
258 value: unknown,
259 ) {
260 return yield* Effect.try({
261 try: () => JSON.stringify(value),
262 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
263 });
264 });
265​
266 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
267 const next = Math.max(Date.now(), last + 1);
268 return [next, next] as const;
269 });
270​
271 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
272 payload: string,
273 updatedAt?: number,
274 ) {
275 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
276 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
277 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
278 if (databaseResult._tag === "Failure") {
279 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
280 Effect.annotateLogs({ cause: databaseResult.failure }),
281 );
282 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
283 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
284 return;
285 }
286 yield* secureStorage
287 .removeItem(PREFERENCES_FALLBACK_KEY)
288 .pipe(
289 Effect.catch((error) =>
290 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
291 Effect.annotateLogs({ error }),
292 ),
293 ),
294 );
295 });
296​
297 const loadUnlocked = Effect.gen(function* () {
298 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
299 const databaseAvailable = databaseResult._tag === "Success";
300 const storedJson = databaseAvailable
301 ? databaseResult.success
302 : Option.none<MobileDatabase.StoredPreferencesJson>();
303 if (databaseResult._tag === "Failure") {
304 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
305 Effect.annotateLogs({ cause: databaseResult.failure }),
306 );
307 }
308​
309 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
310 let fallbackJson: string | null = null;
311 if (fallbackResult._tag === "Success") {
312 fallbackJson = fallbackResult.success;
313 } else if (Option.isNone(storedJson)) {
314 return yield* fallbackResult.failure;
315 } else {
316 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
317 Effect.annotateLogs({ error: fallbackResult.failure }),
318 );
319 }
320​
321 const fallback = parseFallback(fallbackJson);
322 const storedPreferences = Option.isSome(storedJson)
323 ? parsePayload(storedJson.value.payload)
324 : null;
325 const fallbackIsNewer =
326 fallback !== null &&
327 (storedPreferences === null ||
328 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
329​
330 let parsed: Preferences | null = null;
331 if (fallbackIsNewer) {
332 parsed = fallback.preferences;
333 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
334 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
335 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
336 parsed = storedPreferences;
337 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
338 if (fallbackJson !== null) {
339 yield* secureStorage
340 .removeItem(PREFERENCES_FALLBACK_KEY)
341 .pipe(
342 Effect.catch((error) =>
343 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
344 Effect.annotateLogs({ error }),
345 ),
346 ),
347 );
348 }
349 }
350​
351 if (parsed === null) {
352 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
353 const legacyPreferences = parsePayload(legacyJson);
354 parsed = legacyPreferences;
355 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
356 yield* saveJson(legacyJson);
357 yield* secureStorage
358 .removeItem(PREFERENCES_KEY)
359 .pipe(
360 Effect.catch((error) =>
361 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
362 Effect.annotateLogs({ error }),
363 ),
364 ),
365 );
366 }
367 }
368​
369 return parsed === null ? {} : sanitizePreferences(parsed);
370 });
371​
372 const load = lock
373 .withPermits(1)(loadUnlocked)
374 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
375​
376 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
377 lock
378 .withPermits(1)(
379 Effect.gen(function* () {
380 const current = yield* loadUnlocked;
381 const patch = yield* Effect.try({
382 try: () => transform(current),
383 catch: (cause) => new MobilePreferencesSaveError({ cause }),
384 });
385 const next: Preferences = { ...current, ...patch };
386 const payload = yield* encode(PREFERENCES_KEY, next);
387 yield* saveJson(payload);
388 return next;
389 }),
390 )
391 .pipe(
392 Effect.mapError((cause) =>
393 cause instanceof MobilePreferencesSaveError
394 ? cause
395 : new MobilePreferencesSaveError({ cause }),
396 ),
397 ),
398 );
399​
400 return MobilePreferencesStore.of({
401 load,
402 update,
403 savePatch: (patch) => update(() => patch),
404 });
405});
406​
407export const layer = Layer.effect(MobilePreferencesStore, make());