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 { 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 readonly useLastProjectForNewThreads?: boolean;
177 readonly lastThreadProject?: typeof ThreadProject.Type;
178 readonly modelFavorites?: ReadonlyArray<{
179 readonly provider: ProviderInstanceId;
180 readonly model: string;
181 }>;
182 readonly threadListSettledShelfExpanded?: boolean;
183 readonly threadListSnoozedShelfExpanded?: boolean;
184 readonly threadListWorkingShelfExpanded?: boolean;
185 readonly threadListFilters?: ThreadListFilters;
186 readonly pullRequestListFilters?: PullRequestListPreferences;
187 readonly workspaceSelections?: WorkspaceSelections;
188 readonly pullRequestSavedViews?: ReadonlyArray<PullRequestSavedView>;
189 readonly issueSavedViews?: ReadonlyArray<IssueSavedView>;
190}
191
192export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
193 "MobilePreferencesLoadError",
194 { cause: Schema.Defect() },
195) {
196 override get message(): string {
197 return "Failed to load mobile preferences.";
198 }
199}
200
201export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
202 "MobilePreferencesSaveError",
203 { cause: Schema.Defect() },
204) {
205 override get message(): string {
206 return "Failed to save mobile preferences.";
207 }
208}
209
210const isMobilePreferencesSaveError = Schema.is(MobilePreferencesSaveError);
211
212interface PreferencesFallback {
213 readonly payload: string;
214 readonly updatedAt: number;
215 readonly preferences: Preferences;
216}
217
218export class MobilePreferencesStore extends Context.Service<
219 MobilePreferencesStore,
220 {
221 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
222 readonly savePatch: (
223 patch: Partial<Preferences>,
224 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
225 readonly update: (
226 transform: (current: Preferences) => Partial<Preferences>,
227 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
228 }
229>()("@t3tools/mobile/persistence/mobile-preferences/MobilePreferencesStore") {}
230
231const isToolCallVisibility = Schema.is(ToolCallVisibility);
232const isPullRequestMergeMethod = Schema.is(PullRequestMergeMethod);
233
234function sanitizePreferences(parsed: Preferences): Preferences {
235 const preferences: {
236 navigationTabOrder?: readonly string[];
237 hiddenNavigationTabs?: readonly string[];
238 sharedSlotTab?: "pullRequests" | "issues";
239 pullRequestHideTestFiles?: boolean;
240 pullRequestActivityVisibility?: PullRequestActivityVisibility;
241 pullRequestMergeMethod?: PullRequestMergeMethod;
242 liveActivitiesEnabled?: boolean;
243 themeId?: MobileThemeId;
244 lightThemeId?: MobileThemeId;
245 darkThemeId?: MobileThemeId;
246 themeMode?: MobileThemeMode;
247 androidNavigationStyle?: AndroidNavigationStyle;
248 baseFontSize?: number;
249 terminalFontSize?: number | null;
250 markdownFontSize?: number;
251 codeFontSize?: number | null;
252 codeWordBreak?: boolean;
253 mathRenderingEnabled?: boolean;
254 crashReportsEnabled?: boolean;
255 connectionTracesEnabled?: boolean;
256 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
257 collapsedProjectGroups?: readonly string[];
258 dismissedDatabaseStorageNotices?: readonly string[];
259 connectDevicesSeenThrough?: Readonly<Record<string, number>>;
260 composerEnterBehavior?: ComposerEnterBehavior;
261 followUpBehavior?: FollowUpBehavior;
262 language?: string;
263 microphones?: ReadonlyArray<MicrophoneEntry>;
264 projectGroupingEnabled?: boolean;
265 projectGroupingMode?: SidebarProjectGroupingMode;
266 toolCallVisibility?: ToolCallVisibility;
267 workingShelfEnabled?: boolean;
268 useLastProjectForNewThreads?: boolean;
269 lastThreadProject?: typeof ThreadProject.Type;
270 modelFavorites?: Preferences["modelFavorites"];
271 threadListSettledShelfExpanded?: boolean;
272 threadListSnoozedShelfExpanded?: boolean;
273 threadListWorkingShelfExpanded?: boolean;
274 threadListFilters?: ThreadListFilters;
275 pullRequestListFilters?: PullRequestListPreferences;
276 workspaceSelections?: WorkspaceSelections;
277 pullRequestSavedViews?: ReadonlyArray<PullRequestSavedView>;
278 issueSavedViews?: ReadonlyArray<IssueSavedView>;
279 } = {};
280
281 if (Array.isArray(parsed.hiddenNavigationTabs)) {
282 preferences.hiddenNavigationTabs = parsed.hiddenNavigationTabs.filter(
283 (tab): tab is string => typeof tab === "string",
284 );
285 }
286
287 if (Array.isArray(parsed.navigationTabOrder)) {
288 preferences.navigationTabOrder = parsed.navigationTabOrder.filter(
289 (tab): tab is string => typeof tab === "string",
290 );
291 }
292
293 if (parsed.sharedSlotTab === "pullRequests" || parsed.sharedSlotTab === "issues") {
294 preferences.sharedSlotTab = parsed.sharedSlotTab;
295 }
296
297 if (typeof parsed.pullRequestHideTestFiles === "boolean") {
298 preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles;
299 }
300
301 if (isPullRequestActivityVisibility(parsed.pullRequestActivityVisibility)) {
302 preferences.pullRequestActivityVisibility = parsed.pullRequestActivityVisibility;
303 }
304
305 if (isPullRequestMergeMethod(parsed.pullRequestMergeMethod)) {
306 preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod;
307 }
308
309 if (typeof parsed.liveActivitiesEnabled === "boolean") {
310 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
311 }
312 if (
313 typeof parsed.themeId === "string" &&
314 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
315 ) {
316 preferences.themeId = parsed.themeId as MobileThemeId;
317 }
318 if (
319 typeof parsed.lightThemeId === "string" &&
320 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
321 ) {
322 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
323 }
324 if (
325 typeof parsed.darkThemeId === "string" &&
326 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
327 ) {
328 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
329 }
330 if (
331 parsed.themeMode === "system" ||
332 parsed.themeMode === "light" ||
333 parsed.themeMode === "dark"
334 ) {
335 preferences.themeMode = parsed.themeMode;
336 }
337 if (parsed.androidNavigationStyle === "one-ui" || parsed.androidNavigationStyle === "material") {
338 preferences.androidNavigationStyle = parsed.androidNavigationStyle;
339 }
340 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
341 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
342 preferences.terminalFontSize = parsed.terminalFontSize;
343 }
344 if (typeof parsed.markdownFontSize === "number") {
345 preferences.markdownFontSize = parsed.markdownFontSize;
346 }
347 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
348 preferences.codeFontSize = parsed.codeFontSize;
349 }
350 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
351 if (typeof parsed.mathRenderingEnabled === "boolean")
352 preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
353 if (typeof parsed.crashReportsEnabled === "boolean") {
354 preferences.crashReportsEnabled = parsed.crashReportsEnabled;
355 }
356 if (typeof parsed.connectionTracesEnabled === "boolean") {
357 preferences.connectionTracesEnabled = parsed.connectionTracesEnabled;
358 }
359 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
360 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
361 (account): account is string => typeof account === "string",
362 );
363 }
364 if (Array.isArray(parsed.collapsedProjectGroups)) {
365 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
366 (key): key is string => typeof key === "string",
367 );
368 }
369 if (Array.isArray(parsed.dismissedDatabaseStorageNotices)) {
370 preferences.dismissedDatabaseStorageNotices = parsed.dismissedDatabaseStorageNotices.filter(
371 (value): value is string => typeof value === "string",
372 );
373 }
374 if (
375 typeof parsed.connectDevicesSeenThrough === "object" &&
376 parsed.connectDevicesSeenThrough !== null
377 ) {
378 preferences.connectDevicesSeenThrough = Object.fromEntries(
379 Object.entries(parsed.connectDevicesSeenThrough).filter(
380 (entry): entry is [string, number] => typeof entry[1] === "number",
381 ),
382 );
383 }
384 if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
385 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
386 }
387 if (parsed.followUpBehavior === "queue" || parsed.followUpBehavior === "steer") {
388 preferences.followUpBehavior = parsed.followUpBehavior;
389 }
390 if (typeof parsed.language === "string") preferences.language = parsed.language;
391 if (Array.isArray(parsed.microphones)) {
392 preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => {
393 if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return [];
394 if (!("uid" in entry)) return [{ kind: entry.kind }];
395 return typeof entry.uid === "string" && typeof entry.name === "string"
396 ? [{ kind: entry.kind, uid: entry.uid, name: entry.name }]
397 : [];
398 });
399 }
400 if (typeof parsed.projectGroupingEnabled === "boolean") {
401 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
402 }
403 if (
404 parsed.projectGroupingMode === "repository" ||
405 parsed.projectGroupingMode === "repository_path" ||
406 parsed.projectGroupingMode === "separate"
407 ) {
408 preferences.projectGroupingMode = parsed.projectGroupingMode;
409 }
410 if (isToolCallVisibility(parsed.toolCallVisibility)) {
411 preferences.toolCallVisibility = parsed.toolCallVisibility;
412 }
413 if (typeof parsed.workingShelfEnabled === "boolean") {
414 preferences.workingShelfEnabled = parsed.workingShelfEnabled;
415 }
416 if (typeof parsed.useLastProjectForNewThreads === "boolean") {
417 preferences.useLastProjectForNewThreads = parsed.useLastProjectForNewThreads;
418 }
419 if (isThreadProject(parsed.lastThreadProject)) {
420 preferences.lastThreadProject = parsed.lastThreadProject;
421 }
422 if (Array.isArray(parsed.modelFavorites)) {
423 preferences.modelFavorites = parsed.modelFavorites.filter(
424 (favorite) =>
425 typeof favorite === "object" &&
426 favorite !== null &&
427 typeof favorite.provider === "string" &&
428 favorite.provider.length > 0 &&
429 typeof favorite.model === "string" &&
430 favorite.model.trim().length > 0,
431 );
432 }
433 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
434 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
435 }
436 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
437 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
438 }
439 if (typeof parsed.threadListWorkingShelfExpanded === "boolean") {
440 preferences.threadListWorkingShelfExpanded = parsed.threadListWorkingShelfExpanded;
441 }
442 if (isThreadListFilters(parsed.threadListFilters)) {
443 preferences.threadListFilters = parsed.threadListFilters;
444 }
445 if (isPullRequestListPreferences(parsed.pullRequestListFilters)) {
446 preferences.pullRequestListFilters = parsed.pullRequestListFilters;
447 }
448 if (isWorkspaceSelections(parsed.workspaceSelections)) {
449 preferences.workspaceSelections = parsed.workspaceSelections;
450 }
451 if (Array.isArray(parsed.pullRequestSavedViews)) {
452 preferences.pullRequestSavedViews = parsed.pullRequestSavedViews.filter(isPullRequestSavedView);
453 }
454 if (Array.isArray(parsed.issueSavedViews)) {
455 preferences.issueSavedViews = parsed.issueSavedViews.filter(isIssueSavedView);
456 }
457 return preferences;
458}
459
460const make = Effect.fn("MobilePreferencesStore.make")(function* () {
461 const database = yield* MobileDatabase.MobileDatabase;
462 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
463 const lock = yield* Semaphore.make(1);
464 const lastUpdatedAt = yield* Ref.make(0);
465
466 const parsePayload = (raw: string | null): Preferences | null => {
467 if (raw === null || !raw.trim()) return null;
468 let parsed: unknown;
469 try {
470 parsed = JSON.parse(raw);
471 } catch (cause) {
472 console.warn(
473 "[mobile-storage] ignored invalid JSON",
474 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
475 );
476 return null;
477 }
478 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
479 ? (parsed as Preferences)
480 : null;
481 };
482
483 const parseFallback = (raw: string | null): PreferencesFallback | null => {
484 if (raw === null || !raw.trim()) return null;
485 let parsed: unknown;
486 try {
487 parsed = JSON.parse(raw);
488 } catch (cause) {
489 console.warn(
490 "[mobile-storage] ignored invalid JSON",
491 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
492 );
493 return null;
494 }
495 if (
496 typeof parsed !== "object" ||
497 parsed === null ||
498 !("payload" in parsed) ||
499 typeof parsed.payload !== "string" ||
500 !("updatedAt" in parsed) ||
501 typeof parsed.updatedAt !== "number"
502 ) {
503 return null;
504 }
505 const preferences = parsePayload(parsed.payload);
506 return preferences === null
507 ? null
508 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
509 };
510
511 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
512 key: string,
513 value: unknown,
514 ) {
515 return yield* encodeJson(value).pipe(
516 Effect.mapError((cause) => new MobileStorageEncodeError({ key, cause })),
517 );
518 });
519
520 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
521 const next = Math.max(Date.now(), last + 1);
522 return [next, next] as const;
523 });
524
525 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
526 payload: string,
527 updatedAt?: number,
528 ) {
529 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
530 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
531 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
532 if (databaseResult._tag === "Failure") {
533 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
534 Effect.annotateLogs({ cause: databaseResult.failure }),
535 );
536 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
537 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
538 return;
539 }
540 yield* secureStorage
541 .removeItem(PREFERENCES_FALLBACK_KEY)
542 .pipe(
543 Effect.catch((error) =>
544 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
545 Effect.annotateLogs({ error }),
546 ),
547 ),
548 );
549 });
550
551 const loadUnlocked = Effect.gen(function* () {
552 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
553 const databaseAvailable = databaseResult._tag === "Success";
554 const storedJson = databaseAvailable
555 ? databaseResult.success
556 : Option.none<MobileDatabase.StoredPreferencesJson>();
557 if (databaseResult._tag === "Failure") {
558 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
559 Effect.annotateLogs({ cause: databaseResult.failure }),
560 );
561 }
562
563 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
564 let fallbackJson: string | null = null;
565 if (fallbackResult._tag === "Success") {
566 fallbackJson = fallbackResult.success;
567 } else if (Option.isNone(storedJson)) {
568 return yield* fallbackResult.failure;
569 } else {
570 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
571 Effect.annotateLogs({ error: fallbackResult.failure }),
572 );
573 }
574
575 const fallback = parseFallback(fallbackJson);
576 const storedPreferences = Option.isSome(storedJson)
577 ? parsePayload(storedJson.value.payload)
578 : null;
579 const fallbackIsNewer =
580 fallback !== null &&
581 (storedPreferences === null ||
582 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
583
584 let parsed: Preferences | null = null;
585 if (fallbackIsNewer) {
586 parsed = fallback.preferences;
587 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
588 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
589 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
590 parsed = storedPreferences;
591 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
592 if (fallbackJson !== null) {
593 yield* secureStorage
594 .removeItem(PREFERENCES_FALLBACK_KEY)
595 .pipe(
596 Effect.catch((error) =>
597 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
598 Effect.annotateLogs({ error }),
599 ),
600 ),
601 );
602 }
603 }
604
605 if (parsed === null) {
606 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
607 const legacyPreferences = parsePayload(legacyJson);
608 parsed = legacyPreferences;
609 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
610 yield* saveJson(legacyJson);
611 yield* secureStorage
612 .removeItem(PREFERENCES_KEY)
613 .pipe(
614 Effect.catch((error) =>
615 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
616 Effect.annotateLogs({ error }),
617 ),
618 ),
619 );
620 }
621 }
622
623 return parsed === null ? {} : sanitizePreferences(parsed);
624 });
625
626 const load = lock
627 .withPermits(1)(loadUnlocked)
628 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
629
630 const update = Effect.fn("MobilePreferencesStore.update")(
631 (transform: (current: Preferences) => Partial<Preferences>) =>
632 lock
633 .withPermits(1)(
634 Effect.gen(function* () {
635 const current = yield* loadUnlocked;
636 const patch = yield* Effect.try({
637 try: () => transform(current),
638 catch: (cause) => new MobilePreferencesSaveError({ cause }),
639 });
640 const next: Preferences = { ...current, ...patch };
641 const payload = yield* encode(PREFERENCES_KEY, next);
642 yield* saveJson(payload);
643 return next;
644 }),
645 )
646 .pipe(
647 Effect.mapError((cause) =>
648 isMobilePreferencesSaveError(cause) ? cause : new MobilePreferencesSaveError({ cause }),
649 ),
650 ),
651 );
652
653 return MobilePreferencesStore.of({
654 load,
655 update,
656 savePatch: Effect.fn("MobilePreferencesStore.savePatch")((patch) => update(() => patch)),
657 });
658});
659
660export const layer = Layer.effect(MobilePreferencesStore, make());