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

mobile-preferences.ts

702 lines27.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 { SavedViewIdentity } from "@t3tools/client-runtime/saved-views";
9import {
10 HostPressureDismissal,
11 type HostPressureDismissals,
12} from "@t3tools/client-runtime/host-pressure-dismissals";
13import {
14 EnvironmentId,
15 IssueInvolvement,
16 IssueListSort,
17 IssueListState,
18 PullRequestInvolvement,
19 PullRequestListFilters,
20 PullRequestListState,
21 type ProviderInstanceId,
22 PullRequestMergeMethod,
23 type SidebarProjectGroupingMode,
24} from "@t3tools/contracts";
25import { ToolCallVisibility } from "@t3tools/contracts/settings";
26import type { AndroidNavigationStyle } from "../lib/androidNavigationStyle";
27import type { MobileFontId, MobileMonoFontId } from "../lib/fontFamilies";
28import type { ComposerEnterBehavior } from "../lib/composerEnterBehavior";
29import type { FollowUpBehavior } from "../lib/followUpBehavior";
30import { isMicrophoneKind, type MicrophoneEntry } from "../lib/microphonePriority";
31import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
32import * as MobileDatabase from "./mobile-database";
33import * as MobileSecureStorage from "./mobile-secure-storage";
34import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
35​
36const PREFERENCES_KEY = "t3code.preferences";
37const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
38const encodeJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
39​
40export const PullRequestListControls = Schema.Struct({
41 state: PullRequestListState,
42 involvement: PullRequestInvolvement,
43 filters: PullRequestListFilters,
44 projectId: Schema.optional(Schema.String),
45 projectEnvironmentId: Schema.optional(Schema.String),
46 sort: Schema.Literals(["updated", "created", "oldest"]),
47});
48export type PullRequestListControls = typeof PullRequestListControls.Type;
49​
50export const PullRequestSavedView = Schema.Struct({
51 ...SavedViewIdentity.fields,
52 environmentId: Schema.NullOr(Schema.String),
53 controls: PullRequestListControls,
54 query: Schema.String,
55});
56export type PullRequestSavedView = typeof PullRequestSavedView.Type;
57const isPullRequestSavedView = Schema.is(PullRequestSavedView);
58​
59export const IssueSavedView = Schema.Struct({
60 ...SavedViewIdentity.fields,
61 query: Schema.String,
62 state: IssueListState,
63 involvement: IssueInvolvement,
64 sort: IssueListSort,
65 labels: Schema.Array(Schema.String),
66 assignee: Schema.NullOr(
67 Schema.Struct({ login: Schema.String, name: Schema.NullOr(Schema.String) }),
68 ),
69});
70export type IssueSavedView = typeof IssueSavedView.Type;
71const isIssueSavedView = Schema.is(IssueSavedView);
72const isHostPressureDismissal = Schema.is(HostPressureDismissal);
73​
74const ThreadListFilters = Schema.Struct({
75 environmentId: Schema.NullOr(EnvironmentId),
76 projectKey: Schema.NullOr(Schema.String),
77});
78export type ThreadListFilters = typeof ThreadListFilters.Type;
79​
80const PullRequestListPreferences = Schema.Struct({
81 environmentId: Schema.NullOr(Schema.String),
82 controls: Schema.Record(Schema.String, PullRequestListControls),
83});
84export type PullRequestListPreferences = typeof PullRequestListPreferences.Type;
85​
86/**
87 * The page each workspace tab last showed, reopened when the tab returns with columns. `key` is
88 * that page's route key: reopening under the same key reuses the screen a tab kept mounted.
89 */
90const WorkspaceSelections = Schema.Struct({
91 threads: Schema.optional(
92 Schema.Struct({
93 environmentId: Schema.String,
94 threadId: Schema.String,
95 key: Schema.optional(Schema.String),
96 }),
97 ),
98 pullRequests: Schema.optional(
99 Schema.Struct({
100 environmentId: Schema.String,
101 projectId: Schema.String,
102 repository: Schema.String,
103 number: Schema.Number,
104 host: Schema.optional(Schema.String),
105 key: Schema.optional(Schema.String),
106 }),
107 ),
108 issues: Schema.optional(
109 Schema.Struct({
110 environmentId: Schema.String,
111 projectId: Schema.String,
112 tracker: Schema.String,
113 host: Schema.optional(Schema.String),
114 scope: Schema.String,
115 issueKey: Schema.String,
116 key: Schema.optional(Schema.String),
117 }),
118 ),
119 settings: Schema.optional(Schema.String),
120 settingsKey: Schema.optional(Schema.String),
121 /** A draft the threads tab showed after its last chat; only meaningful in its session. */
122 threadsDraft: Schema.optional(Schema.Struct({ key: Schema.String, params: Schema.Unknown })),
123});
124export type WorkspaceSelections = typeof WorkspaceSelections.Type;
125​
126const PullRequestActivityVisibility = Schema.Struct({
127 bots: Schema.Boolean,
128 resolved: Schema.Boolean,
129});
130export type PullRequestActivityVisibility = typeof PullRequestActivityVisibility.Type;
131​
132const isThreadListFilters = Schema.is(ThreadListFilters);
133const isPullRequestActivityVisibility = Schema.is(PullRequestActivityVisibility);
134const isWorkspaceSelections = Schema.is(WorkspaceSelections);
135const isPullRequestListPreferences = Schema.is(PullRequestListPreferences);
136const ThreadProject = Schema.Struct({
137 environmentId: Schema.NonEmptyString,
138 projectId: Schema.NonEmptyString,
139});
140const isThreadProject = Schema.is(ThreadProject);
141​
142export interface Preferences {
143 readonly navigationTabOrder?: readonly string[];
144 readonly hiddenNavigationTabs?: readonly string[];
145 /** Whether pull requests or issues last held the tab bar slot they share. */
146 readonly sharedSlotTab?: "pullRequests" | "issues";
147 readonly pullRequestHideTestFiles?: boolean;
148 readonly pullRequestHideViewedFiles?: boolean;
149 /** Which hidden-by-default PR activity is shown: bot comments and resolved or dismissed ones. */
150 readonly pullRequestActivityVisibility?: PullRequestActivityVisibility;
151 readonly pullRequestMergeMethod?: PullRequestMergeMethod;
152 readonly liveActivitiesEnabled?: boolean;
153 readonly themeId?: MobileThemeId;
154 readonly lightThemeId?: MobileThemeId;
155 readonly darkThemeId?: MobileThemeId;
156 readonly themeMode?: MobileThemeMode;
157 readonly androidNavigationStyle?: AndroidNavigationStyle;
158 readonly baseFontSize?: number;
159 readonly fontId?: MobileFontId;
160 readonly monoFontId?: MobileMonoFontId;
161 readonly terminalFontSize?: number | null;
162 readonly markdownFontSize?: number;
163 readonly codeFontSize?: number | null;
164 readonly codeWordBreak?: boolean;
165 readonly mathRenderingEnabled?: boolean;
166 /** Unset means on: crash reports are sent unless the user turns them off. */
167 readonly crashReportsEnabled?: boolean;
168 /** Unset means on: connection traces are sent unless the user turns them off. */
169 readonly connectionTracesEnabled?: boolean;
170 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
171 readonly collapsedProjectGroups?: readonly string[];
172 readonly dismissedDatabaseStorageNotices?: readonly string[];
173 /** Per host, when the newest T3 Connect device this phone has announced first signed in. */
174 readonly connectDevicesSeenThrough?: Readonly<Record<string, number>>;
175 readonly hostPressureDismissals?: HostPressureDismissals;
176 /** Hardware-keyboard Return behavior in the composer. */
177 readonly composerEnterBehavior?: ComposerEnterBehavior;
178 readonly followUpBehavior?: FollowUpBehavior;
179 /** The client `language` setting: a locale code or "system". Unset means English. */
180 readonly language?: string;
181 readonly microphones?: ReadonlyArray<MicrophoneEntry>;
182 readonly projectGroupingEnabled?: boolean;
183 readonly projectGroupingMode?: SidebarProjectGroupingMode;
184 readonly toolCallVisibility?: ToolCallVisibility;
185 /** Thread list card layout, stored like the web client's `sidebarRowLayout`. */
186 readonly threadRowLayout?: Readonly<Record<string, ReadonlyArray<string>>>;
187 readonly workingShelfEnabled?: boolean;
188 /** The kind of question the Workflows tab's Needs you list was last narrowed to. */
189 readonly workflowQuestionKind?: string;
190 readonly useLastProjectForNewThreads?: boolean;
191 readonly lastThreadProject?: typeof ThreadProject.Type;
192 readonly modelFavorites?: ReadonlyArray<{
193 readonly provider: ProviderInstanceId;
194 readonly model: string;
195 }>;
196 readonly threadListSettledShelfExpanded?: boolean;
197 readonly threadListSnoozedShelfExpanded?: boolean;
198 readonly threadListWorkingShelfExpanded?: boolean;
199 readonly threadListFilters?: ThreadListFilters;
200 readonly pullRequestListFilters?: PullRequestListPreferences;
201 readonly workspaceSelections?: WorkspaceSelections;
202 readonly pullRequestSavedViews?: ReadonlyArray<PullRequestSavedView>;
203 readonly issueSavedViews?: ReadonlyArray<IssueSavedView>;
205​
206export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
207 "MobilePreferencesLoadError",
208 { cause: Schema.Defect() },
209) {
210 override get message(): string {
211 return "Failed to load mobile preferences.";
212 }
214​
215export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
216 "MobilePreferencesSaveError",
217 { cause: Schema.Defect() },
218) {
219 override get message(): string {
220 return "Failed to save mobile preferences.";
221 }
223​
224const isMobilePreferencesSaveError = Schema.is(MobilePreferencesSaveError);
225​
226interface PreferencesFallback {
227 readonly payload: string;
228 readonly updatedAt: number;
229 readonly preferences: Preferences;
231​
232export class MobilePreferencesStore extends Context.Service<
233 MobilePreferencesStore,
234 {
235 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
236 readonly savePatch: (
237 patch: Partial<Preferences>,
238 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
239 readonly update: (
240 transform: (current: Preferences) => Partial<Preferences>,
241 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
242 }
243>()("@t3tools/mobile/persistence/mobile-preferences/MobilePreferencesStore") {}
244​
245const isToolCallVisibility = Schema.is(ToolCallVisibility);
246const isPullRequestMergeMethod = Schema.is(PullRequestMergeMethod);
247​
248function sanitizePreferences(parsed: Preferences): Preferences {
249 const preferences: {
250 navigationTabOrder?: readonly string[];
251 hiddenNavigationTabs?: readonly string[];
252 sharedSlotTab?: "pullRequests" | "issues";
253 pullRequestHideTestFiles?: boolean;
254 pullRequestHideViewedFiles?: boolean;
255 pullRequestActivityVisibility?: PullRequestActivityVisibility;
256 pullRequestMergeMethod?: PullRequestMergeMethod;
257 liveActivitiesEnabled?: boolean;
258 themeId?: MobileThemeId;
259 lightThemeId?: MobileThemeId;
260 darkThemeId?: MobileThemeId;
261 themeMode?: MobileThemeMode;
262 androidNavigationStyle?: AndroidNavigationStyle;
263 baseFontSize?: number;
264 fontId?: MobileFontId;
265 monoFontId?: MobileMonoFontId;
266 terminalFontSize?: number | null;
267 markdownFontSize?: number;
268 codeFontSize?: number | null;
269 codeWordBreak?: boolean;
270 mathRenderingEnabled?: boolean;
271 crashReportsEnabled?: boolean;
272 connectionTracesEnabled?: boolean;
273 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
274 collapsedProjectGroups?: readonly string[];
275 dismissedDatabaseStorageNotices?: readonly string[];
276 connectDevicesSeenThrough?: Readonly<Record<string, number>>;
277 hostPressureDismissals?: HostPressureDismissals;
278 composerEnterBehavior?: ComposerEnterBehavior;
279 followUpBehavior?: FollowUpBehavior;
280 language?: string;
281 microphones?: ReadonlyArray<MicrophoneEntry>;
282 projectGroupingEnabled?: boolean;
283 projectGroupingMode?: SidebarProjectGroupingMode;
284 toolCallVisibility?: ToolCallVisibility;
285 threadRowLayout?: Readonly<Record<string, ReadonlyArray<string>>>;
286 workingShelfEnabled?: boolean;
287 workflowQuestionKind?: string;
288 useLastProjectForNewThreads?: boolean;
289 lastThreadProject?: typeof ThreadProject.Type;
290 modelFavorites?: Preferences["modelFavorites"];
291 threadListSettledShelfExpanded?: boolean;
292 threadListSnoozedShelfExpanded?: boolean;
293 threadListWorkingShelfExpanded?: boolean;
294 threadListFilters?: ThreadListFilters;
295 pullRequestListFilters?: PullRequestListPreferences;
296 workspaceSelections?: WorkspaceSelections;
297 pullRequestSavedViews?: ReadonlyArray<PullRequestSavedView>;
298 issueSavedViews?: ReadonlyArray<IssueSavedView>;
299 } = {};
300​
301 if (Array.isArray(parsed.hiddenNavigationTabs)) {
302 preferences.hiddenNavigationTabs = parsed.hiddenNavigationTabs.filter(
303 (tab): tab is string => typeof tab === "string",
304 );
305 }
306​
307 if (Array.isArray(parsed.navigationTabOrder)) {
308 preferences.navigationTabOrder = parsed.navigationTabOrder.filter(
309 (tab): tab is string => typeof tab === "string",
310 );
311 }
312​
313 if (parsed.sharedSlotTab === "pullRequests" || parsed.sharedSlotTab === "issues") {
314 preferences.sharedSlotTab = parsed.sharedSlotTab;
315 }
316​
317 if (typeof parsed.pullRequestHideTestFiles === "boolean") {
318 preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles;
319 }
320​
321 if (typeof parsed.pullRequestHideViewedFiles === "boolean") {
322 preferences.pullRequestHideViewedFiles = parsed.pullRequestHideViewedFiles;
323 }
324​
325 if (isPullRequestActivityVisibility(parsed.pullRequestActivityVisibility)) {
326 preferences.pullRequestActivityVisibility = parsed.pullRequestActivityVisibility;
327 }
328​
329 if (isPullRequestMergeMethod(parsed.pullRequestMergeMethod)) {
330 preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod;
331 }
332​
333 if (typeof parsed.liveActivitiesEnabled === "boolean") {
334 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
335 }
336 if (
337 typeof parsed.themeId === "string" &&
338 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
339 ) {
340 preferences.themeId = parsed.themeId as MobileThemeId;
341 }
342 if (
343 typeof parsed.lightThemeId === "string" &&
344 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
345 ) {
346 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
347 }
348 if (
349 typeof parsed.darkThemeId === "string" &&
350 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
351 ) {
352 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
353 }
354 if (
355 parsed.themeMode === "system" ||
356 parsed.themeMode === "light" ||
357 parsed.themeMode === "dark"
358 ) {
359 preferences.themeMode = parsed.themeMode;
360 }
361 if (parsed.androidNavigationStyle === "one-ui" || parsed.androidNavigationStyle === "material") {
362 preferences.androidNavigationStyle = parsed.androidNavigationStyle;
363 }
364 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
365 if (parsed.fontId === "system" || parsed.fontId === "dm-sans") preferences.fontId = parsed.fontId;
366 if (parsed.monoFontId === "system" || parsed.monoFontId === "meslo") {
367 preferences.monoFontId = parsed.monoFontId;
368 }
369 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
370 preferences.terminalFontSize = parsed.terminalFontSize;
371 }
372 if (typeof parsed.markdownFontSize === "number") {
373 preferences.markdownFontSize = parsed.markdownFontSize;
374 }
375 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
376 preferences.codeFontSize = parsed.codeFontSize;
377 }
378 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
379 if (typeof parsed.mathRenderingEnabled === "boolean")
380 preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
381 if (typeof parsed.crashReportsEnabled === "boolean") {
382 preferences.crashReportsEnabled = parsed.crashReportsEnabled;
383 }
384 if (typeof parsed.connectionTracesEnabled === "boolean") {
385 preferences.connectionTracesEnabled = parsed.connectionTracesEnabled;
386 }
387 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
388 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
389 (account): account is string => typeof account === "string",
390 );
391 }
392 if (Array.isArray(parsed.collapsedProjectGroups)) {
393 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
394 (key): key is string => typeof key === "string",
395 );
396 }
397 if (Array.isArray(parsed.dismissedDatabaseStorageNotices)) {
398 preferences.dismissedDatabaseStorageNotices = parsed.dismissedDatabaseStorageNotices.filter(
399 (value): value is string => typeof value === "string",
400 );
401 }
402 if (
403 typeof parsed.connectDevicesSeenThrough === "object" &&
404 parsed.connectDevicesSeenThrough !== null
405 ) {
406 preferences.connectDevicesSeenThrough = Object.fromEntries(
407 Object.entries(parsed.connectDevicesSeenThrough).filter(
408 (entry): entry is [string, number] => typeof entry[1] === "number",
409 ),
410 );
411 }
412 if (Array.isArray(parsed.hostPressureDismissals)) {
413 preferences.hostPressureDismissals =
414 parsed.hostPressureDismissals.filter(isHostPressureDismissal);
415 }
416 if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
417 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
418 }
419 if (parsed.followUpBehavior === "queue" || parsed.followUpBehavior === "steer") {
420 preferences.followUpBehavior = parsed.followUpBehavior;
421 }
422 if (typeof parsed.language === "string") preferences.language = parsed.language;
423 if (Array.isArray(parsed.microphones)) {
424 preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => {
425 if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return [];
426 if (!("uid" in entry)) return [{ kind: entry.kind }];
427 return typeof entry.uid === "string" && typeof entry.name === "string"
428 ? [{ kind: entry.kind, uid: entry.uid, name: entry.name }]
429 : [];
430 });
431 }
432 if (typeof parsed.projectGroupingEnabled === "boolean") {
433 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
434 }
435 if (
436 parsed.projectGroupingMode === "repository" ||
437 parsed.projectGroupingMode === "repository_path" ||
438 parsed.projectGroupingMode === "separate"
439 ) {
440 preferences.projectGroupingMode = parsed.projectGroupingMode;
441 }
442 if (isToolCallVisibility(parsed.toolCallVisibility)) {
443 preferences.toolCallVisibility = parsed.toolCallVisibility;
444 }
445 if (typeof parsed.threadRowLayout === "object" && parsed.threadRowLayout !== null) {
446 preferences.threadRowLayout = Object.fromEntries(
447 Object.entries(parsed.threadRowLayout).flatMap(([line, ids]) =>
448 Array.isArray(ids) ? [[line, ids.filter((id) => typeof id === "string")]] : [],
449 ),
450 );
451 }
452 if (typeof parsed.workingShelfEnabled === "boolean") {
453 preferences.workingShelfEnabled = parsed.workingShelfEnabled;
454 }
455 if (typeof parsed.workflowQuestionKind === "string") {
456 preferences.workflowQuestionKind = parsed.workflowQuestionKind;
457 }
458 if (typeof parsed.useLastProjectForNewThreads === "boolean") {
459 preferences.useLastProjectForNewThreads = parsed.useLastProjectForNewThreads;
460 }
461 if (isThreadProject(parsed.lastThreadProject)) {
462 preferences.lastThreadProject = parsed.lastThreadProject;
463 }
464 if (Array.isArray(parsed.modelFavorites)) {
465 preferences.modelFavorites = parsed.modelFavorites.filter(
466 (favorite) =>
467 typeof favorite === "object" &&
468 favorite !== null &&
469 typeof favorite.provider === "string" &&
470 favorite.provider.length > 0 &&
471 typeof favorite.model === "string" &&
472 favorite.model.trim().length > 0,
473 );
474 }
475 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
476 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
477 }
478 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
479 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
480 }
481 if (typeof parsed.threadListWorkingShelfExpanded === "boolean") {
482 preferences.threadListWorkingShelfExpanded = parsed.threadListWorkingShelfExpanded;
483 }
484 if (isThreadListFilters(parsed.threadListFilters)) {
485 preferences.threadListFilters = parsed.threadListFilters;
486 }
487 if (isPullRequestListPreferences(parsed.pullRequestListFilters)) {
488 preferences.pullRequestListFilters = parsed.pullRequestListFilters;
489 }
490 if (isWorkspaceSelections(parsed.workspaceSelections)) {
491 preferences.workspaceSelections = parsed.workspaceSelections;
492 }
493 if (Array.isArray(parsed.pullRequestSavedViews)) {
494 preferences.pullRequestSavedViews = parsed.pullRequestSavedViews.filter(isPullRequestSavedView);
495 }
496 if (Array.isArray(parsed.issueSavedViews)) {
497 preferences.issueSavedViews = parsed.issueSavedViews.filter(isIssueSavedView);
498 }
499 return preferences;
501​
502const make = Effect.fn("MobilePreferencesStore.make")(function* () {
503 const database = yield* MobileDatabase.MobileDatabase;
504 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
505 const lock = yield* Semaphore.make(1);
506 const lastUpdatedAt = yield* Ref.make(0);
507​
508 const parsePayload = (raw: string | null): Preferences | null => {
509 if (raw === null || !raw.trim()) return null;
510 let parsed: unknown;
511 try {
512 parsed = JSON.parse(raw);
513 } catch (cause) {
514 console.warn(
515 "[mobile-storage] ignored invalid JSON",
516 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
517 );
518 return null;
519 }
520 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
521 ? (parsed as Preferences)
522 : null;
523 };
524​
525 const parseFallback = (raw: string | null): PreferencesFallback | null => {
526 if (raw === null || !raw.trim()) return null;
527 let parsed: unknown;
528 try {
529 parsed = JSON.parse(raw);
530 } catch (cause) {
531 console.warn(
532 "[mobile-storage] ignored invalid JSON",
533 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
534 );
535 return null;
536 }
537 if (
538 typeof parsed !== "object" ||
539 parsed === null ||
540 !("payload" in parsed) ||
541 typeof parsed.payload !== "string" ||
542 !("updatedAt" in parsed) ||
543 typeof parsed.updatedAt !== "number"
544 ) {
545 return null;
546 }
547 const preferences = parsePayload(parsed.payload);
548 return preferences === null
549 ? null
550 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
551 };
552​
553 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
554 key: string,
555 value: unknown,
556 ) {
557 return yield* encodeJson(value).pipe(
558 Effect.mapError((cause) => new MobileStorageEncodeError({ key, cause })),
559 );
560 });
561​
562 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
563 const next = Math.max(Date.now(), last + 1);
564 return [next, next] as const;
565 });
566​
567 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
568 payload: string,
569 updatedAt?: number,
570 ) {
571 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
572 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
573 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
574 if (databaseResult._tag === "Failure") {
575 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
576 Effect.annotateLogs({ cause: databaseResult.failure }),
577 );
578 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
579 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
580 return;
581 }
582 yield* secureStorage
583 .removeItem(PREFERENCES_FALLBACK_KEY)
584 .pipe(
585 Effect.catch((error) =>
586 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
587 Effect.annotateLogs({ error }),
588 ),
589 ),
590 );
591 });
592​
593 const loadUnlocked = Effect.gen(function* () {
594 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
595 const databaseAvailable = databaseResult._tag === "Success";
596 const storedJson = databaseAvailable
597 ? databaseResult.success
598 : Option.none<MobileDatabase.StoredPreferencesJson>();
599 if (databaseResult._tag === "Failure") {
600 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
601 Effect.annotateLogs({ cause: databaseResult.failure }),
602 );
603 }
604​
605 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
606 let fallbackJson: string | null = null;
607 if (fallbackResult._tag === "Success") {
608 fallbackJson = fallbackResult.success;
609 } else if (Option.isNone(storedJson)) {
610 return yield* fallbackResult.failure;
611 } else {
612 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
613 Effect.annotateLogs({ error: fallbackResult.failure }),
614 );
615 }
616​
617 const fallback = parseFallback(fallbackJson);
618 const storedPreferences = Option.isSome(storedJson)
619 ? parsePayload(storedJson.value.payload)
620 : null;
621 const fallbackIsNewer =
622 fallback !== null &&
623 (storedPreferences === null ||
624 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
625​
626 let parsed: Preferences | null = null;
627 if (fallbackIsNewer) {
628 parsed = fallback.preferences;
629 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
630 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
631 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
632 parsed = storedPreferences;
633 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
634 if (fallbackJson !== null) {
635 yield* secureStorage
636 .removeItem(PREFERENCES_FALLBACK_KEY)
637 .pipe(
638 Effect.catch((error) =>
639 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
640 Effect.annotateLogs({ error }),
641 ),
642 ),
643 );
644 }
645 }
646​
647 if (parsed === null) {
648 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
649 const legacyPreferences = parsePayload(legacyJson);
650 parsed = legacyPreferences;
651 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
652 yield* saveJson(legacyJson);
653 yield* secureStorage
654 .removeItem(PREFERENCES_KEY)
655 .pipe(
656 Effect.catch((error) =>
657 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
658 Effect.annotateLogs({ error }),
659 ),
660 ),
661 );
662 }
663 }
664​
665 return parsed === null ? {} : sanitizePreferences(parsed);
666 });
667​
668 const load = lock
669 .withPermits(1)(loadUnlocked)
670 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
671​
672 const update = Effect.fn("MobilePreferencesStore.update")(
673 (transform: (current: Preferences) => Partial<Preferences>) =>
674 lock
675 .withPermits(1)(
676 Effect.gen(function* () {
677 const current = yield* loadUnlocked;
678 const patch = yield* Effect.try({
679 try: () => transform(current),
680 catch: (cause) => new MobilePreferencesSaveError({ cause }),
681 });
682 const next: Preferences = { ...current, ...patch };
683 const payload = yield* encode(PREFERENCES_KEY, next);
684 yield* saveJson(payload);
685 return next;
686 }),
687 )
688 .pipe(
689 Effect.mapError((cause) =>
690 isMobilePreferencesSaveError(cause) ? cause : new MobilePreferencesSaveError({ cause }),
691 ),
692 ),
693 );
694​
695 return MobilePreferencesStore.of({
696 load,
697 update,
698 savePatch: Effect.fn("MobilePreferencesStore.savePatch")((patch) => update(() => patch)),
699 });
700});
701​
702export const layer = Layer.effect(MobilePreferencesStore, make());