Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

storage.ts

220 lines6.8 KB

1import * as Arr from "effect/Array";
2import { pipe } from "effect/Function";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as SecureStore from "expo-secure-store";
6import { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts";
7​
8import {
9 isRelayManagedConnection,
10 type SavedRemoteConnection,
11 toStableSavedRemoteConnection,
12} from "./connection";
13​
14const CONNECTIONS_KEY = "t3code.connections";
15const PREFERENCES_KEY = "t3code.preferences";
16const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
17const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
18const SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
19​
20export interface CachedShellSnapshot {
21 readonly schemaVersion: typeof SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION;
22 readonly environmentId: EnvironmentId;
23 readonly snapshotReceivedAt: string;
24 readonly snapshot: OrchestrationShellSnapshot;
26​
27export interface MobilePreferences {
28 readonly liveActivitiesEnabled?: boolean;
29 readonly terminalFontSize?: number;
31​
32const CachedShellSnapshotSchema = Schema.Struct({
33 schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
34 environmentId: EnvironmentId,
35 snapshotReceivedAt: Schema.String,
36 snapshot: OrchestrationShellSnapshot,
37});
38const decodeCachedShellSnapshot = Schema.decodeUnknownOption(CachedShellSnapshotSchema);
39​
40async function readStorageItem(key: string): Promise<string | null> {
41 return await SecureStore.getItemAsync(key);
43​
44async function writeStorageItem(key: string, value: string): Promise<void> {
45 await SecureStore.setItemAsync(key, value);
47​
48async function readJsonStorageItem<T>(key: string): Promise<T | null> {
49 const raw = (await readStorageItem(key)) ?? "";
50 if (!raw.trim()) {
51 return null;
52 }
53​
54 try {
55 return JSON.parse(raw) as T;
56 } catch {
57 return null;
58 }
60​
61function cachedShellSnapshotFileName(environmentId: EnvironmentId): string {
62 return `${encodeURIComponent(environmentId)}.json`;
64​
65async function getShellSnapshotCacheDirectory() {
66 const { Directory, Paths } = await import("expo-file-system");
67 const directory = new Directory(Paths.document, SHELL_SNAPSHOT_CACHE_DIRECTORY);
68 directory.create({ idempotent: true, intermediates: true });
69 return directory;
71​
72export async function loadCachedShellSnapshot(
73 environmentId: EnvironmentId,
74): Promise<CachedShellSnapshot | null> {
75 try {
76 const { File } = await import("expo-file-system");
77 const directory = await getShellSnapshotCacheDirectory();
78 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
79 if (!file.exists) {
80 return null;
81 }
82​
83 const parsed = JSON.parse(await file.text()) as unknown;
84 const decoded = decodeCachedShellSnapshot(parsed);
85 if (Option.isNone(decoded) || decoded.value.environmentId !== environmentId) {
86 return null;
87 }
88​
89 return decoded.value;
90 } catch {
91 return null;
92 }
94​
95export async function saveCachedShellSnapshot(
96 environmentId: EnvironmentId,
97 snapshot: OrchestrationShellSnapshot,
98): Promise<void> {
99 try {
100 const { File } = await import("expo-file-system");
101 const directory = await getShellSnapshotCacheDirectory();
102 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
103 const document: CachedShellSnapshot = {
104 schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
105 environmentId,
106 snapshotReceivedAt: new Date().toISOString(),
107 snapshot,
108 };
109​
110 if (!file.exists) {
111 file.create({ intermediates: true, overwrite: true });
112 }
113 file.write(JSON.stringify(document));
114 } catch {
115 // Cache persistence is best-effort and should never block live data.
116 }
118​
119export async function clearCachedShellSnapshot(environmentId: EnvironmentId): Promise<void> {
120 try {
121 const { File } = await import("expo-file-system");
122 const directory = await getShellSnapshotCacheDirectory();
123 const file = new File(directory, cachedShellSnapshotFileName(environmentId));
124 if (file.exists) {
125 file.delete();
126 }
127 } catch {
128 // Ignore cache cleanup failures.
129 }
131​
132export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
133 const parsed = await readJsonStorageItem<{
134 readonly connections?: ReadonlyArray<SavedRemoteConnection>;
135 }>(CONNECTIONS_KEY);
136 if (!parsed) {
137 return [];
138 }
139​
140 return pipe(
141 parsed.connections ?? [],
142 Arr.filter(
143 (c) => !!c.environmentId && (!!c.bearerToken?.trim() || isRelayManagedConnection(c)),
144 ),
145 );
147​
148export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
149 const current = await loadSavedConnections();
150 const stableConnection = toStableSavedRemoteConnection(connection);
151 const next = current.some((entry) => entry.environmentId === connection.environmentId)
152 ? pipe(
153 current,
154 Arr.map((entry) =>
155 entry.environmentId === connection.environmentId ? stableConnection : entry,
156 ),
157 )
158 : pipe(current, Arr.append(stableConnection));
159​
160 await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
162​
163export async function clearSavedConnection(environmentId: EnvironmentId): Promise<void> {
164 const current = await loadSavedConnections();
165 const next = pipe(
166 current,
167 Arr.filter((entry) => entry.environmentId !== environmentId),
168 );
169 await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
171​
172export async function loadPreferences(): Promise<MobilePreferences> {
173 const parsed = await readJsonStorageItem<MobilePreferences>(PREFERENCES_KEY);
174 if (!parsed || typeof parsed !== "object") {
175 return {};
176 }
177​
178 const preferences: {
179 liveActivitiesEnabled?: boolean;
180 terminalFontSize?: number;
181 } = {};
182​
183 if (typeof parsed.liveActivitiesEnabled === "boolean") {
184 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
185 }
186 if (typeof parsed.terminalFontSize === "number") {
187 preferences.terminalFontSize = parsed.terminalFontSize;
188 }
189​
190 return preferences;
192​
193export async function savePreferencesPatch(
194 patch: Partial<MobilePreferences>,
195): Promise<MobilePreferences> {
196 const current = await loadPreferences();
197 const next: MobilePreferences = {
198 ...current,
199 ...patch,
200 };
201 await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
202 return next;
204​
205export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
206 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
207 if (existing?.trim()) {
208 return existing;
209 }
210​
211 const { uuidv4 } = await import("./uuid");
212 const deviceId = uuidv4();
213 await writeStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
214 return deviceId;
216​
217export async function loadAgentAwarenessDeviceId(): Promise<string | null> {
218 const existing = await readStorageItem(AGENT_AWARENESS_DEVICE_ID_KEY);
219 return existing?.trim() ? existing : null;