Open History to see the last commit
1import {
2 ORCHESTRATION_CACHE_SCHEMA_VERSION,
3 ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
4 COMPACT_THREAD_CACHE_SCHEMA_VERSION,
5 StoredOrchestrationThreadSnapshot,
6} from "@t3tools/client-runtime/platform";
7import {
8 CommandId,
9 EnvironmentId,
10 ProjectId,
11 ProviderInstanceId,
12 RunId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2ShellSnapshot,
16 type OrchestrationV2ThreadDetailSnapshot,
17 type ThreadPullRequestLink,
18} from "@t3tools/contracts";
19import { describe, expect, it } from "@effect/vitest";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Logger from "effect/Logger";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25
26import * as MobileDatabase from "../persistence/mobile-database";
27import { make } from "./environment-cache-store";
28
29const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
30const PROJECT_ID = ProjectId.make("project-1");
31const THREAD_ID = ThreadId.make("thread-1");
32const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
33const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
34const encodeLegacyThreadSnapshot = Schema.encodeEffect(
35 Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
36);
37const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
38 schemaVersion: 1,
39 snapshotSequence: 3,
40 projects: [
41 {
42 id: PROJECT_ID,
43 title: "Project",
44 workspaceRoot: "/repo",
45 repositoryIdentity: null,
46 defaultModelSelection: null,
47 scripts: [],
48 createdAt: "2026-07-29T12:00:00.000Z",
49 updatedAt: "2026-07-29T12:00:00.000Z",
50 },
51 ],
52 threads: [
53 {
54 id: THREAD_ID,
55 projectId: PROJECT_ID,
56 title: "Thread",
57 providerInstanceId: PROVIDER_INSTANCE_ID,
58 modelSelection: {
59 instanceId: PROVIDER_INSTANCE_ID,
60 model: "gpt-5.4",
61 },
62 runtimeMode: "full-access",
63 interactionMode: "default",
64 branch: null,
65 worktreePath: null,
66 activeProviderThreadId: null,
67 lineage: {
68 rootThreadId: THREAD_ID,
69 parentThreadId: null,
70 relationshipToParent: null,
71 },
72 forkedFrom: null,
73 createdBy: "user",
74 creationSource: "mobile",
75 latestRunId: null,
76 activeRunId: null,
77 status: "idle",
78 pendingRuntimeRequest: null,
79 latestVisibleMessage: null,
80 latestUserMessageAt: NOW,
81 activityRunStartedAt: NOW,
82 activityRunStatus: "running",
83 hasActionableProposedPlan: false,
84 itemCount: 0,
85 visibleItemCount: 0,
86 createdAt: NOW,
87 updatedAt: NOW,
88 archivedAt: null,
89 settledOverride: null,
90 settledAt: NOW,
91 unsettledAt: NOW,
92 lastVisitedAt: null,
93 titleRegeneration: {
94 requestId: CommandId.make("title-regeneration-1"),
95 startedAt: NOW,
96 },
97 deletedAt: null,
98 },
99 ],
100 archivedThreads: [],
101};
102const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
103 snapshotSequence: 4,
104 projection: {
105 thread: {
106 id: THREAD_ID,
107 projectId: PROJECT_ID,
108 title: "Thread",
109 providerInstanceId: PROVIDER_INSTANCE_ID,
110 modelSelection: {
111 instanceId: PROVIDER_INSTANCE_ID,
112 model: "gpt-5.4",
113 },
114 runtimeMode: "full-access",
115 interactionMode: "default",
116 branch: null,
117 worktreePath: null,
118 activeProviderThreadId: null,
119 lineage: {
120 rootThreadId: THREAD_ID,
121 parentThreadId: null,
122 relationshipToParent: null,
123 },
124 forkedFrom: null,
125 createdBy: "user",
126 creationSource: "mobile",
127 createdAt: NOW,
128 updatedAt: NOW,
129 archivedAt: null,
130 settledOverride: null,
131 settledAt: NOW,
132 lastVisitedAt: null,
133 deletedAt: null,
134 },
135 runs: [],
136 attempts: [],
137 nodes: [],
138 subagents: [],
139 providerSessions: [],
140 providerThreads: [],
141 providerTurns: [],
142 runtimeRequests: [],
143 messages: [],
144 plans: [],
145 turnItems: [],
146 checkpointScopes: [],
147 checkpoints: [],
148 contextHandoffs: [],
149 contextTransfers: [],
150 visibleTurnItems: [],
151 updatedAt: NOW,
152 },
153};
154
155function cacheId(
156 environmentId: EnvironmentId,
157 kind: MobileDatabase.ClientCacheKind,
158 cacheKey: string,
159) {
160 return `${environmentId}:${kind}:${cacheKey}`;
161}
162
163function threadSnapshotWithItems(): OrchestrationV2ThreadDetailSnapshot {
164 const local = {
165 id: TurnItemId.make("local-notice"),
166 threadId: THREAD_ID,
167 runId: null,
168 nodeId: null,
169 providerThreadId: null,
170 providerTurnId: null,
171 nativeItemRef: null,
172 parentItemId: null,
173 ordinal: 10,
174 status: "completed" as const,
175 title: null,
176 startedAt: NOW,
177 completedAt: NOW,
178 updatedAt: NOW,
179 type: "system_notice" as const,
180 message: "A settled local notice.",
181 };
182 const hidden = { ...local, id: TurnItemId.make("hidden-notice"), ordinal: 11 };
183 const inherited = {
184 ...local,
185 id: TurnItemId.make("inherited-notice"),
186 threadId: ThreadId.make("parent-thread"),
187 };
188 return {
189 ...THREAD_SNAPSHOT,
190 historyCursor: "older-page",
191 hasMoreHistory: true,
192 latestLocalTurnOrdinal: 11,
193 projection: {
194 ...THREAD_SNAPSHOT.projection,
195 turnItems: [local, hidden],
196 visibleTurnItems: [
197 {
198 position: 0,
199 visibility: "inherited",
200 sourceThreadId: inherited.threadId,
201 sourceItemId: inherited.id,
202 item: inherited,
203 },
204 {
205 position: 1,
206 visibility: "local",
207 sourceThreadId: THREAD_ID,
208 sourceItemId: local.id,
209 item: local,
210 },
211 ],
212 },
213 };
214}
215
216function makeDatabase() {
217 const values = new Map<string, string>();
218 const schemaVersions = new Map<string, number>();
219 const removed: Array<string> = [];
220 const database = MobileDatabase.MobileDatabase.of({
221 loadCache: (environmentId, kind, cacheKey) =>
222 Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
223 listCache: (kind) =>
224 Effect.sync(() =>
225 [...values.entries()]
226 .filter(([key]) => key.split(":")[1] === kind)
227 .map(([, payload]) => payload),
228 ),
229 saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
230 Effect.sync(() => {
231 const id = cacheId(environmentId, kind, cacheKey);
232 values.set(id, payload);
233 schemaVersions.set(id, schemaVersion);
234 }),
235 removeCache: (environmentId, kind, cacheKey) =>
236 Effect.sync(() => {
237 const id = cacheId(environmentId, kind, cacheKey);
238 removed.push(id);
239 values.delete(id);
240 }),
241 clearCacheKind: (environmentId, kind) =>
242 Effect.sync(() => {
243 for (const key of values.keys()) {
244 if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
245 }
246 }),
247 clearEnvironmentCache: (environmentId) =>
248 Effect.sync(() => {
249 for (const key of values.keys()) {
250 if (key.startsWith(`${environmentId}:`)) values.delete(key);
251 }
252 }),
253 clearAllCaches: Effect.sync(() => values.clear()),
254 inspectCaches: Effect.succeed([]),
255 loadPreferencesJson: Effect.succeed(Option.none()),
256 savePreferencesJson: () => Effect.void,
257 });
258 return { database, removed, schemaVersions, values };
259}
260
261describe("mobile SQLite environment cache store", () => {
262 it.effect("loads a V5 record and migrates to V6 on the next save without losing items", () =>
263 Effect.gen(function* () {
264 const memory = makeDatabase();
265 const store = yield* make().pipe(
266 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
267 );
268 const snapshot = threadSnapshotWithItems();
269 const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID);
270 const raw = yield* encodeLegacyThreadSnapshot({
271 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
272 environmentId: ENVIRONMENT_ID,
273 threadId: THREAD_ID,
274 snapshot,
275 });
276 memory.values.set(id, raw);
277 const loaded = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
278 expect(loaded).toEqual(snapshot);
279 expect(memory.values.get(id)).toBe(raw);
280 yield* store.saveThread(ENVIRONMENT_ID, loaded);
281 expect(memory.schemaVersions.get(id)).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION);
282 expect(Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID))).toEqual(
283 snapshot,
284 );
285 expect(memory.removed).toEqual([]);
286 }),
287 );
288
289 it.effect("discards corrupt or partial thread records so they can be refetched", () =>
290 Effect.gen(function* () {
291 const memory = makeDatabase();
292 const store = yield* make().pipe(
293 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
294 );
295 const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID);
296 yield* store.saveThread(ENVIRONMENT_ID, threadSnapshotWithItems());
297 const raw = memory.values.get(id)!;
298 const partial = JSON.parse(raw);
299 delete partial.snapshot.projection.visibleTurnItems;
300 const invalidItem = JSON.parse(raw);
301 delete invalidItem.snapshot.projection.visibleTurnItems[1].item.message;
302 const corruptions = [
303 partial,
304 invalidItem,
305 ...[
306 (value: typeof partial) => {
307 delete value.snapshot.turnItemCount;
308 },
309 (value: typeof partial) => {
310 delete value.snapshot.turnItemsOmitLocalVisible;
311 },
312 (value: typeof partial) => {
313 value.snapshot.turnItemsOmitLocalVisible = false;
314 },
315 (value: typeof partial) => {
316 value.snapshot.projection.visibleTurnItems.pop();
317 },
318 (value: typeof partial) => {
319 value.snapshot.projection.visibleTurnItems.shift();
320 },
321 (value: typeof partial) => {
322 value.snapshot.projection.turnItems.pop();
323 },
324 (value: typeof partial) => {
325 value.snapshot.turnItemCount = 0;
326 },
327 (value: typeof partial) => {
328 value.snapshot.projection.visibleTurnItems[1].sourceItemId = "wrong-item";
329 },
330 (value: typeof partial) => {
331 value.snapshot.projection.visibleTurnItems[1].visibility = "inherited";
332 },
333 (value: typeof partial) => {
334 value.snapshot.projection.visibleTurnItems[1].item.threadId = "wrong-thread";
335 },
336 (value: typeof partial) => {
337 value.snapshot.projection.thread.id = "wrong-thread";
338 },
339 (value: typeof partial) => {
340 value.snapshot.projection.turnItems.push(
341 value.snapshot.projection.visibleTurnItems[1].item,
342 );
343 },
344 (value: typeof partial) => {
345 value.snapshot.projection.visibleTurnItems.push(
346 value.snapshot.projection.visibleTurnItems[1],
347 );
348 },
349 ].map((corrupt) => {
350 const value = JSON.parse(raw);
351 corrupt(value);
352 return value;
353 }),
354 ];
355 const invalidRecords = ["{broken", ...corruptions.map((value) => JSON.stringify(value))];
356 for (const invalid of invalidRecords) {
357 memory.values.set(id, invalid);
358 expect(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID)).toEqual(Option.none());
359 expect(memory.values.has(id)).toBe(false);
360 }
361 expect(memory.removed).toEqual(invalidRecords.map(() => id));
362 yield* store.saveThread(ENVIRONMENT_ID, threadSnapshotWithItems());
363 expect(Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID))).toEqual(
364 threadSnapshotWithItems(),
365 );
366 }),
367 );
368
369 it.effect("round-trips V5 exactly and restores shared items before returning to a consumer", () =>
370 Effect.gen(function* () {
371 const memory = makeDatabase();
372 const store = yield* make().pipe(
373 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
374 );
375 const original = threadSnapshotWithItems();
376 const local = original.projection.visibleTurnItems[1]!;
377 const inherited = original.projection.visibleTurnItems[0]!;
378 const synthetic = { ...local.item, id: TurnItemId.make("synthetic-notice"), ordinal: 12 };
379 const fork = {
380 id: TurnItemId.make("fork-marker"),
381 threadId: THREAD_ID,
382 runId: null,
383 nodeId: null,
384 providerTurnId: null,
385 nativeItemRef: null,
386 parentItemId: null,
387 ordinal: 0,
388 status: "completed" as const,
389 title: null,
390 startedAt: null,
391 completedAt: NOW,
392 updatedAt: NOW,
393 type: "fork" as const,
394 source: {
395 type: "run" as const,
396 threadId: ThreadId.make("parent-thread"),
397 runId: RunId.make("parent-run"),
398 },
399 targetThreadId: THREAD_ID,
400 };
401 const snapshot = {
402 ...original,
403 projection: {
404 ...original.projection,
405 turnItems: [local.item, synthetic, original.projection.turnItems[1]!],
406 visibleTurnItems: [
407 { ...local, position: 0 },
408 {
409 ...inherited,
410 position: 1,
411 sourceItemId: local.sourceItemId,
412 item: { ...inherited.item, id: local.item.id },
413 },
414 {
415 ...local,
416 position: 2,
417 visibility: "synthetic" as const,
418 sourceItemId: synthetic.id,
419 item: synthetic,
420 },
421 {
422 position: 3,
423 visibility: "synthetic" as const,
424 sourceThreadId: fork.source.threadId,
425 sourceItemId: fork.id,
426 item: fork,
427 },
428 ],
429 },
430 };
431 yield* store.saveThread(ENVIRONMENT_ID, snapshot);
432 const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID);
433 const encoded = JSON.parse(memory.values.get(id)!);
434 expect(encoded.schemaVersion).toBe(6);
435 expect(memory.schemaVersions.get(id)).toBe(6);
436 expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(true);
437 expect(encoded.snapshot.turnItemCount).toBe(3);
438 expect(encoded.snapshot.visibleTurnItemCount).toBe(4);
439 expect(encoded.snapshot.projection.turnItems.map((item: { id: string }) => item.id)).toEqual([
440 "hidden-notice",
441 ]);
442
443 const duplicate = JSON.parse(memory.values.get(id)!);
444 duplicate.snapshot.projection.visibleTurnItems.push({
445 ...duplicate.snapshot.projection.visibleTurnItems[1],
446 position: 4,
447 });
448 duplicate.snapshot.visibleTurnItemCount += 1;
449 memory.values.set(id, JSON.stringify(duplicate));
450 expect(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID)).toEqual(Option.none());
451 expect(memory.values.has(id)).toBe(false);
452 expect(memory.removed).toEqual([id]);
453 yield* store.saveThread(ENVIRONMENT_ID, snapshot);
454
455 const loaded = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
456 expect(loaded).toEqual(snapshot);
457 expect(loaded).not.toHaveProperty("turnItemsOmitLocalVisible");
458 expect(loaded).not.toHaveProperty("turnItemCount");
459 expect(loaded).not.toHaveProperty("visibleTurnItemCount");
460 expect(loaded.projection.turnItems[0]).toBe(loaded.projection.visibleTurnItems[0]!.item);
461 expect(loaded.projection.turnItems[1]).toBe(loaded.projection.visibleTurnItems[2]!.item);
462 expect(snapshot.projection.turnItems).toHaveLength(3);
463 }),
464 );
465
466 it.effect("keeps a full projection when visible rows cannot reproduce the original items", () =>
467 Effect.gen(function* () {
468 const memory = makeDatabase();
469 const store = yield* make().pipe(
470 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
471 );
472 const original = threadSnapshotWithItems();
473 const local = original.projection.turnItems[0]!;
474 for (const turnItems of [
475 [{ ...local }, original.projection.turnItems[1]!],
476 [{ ...local, message: "Newer than the visible row." }, original.projection.turnItems[1]!],
477 original.projection.turnItems.toReversed(),
478 ]) {
479 const snapshot = { ...original, projection: { ...original.projection, turnItems } };
480 yield* store.saveThread(ENVIRONMENT_ID, snapshot);
481 const raw = memory.values.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))!;
482 const encoded = JSON.parse(raw);
483 expect(encoded.schemaVersion).toBe(6);
484 expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(false);
485 expect(encoded.snapshot.turnItemCount).toBe(2);
486 expect(encoded.snapshot.projection.turnItems).toHaveLength(2);
487 expect(Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID))).toEqual(
488 snapshot,
489 );
490 }
491 }),
492 );
493
494 it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
495 Effect.gen(function* () {
496 const memory = makeDatabase();
497 const store = yield* make().pipe(
498 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
499 );
500
501 yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
502 yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
503
504 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
505 const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
506
507 expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
508 expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
509 "2026-07-29T12:00:00.000Z",
510 );
511 expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
512 "2026-07-29T12:00:00.000Z",
513 );
514 expect(DateTime.formatIso(shell.threads[0]!.activityRunStartedAt!)).toBe(
515 "2026-07-29T12:00:00.000Z",
516 );
517 expect(DateTime.formatIso(shell.threads[0]!.unsettledAt!)).toBe("2026-07-29T12:00:00.000Z");
518 expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
519 "2026-07-29T12:00:00.000Z",
520 );
521 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
522 ORCHESTRATION_CACHE_SCHEMA_VERSION,
523 );
524 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
525 COMPACT_THREAD_CACHE_SCHEMA_VERSION,
526 );
527 }),
528 );
529
530 it.live("returns cached threads before their pull request links, which load after", () =>
531 Effect.gen(function* () {
532 const memory = makeDatabase();
533 const store = yield* make().pipe(
534 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
535 );
536 const link: ThreadPullRequestLink = {
537 host: "github.com",
538 repository: "pingdotgg/t3code",
539 number: 42,
540 url: "https://github.com/pingdotgg/t3code/pull/42",
541 source: "agent",
542 linkedAt: "2026-07-29T12:00:00.000Z",
543 snapshot: null,
544 stack: null,
545 };
546 const linked = { ...SHELL_SNAPSHOT.threads[0]!, pullRequests: [link] };
547 const unlinked = { ...SHELL_SNAPSHOT.threads[0]!, id: ThreadId.make("thread-2") };
548 yield* store.saveShell(ENVIRONMENT_ID, {
549 ...SHELL_SNAPSHOT,
550 threads: [linked, unlinked],
551 });
552
553 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
554 expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]);
555 const links = yield* shell.loadPullRequests!;
556 expect([...links]).toEqual([[THREAD_ID, [link]]]);
557 }),
558 );
559
560 it.live("keeps cached threads when their pull request links cannot be read", () => {
561 const messages: Array<unknown> = [];
562 const logger = Logger.make(({ message }) => {
563 messages.push(message);
564 });
565 return Effect.gen(function* () {
566 const memory = makeDatabase();
567 const store = yield* make().pipe(
568 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
569 );
570 const link: ThreadPullRequestLink = {
571 host: "github.com",
572 repository: "pingdotgg/t3code",
573 number: 5,
574 url: "https://github.com/pingdotgg/t3code/pull/5",
575 source: "agent",
576 linkedAt: "2026-07-29T12:00:00.000Z",
577 snapshot: null,
578 stack: null,
579 };
580 const readable = {
581 ...SHELL_SNAPSHOT.threads[0]!,
582 id: ThreadId.make("thread-2"),
583 pullRequests: [link],
584 };
585 yield* store.saveShell(ENVIRONMENT_ID, {
586 ...SHELL_SNAPSHOT,
587 threads: [SHELL_SNAPSHOT.threads[0]!, readable],
588 });
589 const id = cacheId(ENVIRONMENT_ID, "shell", "snapshot");
590 const payload = JSON.parse(memory.values.get(id)!);
591 payload.snapshot.threads[0].pullRequests = [{ number: -1 }];
592 memory.values.set(id, JSON.stringify(payload));
593
594 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
595 expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]);
596 expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]);
597 expect(messages).toHaveLength(1);
598 expect(memory.removed).toEqual([]);
599 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
600 });
601
602 it.effect("deletes a corrupt cache record and treats it as a miss", () =>
603 Effect.gen(function* () {
604 const memory = makeDatabase();
605 const store = yield* make().pipe(
606 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
607 );
608 const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
609 memory.values.set(id, "{not-json");
610
611 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
612 expect(memory.removed).toEqual([id]);
613 }),
614 );
615});