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