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

shellCacheEncoding.test.ts

348 lines12.6 KB

1import {
2 CommandId,
3 EnvironmentId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 type OrchestrationV2ShellSnapshot,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Schema from "effect/Schema";
14import { vi } from "vite-plus/test";
15import * as Deferred from "effect/Deferred";
16​
17import {
18 ORCHESTRATION_CACHE_SCHEMA_VERSION,
19 StoredOrchestrationShellSnapshot,
20} from "./orchestrationCache.ts";
21import { makeStoredShellSnapshotEncoder } from "./shellCacheEncoding.ts";
22​
23const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
24const PROJECT_ID = ProjectId.make("project-1");
25const THREAD_ID = ThreadId.make("thread-1");
26const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
27const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
28const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
29 schemaVersion: 1,
30 snapshotSequence: 3,
31 projects: [
32 {
33 id: PROJECT_ID,
34 title: "Project",
35 workspaceRoot: "/repo",
36 repositoryIdentity: null,
37 defaultModelSelection: null,
38 scripts: [],
39 createdAt: "2026-07-29T12:00:00.000Z",
40 updatedAt: "2026-07-29T12:00:00.000Z",
41 },
42 ],
43 threads: [
44 {
45 id: THREAD_ID,
46 projectId: PROJECT_ID,
47 title: "Thread",
48 providerInstanceId: PROVIDER_INSTANCE_ID,
49 modelSelection: {
50 instanceId: PROVIDER_INSTANCE_ID,
51 model: "gpt-5.4",
52 },
53 runtimeMode: "full-access",
54 interactionMode: "default",
55 branch: null,
56 worktreePath: null,
57 activeProviderThreadId: null,
58 lineage: {
59 rootThreadId: THREAD_ID,
60 parentThreadId: null,
61 relationshipToParent: null,
62 },
63 forkedFrom: null,
64 createdBy: "user",
65 creationSource: "mobile",
66 latestRunId: null,
67 activeRunId: null,
68 status: "idle",
69 pendingRuntimeRequest: null,
70 latestVisibleMessage: null,
71 latestUserMessageAt: NOW,
72 activityRunStartedAt: NOW,
73 activityRunStatus: "running",
74 hasActionableProposedPlan: false,
75 itemCount: 0,
76 visibleItemCount: 0,
77 createdAt: NOW,
78 updatedAt: NOW,
79 archivedAt: null,
80 settledOverride: null,
81 settledAt: NOW,
82 unsettledAt: NOW,
83 lastVisitedAt: null,
84 titleRegeneration: {
85 requestId: CommandId.make("title-regeneration-1"),
86 startedAt: NOW,
87 },
88 deletedAt: null,
89 },
90 ],
91 archivedThreads: [],
92};
93​
94describe("cooperative shell cache encoding", () => {
95 // A fresh encoder per call keeps these cases cold; the cache has its own cases below.
96 const encodeStoredShellSnapshot = (stored: typeof StoredOrchestrationShellSnapshot.Type) =>
97 makeStoredShellSnapshotEncoder()(stored);
98 const encodeOriginal = Schema.encodeEffect(
99 Schema.fromJsonString(StoredOrchestrationShellSnapshot),
100 );
101 const stored = {
102 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
103 environmentId: ENVIRONMENT_ID,
104 snapshot: {
105 ...SHELL_SNAPSHOT,
106 projects: SHELL_SNAPSHOT.projects.map((project) => ({
107 ...project,
108 title: " Project ",
109 unexpected: "drop this field",
110 })),
111 threads: Array.from({ length: 64 }, (_, index) => ({
112 ...SHELL_SNAPSHOT.threads[0]!,
113 id: ThreadId.make(`thread-${index}`),
114 branch: " main ",
115 activityRunStartedAt: index % 2 === 0 ? NOW : null,
116 unsettledAt: index % 2 === 0 ? NOW : null,
117 modelSelection: {
118 instanceId: PROVIDER_INSTANCE_ID,
119 model: " gpt-5.4 ",
120 unexpected: "drop this field",
121 },
122 unexpected: "drop this field",
123 })),
124 archivedThreads: [{ ...SHELL_SNAPSHOT.threads[0]!, archivedAt: NOW }],
125 unexpected: "drop this field",
126 },
127 unexpected: "drop this field",
128 };
129​
130 it.effect("preserves exact JSON, transforms, nulls, dates, and unknown-field stripping", () =>
131 Effect.gen(function* () {
132 const expected = yield* encodeOriginal(stored);
133 const actual = yield* encodeStoredShellSnapshot(stored);
134 expect(actual).toBe(expected);
135 const parsed = JSON.parse(actual);
136 expect(parsed).not.toHaveProperty("unexpected");
137 expect(parsed.snapshot).not.toHaveProperty("unexpected");
138 expect(parsed.snapshot.projects[0]).not.toHaveProperty("unexpected");
139 expect(parsed.snapshot.projects[0].title).toBe("Project");
140 expect(parsed.snapshot.threads[0]).not.toHaveProperty("unexpected");
141 expect(parsed.snapshot.threads[0].branch).toBe("main");
142 expect(parsed.snapshot.threads[0].modelSelection).toEqual({
143 instanceId: "codex",
144 model: "gpt-5.4",
145 });
146 expect(parsed.snapshot.threads[0].activityRunStartedAt).toBe(DateTime.formatIso(NOW));
147 expect(parsed.snapshot.threads[1].activityRunStartedAt).toBeNull();
148 expect(parsed.snapshot.archivedThreads[0].archivedAt).toBe(DateTime.formatIso(NOW));
149 }),
150 );
151​
152 it.effect("preserves optional fields and dates across chunk boundaries and archived rows", () =>
153 Effect.gen(function* () {
154 const base = SHELL_SNAPSHOT.threads[0]!;
155 const { titleRegeneration: _, unsettledAt: __, ...withoutOptional } = base;
156 const row = (index: number) =>
157 index % 3 === 0
158 ? { ...withoutOptional, id: ThreadId.make(`row-${index}`) }
159 : {
160 ...base,
161 id: ThreadId.make(`row-${index}`),
162 snoozedUntil: DateTime.add(NOW, { minutes: index }),
163 pinnedAt: index % 2 === 0 ? null : NOW,
164 };
165 const mixed = {
166 ...stored,
167 snapshot: {
168 ...stored.snapshot,
169 threads: Array.from({ length: 65 }, (_, index) => row(index)),
170 archivedThreads: Array.from({ length: 33 }, (_, index) => ({
171 ...row(index + 100),
172 archivedAt: DateTime.add(NOW, { hours: index }),
173 })),
174 },
175 };
176 const actual = yield* encodeStoredShellSnapshot(mixed);
177 expect(actual).toBe(yield* encodeOriginal(mixed));
178 const parsed = JSON.parse(actual);
179 expect(parsed.snapshot.threads).toHaveLength(65);
180 expect(parsed.snapshot.threads[63]).not.toHaveProperty("titleRegeneration");
181 expect(parsed.snapshot.threads[63]).not.toHaveProperty("unsettledAt");
182 expect(parsed.snapshot.threads[64].snoozedUntil).toBe(
183 DateTime.formatIso(DateTime.add(NOW, { minutes: 64 })),
184 );
185 expect(parsed.snapshot.archivedThreads).toHaveLength(33);
186 expect(parsed.snapshot.archivedThreads[32].archivedAt).toBe(
187 DateTime.formatIso(DateTime.add(NOW, { hours: 32 })),
188 );
189 }),
190 );
191​
192 it.effect("yields to a host timer between every 32-row chunk", () =>
193 Effect.gen(function* () {
194 const setTimer = vi.spyOn(globalThis, "setTimeout");
195 try {
196 yield* encodeStoredShellSnapshot({
197 ...stored,
198 snapshot: {
199 ...stored.snapshot,
200 threads: Array.from({ length: 65 }, () => ({ ...stored.snapshot.threads[0]! })),
201 archivedThreads: Array.from({ length: 33 }, () => ({
202 ...stored.snapshot.archivedThreads[0]!,
203 })),
204 },
205 });
206 // Five row chunks (3 active + 2 archived): four yields between them, one before the envelope.
207 expect(setTimer).toHaveBeenCalledTimes(5);
208 } finally {
209 vi.restoreAllMocks();
210 }
211 }),
212 );
213​
214 it.effect("still rejects invalid active and archived rows after an encoding chunk yields", () =>
215 Effect.gen(function* () {
216 const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
217 const invalidActive = {
218 ...stored,
219 snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
220 };
221 const invalidArchived = {
222 ...stored,
223 snapshot: { ...stored.snapshot, archivedThreads: [invalidRow] },
224 };
225 const invalidEnvelope = { ...stored, snapshot: { ...stored.snapshot, snapshotSequence: -1 } };
226 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidActive))).toBe(true);
227 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidArchived))).toBe(true);
228 expect(yield* Effect.isFailure(encodeOriginal(invalidEnvelope))).toBe(true);
229 expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidEnvelope))).toBe(true);
230 }),
231 );
232​
233 it.effect("keeps concurrent saves independent", () =>
234 Effect.gen(function* () {
235 const other = {
236 ...stored,
237 environmentId: EnvironmentId.make("environment-2"),
238 snapshot: {
239 ...stored.snapshot,
240 threads: stored.snapshot.threads.slice(0, 40).map((thread) => ({
241 ...thread,
242 title: `Other ${thread.id}`,
243 })),
244 archivedThreads: [],
245 },
246 };
247 const [first, second] = yield* Effect.all(
248 [encodeStoredShellSnapshot(stored), encodeStoredShellSnapshot(other)],
249 { concurrency: "unbounded" },
250 );
251 expect(first).toBe(yield* encodeOriginal(stored));
252 expect(second).toBe(yield* encodeOriginal(other));
253 }),
254 );
255​
256 it.effect("cancels the pending host timer when encoding is interrupted", () =>
257 Effect.gen(function* () {
258 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
259 const fakeSetTimeout = globalThis.setTimeout;
260 const scheduled = yield* Deferred.make<ReturnType<typeof setTimeout>>();
261 vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
262 // @effect-diagnostics-next-line globalTimers:off - Observes the encoder's own host timer.
263 const timer = fakeSetTimeout(...args);
264 Deferred.doneUnsafe(scheduled, Effect.succeed(timer));
265 return timer;
266 });
267 const clearTimer = vi.spyOn(globalThis, "clearTimeout");
268 const fiber = yield* Effect.forkScoped(
269 Effect.suspend(() => encodeStoredShellSnapshot(stored)),
270 );
271 try {
272 const pendingTimer = yield* Deferred.await(scheduled);
273 expect(vi.getTimerCount()).toBe(1);
274 yield* Fiber.interrupt(fiber);
275 expect(clearTimer).toHaveBeenCalledWith(pendingTimer);
276 expect(vi.getTimerCount()).toBe(0);
277 } finally {
278 yield* Fiber.interrupt(fiber);
279 vi.restoreAllMocks();
280 vi.useRealTimers();
281 }
282 }),
283 );
284​
285 it.effect("reuses encoded rows across saves without changing the payload", () =>
286 Effect.gen(function* () {
287 const encode = makeStoredShellSnapshotEncoder();
288 expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
289​
290 const setTimer = vi.spyOn(globalThis, "setTimeout");
291 try {
292 // Same row references, new envelope: no row work, so no host yields.
293 const resaved = {
294 ...stored,
295 snapshot: { ...stored.snapshot, snapshotSequence: 4 },
296 };
297 expect(yield* encode(resaved)).toBe(yield* encodeOriginal(resaved));
298 expect(setTimer).not.toHaveBeenCalled();
299 } finally {
300 vi.restoreAllMocks();
301 }
302 }),
303 );
304​
305 it.effect("encodes replaced, added, and moved-to-archive rows on a warm encoder", () =>
306 Effect.gen(function* () {
307 const encode = makeStoredShellSnapshotEncoder();
308 yield* encode(stored);
309 const [first, second, ...rest] = stored.snapshot.threads;
310 const next = {
311 ...stored,
312 snapshot: {
313 ...stored.snapshot,
314 threads: [
315 { ...first!, title: "Renamed", itemCount: 9 },
316 ...rest,
317 { ...first!, id: ThreadId.make("thread-new"), branch: " feature " },
318 ],
319 archivedThreads: [
320 ...stored.snapshot.archivedThreads,
321 { ...second!, archivedAt: DateTime.add(NOW, { hours: 1 }) },
322 ],
323 },
324 };
325 const actual = yield* encode(next);
326 expect(actual).toBe(yield* encodeOriginal(next));
327 const parsed = JSON.parse(actual);
328 expect(parsed.snapshot.threads[0].title).toBe("Renamed");
329 expect(parsed.snapshot.threads.at(-1).branch).toBe("feature");
330 expect(parsed.snapshot.archivedThreads).toHaveLength(2);
331 }),
332 );
333​
334 it.effect("does not cache rows from a failed encode", () =>
335 Effect.gen(function* () {
336 const encode = makeStoredShellSnapshotEncoder();
337 const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };
338 const invalid = {
339 ...stored,
340 snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },
341 };
342 expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
343 expect(yield* Effect.isFailure(encode(invalid))).toBe(true);
344 // Valid rows from the failed save still encode correctly afterwards.
345 expect(yield* encode(stored)).toBe(yield* encodeOriginal(stored));
346 }),
347 );
348});