The best way to control Claude Code, Codex and more from any computer or phone

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