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

environment-cache-store.test.ts

702 lines24.5 KB

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