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