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