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