Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-preferences.ts

417 lines15.4 KB

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 /**
43 * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
44 * no client-settings sync, so the legacy grouped thread list is opted into
45 * per device. Deliberately a fresh key (was `threadListV2Enabled`, an
46 * opt-out): sanitizing drops the old key, so every device resets to the
47 * default flat list — see `resolveThreadListV2Enabled`.
48 */
49 readonly legacyThreadListEnabled?: boolean;
50 /** Device-local counterpart of desktop's `planModeEnabled` legacy flag. */
51 readonly planModeEnabled?: boolean;
52 /** Model favorites belong to this device, like the web client setting. */
53 readonly modelFavorites?: ReadonlyArray<{
54 readonly provider: ProviderInstanceId;
55 readonly model: string;
56 }>;
57 /** Fresh keys reset both shelves to collapsed when users update. */
58 readonly threadListSettledShelfExpanded?: boolean;
59 readonly threadListSnoozedShelfExpanded?: boolean;
61​
62export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
63 "MobilePreferencesLoadError",
64 { cause: Schema.Defect() },
65) {
66 override get message(): string {
67 return "Failed to load mobile preferences.";
68 }
70​
71export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
72 "MobilePreferencesSaveError",
73 { cause: Schema.Defect() },
74) {
75 override get message(): string {
76 return "Failed to save mobile preferences.";
77 }
79​
80interface PreferencesFallback {
81 readonly payload: string;
82 readonly updatedAt: number;
83 readonly preferences: Preferences;
85​
86export class MobilePreferencesStore extends Context.Service<
87 MobilePreferencesStore,
88 {
89 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
90 readonly savePatch: (
91 patch: Partial<Preferences>,
92 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
93 readonly update: (
94 transform: (current: Preferences) => Partial<Preferences>,
95 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
96 }
97>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
98​
99function sanitizePreferences(parsed: Preferences): Preferences {
100 const preferences: {
101 liveActivitiesEnabled?: boolean;
102 themeId?: MobileThemeId;
103 lightThemeId?: MobileThemeId;
104 darkThemeId?: MobileThemeId;
105 themeMode?: MobileThemeMode;
106 baseFontSize?: number;
107 terminalFontSize?: number | null;
108 markdownFontSize?: number;
109 codeFontSize?: number | null;
110 codeWordBreak?: boolean;
111 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
112 collapsedProjectGroups?: readonly string[];
113 composerEnterBehavior?: ComposerEnterBehavior;
114 followUpBehavior?: FollowUpBehavior;
115 projectGroupingEnabled?: boolean;
116 projectGroupingMode?: SidebarProjectGroupingMode;
117 legacyThreadListEnabled?: boolean;
118 planModeEnabled?: boolean;
119 modelFavorites?: Preferences["modelFavorites"];
120 threadListSettledShelfExpanded?: boolean;
121 threadListSnoozedShelfExpanded?: 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 (typeof parsed.projectGroupingEnabled === "boolean") {
180 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
181 }
182 if (
183 parsed.projectGroupingMode === "repository" ||
184 parsed.projectGroupingMode === "repository_path" ||
185 parsed.projectGroupingMode === "separate"
186 ) {
187 preferences.projectGroupingMode = parsed.projectGroupingMode;
188 }
189 if (typeof parsed.legacyThreadListEnabled === "boolean") {
190 preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
191 }
192 if (typeof parsed.planModeEnabled === "boolean") {
193 preferences.planModeEnabled = parsed.planModeEnabled;
194 }
195 if (Array.isArray(parsed.modelFavorites)) {
196 preferences.modelFavorites = parsed.modelFavorites.filter(
197 (favorite) =>
198 typeof favorite === "object" &&
199 favorite !== null &&
200 typeof favorite.provider === "string" &&
201 favorite.provider.length > 0 &&
202 typeof favorite.model === "string" &&
203 favorite.model.trim().length > 0,
204 );
205 }
206 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
207 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
208 }
209 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
210 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
211 }
212 return preferences;
214​
215export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
216 const database = yield* MobileDatabase.MobileDatabase;
217 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
218 const lock = yield* Semaphore.make(1);
219 const lastUpdatedAt = yield* Ref.make(0);
220​
221 const parsePayload = (raw: string | null): Preferences | null => {
222 if (raw === null || !raw.trim()) return null;
223 let parsed: unknown;
224 try {
225 parsed = JSON.parse(raw);
226 } catch (cause) {
227 console.warn(
228 "[mobile-storage] ignored invalid JSON",
229 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
230 );
231 return null;
232 }
233 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
234 ? (parsed as Preferences)
235 : null;
236 };
237​
238 const parseFallback = (raw: string | null): PreferencesFallback | null => {
239 if (raw === null || !raw.trim()) return null;
240 let parsed: unknown;
241 try {
242 parsed = JSON.parse(raw);
243 } catch (cause) {
244 console.warn(
245 "[mobile-storage] ignored invalid JSON",
246 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
247 );
248 return null;
249 }
250 if (
251 typeof parsed !== "object" ||
252 parsed === null ||
253 !("payload" in parsed) ||
254 typeof parsed.payload !== "string" ||
255 !("updatedAt" in parsed) ||
256 typeof parsed.updatedAt !== "number"
257 ) {
258 return null;
259 }
260 const preferences = parsePayload(parsed.payload);
261 return preferences === null
262 ? null
263 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
264 };
265​
266 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
267 key: string,
268 value: unknown,
269 ) {
270 return yield* Effect.try({
271 try: () => JSON.stringify(value),
272 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
273 });
274 });
275​
276 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
277 const next = Math.max(Date.now(), last + 1);
278 return [next, next] as const;
279 });
280​
281 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
282 payload: string,
283 updatedAt?: number,
284 ) {
285 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
286 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
287 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
288 if (databaseResult._tag === "Failure") {
289 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
290 Effect.annotateLogs({ cause: databaseResult.failure }),
291 );
292 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
293 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
294 return;
295 }
296 yield* secureStorage
297 .removeItem(PREFERENCES_FALLBACK_KEY)
298 .pipe(
299 Effect.catch((error) =>
300 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
301 Effect.annotateLogs({ error }),
302 ),
303 ),
304 );
305 });
306​
307 const loadUnlocked = Effect.gen(function* () {
308 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
309 const databaseAvailable = databaseResult._tag === "Success";
310 const storedJson = databaseAvailable
311 ? databaseResult.success
312 : Option.none<MobileDatabase.StoredPreferencesJson>();
313 if (databaseResult._tag === "Failure") {
314 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
315 Effect.annotateLogs({ cause: databaseResult.failure }),
316 );
317 }
318​
319 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
320 let fallbackJson: string | null = null;
321 if (fallbackResult._tag === "Success") {
322 fallbackJson = fallbackResult.success;
323 } else if (Option.isNone(storedJson)) {
324 return yield* fallbackResult.failure;
325 } else {
326 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
327 Effect.annotateLogs({ error: fallbackResult.failure }),
328 );
329 }
330​
331 const fallback = parseFallback(fallbackJson);
332 const storedPreferences = Option.isSome(storedJson)
333 ? parsePayload(storedJson.value.payload)
334 : null;
335 const fallbackIsNewer =
336 fallback !== null &&
337 (storedPreferences === null ||
338 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
339​
340 let parsed: Preferences | null = null;
341 if (fallbackIsNewer) {
342 parsed = fallback.preferences;
343 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
344 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
345 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
346 parsed = storedPreferences;
347 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
348 if (fallbackJson !== null) {
349 yield* secureStorage
350 .removeItem(PREFERENCES_FALLBACK_KEY)
351 .pipe(
352 Effect.catch((error) =>
353 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
354 Effect.annotateLogs({ error }),
355 ),
356 ),
357 );
358 }
359 }
360​
361 if (parsed === null) {
362 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
363 const legacyPreferences = parsePayload(legacyJson);
364 parsed = legacyPreferences;
365 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
366 yield* saveJson(legacyJson);
367 yield* secureStorage
368 .removeItem(PREFERENCES_KEY)
369 .pipe(
370 Effect.catch((error) =>
371 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
372 Effect.annotateLogs({ error }),
373 ),
374 ),
375 );
376 }
377 }
378​
379 return parsed === null ? {} : sanitizePreferences(parsed);
380 });
381​
382 const load = lock
383 .withPermits(1)(loadUnlocked)
384 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
385​
386 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
387 lock
388 .withPermits(1)(
389 Effect.gen(function* () {
390 const current = yield* loadUnlocked;
391 const patch = yield* Effect.try({
392 try: () => transform(current),
393 catch: (cause) => new MobilePreferencesSaveError({ cause }),
394 });
395 const next: Preferences = { ...current, ...patch };
396 const payload = yield* encode(PREFERENCES_KEY, next);
397 yield* saveJson(payload);
398 return next;
399 }),
400 )
401 .pipe(
402 Effect.mapError((cause) =>
403 cause instanceof MobilePreferencesSaveError
404 ? cause
405 : new MobilePreferencesSaveError({ cause }),
406 ),
407 ),
408 );
409​
410 return MobilePreferencesStore.of({
411 load,
412 update,
413 savePatch: (patch) => update(() => patch),
414 });
415});
416​
417export const layer = Layer.effect(MobilePreferencesStore, make());