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

environment-cache-store.test.ts

431 lines14.5 KB

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 * as 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(
166 environmentId: EnvironmentId,
167 kind: MobileDatabase.ClientCacheKind,
168 cacheKey: string,
169) {
170 return `${environmentId}:${kind}:${cacheKey}`;
172​
173function makeDatabase() {
174 const values = new Map<string, string>();
175 const schemaVersions = new Map<string, number>();
176 const removed: Array<string> = [];
177 const database = MobileDatabase.MobileDatabase.of({
178 loadCache: (environmentId, kind, cacheKey) =>
179 Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
180 listCache: (kind) =>
181 Effect.sync(() =>
182 [...values.entries()]
183 .filter(([key]) => key.split(":")[1] === kind)
184 .map(([, payload]) => payload),
185 ),
186 saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
187 Effect.sync(() => {
188 const id = cacheId(environmentId, kind, cacheKey);
189 values.set(id, payload);
190 schemaVersions.set(id, schemaVersion);
191 }),
192 removeCache: (environmentId, kind, cacheKey) =>
193 Effect.sync(() => {
194 const id = cacheId(environmentId, kind, cacheKey);
195 removed.push(id);
196 values.delete(id);
197 }),
198 clearCacheKind: (environmentId, kind) =>
199 Effect.sync(() => {
200 for (const key of values.keys()) {
201 if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
202 }
203 }),
204 clearEnvironmentCache: (environmentId) =>
205 Effect.sync(() => {
206 for (const key of values.keys()) {
207 if (key.startsWith(`${environmentId}:`)) values.delete(key);
208 }
209 }),
210 clearAllCaches: Effect.sync(() => values.clear()),
211 inspectCaches: Effect.succeed([]),
212 loadPreferencesJson: Effect.succeed(Option.none()),
213 savePreferencesJson: () => Effect.void,
214 });
215 return { database, removed, schemaVersions, values };
217​
218describe("mobile SQLite environment cache store", () => {
219 it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
220 Effect.gen(function* () {
221 const memory = makeDatabase();
222 const store = yield* make().pipe(
223 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
224 );
225​
226 yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
227 yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
228​
229 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
230 const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
231​
232 expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
233 expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
234 "2026-07-29T12:00:00.000Z",
235 );
236 expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
237 "2026-07-29T12:00:00.000Z",
238 );
239 // Working and unsettled threads are exactly what a backgrounded app
240 // caches; a decode failure here discards the whole shell on relaunch.
241 expect(DateTime.formatIso(shell.threads[0]!.activityRunStartedAt!)).toBe(
242 "2026-07-29T12:00:00.000Z",
243 );
244 expect(DateTime.formatIso(shell.threads[0]!.unsettledAt!)).toBe("2026-07-29T12:00:00.000Z");
245 expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
246 "2026-07-29T12:00:00.000Z",
247 );
248 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
249 ORCHESTRATION_CACHE_SCHEMA_VERSION,
250 );
251 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
252 ORCHESTRATION_CACHE_SCHEMA_VERSION,
253 );
254 }),
255 );
256​
257 it.effect("round-trips schema-validated VCS refs", () =>
258 Effect.gen(function* () {
259 const memory = makeDatabase();
260 const store = yield* make().pipe(
261 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
262 );
263​
264 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
265​
266 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
267 }),
268 );
269​
270 it.effect("deletes a corrupt cache record and treats it as a miss", () =>
271 Effect.gen(function* () {
272 const memory = makeDatabase();
273 const store = yield* make().pipe(
274 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
275 );
276 const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
277 memory.values.set(id, "{not-json");
278​
279 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
280 expect(memory.removed).toEqual([id]);
281 }),
282 );
283​
284 it.effect("removes one persisted VCS ref snapshot", () =>
285 Effect.gen(function* () {
286 const memory = makeDatabase();
287 const store = yield* make().pipe(
288 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
289 );
290 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
291​
292 yield* store.removeVcsRefs(ENVIRONMENT_ID, "/repo");
293​
294 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
295 expect(memory.removed).toContain(cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"));
296 }),
297 );
298​
299 it.effect("clears every persisted VCS ref snapshot in one environment", () =>
300 Effect.gen(function* () {
301 const memory = makeDatabase();
302 const store = yield* make().pipe(
303 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
304 );
305 const otherEnvironmentId = EnvironmentId.make("environment-2");
306 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
307 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo-worktree", REFS);
308 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
309​
310 yield* store.clearVcsRefs(ENVIRONMENT_ID);
311​
312 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
313 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo-worktree")).toEqual(Option.none());
314 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
315 }),
316 );
317​
318 it.effect("clears one environment without touching another", () =>
319 Effect.gen(function* () {
320 const memory = makeDatabase();
321 const store = yield* make().pipe(
322 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
323 );
324 const otherEnvironmentId = EnvironmentId.make("environment-2");
325 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
326 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
327​
328 yield* store.clear(ENVIRONMENT_ID);
329​
330 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
331 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
332 }),
333 );
334});
335​
336describe("cooperative shell cache encoding", () => {
337 const encodeOriginal = Schema.encodeEffect(
338 Schema.fromJsonString(StoredOrchestrationShellSnapshot),
339 );
340 const stored = {
341 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
342 environmentId: ENVIRONMENT_ID,
343 snapshot: {
344 ...SHELL_SNAPSHOT,
345 projects: SHELL_SNAPSHOT.projects.map((project) => ({
346 ...project,
347 title: " Project ",
348 unexpected: "drop this field",
349 })),
350 threads: Array.from({ length: 64 }, (_, index) => ({
351 ...SHELL_SNAPSHOT.threads[0]!,
352 id: ThreadId.make(`thread-${index}`),
353 branch: " main ",
354 activityRunStartedAt: index % 2 === 0 ? NOW : null,
355 unsettledAt: index % 2 === 0 ? NOW : null,
356 modelSelection: {
357 instanceId: PROVIDER_INSTANCE_ID,
358 model: " gpt-5.4 ",
359 unexpected: "drop this field",
360 },
361 unexpected: "drop this field",
362 })),
363 archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
364 unexpected: "drop this field",
365 },
366 unexpected: "drop this field",
367 };
368​
369 it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
370 Effect.gen(function* () {
371 const expected = yield* encodeOriginal(stored);
372 const actual = yield* encodeStoredShellSnapshot(stored);
373 expect(actual).toBe(expected);
374 const parsed = JSON.parse(actual);
375 expect(parsed).not.toHaveProperty("unexpected");
376 expect(parsed.snapshot).not.toHaveProperty("unexpected");
377 expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
378 expect(parsed.snapshot.projects[0].title).toBe("Project");
379 expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
380 expect(parsed.snapshot.threads[0].branch).toBe("main");
381 expect(parsed.snapshot.threads[0].modelSelection).toEqual({
382 instanceId: "codex",
383 model: "gpt-5.4",
384 });
385 expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
386 expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
387 expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
388 }),
389 );
390​
391 it.effect("still rejects invalid rows after an encoding batch yields", () =>
392 Effect.gen(function* () {
393 const invalid = {
394 ...stored,
395 snapshot: {
396 ...stored.snapshot,
397 threads: [...stored.snapshot.threads, { ...stored.snapshot.threads[0]!, itemCount: -1 }],
398 },
399 };
400 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalid))).toBe(true);
401 }),
402 );
403​
404 it.effect("cancels the pending host timer when encoding is interrupted", () =>
405 Effect.gen(function* () {
406 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
407 const fakeSetTimeout = globalThis.setTimeout;
408 const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
409 vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
410 const timer = fakeSetTimeout(...args);
411 Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
412 return timer;
413 });
414 const clearTimer = vi.spyOn(globalThis, "clearTimeout");
415 const fiber = yield* Effect.forkScoped(
416 Effect.suspend(() => encodeStoredShellSnapshot(stored)),
417 );
418 try {
419 const pendingTimer = yield* Deferred.await(scheduled);
420 expect(vi.getTimerCount()).toBe(1);
421 yield* Fiber.interrupt(fiber);
422 expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
423 expect(vi.getTimerCount()).toBe(0);
424 } finally {
425 yield* Fiber.interrupt(fiber);
426 vi.restoreAllMocks();
427 vi.useRealTimers();
428 }
429 }),
430 );
431});