Open History to see the last commit
1import * as Arr from "effect/Array";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import { pipe } from "effect/Function";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8
9import * as MobileSecureStorage from "./mobile-secure-storage";
10
11const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
12const ANALYTICS_DEVICE_ID_KEY = "t3code.analytics.device-id";
13const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
14const RECENT_THREAD_SHORTCUTS_KEY = "t3code.recent-thread-shortcuts";
15const encodeJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
16
17export class MobileStorageDecodeError extends Schema.TaggedError<MobileStorageDecodeError>()(
18 "MobileStorageDecodeError",
19 {
20 key: Schema.String,
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Failed to decode mobile storage value for key ${this.key}.`;
26 }
27}
28
29export class MobileStorageEncodeError extends Schema.TaggedError<MobileStorageEncodeError>()(
30 "MobileStorageEncodeError",
31 {
32 key: Schema.String,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to encode mobile storage value for key ${this.key}.`;
38 }
39}
40
41export class MobileDeviceIdGenerationError extends Schema.TaggedError<MobileDeviceIdGenerationError>()(
42 "MobileDeviceIdGenerationError",
43 { cause: Schema.Defect() },
44) {
45 override get message(): string {
46 return "Failed to generate the mobile agent-awareness device id.";
47 }
48}
49
50export interface AgentAwarenessRegistrationRecord {
51 readonly identity: string;
52 readonly signature: string;
53 readonly pushToStartToken?: string;
54}
55
56export interface RecentThreadShortcut {
57 readonly environmentId: string;
58 readonly threadId: string;
59 readonly title: string;
60}
61
62export class MobileStorage extends Context.Service<
63 MobileStorage,
64 {
65 readonly loadOrCreateAgentAwarenessDeviceId: Effect.Effect<
66 string,
67 MobileSecureStorage.MobileSecureStorageError | MobileDeviceIdGenerationError
68 >;
69 /** Random and used only by analytics, so its hash links to nothing the relay stores. */
70 readonly loadOrCreateAnalyticsDeviceId: Effect.Effect<
71 string,
72 MobileSecureStorage.MobileSecureStorageError | MobileDeviceIdGenerationError
73 >;
74 readonly loadAgentAwarenessDeviceId: Effect.Effect<
75 string | null,
76 MobileSecureStorage.MobileSecureStorageError
77 >;
78 readonly loadAgentAwarenessRegistrationRecord: Effect.Effect<
79 AgentAwarenessRegistrationRecord | null,
80 MobileSecureStorage.MobileSecureStorageError
81 >;
82 readonly saveAgentAwarenessRegistrationRecord: (
83 record: AgentAwarenessRegistrationRecord,
84 ) => Effect.Effect<
85 void,
86 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
87 >;
88 readonly clearAgentAwarenessRegistrationRecord: Effect.Effect<
89 void,
90 MobileSecureStorage.MobileSecureStorageError
91 >;
92 readonly loadRecentThreadShortcuts: Effect.Effect<
93 ReadonlyArray<RecentThreadShortcut>,
94 MobileSecureStorage.MobileSecureStorageError
95 >;
96 readonly saveRecentThreadShortcuts: (
97 threads: ReadonlyArray<RecentThreadShortcut>,
98 ) => Effect.Effect<
99 void,
100 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
101 >;
102 }
103>()("@t3tools/mobile/persistence/mobile-storage/MobileStorage") {}
104
105export const make = Effect.fn("MobileStorage.make")(function* () {
106 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
107 const deviceIdLock = yield* Semaphore.make(1);
108
109 const parseJson = <A>(key: string, raw: string): A | null => {
110 if (!raw.trim()) return null;
111 try {
112 return JSON.parse(raw) as A;
113 } catch (cause) {
114 console.warn(
115 "[mobile-storage] ignored invalid JSON",
116 new MobileStorageDecodeError({ key, cause }),
117 );
118 return null;
119 }
120 };
121
122 const readJson = Effect.fn("MobileStorage.readJson")(function* <A>(key: string) {
123 const raw = (yield* secureStorage.getItem(key)) ?? "";
124 return parseJson<A>(key, raw);
125 });
126
127 const writeJson = Effect.fn("MobileStorage.writeJson")(function* (key: string, value: unknown) {
128 const encoded = yield* encodeJson(value).pipe(
129 Effect.mapError((cause) => new MobileStorageEncodeError({ key, cause })),
130 );
131 yield* secureStorage.setItem(key, encoded);
132 });
133
134 const loadOrCreateRandomId = Effect.fn("MobileStorage.loadOrCreateRandomId")(function* (
135 key: string,
136 ) {
137 const existing = yield* secureStorage.getItem(key);
138 if (existing?.trim()) return existing;
139 const created = yield* Effect.tryPromise({
140 try: () => import("../lib/uuid").then(({ uuidv4 }) => uuidv4()),
141 catch: (cause) => new MobileDeviceIdGenerationError({ cause }),
142 });
143 yield* secureStorage.setItem(key, created);
144 return created;
145 }, deviceIdLock.withPermits(1));
146 const loadOrCreateAgentAwarenessDeviceId = loadOrCreateRandomId(AGENT_AWARENESS_DEVICE_ID_KEY);
147
148 const loadAgentAwarenessDeviceId = secureStorage
149 .getItem(AGENT_AWARENESS_DEVICE_ID_KEY)
150 .pipe(Effect.map((existing) => (existing?.trim() ? existing : null)));
151
152 const loadAgentAwarenessRegistrationRecord = readJson<AgentAwarenessRegistrationRecord>(
153 AGENT_AWARENESS_REGISTRATION_KEY,
154 ).pipe(
155 Effect.map((parsed) => {
156 if (
157 !parsed ||
158 typeof parsed !== "object" ||
159 typeof parsed.identity !== "string" ||
160 typeof parsed.signature !== "string"
161 ) {
162 return null;
163 }
164 return {
165 identity: parsed.identity,
166 signature: parsed.signature,
167 ...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
168 ? { pushToStartToken: parsed.pushToStartToken }
169 : {}),
170 };
171 }),
172 );
173
174 const loadRecentThreadShortcuts = readJson<{
175 readonly threads?: ReadonlyArray<RecentThreadShortcut>;
176 }>(RECENT_THREAD_SHORTCUTS_KEY).pipe(
177 Effect.map((parsed) =>
178 pipe(
179 parsed?.threads ?? [],
180 Arr.filter(
181 (thread) =>
182 typeof thread?.environmentId === "string" &&
183 thread.environmentId.length > 0 &&
184 typeof thread.threadId === "string" &&
185 thread.threadId.length > 0 &&
186 typeof thread.title === "string",
187 ),
188 ),
189 ),
190 );
191
192 return MobileStorage.of({
193 loadOrCreateAgentAwarenessDeviceId,
194 loadOrCreateAnalyticsDeviceId: loadOrCreateRandomId(ANALYTICS_DEVICE_ID_KEY),
195 loadAgentAwarenessDeviceId,
196 loadAgentAwarenessRegistrationRecord,
197 saveAgentAwarenessRegistrationRecord: Effect.fn(
198 "MobileStorage.saveAgentAwarenessRegistrationRecord",
199 )((record) => writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record)),
200 clearAgentAwarenessRegistrationRecord: secureStorage.setItem(
201 AGENT_AWARENESS_REGISTRATION_KEY,
202 "",
203 ),
204 loadRecentThreadShortcuts,
205 saveRecentThreadShortcuts: Effect.fn("MobileStorage.saveRecentThreadShortcuts")((threads) =>
206 writeJson(RECENT_THREAD_SHORTCUTS_KEY, { threads }),
207 ),
208 });
209});
210
211export const layer = Layer.effect(MobileStorage, make());