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