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