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

mobile-preferences.ts

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