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