Open History to see the last commit
1import * as Arr from "effect/Array";
2import { pipe } from "effect/Function";
3import * as Schema from "effect/Schema";
4import * as SecureStore from "expo-secure-store";
5import { EnvironmentId } from "@t3tools/contracts";
6
7import {
8 isRelayManagedConnection,
9 type SavedRemoteConnection,
10 toStableSavedRemoteConnection,
11} from "./connection";
12
13const CONNECTIONS_KEY = "t3code.connections";
14const PREFERENCES_KEY = "t3code.preferences";
15const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
16const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
17const MobileStorageKey = Schema.Literals([
18 CONNECTIONS_KEY,
19 PREFERENCES_KEY,
20 AGENT_AWARENESS_DEVICE_ID_KEY,
21 AGENT_AWARENESS_REGISTRATION_KEY,
22]);
23type MobileStorageKeyValue = typeof MobileStorageKey.Type;
24
25export class MobileSecureStorageError extends Schema.TaggedErrorClass<MobileSecureStorageError>()(
26 "MobileSecureStorageError",
27 {
28 operation: Schema.Literals(["read", "write", "generate-device-id"]),
29 key: MobileStorageKey,
30 cause: Schema.Defect(),
31 },
32) {
33 override get message(): string {
34 return `Mobile secure storage operation ${this.operation} failed for key ${this.key}.`;
35 }
36}
37
38export class MobileStorageDecodeError extends Schema.TaggedErrorClass<MobileStorageDecodeError>()(
39 "MobileStorageDecodeError",
40 {
41 key: MobileStorageKey,
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Failed to decode mobile storage value for key ${this.key}.`;
47 }
48}
49
50export class MobileStorageEncodeError extends Schema.TaggedErrorClass<MobileStorageEncodeError>()(
51 "MobileStorageEncodeError",
52 {
53 key: MobileStorageKey,
54 cause: Schema.Defect(),
55 },
56) {
57 override get message(): string {
58 return `Failed to encode mobile storage value for key ${this.key}.`;
59 }
60}
61
62export interface Preferences {
63 readonly liveActivitiesEnabled?: boolean;
64 readonly baseFontSize?: number;
65 /** Terminal font size override; null/absent means derived from baseFontSize. */
66 readonly terminalFontSize?: number | null;
67 /** Legacy key predating baseFontSize; read once for migration. */
68 readonly markdownFontSize?: number;
69 /** Code/diff font size override; null/absent means derived from baseFontSize. */
70 readonly codeFontSize?: number | null;
71 readonly codeWordBreak?: boolean;
72 /** Cloud account ids that opted out of the T3 Connect onboarding sheet. */
73 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
74}
75
76async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
77 try {
78 return await SecureStore.getItemAsync(key);
79 } catch (cause) {
80 throw new MobileSecureStorageError({ operation: "read", key, cause });
81 }
82}
83
84async function writeStorageItem(key: MobileStorageKeyValue, value: string): Promise<void> {
85 try {
86 await SecureStore.setItemAsync(key, value);
87 } catch (cause) {
88 throw new MobileSecureStorageError({ operation: "write", key, cause });
89 }
90}
91
92async function readJsonStorageItem<T>(key: MobileStorageKeyValue): Promise<T | null> {
93 const raw = (await readStorageItem(key)) ?? "";
94 if (!raw.trim()) {
95 return null;
96 }
97
98 try {
99 return JSON.parse(raw) as T;
100 } catch (cause) {
101 console.warn(
102 "[mobile-storage] ignored invalid JSON",
103 new MobileStorageDecodeError({ key, cause }),
104 );
105 return null;
106 }
107}
108
109async function writeJsonStorageItem(key: MobileStorageKeyValue, value: unknown) {
110 let encoded: string;
111 try {
112 encoded = JSON.stringify(value);
113 } catch (cause) {
114 throw new MobileStorageEncodeError({ key, cause });
115 }
116 await writeStorageItem(key, encoded);
117}
118
119export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
120 const parsed = await readJsonStorageItem<{
121 readonly connections?: ReadonlyArray<SavedRemoteConnection>;
122 }>(CONNECTIONS_KEY);
123 if (!parsed) {
124 return [];
125 }
126
127 return pipe(
128 parsed.connections ?? [],
129 Arr.filter(
130 (c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
131 ),
132 );
133}
134
135export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
136 const current = await loadSavedConnections();
137 const stableConnection = toStableSavedRemoteConnection(connection);
138 const next = current.some((entry) => entry.environmentId === connection.environmentId)
139 ? pipe(
140 current,
141 Arr.map((entry) =>
142 entry.environmentId === connection.environmentId ? stableConnection : entry,
143 ),
144 )
145 : pipe(current, Arr.append(stableConnection));
146
147 await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
148}
149
150export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
151 const current = await loadSavedConnections();
152 const next = pipe(
153 current,
154 Arr.filter((entry) => entry.environmentId !== environmentId),
155 );
156 await writeJsonStorageItem(CONNECTIONS_KEY, { connections: next });
157}
158
159export async function loadPreferences(): Promise<Preferences> {
160 const parsed = await readJsonStorageItem<Preferences>(PREFERENCES_KEY);
161 if (!parsed || typeof parsed !== "object") {
162 return {};
163 }
164
165 const preferences: {
166 liveActivitiesEnabled?: boolean;
167 baseFontSize?: number;
168 terminalFontSize?: number | null;
169 markdownFontSize?: number;
170 codeFontSize?: number | null;
171 codeWordBreak?: boolean;
172 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
173 } = {};
174
175 if (typeof parsed.liveActivitiesEnabled === "boolean") {
176 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
177 }
178 if (typeof parsed.baseFontSize === "number") {
179 preferences.baseFontSize = parsed.baseFontSize;
180 }
181 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
182 preferences.terminalFontSize = parsed.terminalFontSize;
183 }
184 if (typeof parsed.markdownFontSize === "number") {
185 preferences.markdownFontSize = parsed.markdownFontSize;
186 }
187 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
188 preferences.codeFontSize = parsed.codeFontSize;
189 }
190 if (typeof parsed.codeWordBreak === "boolean") {
191 preferences.codeWordBreak = parsed.codeWordBreak;
192 }
193 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
194 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
195 (account): account is string => typeof account === "string",
196 );
197 }
198
199 return preferences;
200}
201
202// Preference writes are read-modify-write over one JSON blob; concurrent
203// writers would drop each other's fields, so all writes are serialized here.
204let preferencesWriteQueue: Promise<unknown> = Promise.resolve();
205
206export async function updatePreferences(
207 update: (current: Preferences) => Partial<Preferences>,
208): Promise<Preferences> {
209 const task = preferencesWriteQueue.then(async () => {
210 const current = await loadPreferences();
211 const next: Preferences = {
212 ...current,
213 ...update(current),
214 };
215 await writeJsonStorageItem(PREFERENCES_KEY, next);
216 return next;
217 });
218 preferencesWriteQueue = task.catch(() => undefined);
219 return task;
220}
221
222export async function savePreferencesPatch(patch: Partial<Preferences>): Promise<Preferences> {
223 return updatePreferences(() => patch);
224}
225
226export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
227 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
228 if (existing?.trim()) {
229 return existing;
230 }
231
232 const deviceId = await import("./uuid")
233 .then(({ uuidv4 }) => uuidv4())
234 .catch((cause) => {
235 throw new MobileSecureStorageError({
236 operation: "generate-device-id",
237 key: AGENT_AWARENESS_DEVICE_ID_KEY,
238 cause,
239 });
240 });
241 await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
242 return deviceId;
243}
244
245export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
246 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
247 return existing?.trim() ? existing : null;
248}
249
250export interface AgentAwarenessRegistrationRecord {
251 readonly identity: string;
252 readonly signature: string;
253 // Last push-to-start token the relay accepted. Registrations triggered
254 // without a token event merge it back in so token absence never reads as a
255 // change (which would defeat the register-once skip every launch).
256 readonly pushToStartToken?: string;
257}
258
259// Remembers the account identity and payload signature the relay last accepted
260// so the app does not re-register on every launch while nothing has changed.
261// Cleared only on sign-out.
262export async function loadAgentAwarenessRegistrationRecord(): Promise<AgentAwarenessRegistrationRecord | null> {
263 const parsed = await readJsonStorageItem<AgentAwarenessRegistrationRecord>(
264 AGENT_AWARENESS_REGISTRATION_KEY,
265 );
266 if (
267 !parsed ||
268 typeof parsed !== "object" ||
269 typeof parsed.identity !== "string" ||
270 typeof parsed.signature !== "string"
271 ) {
272 return null;
273 }
274 return {
275 identity: parsed.identity,
276 signature: parsed.signature,
277 ...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
278 ? { pushToStartToken: parsed.pushToStartToken }
279 : {}),
280 };
281}
282
283export async function saveAgentAwarenessRegistrationRecord(
284 record: AgentAwarenessRegistrationRecord,
285): Promise<void> {
286 await writeJsonStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, record);
287}
288
289export async function clearAgentAwarenessRegistrationRecord(): Promise<void> {
290 await writeStorageItem(AGENT_AWARENESS_REGISTRATION_KEY, "");
291}