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