Open History to see the last commit
1import {
2 ORCHESTRATION_CACHE_SCHEMA_VERSION,
3 StoredOrchestrationShellSnapshot,
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 VcsListRefsResult,
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 Fiber from "effect/Fiber";
19import * as Schema from "effect/Schema";
20import { vi } from "vite-plus/test";
21import * as Deferred from "effect/Deferred";
22import * as Option from "effect/Option";
23
24import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
25import { make } from "./environment-cache-store";
26import { encodeStoredShellSnapshot } from "./shell-cache-encoding";
27
28const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
29const PROJECT_ID = ProjectId.make("project-1");
30const THREAD_ID = ThreadId.make("thread-1");
31const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
32const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
33const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
34 schemaVersion: 1,
35 snapshotSequence: 3,
36 projects: [
37 {
38 id: PROJECT_ID,
39 title: "Project",
40 workspaceRoot: "/repo",
41 repositoryIdentity: null,
42 defaultModelSelection: null,
43 scripts: [],
44 createdAt: "2026-07-29T12:00:00.000Z",
45 updatedAt: "2026-07-29T12:00:00.000Z",
46 },
47 ],
48 threads: [
49 {
50 id: THREAD_ID,
51 projectId: PROJECT_ID,
52 title: "Thread",
53 providerInstanceId: PROVIDER_INSTANCE_ID,
54 modelSelection: {
55 instanceId: PROVIDER_INSTANCE_ID,
56 model: "gpt-5.4",
57 },
58 runtimeMode: "full-access",
59 interactionMode: "default",
60 branch: null,
61 worktreePath: null,
62 activeProviderThreadId: null,
63 lineage: {
64 rootThreadId: THREAD_ID,
65 parentThreadId: null,
66 relationshipToParent: null,
67 },
68 forkedFrom: null,
69 createdBy: "user",
70 creationSource: "mobile",
71 latestRunId: null,
72 activeRunId: null,
73 status: "idle",
74 pendingRuntimeRequest: null,
75 latestVisibleMessage: null,
76 latestUserMessageAt: NOW,
77 activityRunStartedAt: NOW,
78 activityRunStatus: "running",
79 hasActionableProposedPlan: false,
80 itemCount: 0,
81 visibleItemCount: 0,
82 createdAt: NOW,
83 updatedAt: NOW,
84 archivedAt: null,
85 settledOverride: null,
86 settledAt: NOW,
87 unsettledAt: NOW,
88 lastVisitedAt: null,
89 titleRegeneration: {
90 requestId: CommandId.make("title-regeneration-1"),
91 startedAt: NOW,
92 },
93 deletedAt: null,
94 },
95 ],
96 archivedThreads: [],
97};
98const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
99 snapshotSequence: 4,
100 projection: {
101 thread: {
102 id: THREAD_ID,
103 projectId: PROJECT_ID,
104 title: "Thread",
105 providerInstanceId: PROVIDER_INSTANCE_ID,
106 modelSelection: {
107 instanceId: PROVIDER_INSTANCE_ID,
108 model: "gpt-5.4",
109 },
110 runtimeMode: "full-access",
111 interactionMode: "default",
112 branch: null,
113 worktreePath: null,
114 activeProviderThreadId: null,
115 lineage: {
116 rootThreadId: THREAD_ID,
117 parentThreadId: null,
118 relationshipToParent: null,
119 },
120 forkedFrom: null,
121 createdBy: "user",
122 creationSource: "mobile",
123 createdAt: NOW,
124 updatedAt: NOW,
125 archivedAt: null,
126 settledOverride: null,
127 settledAt: NOW,
128 lastVisitedAt: null,
129 deletedAt: null,
130 },
131 runs: [],
132 attempts: [],
133 nodes: [],
134 subagents: [],
135 providerSessions: [],
136 providerThreads: [],
137 providerTurns: [],
138 runtimeRequests: [],
139 messages: [],
140 plans: [],
141 turnItems: [],
142 checkpointScopes: [],
143 checkpoints: [],
144 contextHandoffs: [],
145 contextTransfers: [],
146 visibleTurnItems: [],
147 updatedAt: NOW,
148 },
149};
150const REFS: VcsListRefsResult = {
151 refs: [
152 {
153 name: "main",
154 current: true,
155 isDefault: true,
156 worktreePath: "/repo",
157 },
158 ],
159 isRepo: true,
160 hasPrimaryRemote: true,
161 nextCursor: null,
162 totalCount: 1,
163};
164
165function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey: string) {
166 return `${environmentId}:${kind}:${cacheKey}`;
167}
168
169function makeDatabase() {
170 const values = new Map<string, string>();
171 const schemaVersions = new Map<string, number>();
172 const removed: Array<string> = [];
173 const database = MobileDatabase.of({
174 loadCache: (environmentId, kind, cacheKey) =>
175 Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
176 listCache: (kind) =>
177 Effect.sync(() =>
178 [...values.entries()]
179 .filter(([key]) => key.split(":")[1] === kind)
180 .map(([, payload]) => payload),
181 ),
182 saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
183 Effect.sync(() => {
184 const id = cacheId(environmentId, kind, cacheKey);
185 values.set(id, payload);
186 schemaVersions.set(id, schemaVersion);
187 }),
188 removeCache: (environmentId, kind, cacheKey) =>
189 Effect.sync(() => {
190 const id = cacheId(environmentId, kind, cacheKey);
191 removed.push(id);
192 values.delete(id);
193 }),
194 clearCacheKind: (environmentId, kind) =>
195 Effect.sync(() => {
196 for (const key of values.keys()) {
197 if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
198 }
199 }),
200 clearEnvironmentCache: (environmentId) =>
201 Effect.sync(() => {
202 for (const key of values.keys()) {
203 if (key.startsWith(`${environmentId}:`)) values.delete(key);
204 }
205 }),
206 clearAllCaches: Effect.sync(() => values.clear()),
207 inspectCaches: Effect.succeed([]),
208 loadPreferencesJson: Effect.succeed(Option.none()),
209 savePreferencesJson: () => Effect.void,
210 });
211 return { database, removed, schemaVersions, values };
212}
213
214describe("mobile SQLite environment cache store", () => {
215 it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
216 Effect.gen(function* () {
217 const memory = makeDatabase();
218 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
219
220 yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
221 yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
222
223 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
224 const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
225
226 expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
227 expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
228 "2026-07-29T12:00:00.000Z",
229 );
230 expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
231 "2026-07-29T12:00:00.000Z",
232 );
233 // Working and unsettled threads are exactly what a backgrounded app
234 // caches; a decode failure here discards the whole shell on relaunch.
235 expect(DateTime.formatIso(shell.threads[0]!.activityRunStartedAt!)).toBe(
236 "2026-07-29T12:00:00.000Z",
237 );
238 expect(DateTime.formatIso(shell.threads[0]!.unsettledAt!)).toBe("2026-07-29T12:00:00.000Z");
239 expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
240 "2026-07-29T12:00:00.000Z",
241 );
242 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
243 ORCHESTRATION_CACHE_SCHEMA_VERSION,
244 );
245 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
246 ORCHESTRATION_CACHE_SCHEMA_VERSION,
247 );
248 }),
249 );
250
251 it.effect("round-trips schema-validated VCS refs", () =>
252 Effect.gen(function* () {
253 const memory = makeDatabase();
254 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
255
256 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
257
258 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
259 }),
260 );
261
262 it.effect("deletes a corrupt cache record and treats it as a miss", () =>
263 Effect.gen(function* () {
264 const memory = makeDatabase();
265 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
266 const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
267 memory.values.set(id, "{not-json");
268
269 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
270 expect(memory.removed).toEqual([id]);
271 }),
272 );
273
274 it.effect("removes one persisted VCS ref snapshot", () =>
275 Effect.gen(function* () {
276 const memory = makeDatabase();
277 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
278 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
279
280 yield* store.removeVcsRefs(ENVIRONMENT_ID, "/repo");
281
282 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
283 expect(memory.removed).toContain(cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"));
284 }),
285 );
286
287 it.effect("clears every persisted VCS ref snapshot in one environment", () =>
288 Effect.gen(function* () {
289 const memory = makeDatabase();
290 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
291 const otherEnvironmentId = EnvironmentId.make("environment-2");
292 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
293 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo-worktree", REFS);
294 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
295
296 yield* store.clearVcsRefs(ENVIRONMENT_ID);
297
298 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
299 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo-worktree")).toEqual(Option.none());
300 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
301 }),
302 );
303
304 it.effect("clears one environment without touching another", () =>
305 Effect.gen(function* () {
306 const memory = makeDatabase();
307 const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
308 const otherEnvironmentId = EnvironmentId.make("environment-2");
309 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
310 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
311
312 yield* store.clear(ENVIRONMENT_ID);
313
314 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
315 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
316 }),
317 );
318});
319
320describe("cooperative shell cache encoding", () => {
321 const encodeOriginal = Schema.encodeEffect(
322 Schema.fromJsonString(StoredOrchestrationShellSnapshot),
323 );
324 const stored = {
325 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
326 environmentId: ENVIRONMENT_ID,
327 snapshot: {
328 ...SHELL_SNAPSHOT,
329 projects: SHELL_SNAPSHOT.projects.map((project) => ({
330 ...project,
331 title: " Project ",
332 unexpected: "drop this field",
333 })),
334 threads: Array.from({ length: 64 }, (_, index) => ({
335 ...SHELL_SNAPSHOT.threads[0]!,
336 id: ThreadId.make(`thread-${index}`),
337 branch: " main ",
338 activityRunStartedAt: index % 2 === 0 ? NOW : null,
339 unsettledAt: index % 2 === 0 ? NOW : null,
340 modelSelection: {
341 instanceId: PROVIDER_INSTANCE_ID,
342 model: " gpt-5.4 ",
343 unexpected: "drop this field",
344 },
345 unexpected: "drop this field",
346 })),
347 archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
348 unexpected: "drop this field",
349 },
350 unexpected: "drop this field",
351 };
352
353 it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
354 Effect.gen(function* () {
355 const expected = yield* encodeOriginal(stored);
356 const actual = yield* encodeStoredShellSnapshot(stored);
357 expect(actual).toBe(expected);
358 const parsed = JSON.parse(actual);
359 expect(parsed).not.toHaveProperty("unexpected");
360 expect(parsed.snapshot).not.toHaveProperty("unexpected");
361 expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
362 expect(parsed.snapshot.projects[0].title).toBe("Project");
363 expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
364 expect(parsed.snapshot.threads[0].branch).toBe("main");
365 expect(parsed.snapshot.threads[0].modelSelection).toEqual({
366 instanceId: "codex",
367 model: "gpt-5.4",
368 });
369 expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
370 expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
371 expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
372 }),
373 );
374
375 it.effect("still rejects invalid rows after an encoding batch yields", () =>
376 Effect.gen(function* () {
377 const invalid = {
378 ...stored,
379 snapshot: {
380 ...stored.snapshot,
381 threads: [...stored.snapshot.threads, { ...stored.snapshot.threads[0]!, itemCount: -1 }],
382 },
383 };
384 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalid))).toBe(true);
385 }),
386 );
387
388 it.effect("cancels the pending host timer when encoding is interrupted", () =>
389 Effect.gen(function* () {
390 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
391 const fakeSetTimeout = globalThis.setTimeout;
392 const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
393 vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
394 const timer = fakeSetTimeout(...args);
395 Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
396 return timer;
397 });
398 const clearTimer = vi.spyOn(globalThis, "clearTimeout");
399 const fiber = yield* Effect.forkScoped(
400 Effect.suspend(() => encodeStoredShellSnapshot(stored)),
401 );
402 try {
403 const pendingTimer = yield* Deferred.await(scheduled);
404 expect(vi.getTimerCount()).toBe(1);
405 yield* Fiber.interrupt(fiber);
406 expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
407 expect(vi.getTimerCount()).toBe(0);
408 } finally {
409 yield* Fiber.interrupt(fiber);
410 vi.restoreAllMocks();
411 vi.useRealTimers();
412 }
413 }),
414 );
415});