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