Open History to see the last commit
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 type { ComposerEnterBehavior } from "../lib/composerEnterBehavior";
10import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
11
12import * as MobileDatabase from "./mobile-database";
13import * as MobileSecureStorage from "./mobile-secure-storage";
14import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
15
16const PREFERENCES_KEY = "t3code.preferences";
17const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
18
19export interface Preferences {
20 readonly liveActivitiesEnabled?: boolean;
21 readonly themeId?: MobileThemeId;
22 readonly lightThemeId?: MobileThemeId;
23 readonly darkThemeId?: MobileThemeId;
24 readonly themeMode?: MobileThemeMode;
25 readonly materialYouStyleLayoutEnabled?: boolean;
26 readonly baseFontSize?: number;
27 readonly terminalFontSize?: number | null;
28 readonly markdownFontSize?: number;
29 readonly codeFontSize?: number | null;
30 readonly codeWordBreak?: boolean;
31 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
32 readonly collapsedProjectGroups?: readonly string[];
33 /** What the Return key does in the composer on a hardware keyboard. iOS only. */
34 readonly composerEnterBehavior?: ComposerEnterBehavior;
35 /** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
36 readonly projectGroupingEnabled?: boolean;
37 readonly projectGroupingMode?: SidebarProjectGroupingMode;
38 /**
39 * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
40 * no client-settings sync, so the legacy grouped thread list is opted into
41 * per device. Deliberately a fresh key (was `threadListV2Enabled`, an
42 * opt-out): sanitizing drops the old key, so every device resets to the
43 * default flat list — see `resolveThreadListV2Enabled`.
44 */
45 readonly legacyThreadListEnabled?: boolean;
46 /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
47 readonly planModeEnabled?: boolean;
48 /** Fresh keys reset both shelves to collapsed when users update. */
49 readonly threadListSettledShelfExpanded?: boolean;
50 readonly threadListSnoozedShelfExpanded?: boolean;
51}
52
53export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
54 "MobilePreferencesLoadError",
55 { cause: Schema.Defect() },
56) {
57 override get message(): string {
58 return "Failed to load mobile preferences.";
59 }
60}
61
62export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
63 "MobilePreferencesSaveError",
64 { cause: Schema.Defect() },
65) {
66 override get message(): string {
67 return "Failed to save mobile preferences.";
68 }
69}
70
71interface PreferencesFallback {
72 readonly payload: string;
73 readonly updatedAt: number;
74 readonly preferences: Preferences;
75}
76
77export class MobilePreferencesStore extends Context.Service<
78 MobilePreferencesStore,
79 {
80 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
81 readonly savePatch: (
82 patch: Partial<Preferences>,
83 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
84 readonly update: (
85 transform: (current: Preferences) => Partial<Preferences>,
86 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
87 }
88>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
89
90function sanitizePreferences(parsed: Preferences): Preferences {
91 const preferences: {
92 liveActivitiesEnabled?: boolean;
93 themeId?: MobileThemeId;
94 lightThemeId?: MobileThemeId;
95 darkThemeId?: MobileThemeId;
96 themeMode?: MobileThemeMode;
97 materialYouStyleLayoutEnabled?: boolean;
98 baseFontSize?: number;
99 terminalFontSize?: number | null;
100 markdownFontSize?: number;
101 codeFontSize?: number | null;
102 codeWordBreak?: boolean;
103 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
104 collapsedProjectGroups?: readonly string[];
105 composerEnterBehavior?: ComposerEnterBehavior;
106 projectGroupingEnabled?: boolean;
107 projectGroupingMode?: SidebarProjectGroupingMode;
108 legacyThreadListEnabled?: boolean;
109 planModeEnabled?: boolean;
110 threadListSettledShelfExpanded?: boolean;
111 threadListSnoozedShelfExpanded?: boolean;
112 } = {};
113
114 if (typeof parsed.liveActivitiesEnabled === "boolean") {
115 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
116 }
117 if (
118 typeof parsed.themeId === "string" &&
119 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
120 ) {
121 preferences.themeId = parsed.themeId as MobileThemeId;
122 }
123 if (
124 typeof parsed.lightThemeId === "string" &&
125 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
126 ) {
127 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
128 }
129 if (
130 typeof parsed.darkThemeId === "string" &&
131 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
132 ) {
133 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
134 }
135 if (
136 parsed.themeMode === "system" ||
137 parsed.themeMode === "light" ||
138 parsed.themeMode === "dark"
139 ) {
140 preferences.themeMode = parsed.themeMode;
141 }
142 if (typeof parsed.materialYouStyleLayoutEnabled === "boolean") {
143 preferences.materialYouStyleLayoutEnabled = parsed.materialYouStyleLayoutEnabled;
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 (typeof parsed.threadListSettledShelfExpanded === "boolean") {
186 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
187 }
188 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
189 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
190 }
191 return preferences;
192}
193
194export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
195 const database = yield* MobileDatabase.MobileDatabase;
196 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
197 const lock = yield* Semaphore.make(1);
198 const lastUpdatedAt = yield* Ref.make(0);
199
200 const parsePayload = (raw: string | null): Preferences | null => {
201 if (raw === null || !raw.trim()) return null;
202 let parsed: unknown;
203 try {
204 parsed = JSON.parse(raw);
205 } catch (cause) {
206 console.warn(
207 "[mobile-storage] ignored invalid JSON",
208 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
209 );
210 return null;
211 }
212 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
213 ? (parsed as Preferences)
214 : null;
215 };
216
217 const parseFallback = (raw: string | null): PreferencesFallback | null => {
218 if (raw === null || !raw.trim()) return null;
219 let parsed: unknown;
220 try {
221 parsed = JSON.parse(raw);
222 } catch (cause) {
223 console.warn(
224 "[mobile-storage] ignored invalid JSON",
225 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
226 );
227 return null;
228 }
229 if (
230 typeof parsed !== "object" ||
231 parsed === null ||
232 !("payload" in parsed) ||
233 typeof parsed.payload !== "string" ||
234 !("updatedAt" in parsed) ||
235 typeof parsed.updatedAt !== "number"
236 ) {
237 return null;
238 }
239 const preferences = parsePayload(parsed.payload);
240 return preferences === null
241 ? null
242 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
243 };
244
245 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
246 key: string,
247 value: unknown,
248 ) {
249 return yield* Effect.try({
250 try: () => JSON.stringify(value),
251 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
252 });
253 });
254
255 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
256 const next = Math.max(Date.now(), last + 1);
257 return [next, next] as const;
258 });
259
260 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
261 payload: string,
262 updatedAt?: number,
263 ) {
264 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
265 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
266 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
267 if (databaseResult._tag === "Failure") {
268 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
269 Effect.annotateLogs({ cause: databaseResult.failure }),
270 );
271 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
272 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
273 return;
274 }
275 yield* secureStorage
276 .removeItem(PREFERENCES_FALLBACK_KEY)
277 .pipe(
278 Effect.catch((error) =>
279 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
280 Effect.annotateLogs({ error }),
281 ),
282 ),
283 );
284 });
285
286 const loadUnlocked = Effect.gen(function* () {
287 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
288 const databaseAvailable = databaseResult._tag === "Success";
289 const storedJson = databaseAvailable
290 ? databaseResult.success
291 : Option.none<MobileDatabase.StoredPreferencesJson>();
292 if (databaseResult._tag === "Failure") {
293 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
294 Effect.annotateLogs({ cause: databaseResult.failure }),
295 );
296 }
297
298 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
299 let fallbackJson: string | null = null;
300 if (fallbackResult._tag === "Success") {
301 fallbackJson = fallbackResult.success;
302 } else if (Option.isNone(storedJson)) {
303 return yield* fallbackResult.failure;
304 } else {
305 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
306 Effect.annotateLogs({ error: fallbackResult.failure }),
307 );
308 }
309
310 const fallback = parseFallback(fallbackJson);
311 const storedPreferences = Option.isSome(storedJson)
312 ? parsePayload(storedJson.value.payload)
313 : null;
314 const fallbackIsNewer =
315 fallback !== null &&
316 (storedPreferences === null ||
317 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
318
319 let parsed: Preferences | null = null;
320 if (fallbackIsNewer) {
321 parsed = fallback.preferences;
322 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
323 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
324 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
325 parsed = storedPreferences;
326 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
327 if (fallbackJson !== null) {
328 yield* secureStorage
329 .removeItem(PREFERENCES_FALLBACK_KEY)
330 .pipe(
331 Effect.catch((error) =>
332 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
333 Effect.annotateLogs({ error }),
334 ),
335 ),
336 );
337 }
338 }
339
340 if (parsed === null) {
341 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
342 const legacyPreferences = parsePayload(legacyJson);
343 parsed = legacyPreferences;
344 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
345 yield* saveJson(legacyJson);
346 yield* secureStorage
347 .removeItem(PREFERENCES_KEY)
348 .pipe(
349 Effect.catch((error) =>
350 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
351 Effect.annotateLogs({ error }),
352 ),
353 ),
354 );
355 }
356 }
357
358 return parsed === null ? {} : sanitizePreferences(parsed);
359 });
360
361 const load = lock
362 .withPermits(1)(loadUnlocked)
363 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
364
365 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
366 lock
367 .withPermits(1)(
368 Effect.gen(function* () {
369 const current = yield* loadUnlocked;
370 const patch = yield* Effect.try({
371 try: () => transform(current),
372 catch: (cause) => new MobilePreferencesSaveError({ cause }),
373 });
374 const next: Preferences = { ...current, ...patch };
375 const payload = yield* encode(PREFERENCES_KEY, next);
376 yield* saveJson(payload);
377 return next;
378 }),
379 )
380 .pipe(
381 Effect.mapError((cause) =>
382 cause instanceof MobilePreferencesSaveError
383 ? cause
384 : new MobilePreferencesSaveError({ cause }),
385 ),
386 ),
387 );
388
389 return MobilePreferencesStore.of({
390 load,
391 update,
392 savePatch: (patch) => update(() => patch),
393 });
394});
395
396export const layer = Layer.effect(MobilePreferencesStore, make());