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

mobile-preferences.ts

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