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

environment-cache-store.test.ts

664 lines23.7 KB

1import {
2 ORCHESTRATION_CACHE_SCHEMA_VERSION,
3 StoredOrchestrationShellSnapshot,
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 Fiber from "effect/Fiber";
20import * as Logger from "effect/Logger";
21import * as Schema from "effect/Schema";
22import { vi } from "vite-plus/test";
23import * as Deferred from "effect/Deferred";
24import * as Option from "effect/Option";
25​
26import * as MobileDatabase from "../persistence/mobile-database";
27import { make } from "./environment-cache-store";
28import { makeStoredShellSnapshotEncoder } from "./shell-cache-encoding";
29​
30const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
31const PROJECT_ID = ProjectId.make("project-1");
32const THREAD_ID = ThreadId.make("thread-1");
33const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
34const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
35const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
36 schemaVersion: 1,
37 snapshotSequence: 3,
38 projects: [
39 {
40 id: PROJECT_ID,
41 title: "Project",
42 workspaceRoot: "/repo",
43 repositoryIdentity: null,
44 defaultModelSelection: null,
45 scripts: [],
46 createdAt: "2026-07-29T12:00:00.000Z",
47 updatedAt: "2026-07-29T12:00:00.000Z",
48 },
49 ],
50 threads: [
51 {
52 id: THREAD_ID,
53 projectId: PROJECT_ID,
54 title: "Thread",
55 providerInstanceId: PROVIDER_INSTANCE_ID,
56 modelSelection: {
57 instanceId: PROVIDER_INSTANCE_ID,
58 model: "gpt-5.4",
59 },
60 runtimeMode: "full-access",
61 interactionMode: "default",
62 branch: null,
63 worktreePath: null,
64 activeProviderThreadId: null,
65 lineage: {
66 rootThreadId: THREAD_ID,
67 parentThreadId: null,
68 relationshipToParent: null,
69 },
70 forkedFrom: null,
71 createdBy: "user",
72 creationSource: "mobile",
73 latestRunId: null,
74 activeRunId: null,
75 status: "idle",
76 pendingRuntimeRequest: null,
77 latestVisibleMessage: null,
78 latestUserMessageAt: NOW,
79 activityRunStartedAt: NOW,
80 activityRunStatus: "running",
81 hasActionableProposedPlan: false,
82 itemCount: 0,
83 visibleItemCount: 0,
84 createdAt: NOW,
85 updatedAt: NOW,
86 archivedAt: null,
87 settledOverride: null,
88 settledAt: NOW,
89 unsettledAt: NOW,
90 lastVisitedAt: null,
91 titleRegeneration: {
92 requestId: CommandId.make("title-regeneration-1"),
93 startedAt: NOW,
94 },
95 deletedAt: null,
96 },
97 ],
98 archivedThreads: [],
99};
100const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
101 snapshotSequence: 4,
102 projection: {
103 thread: {
104 id: THREAD_ID,
105 projectId: PROJECT_ID,
106 title: "Thread",
107 providerInstanceId: PROVIDER_INSTANCE_ID,
108 modelSelection: {
109 instanceId: PROVIDER_INSTANCE_ID,
110 model: "gpt-5.4",
111 },
112 runtimeMode: "full-access",
113 interactionMode: "default",
114 branch: null,
115 worktreePath: null,
116 activeProviderThreadId: null,
117 lineage: {
118 rootThreadId: THREAD_ID,
119 parentThreadId: null,
120 relationshipToParent: null,
121 },
122 forkedFrom: null,
123 createdBy: "user",
124 creationSource: "mobile",
125 createdAt: NOW,
126 updatedAt: NOW,
127 archivedAt: null,
128 settledOverride: null,
129 settledAt: NOW,
130 lastVisitedAt: null,
131 deletedAt: null,
132 },
133 runs: [],
134 attempts: [],
135 nodes: [],
136 subagents: [],
137 providerSessions: [],
138 providerThreads: [],
139 providerTurns: [],
140 runtimeRequests: [],
141 messages: [],
142 plans: [],
143 turnItems: [],
144 checkpointScopes: [],
145 checkpoints: [],
146 contextHandoffs: [],
147 contextTransfers: [],
148 visibleTurnItems: [],
149 updatedAt: NOW,
150 },
151};
152const REFS: VcsListRefsResult = {
153 refs: [
154 {
155 name: "main",
156 current: true,
157 isDefault: true,
158 worktreePath: "/repo",
159 },
160 ],
161 isRepo: true,
162 hasPrimaryRemote: true,
163 nextCursor: null,
164 totalCount: 1,
165};
166​
167function cacheId(
168 environmentId: EnvironmentId,
169 kind: MobileDatabase.ClientCacheKind,
170 cacheKey: string,
171) {
172 return `${environmentId}:${kind}:${cacheKey}`;
174​
175function makeDatabase() {
176 const values = new Map<string, string>();
177 const schemaVersions = new Map<string, number>();
178 const removed: Array<string> = [];
179 const database = MobileDatabase.MobileDatabase.of({
180 loadCache: (environmentId, kind, cacheKey) =>
181 Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
182 listCache: (kind) =>
183 Effect.sync(() =>
184 [...values.entries()]
185 .filter(([key]) => key.split(":")[1] === kind)
186 .map(([, payload]) => payload),
187 ),
188 saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
189 Effect.sync(() => {
190 const id = cacheId(environmentId, kind, cacheKey);
191 values.set(id, payload);
192 schemaVersions.set(id, schemaVersion);
193 }),
194 removeCache: (environmentId, kind, cacheKey) =>
195 Effect.sync(() => {
196 const id = cacheId(environmentId, kind, cacheKey);
197 removed.push(id);
198 values.delete(id);
199 }),
200 clearCacheKind: (environmentId, kind) =>
201 Effect.sync(() => {
202 for (const key of values.keys()) {
203 if (key.startsWith(`${environmentId}:${kind}:`)) values.delete(key);
204 }
205 }),
206 clearEnvironmentCache: (environmentId) =>
207 Effect.sync(() => {
208 for (const key of values.keys()) {
209 if (key.startsWith(`${environmentId}:`)) values.delete(key);
210 }
211 }),
212 clearAllCaches: Effect.sync(() => values.clear()),
213 inspectCaches: Effect.succeed([]),
214 loadPreferencesJson: Effect.succeed(Option.none()),
215 savePreferencesJson: () => Effect.void,
216 });
217 return { database, removed, schemaVersions, values };
219​
220describe("mobile SQLite environment cache store", () => {
221 it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
222 Effect.gen(function* () {
223 const memory = makeDatabase();
224 const store = yield* make().pipe(
225 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
226 );
227​
228 yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
229 yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
230​
231 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
232 const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
233​
234 expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
235 expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
236 "2026-07-29T12:00:00.000Z",
237 );
238 expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
239 "2026-07-29T12:00:00.000Z",
240 );
241 // Working and unsettled threads are exactly what a backgrounded app
242 // caches; a decode failure here discards the whole shell on relaunch.
243 expect(DateTime.formatIso(shell.threads[0]!.activityRunStartedAt!)).toBe(
244 "2026-07-29T12:00:00.000Z",
245 );
246 expect(DateTime.formatIso(shell.threads[0]!.unsettledAt!)).toBe("2026-07-29T12:00:00.000Z");
247 expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
248 "2026-07-29T12:00:00.000Z",
249 );
250 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
251 ORCHESTRATION_CACHE_SCHEMA_VERSION,
252 );
253 expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
254 ORCHESTRATION_CACHE_SCHEMA_VERSION,
255 );
256 }),
257 );
258​
259 it.live("returns cached threads before their pull request links, which load after", () =>
260 Effect.gen(function* () {
261 const memory = makeDatabase();
262 const store = yield* make().pipe(
263 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
264 );
265 const link: ThreadPullRequestLink = {
266 host: "github.com",
267 repository: "pingdotgg/t3code",
268 number: 42,
269 url: "https://github.com/pingdotgg/t3code/pull/42",
270 source: "agent",
271 linkedAt: "2026-07-29T12:00:00.000Z",
272 snapshot: null,
273 stack: null,
274 };
275 const linked = { ...SHELL_SNAPSHOT.threads[0]!, pullRequests: [link] };
276 const unlinked = { ...SHELL_SNAPSHOT.threads[0]!, id: ThreadId.make("thread-2") };
277 yield* store.saveShell(ENVIRONMENT_ID, {
278 ...SHELL_SNAPSHOT,
279 threads: [linked, unlinked],
280 });
281​
282 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
283 expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]);
284 const links = yield* shell.loadPullRequests!;
285 expect([...links]).toEqual([[THREAD_ID, [link]]]);
286 }),
287 );
288​
289 it.live("keeps cached threads when their pull request links cannot be read", () => {
290 const messages: Array<unknown> = [];
291 const logger = Logger.make(({ message }) => {
292 messages.push(message);
293 });
294 return Effect.gen(function* () {
295 const memory = makeDatabase();
296 const store = yield* make().pipe(
297 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
298 );
299 const link: ThreadPullRequestLink = {
300 host: "github.com",
301 repository: "pingdotgg/t3code",
302 number: 5,
303 url: "https://github.com/pingdotgg/t3code/pull/5",
304 source: "agent",
305 linkedAt: "2026-07-29T12:00:00.000Z",
306 snapshot: null,
307 stack: null,
308 };
309 const readable = {
310 ...SHELL_SNAPSHOT.threads[0]!,
311 id: ThreadId.make("thread-2"),
312 pullRequests: [link],
313 };
314 yield* store.saveShell(ENVIRONMENT_ID, {
315 ...SHELL_SNAPSHOT,
316 threads: [SHELL_SNAPSHOT.threads[0]!, readable],
317 });
318 const id = cacheId(ENVIRONMENT_ID, "shell", "snapshot");
319 const payload = JSON.parse(memory.values.get(id)!);
320 payload.snapshot.threads[0].pullRequests = [{ number: -1 }];
321 memory.values.set(id, JSON.stringify(payload));
322​
323 const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
324 expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]);
325 // Only the thread with the unreadable link loses its links.
326 expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]);
327 expect(messages).toHaveLength(1);
328 expect(memory.removed).toEqual([]);
329 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
330 });
331​
332 it.effect("round-trips schema-validated VCS refs", () =>
333 Effect.gen(function* () {
334 const memory = makeDatabase();
335 const store = yield* make().pipe(
336 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
337 );
338​
339 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
340​
341 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
342 }),
343 );
344​
345 it.effect("deletes a corrupt cache record and treats it as a miss", () =>
346 Effect.gen(function* () {
347 const memory = makeDatabase();
348 const store = yield* make().pipe(
349 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
350 );
351 const id = cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo");
352 memory.values.set(id, "{not-json");
353​
354 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
355 expect(memory.removed).toEqual([id]);
356 }),
357 );
358​
359 it.effect("removes one persisted VCS ref snapshot", () =>
360 Effect.gen(function* () {
361 const memory = makeDatabase();
362 const store = yield* make().pipe(
363 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
364 );
365 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
366​
367 yield* store.removeVcsRefs(ENVIRONMENT_ID, "/repo");
368​
369 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
370 expect(memory.removed).toContain(cacheId(ENVIRONMENT_ID, "vcs-refs", "/repo"));
371 }),
372 );
373​
374 it.effect("clears every persisted VCS ref snapshot in one environment", () =>
375 Effect.gen(function* () {
376 const memory = makeDatabase();
377 const store = yield* make().pipe(
378 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
379 );
380 const otherEnvironmentId = EnvironmentId.make("environment-2");
381 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
382 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo-worktree", REFS);
383 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
384​
385 yield* store.clearVcsRefs(ENVIRONMENT_ID);
386​
387 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
388 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo-worktree")).toEqual(Option.none());
389 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
390 }),
391 );
392​
393 it.effect("clears one environment without touching another", () =>
394 Effect.gen(function* () {
395 const memory = makeDatabase();
396 const store = yield* make().pipe(
397 Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
398 );
399 const otherEnvironmentId = EnvironmentId.make("environment-2");
400 yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
401 yield* store.saveVcsRefs(otherEnvironmentId, "/repo", REFS);
402​
403 yield* store.clear(ENVIRONMENT_ID);
404​
405 expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.none());
406 expect(yield* store.loadVcsRefs(otherEnvironmentId, "/repo")).toEqual(Option.some(REFS));
407 }),
408 );
409});
410​
411describe("cooperative shell cache encoding", () => {
412 // A fresh encoder per call keeps these cases cold; the cache has its own cases below.
413 const encodeStoredShellSnapshot = (stored: typeof StoredOrchestrationShellSnapshot.Type) =>
414 makeStoredShellSnapshotEncoder()(stored);
415 const encodeOriginal = Schema.encodeEffect(
416 Schema.fromJsonString(StoredOrchestrationShellSnapshot),
417 );
418 const stored = {
419 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
420 environmentId: ENVIRONMENT_ID,
421 snapshot: {
422 ...SHELL_SNAPSHOT,
423 projects: SHELL_SNAPSHOT.projects.map((project) => ({
424 ...project,
425 title: " Project ",
426 unexpected: "drop this field",
427 })),
428 threads: Array.from({ length: 64 }, (_, index) => ({
429 ...SHELL_SNAPSHOT.threads[0]!,
430 id: ThreadId.make(`thread-${index}`),
431 branch: " main ",
432 activityRunStartedAt: index % 2 === 0 ? NOW : null,
433 unsettledAt: index % 2 === 0 ? NOW : null,
434 modelSelection: {
435 instanceId: PROVIDER_INSTANCE_ID,
436 model: " gpt-5.4 ",
437 unexpected: "drop this field",
438 },
439 unexpected: "drop this field",
440 })),
441 archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
442 unexpected: "drop this field",
443 },
444 unexpected: "drop this field",
445 };
446​
447 it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
448 Effect.gen(function* () {
449 const expected = yield* encodeOriginal(stored);
450 const actual = yield* encodeStoredShellSnapshot(stored);
451 expect(actual).toBe(expected);
452 const parsed = JSON.parse(actual);
453 expect(parsed).not.toHaveProperty("unexpected");
454 expect(parsed.snapshot).not.toHaveProperty("unexpected");
455 expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
456 expect(parsed.snapshot.projects[0].title).toBe("Project");
457 expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
458 expect(parsed.snapshot.threads[0].branch).toBe("main");
459 expect(parsed.snapshot.threads[0].modelSelection).toEqual({
460 instanceId: "codex",
461 model: "gpt-5.4",
462 });
463 expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
464 expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
465 expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
466 }),
467 );
468​
469 it.effect("preserves optional fields and dates across chunk boundaries and archived rows", () =>
470 Effect.gen(function* () {
471 const base = SHELL_SNAPSHOT.threads[0]!;
472 const { titleRegeneration: _, unsettledAt: __, ...withoutOptional } = base;
473 const row = (index: number) =>
474 index % 3 === 0
475 ? { ...withoutOptional, id: ThreadId.make(`row-${index}`) }
476 : {
477 ...base,
478 id: ThreadId.make(`row-${index}`),
479 snoozedUntil: DateTime.add(NOW, { minutes: index }),
480 pinnedAt: index % 2 === 0 ? null : NOW,
481 };
482 const mixed = {
483 ...stored,
484 snapshot: {
485 ...stored.snapshot,
486 threads: Array.from({ length: 65 }, (_, index) => row(index)),
487 archivedThreads: Array.from({ length: 33 }, (_, index) => ({
488 ...row(index + 100),
489 archivedAt: DateTime.add(NOW, { hours: index }),
490 })),
491 },
492 };
493 const actual = yield* encodeStoredShellSnapshot(mixed);
494 expect(actual).toBe(yield* encodeOriginal(mixed));
495 const parsed = JSON.parse(actual);
496 expect(parsed.snapshot.threads).toHaveLength(65);
497 expect(parsed.snapshot.threads[63]).not.toHaveProperty("titleRegeneration");
498 expect(parsed.snapshot.threads[63]).not.toHaveProperty("unsettledAt");
499 expect(parsed.snapshot.threads[64].snoozedUntil).toBe(
500 DateTime.formatIso(DateTime.add(NOW, { minutes: 64 })),
501 );
502 expect(parsed.snapshot.archivedThreads).toHaveLength(33);
503 expect(parsed.snapshot.archivedThreads[32].archivedAt).toBe(
504 DateTime.formatIso(DateTime.add(NOW, { hours: 32 })),
505 );
506 }),
507 );
508​
509 it.effect("yields to a host timer between every 32-row chunk", () =>
510 Effect.gen(function* () {
511 const setTimer = vi.spyOn(globalThis, "setTimeout");
512 try {
513 yield* encodeStoredShellSnapshot({
514 ...stored,
515 snapshot: {
516 ...stored.snapshot,
517 threads: Array.from({ length: 65 }, () => ({ ...stored.snapshot.threads[0]! })),
518 archivedThreads: Array.from({ length: 33 }, () => ({
519 ...stored.snapshot.archivedThreads[0]!,
520 })),
521 },
522 });
523 // Five row chunks (3 active + 2 archived): four yields between them, one before the envelope.
524 expect(setTimer).toHaveBeenCalledTimes(5);
525 } finally {
526 vi.restoreAllMocks();
527 }
528 }),
529 );
530​
531 it.effect("still rejects invalid active and archived rows after an encoding chunk yields", () =>
532 Effect.gen(function* () {
533 const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
534 const invalidActive = {
535 ...stored,
536 snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
537 };
538 const invalidArchived = {
539 ...stored,
540 snapshot: { ...stored.snapshot, archivedThreads: [invalidRow] },
541 };
542 const invalidEnvelope = { ...stored, snapshot: { ...stored.snapshot, snapshotSequence: -1 } };
543 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidActive))).toBe(true);
544 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidArchived))).toBe(true);
545 expect(yield* Effect.isFailure(encodeOriginal(invalidEnvelope))).toBe(true);
546 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidEnvelope))).toBe(true);
547 }),
548 );
549​
550 it.effect("keeps concurrent saves independent", () =>
551 Effect.gen(function* () {
552 const other = {
553 ...stored,
554 environmentId: EnvironmentId.make("environment-2"),
555 snapshot: {
556 ...stored.snapshot,
557 threads: stored.snapshot.threads.slice(0, 40).map((thread) => ({
558 ...thread,
559 title: `Other ${thread.id}`,
560 })),
561 archivedThreads: [],
562 },
563 };
564 const [first, second] = yield* Effect.all(
565 [encodeStoredShellSnapshot(stored), encodeStoredShellSnapshot(other)],
566 { concurrency: "unbounded" },
567 );
568 expect(first).toBe(yield* encodeOriginal(stored));
569 expect(second).toBe(yield* encodeOriginal(other));
570 }),
571 );
572​
573 it.effect("cancels the pending host timer when encoding is interrupted", () =>
574 Effect.gen(function* () {
575 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
576 const fakeSetTimeout = globalThis.setTimeout;
577 const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
578 vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
579 const timer = fakeSetTimeout(...args);
580 Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
581 return timer;
582 });
583 const clearTimer = vi.spyOn(globalThis, "clearTimeout");
584 const fiber = yield* Effect.forkScoped(
585 Effect.suspend(() => encodeStoredShellSnapshot(stored)),
586 );
587 try {
588 const pendingTimer = yield* Deferred.await(scheduled);
589 expect(vi.getTimerCount()).toBe(1);
590 yield* Fiber.interrupt(fiber);
591 expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
592 expect(vi.getTimerCount()).toBe(0);
593 } finally {
594 yield* Fiber.interrupt(fiber);
595 vi.restoreAllMocks();
596 vi.useRealTimers();
597 }
598 }),
599 );
600​
601 it.effect("reuses encoded rows across saves without changing the payload", () =>
602 Effect.gen(function* () {
603 const encode = makeStoredShellSnapshotEncoder();
604 expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
605​
606 const setTimer = vi.spyOn(globalThis, "setTimeout");
607 try {
608 // Same row references, new envelope: no row work, so no host yields.
609 const resaved = {
610 ...stored,
611 snapshot: { ...stored.snapshot, snapshotSequence: 4 },
612 };
613 expect(yield* encode(resaved)).toBe(yield* encodeOriginal(resaved));
614 expect(setTimer).not.toHaveBeenCalled();
615 } finally {
616 vi.restoreAllMocks();
617 }
618 }),
619 );
620​
621 it.effect("encodes replaced, added, and moved-to-archive rows on a warm encoder", () =>
622 Effect.gen(function* () {
623 const encode = makeStoredShellSnapshotEncoder();
624 yield* encode(stored);
625 const [first, second, ...rest] = stored.snapshot.threads;
626 const next = {
627 ...stored,
628 snapshot: {
629 ...stored.snapshot,
630 threads: [
631 { ...first!, title: "Renamed", itemCount: 9 },
632 ...rest,
633 { ...first!, id: ThreadId.make("thread-new"), branch: " feature " },
634 ],
635 archivedThreads: [
636 ...stored.snapshot.archivedThreads,
637 { ...second!, archivedAt: DateTime.add(NOW, { hours: 1 }) },
638 ],
639 },
640 };
641 const actual = yield* encode(next);
642 expect(actual).toBe(yield* encodeOriginal(next));
643 const parsed = JSON.parse(actual);
644 expect(parsed.snapshot.threads[0].title).toBe("Renamed");
645 expect(parsed.snapshot.threads.at(-1).branch).toBe("feature");
646 expect(parsed.snapshot.archivedThreads).toHaveLength(2);
647 }),
648 );
649​
650 it.effect("does not cache rows from a failed encode", () =>
651 Effect.gen(function* () {
652 const encode = makeStoredShellSnapshotEncoder();
653 const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
654 const invalid = {
655 ...stored,
656 snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
657 };
658 expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
659 expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
660 // Valid rows from the failed save still encode correctly afterwards.
661 expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
662 }),
663 );
664});