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

mobile-preferences.ts

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