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

mobile-preferences.ts

506 lines18.8 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 {
9 EnvironmentId,
10 PullRequestInvolvement,
11 PullRequestListFilters,
12 PullRequestListState,
13 type ProviderInstanceId,
14 type PullRequestMergeMethod,
15 type SidebarProjectGroupingMode,
16} from "@t3tools/contracts";
17import type { ComposerEnterBehavior } from "../lib/composerEnterBehavior";
18import type { FollowUpBehavior } from "../lib/followUpBehavior";
19import { isMicrophoneKind, type MicrophoneEntry } from "../lib/microphonePriority";
20import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
21import * as MobileDatabase from "./mobile-database";
22import * as MobileSecureStorage from "./mobile-secure-storage";
23import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
24​
25const PREFERENCES_KEY = "t3code.preferences";
26const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
27​
28export const PullRequestListControls = Schema.Struct({
29 state: PullRequestListState,
30 involvement: PullRequestInvolvement,
31 filters: PullRequestListFilters,
32 projectId: Schema.optional(Schema.String),
33 projectEnvironmentId: Schema.optional(Schema.String),
34 sort: Schema.Literals(["updated", "created", "oldest"]),
35});
36export type PullRequestListControls = typeof PullRequestListControls.Type;
37​
38const ThreadListFilters = Schema.Struct({
39 environmentId: Schema.NullOr(EnvironmentId),
40 projectKey: Schema.NullOr(Schema.String),
41});
42export type ThreadListFilters = typeof ThreadListFilters.Type;
43​
44const PullRequestListPreferences = Schema.Struct({
45 environmentId: Schema.NullOr(Schema.String),
46 controls: Schema.Record(Schema.String, PullRequestListControls),
47});
48export type PullRequestListPreferences = typeof PullRequestListPreferences.Type;
49​
50const isThreadListFilters = Schema.is(ThreadListFilters);
51const isPullRequestListPreferences = Schema.is(PullRequestListPreferences);
52​
53export interface Preferences {
54 readonly navigationTabOrder?: readonly string[];
55 readonly hiddenNavigationTabs?: readonly string[];
56 readonly pullRequestHideTestFiles?: boolean;
57 readonly pullRequestMergeMethod?: PullRequestMergeMethod;
58 readonly liveActivitiesEnabled?: boolean;
59 readonly themeId?: MobileThemeId;
60 readonly lightThemeId?: MobileThemeId;
61 readonly darkThemeId?: MobileThemeId;
62 readonly themeMode?: MobileThemeMode;
63 readonly baseFontSize?: number;
64 readonly terminalFontSize?: number | null;
65 readonly markdownFontSize?: number;
66 readonly codeFontSize?: number | null;
67 readonly codeWordBreak?: boolean;
68 readonly mathRenderingEnabled?: boolean;
69 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
70 readonly collapsedProjectGroups?: readonly string[];
71 /** Environments whose "reclaim database space" notice was dismissed. */
72 readonly dismissedDatabaseStorageNotices?: readonly string[];
73 /** What the Return key does in the composer on a hardware keyboard. iOS only. */
74 readonly composerEnterBehavior?: ComposerEnterBehavior;
75 readonly followUpBehavior?: FollowUpBehavior;
76 readonly microphones?: ReadonlyArray<MicrophoneEntry>;
77 readonly projectGroupingEnabled?: boolean;
78 readonly projectGroupingMode?: SidebarProjectGroupingMode;
79 readonly planModeEnabled?: boolean;
80 readonly workingShelfEnabled?: boolean;
81 readonly modelFavorites?: ReadonlyArray<{
82 readonly provider: ProviderInstanceId;
83 readonly model: string;
84 }>;
85 readonly threadListSettledShelfExpanded?: boolean;
86 readonly threadListSnoozedShelfExpanded?: boolean;
87 readonly threadListWorkingShelfExpanded?: boolean;
88 readonly threadListFilters?: ThreadListFilters;
89 readonly pullRequestListFilters?: PullRequestListPreferences;
91​
92export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
93 "MobilePreferencesLoadError",
94 { cause: Schema.Defect() },
95) {
96 override get message(): string {
97 return "Failed to load mobile preferences.";
98 }
100​
101export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePreferencesSaveError>()(
102 "MobilePreferencesSaveError",
103 { cause: Schema.Defect() },
104) {
105 override get message(): string {
106 return "Failed to save mobile preferences.";
107 }
109​
110interface PreferencesFallback {
111 readonly payload: string;
112 readonly updatedAt: number;
113 readonly preferences: Preferences;
115​
116export class MobilePreferencesStore extends Context.Service<
117 MobilePreferencesStore,
118 {
119 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
120 readonly savePatch: (
121 patch: Partial<Preferences>,
122 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
123 readonly update: (
124 transform: (current: Preferences) => Partial<Preferences>,
125 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
126 }
127>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
128​
129function sanitizePreferences(parsed: Preferences): Preferences {
130 const preferences: {
131 navigationTabOrder?: readonly string[];
132 hiddenNavigationTabs?: readonly string[];
133 pullRequestHideTestFiles?: boolean;
134 pullRequestMergeMethod?: PullRequestMergeMethod;
135 liveActivitiesEnabled?: boolean;
136 themeId?: MobileThemeId;
137 lightThemeId?: MobileThemeId;
138 darkThemeId?: MobileThemeId;
139 themeMode?: MobileThemeMode;
140 baseFontSize?: number;
141 terminalFontSize?: number | null;
142 markdownFontSize?: number;
143 codeFontSize?: number | null;
144 codeWordBreak?: boolean;
145 mathRenderingEnabled?: boolean;
146 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
147 collapsedProjectGroups?: readonly string[];
148 dismissedDatabaseStorageNotices?: readonly string[];
149 composerEnterBehavior?: ComposerEnterBehavior;
150 followUpBehavior?: FollowUpBehavior;
151 microphones?: ReadonlyArray<MicrophoneEntry>;
152 projectGroupingEnabled?: boolean;
153 projectGroupingMode?: SidebarProjectGroupingMode;
154 planModeEnabled?: boolean;
155 workingShelfEnabled?: boolean;
156 modelFavorites?: Preferences["modelFavorites"];
157 threadListSettledShelfExpanded?: boolean;
158 threadListSnoozedShelfExpanded?: boolean;
159 threadListWorkingShelfExpanded?: boolean;
160 threadListFilters?: ThreadListFilters;
161 pullRequestListFilters?: PullRequestListPreferences;
162 } = {};
163​
164 if (Array.isArray(parsed.hiddenNavigationTabs)) {
165 preferences.hiddenNavigationTabs = parsed.hiddenNavigationTabs.filter(
166 (tab): tab is string => typeof tab === "string",
167 );
168 }
169​
170 if (Array.isArray(parsed.navigationTabOrder)) {
171 preferences.navigationTabOrder = parsed.navigationTabOrder.filter(
172 (tab): tab is string => typeof tab === "string",
173 );
174 }
175​
176 if (typeof parsed.pullRequestHideTestFiles === "boolean") {
177 preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles;
178 }
179​
180 if (
181 parsed.pullRequestMergeMethod === "squash" ||
182 parsed.pullRequestMergeMethod === "merge" ||
183 parsed.pullRequestMergeMethod === "rebase"
184 ) {
185 preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod;
186 }
187​
188 if (typeof parsed.liveActivitiesEnabled === "boolean") {
189 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
190 }
191 if (
192 typeof parsed.themeId === "string" &&
193 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.themeId)
194 ) {
195 preferences.themeId = parsed.themeId as MobileThemeId;
196 }
197 if (
198 typeof parsed.lightThemeId === "string" &&
199 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.lightThemeId)
200 ) {
201 preferences.lightThemeId = parsed.lightThemeId as MobileThemeId;
202 }
203 if (
204 typeof parsed.darkThemeId === "string" &&
205 (MOBILE_THEME_IDS as readonly string[]).includes(parsed.darkThemeId)
206 ) {
207 preferences.darkThemeId = parsed.darkThemeId as MobileThemeId;
208 }
209 if (
210 parsed.themeMode === "system" ||
211 parsed.themeMode === "light" ||
212 parsed.themeMode === "dark"
213 ) {
214 preferences.themeMode = parsed.themeMode;
215 }
216 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
217 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
218 preferences.terminalFontSize = parsed.terminalFontSize;
219 }
220 if (typeof parsed.markdownFontSize === "number") {
221 preferences.markdownFontSize = parsed.markdownFontSize;
222 }
223 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
224 preferences.codeFontSize = parsed.codeFontSize;
225 }
226 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
227 if (typeof parsed.mathRenderingEnabled === "boolean")
228 preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
229 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
230 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
231 (account): account is string => typeof account === "string",
232 );
233 }
234 if (Array.isArray(parsed.collapsedProjectGroups)) {
235 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
236 (key): key is string => typeof key === "string",
237 );
238 }
239 if (Array.isArray(parsed.dismissedDatabaseStorageNotices)) {
240 preferences.dismissedDatabaseStorageNotices = parsed.dismissedDatabaseStorageNotices.filter(
241 (value): value is string => typeof value === "string",
242 );
243 }
244 if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
245 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
246 }
247 if (parsed.followUpBehavior === "queue" || parsed.followUpBehavior === "steer") {
248 preferences.followUpBehavior = parsed.followUpBehavior;
249 }
250 if (Array.isArray(parsed.microphones)) {
251 preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => {
252 if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return [];
253 if (!("uid" in entry)) return [{ kind: entry.kind }];
254 return typeof entry.uid === "string" && typeof entry.name === "string"
255 ? [{ kind: entry.kind, uid: entry.uid, name: entry.name }]
256 : [];
257 });
258 }
259 if (typeof parsed.projectGroupingEnabled === "boolean") {
260 preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
261 }
262 if (
263 parsed.projectGroupingMode === "repository" ||
264 parsed.projectGroupingMode === "repository_path" ||
265 parsed.projectGroupingMode === "separate"
266 ) {
267 preferences.projectGroupingMode = parsed.projectGroupingMode;
268 }
269 if (typeof parsed.planModeEnabled === "boolean") {
270 preferences.planModeEnabled = parsed.planModeEnabled;
271 }
272 if (typeof parsed.workingShelfEnabled === "boolean") {
273 preferences.workingShelfEnabled = parsed.workingShelfEnabled;
274 }
275 if (Array.isArray(parsed.modelFavorites)) {
276 preferences.modelFavorites = parsed.modelFavorites.filter(
277 (favorite) =>
278 typeof favorite === "object" &&
279 favorite !== null &&
280 typeof favorite.provider === "string" &&
281 favorite.provider.length > 0 &&
282 typeof favorite.model === "string" &&
283 favorite.model.trim().length > 0,
284 );
285 }
286 if (typeof parsed.threadListSettledShelfExpanded === "boolean") {
287 preferences.threadListSettledShelfExpanded = parsed.threadListSettledShelfExpanded;
288 }
289 if (typeof parsed.threadListSnoozedShelfExpanded === "boolean") {
290 preferences.threadListSnoozedShelfExpanded = parsed.threadListSnoozedShelfExpanded;
291 }
292 if (typeof parsed.threadListWorkingShelfExpanded === "boolean") {
293 preferences.threadListWorkingShelfExpanded = parsed.threadListWorkingShelfExpanded;
294 }
295 if (isThreadListFilters(parsed.threadListFilters)) {
296 preferences.threadListFilters = parsed.threadListFilters;
297 }
298 if (isPullRequestListPreferences(parsed.pullRequestListFilters)) {
299 preferences.pullRequestListFilters = parsed.pullRequestListFilters;
300 }
301 return preferences;
303​
304export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
305 const database = yield* MobileDatabase.MobileDatabase;
306 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
307 const lock = yield* Semaphore.make(1);
308 const lastUpdatedAt = yield* Ref.make(0);
309​
310 const parsePayload = (raw: string | null): Preferences | null => {
311 if (raw === null || !raw.trim()) return null;
312 let parsed: unknown;
313 try {
314 parsed = JSON.parse(raw);
315 } catch (cause) {
316 console.warn(
317 "[mobile-storage] ignored invalid JSON",
318 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
319 );
320 return null;
321 }
322 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
323 ? (parsed as Preferences)
324 : null;
325 };
326​
327 const parseFallback = (raw: string | null): PreferencesFallback | null => {
328 if (raw === null || !raw.trim()) return null;
329 let parsed: unknown;
330 try {
331 parsed = JSON.parse(raw);
332 } catch (cause) {
333 console.warn(
334 "[mobile-storage] ignored invalid JSON",
335 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
336 );
337 return null;
338 }
339 if (
340 typeof parsed !== "object" ||
341 parsed === null ||
342 !("payload" in parsed) ||
343 typeof parsed.payload !== "string" ||
344 !("updatedAt" in parsed) ||
345 typeof parsed.updatedAt !== "number"
346 ) {
347 return null;
348 }
349 const preferences = parsePayload(parsed.payload);
350 return preferences === null
351 ? null
352 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
353 };
354​
355 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
356 key: string,
357 value: unknown,
358 ) {
359 return yield* Effect.try({
360 try: () => JSON.stringify(value),
361 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
362 });
363 });
364​
365 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
366 const next = Math.max(Date.now(), last + 1);
367 return [next, next] as const;
368 });
369​
370 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
371 payload: string,
372 updatedAt?: number,
373 ) {
374 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
375 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
376 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
377 if (databaseResult._tag === "Failure") {
378 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
379 Effect.annotateLogs({ cause: databaseResult.failure }),
380 );
381 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
382 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
383 return;
384 }
385 yield* secureStorage
386 .removeItem(PREFERENCES_FALLBACK_KEY)
387 .pipe(
388 Effect.catch((error) =>
389 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
390 Effect.annotateLogs({ error }),
391 ),
392 ),
393 );
394 });
395​
396 const loadUnlocked = Effect.gen(function* () {
397 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
398 const databaseAvailable = databaseResult._tag === "Success";
399 const storedJson = databaseAvailable
400 ? databaseResult.success
401 : Option.none<MobileDatabase.StoredPreferencesJson>();
402 if (databaseResult._tag === "Failure") {
403 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
404 Effect.annotateLogs({ cause: databaseResult.failure }),
405 );
406 }
407​
408 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
409 let fallbackJson: string | null = null;
410 if (fallbackResult._tag === "Success") {
411 fallbackJson = fallbackResult.success;
412 } else if (Option.isNone(storedJson)) {
413 return yield* fallbackResult.failure;
414 } else {
415 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
416 Effect.annotateLogs({ error: fallbackResult.failure }),
417 );
418 }
419​
420 const fallback = parseFallback(fallbackJson);
421 const storedPreferences = Option.isSome(storedJson)
422 ? parsePayload(storedJson.value.payload)
423 : null;
424 const fallbackIsNewer =
425 fallback !== null &&
426 (storedPreferences === null ||
427 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
428​
429 let parsed: Preferences | null = null;
430 if (fallbackIsNewer) {
431 parsed = fallback.preferences;
432 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
433 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
434 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
435 parsed = storedPreferences;
436 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
437 if (fallbackJson !== null) {
438 yield* secureStorage
439 .removeItem(PREFERENCES_FALLBACK_KEY)
440 .pipe(
441 Effect.catch((error) =>
442 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
443 Effect.annotateLogs({ error }),
444 ),
445 ),
446 );
447 }
448 }
449​
450 if (parsed === null) {
451 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
452 const legacyPreferences = parsePayload(legacyJson);
453 parsed = legacyPreferences;
454 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
455 yield* saveJson(legacyJson);
456 yield* secureStorage
457 .removeItem(PREFERENCES_KEY)
458 .pipe(
459 Effect.catch((error) =>
460 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
461 Effect.annotateLogs({ error }),
462 ),
463 ),
464 );
465 }
466 }
467​
468 return parsed === null ? {} : sanitizePreferences(parsed);
469 });
470​
471 const load = lock
472 .withPermits(1)(loadUnlocked)
473 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
474​
475 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
476 lock
477 .withPermits(1)(
478 Effect.gen(function* () {
479 const current = yield* loadUnlocked;
480 const patch = yield* Effect.try({
481 try: () => transform(current),
482 catch: (cause) => new MobilePreferencesSaveError({ cause }),
483 });
484 const next: Preferences = { ...current, ...patch };
485 const payload = yield* encode(PREFERENCES_KEY, next);
486 yield* saveJson(payload);
487 return next;
488 }),
489 )
490 .pipe(
491 Effect.mapError((cause) =>
492 cause instanceof MobilePreferencesSaveError
493 ? cause
494 : new MobilePreferencesSaveError({ cause }),
495 ),
496 ),
497 );
498​
499 return MobilePreferencesStore.of({
500 load,
501 update,
502 savePatch: (patch) => update(() => patch),
503 });
504});
505​
506export const layer = Layer.effect(MobilePreferencesStore, make());