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

environment-cache-store.test.ts

301 lines9.9 KB

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