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