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

environment-cache-store.test.ts

401 lines13.3 KB

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