Open History to see the last commit
1import {
2 ORCHESTRATION_CACHE_SCHEMA_VERSION,
3 ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
4} from "@t3tools/client-runtime/platform";
5import {
6 CommandId,
7 EnvironmentId,
8 ProjectId,
9 ProviderInstanceId,
10 ThreadId,
11 type OrchestrationV2ShellSnapshot,
12 type OrchestrationV2ThreadDetailSnapshot,
13 type ThreadPullRequestLink,
14} from "@t3tools/contracts";
15import { describe, expect, it } from "@effect/vitest";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Logger from "effect/Logger";
19import * as Option from "effect/Option";
20
21import * as MobileDatabase from "../persistence/mobile-database";
22import { make } from "./environment-cache-store";
23
24const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
25const PROJECT_ID = ProjectId.make("project-1");
26const THREAD_ID = ThreadId.make("thread-1");
27const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
28const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
29const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
30 schemaVersion: 1,
31 snapshotSequence: 3,
32 projects: [
33 {
34 id: PROJECT_ID,
35 title: "Project",
36 workspaceRoot: "/repo",
37 repositoryIdentity: null,
38 defaultModelSelection: null,
39 scripts: [],
40 createdAt: "2026-07-29T12:00:00.000Z",
41 updatedAt: "2026-07-29T12:00:00.000Z",
42 },
43 ],
44 threads: [
45 {
46 id: THREAD_ID,
47 projectId: PROJECT_ID,
48 title: "Thread",
49 providerInstanceId: PROVIDER_INSTANCE_ID,
50 modelSelection: {
51 instanceId: PROVIDER_INSTANCE_ID,
52 model: "gpt-5.4",
53 },
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: null,
57 worktreePath: null,
58 activeProviderThreadId: null,
59 lineage: {
60 rootThreadId: THREAD_ID,
61 parentThreadId: null,
62 relationshipToParent: null,
63 },
64 forkedFrom: null,
65 createdBy: "user",
66 creationSource: "mobile",
67 latestRunId: null,
68 activeRunId: null,
69 status: "idle",
70 pendingRuntimeRequest: null,
71 latestVisibleMessage: null,
72 latestUserMessageAt: NOW,
73 activityRunStartedAt: NOW,
74 activityRunStatus: "running",
75 hasActionableProposedPlan: false,
76 itemCount: 0,
77 visibleItemCount: 0,
78 createdAt: NOW,
79 updatedAt: NOW,
80 archivedAt: null,
81 settledOverride: null,
82 settledAt: NOW,
83 unsettledAt: NOW,
84 lastVisitedAt: null,
85 titleRegeneration: {
86 requestId: CommandId.make("title-regeneration-1"),
87 startedAt: NOW,
88 },
89 deletedAt: null,
90 },
91 ],
92 archivedThreads: [],
93};
94const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
95 snapshotSequence: 4,
96 projection: {
97 thread: {
98 id: THREAD_ID,
99 projectId: PROJECT_ID,
100 title: "Thread",
101 providerInstanceId: PROVIDER_INSTANCE_ID,
102 modelSelection: {
103 instanceId: PROVIDER_INSTANCE_ID,
104 model: "gpt-5.4",
105 },
106 runtimeMode: "full-access",
107 interactionMode: "default",
108 branch: null,
109 worktreePath: null,
110 activeProviderThreadId: null,
111 lineage: {
112 rootThreadId: THREAD_ID,
113 parentThreadId: null,
114 relationshipToParent: null,
115 },
116 forkedFrom: null,
117 createdBy: "user",
118 creationSource: "mobile",
119 createdAt: NOW,
120 updatedAt: NOW,
121 archivedAt: null,
122 settledOverride: null,
123 settledAt: NOW,
124 lastVisitedAt: null,
125 deletedAt: null,
126 },
127 runs: [],
128 attempts: [],
129 nodes: [],
130 subagents: [],
131 providerSessions: [],
132 providerThreads: [],
133 providerTurns: [],
134 runtimeRequests: [],
135 messages: [],
136 plans: [],
137 turnItems: [],
138 checkpointScopes: [],
139 checkpoints: [],
140 contextHandoffs: [],
141 contextTransfers: [],
142 visibleTurnItems: [],
143 updatedAt: NOW,
144 },
145};
146
147function cacheId(
148 environmentId: EnvironmentId,
149 kind: MobileDatabase.ClientCacheKind,
150 cacheKey: string,
151) {
152 return `${environmentId}:${kind}:${cacheKey}`;
153}
154
155function makeDatabase() {
156 const values = new Map<string, string>();
157 const schemaVersions = new Map<string, number>();
158 const removed: Array<string> = [];
159 const database = MobileDatabase.MobileDatabase.of({
160 loadCache: (environmentId, kind, cacheKey) =>
161 Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
162 listCache: (kind) =>
163 Effect.sync(() =>
164 [...values.entries()]
165 .filter(([key]) => key.split(":")[1] === kind)
166 .map(([, payload]) => payload),
167 ),
168 saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
169 Effect.sync(() => {
170 const id = cacheId(environmentId, kind, cacheKey);
171 values.set(id, payload);
172 schemaVersions.set(id, schemaVersion);
173 }),
174 removeCache: (environmentId, kind, cacheKey) =>
175 Effect.sync(() => {
176 const id = cacheId(environmentId, kind, cacheKey);
177 removed.push(id);
178 values.delete(id);
179 }),
180 clearCacheKind: (environmentId, kind) =>
181 Effect.sync(() => {
182 for (const key of values.keys()) {
183 if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
184 }
185 }),
186 clearEnvironmentCache: (environmentId) =>
187 Effect.sync(() => {
188 for (const key of values.keys()) {
189 if (key.startsWith(`${environmentId}:`)) values.delete(key);
190 }
191 }),
192 clearAllCaches: Effect.sync(() => values.clear()),
193 inspectCaches: Effect.succeed([]),
194 loadPreferencesJson: Effect.succeed(Option.none()),
195 savePreferencesJson: () => Effect.void,
196 });
197 return { database, removed, schemaVersions, values };
198}
199
200describe("mobile SQLite environment cache store", () => {
201 it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
202 Effect.gen(function* () {
203 const memory = makeDatabase();
204 const store = yield* make().pipe(
205 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
206 );
207
208 yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
209 yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
210
211 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
212 const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
213
214 expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
215 expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
216 "2026-07-29T12:00:00.000Z",
217 );
218 expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
219 "2026-07-29T12:00:00.000Z",
220 );
221 expect(DateTime.formatIso(shell.threads[0]!.activityRunStartedAt!)).toBe(
222 "2026-07-29T12:00:00.000Z",
223 );
224 expect(DateTime.formatIso(shell.threads[0]!.unsettledAt!)).toBe("2026-07-29T12:00:00.000Z");
225 expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
226 "2026-07-29T12:00:00.000Z",
227 );
228 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
229 ORCHESTRATION_CACHE_SCHEMA_VERSION,
230 );
231 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
232 ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
233 );
234 }),
235 );
236
237 it.live("returns cached threads before their pull request links, which load after", () =>
238 Effect.gen(function* () {
239 const memory = makeDatabase();
240 const store = yield* make().pipe(
241 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
242 );
243 const link: ThreadPullRequestLink = {
244 host: "github.com",
245 repository: "pingdotgg/t3code",
246 number: 42,
247 url: "https://github.com/pingdotgg/t3code/pull/42",
248 source: "agent",
249 linkedAt: "2026-07-29T12:00:00.000Z",
250 snapshot: null,
251 stack: null,
252 };
253 const linked = { ...SHELL_SNAPSHOT.threads[0]!, pullRequests: [link] };
254 const unlinked = { ...SHELL_SNAPSHOT.threads[0]!, id: ThreadId.make("thread-2") };
255 yield* store.saveShell(ENVIRONMENT_ID, {
256 ...SHELL_SNAPSHOT,
257 threads: [linked, unlinked],
258 });
259
260 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
261 expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]);
262 const links = yield* shell.loadPullRequests!;
263 expect([...links]).toEqual([[THREAD_ID, [link]]]);
264 }),
265 );
266
267 it.live("keeps cached threads when their pull request links cannot be read", () => {
268 const messages: Array<unknown> = [];
269 const logger = Logger.make(({ message }) => {
270 messages.push(message);
271 });
272 return Effect.gen(function* () {
273 const memory = makeDatabase();
274 const store = yield* make().pipe(
275 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
276 );
277 const link: ThreadPullRequestLink = {
278 host: "github.com",
279 repository: "pingdotgg/t3code",
280 number: 5,
281 url: "https://github.com/pingdotgg/t3code/pull/5",
282 source: "agent",
283 linkedAt: "2026-07-29T12:00:00.000Z",
284 snapshot: null,
285 stack: null,
286 };
287 const readable = {
288 ...SHELL_SNAPSHOT.threads[0]!,
289 id: ThreadId.make("thread-2"),
290 pullRequests: [link],
291 };
292 yield* store.saveShell(ENVIRONMENT_ID, {
293 ...SHELL_SNAPSHOT,
294 threads: [SHELL_SNAPSHOT.threads[0]!, readable],
295 });
296 const id = cacheId(ENVIRONMENT_ID, "shell", "snapshot");
297 const payload = JSON.parse(memory.values.get(id)!);
298 payload.snapshot.threads[0].pullRequests = [{ number: -1 }];
299 memory.values.set(id, JSON.stringify(payload));
300
301 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
302 expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]);
303 expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]);
304 expect(messages).toHaveLength(1);
305 expect(memory.removed).toEqual([]);
306 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
307 });
308
309 it.effect("deletes a corrupt cache record and treats it as a miss", () =>
310 Effect.gen(function* () {
311 const memory = makeDatabase();
312 const store = yield* make().pipe(
313 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
314 );
315 const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
316 memory.values.set(id, "{not-json");
317
318 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
319 expect(memory.removed).toEqual([id]);
320 }),
321 );
322});