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

mobile-preferences.ts

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