Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 EnvironmentHttpApi,
4 EventId,
5 MessageId,
6 NodeId,
7 type OrchestrationV2ThreadDetailSnapshot,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2DomainEvent,
16 type OrchestrationV2TurnItem,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23β
24import * as SqlitePersistence from "../persistence/Sqlite.ts";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import { encodeThreadSnapshotBody } from "./threadSnapshotBody.ts";
27import { projectThreadProjectionForWire } from "./WireProjection.ts";
28β
29const provider = ProviderInstanceId.make("codex");
30const modelSelection = { instanceId: provider, model: "gpt-5.4" };
31const PARENT = ThreadId.make("thread:snapshot-body:parent");
32const FORK = ThreadId.make("thread:snapshot-body:fork");
33const parentRun = RunId.make("run:snapshot-body:parent");
34const ITEMS = 1_200;
35// Escapes, a lone surrogate, astral and two-byte text: every JSON.stringify string rule.
36const TEXT = 'quote " slash \\ tab \t nl \n nul \u0000 lone \ud800 astral π η';
37β
38// What HttpApiBuilder sends: JSON.stringify of the endpoint's own success codec (toCodecJson).
39const encodeAsEndpoint = Schema.encodeUnknownSync(
40 [...EnvironmentHttpApi.groups.orchestration.endpoints.threadSnapshot.success][0] as Schema.Codec<
41 unknown,
42 unknown
43 >,
44);
45const referenceBody = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
46 Buffer.from(JSON.stringify(encodeAsEndpoint(snapshot)), "utf8");
47β
48const streamedBody = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
49 encodeThreadSnapshotBody(snapshot).pipe(
50 Effect.flatMap(Stream.runCollect),
51 Effect.map((chunks) => ({
52 chunks: chunks.length,
53 largestChunk: Math.max(...chunks.map((chunk) => chunk.byteLength)),
54 bytes: Buffer.concat([...chunks]),
55 })),
56 );
57β
58const threadCreated = (
59 id: ThreadId,
60 at: DateTime.Utc,
61 forkOf?: RunId,
62): OrchestrationV2DomainEvent => ({
63 id: EventId.make(`event:${id}:created`),
64 type: "thread.created",
65 threadId: id,
66 occurredAt: at,
67 payload: {
68 createdBy: "user",
69 creationSource: "web",
70 id,
71 projectId: ProjectId.make("project:snapshot-body"),
72 title: `${id} ${TEXT}`,
73 providerInstanceId: provider,
74 modelSelection,
75 runtimeMode: "full-access",
76 interactionMode: "default",
77 branch: null,
78 worktreePath: null,
79 activeProviderThreadId: null,
80 lineage:
81 forkOf === undefined
82 ? { parentThreadId: null, relationshipToParent: null, rootThreadId: id }
83 : { parentThreadId: PARENT, relationshipToParent: "fork", rootThreadId: PARENT },
84 forkedFrom: forkOf === undefined ? null : { type: "run", threadId: PARENT, runId: forkOf },
85 createdAt: at,
86 updatedAt: at,
87 archivedAt: null,
88 settledOverride: null,
89 settledAt: null,
90 lastVisitedAt: null,
91 deletedAt: null,
92 },
93});
94β
95const runCreated = (threadId: ThreadId, runId: RunId, at: DateTime.Utc) => {
96 const rootNodeId = NodeId.make(`node:${runId}`);
97 return {
98 id: EventId.make(`event:${runId}:created`),
99 type: "run.created",
100 threadId,
101 runId,
102 nodeId: rootNodeId,
103 driver: ProviderDriverKind.make("codex"),
104 occurredAt: at,
105 payload: {
106 id: runId,
107 threadId,
108 ordinal: 1,
109 providerInstanceId: provider,
110 modelSelection,
111 providerThreadId: null,
112 userMessageId: MessageId.make(`message:${runId}`),
113 rootNodeId,
114 activeAttemptId: null,
115 status: "completed",
116 requestedAt: at,
117 startedAt: at,
118 completedAt: at,
119 checkpointId: null,
120 contextHandoffId: null,
121 },
122 } satisfies OrchestrationV2DomainEvent;
123};
124β
125// One item of each wire-projected shape: omitted output, truncated input, a failed diff.
126const item = (
127 threadId: ThreadId,
128 runId: RunId | null,
129 ordinal: number,
130 at: DateTime.Utc,
131): OrchestrationV2DomainEvent => {
132 const base = {
133 id: TurnItemId.make(`turn-item:${threadId}:${ordinal}`),
134 threadId,
135 runId,
136 nodeId: null,
137 providerThreadId: null,
138 providerTurnId: null,
139 nativeItemRef: null,
140 parentItemId: null,
141 ordinal,
142 status: "completed" as const,
143 title: `${ordinal} ${TEXT}`,
144 startedAt: at,
145 completedAt: at,
146 updatedAt: at,
147 };
148 const payloads: ReadonlyArray<OrchestrationV2TurnItem> = [
149 {
150 ...base,
151 type: "command_execution",
152 input: `echo ${ordinal} ${TEXT}`,
153 output: `${TEXT}\n`.repeat(40),
154 exitCode: ordinal % 7 === 0 ? 1 : 0,
155 },
156 {
157 ...base,
158 type: "dynamic_tool",
159 toolName: "search",
160 input: { query: TEXT, pages: Array.from({ length: 900 }, (_, page) => page) },
161 output: [{ type: "text", text: TEXT }],
162 },
163 {
164 ...base,
165 status: "failed",
166 type: "file_change",
167 fileName: `src/${ordinal}.ts`,
168 diffStr: `@@ ${TEXT}\n`.repeat(20),
169 },
170 {
171 ...base,
172 type: "assistant_message",
173 messageId: MessageId.make(`message:${threadId}:${ordinal}`),
174 text: TEXT.repeat(3),
175 streaming: false,
176 },
177 // No progress: the wire projection sets it to undefined, which the endpoint sends as null.
178 {
179 ...base,
180 type: "subagent",
181 subagentId: NodeId.make(`node:${threadId}:task:${ordinal}`),
182 origin: "app_owned",
183 driver: ProviderDriverKind.make("codex"),
184 providerInstanceId: provider,
185 childThreadId: null,
186 prompt: `Look into ${TEXT}`,
187 result: ordinal % 2 === 0 ? null : TEXT,
188 },
189 ];
190 return {
191 id: EventId.make(`event:${threadId}:item:${ordinal}`),
192 type: "turn-item.updated",
193 threadId,
194 ...(runId === null ? {} : { runId }),
195 occurredAt: at,
196 payload: payloads[ordinal % payloads.length]!,
197 };
198};
199β
200const seed = Effect.gen(function* () {
201 const projections = yield* ProjectionStore.ProjectionStoreV2;
202 const at = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z");
203 const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
204 threadCreated(PARENT, at),
205 runCreated(PARENT, parentRun, at),
206 ...Array.from({ length: ITEMS }, (_, index) => item(PARENT, parentRun, index + 1, at)),
207 // Larger than a chunk, astral throughout, at both offsets: chunks split inside one member.
208 ...["", "x"].map((prefix, index) => {
209 const event = item(PARENT, parentRun, 1_000 * ITEMS + index * 5, at) as Extract<
210 OrchestrationV2DomainEvent,
211 { type: "turn-item.updated" }
212 >;
213 return { ...event, payload: { ...event.payload, input: prefix + "π".repeat(600_000) } };
214 }),
215 threadCreated(FORK, at, parentRun),
216 ...Array.from({ length: 40 }, (_, index) => item(FORK, null, index + 1, at)),
217 ];
218 for (const event of events) yield* projections.apply(event);
219});
220β
221const seededStore = <E>(events: Effect.Effect<void, E, ProjectionStore.ProjectionStoreV2>) =>
222 Layer.effectDiscard(events).pipe(
223 Layer.provideMerge(ProjectionStore.layer),
224 Layer.provideMerge(SqlitePersistence.layerMemory),
225 );
226β
227const TestLayer = seededStore(seed);
228β
229const cycle: Record<string, unknown> = {};
230cycle.self = cycle;
231const sparse: Array<number> = [];
232sparse[2] = 3;
233// Values JSON cannot carry, for a field the schema leaves unknown.
234const NOT_JSON_VALUES: ReadonlyArray<unknown> = [
235 undefined,
236 Number.NaN,
237 DateTime.toDateUtc(DateTime.makeUnsafe(0)),
238 () => 1,
239 1n,
240 cycle,
241 Object("boxed"),
242 sparse,
243];
244β
245const runtimeRequests = (answerSets: ReadonlyArray<Readonly<Record<string, unknown>>>) => {
246 const at = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z");
247 return answerSets.map((answers, index) => ({
248 id: RuntimeRequestId.make(`runtime-request:snapshot-body:${index}`),
249 nodeId: NodeId.make(`node:${parentRun}`),
250 providerTurnId: null,
251 nativeRequestRef: null,
252 kind: "user_input" as const,
253 status: "resolved" as const,
254 responseCapability: { type: "message" as const },
255 createdAt: at,
256 resolvedAt: at,
257 answers,
258 }));
259};
260β
261it.layer(TestLayer)("thread snapshot body", (it) => {
262 it.effect("streams a long thread and its fork as the endpoint encodes them", () =>
263 Effect.gen(function* () {
264 const projections = yield* ProjectionStore.ProjectionStoreV2;
265 for (const threadId of [PARENT, FORK]) {
266 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(threadId);
267 const snapshot = {
268 snapshotSequence,
269 projection: projectThreadProjectionForWire(projection),
270 };
271 const streamed = yield* streamedBody(snapshot);
272 assert.isTrue(streamed.bytes.equals(referenceBody(snapshot)));
273 if (threadId === PARENT) {
274 assert.strictEqual(snapshot.projection.turnItems.length, ITEMS + 2);
275 assert.isTrue(
276 snapshot.projection.turnItems.some(
277 (item) =>
278 item.type === "subagent" && "progress" in item && item.progress === undefined,
279 ),
280 );
281 assert.isAtMost(streamed.largestChunk, 1024 * 1024);
282 } else {
283 // Inherited rows hold parent items that are not in this thread's turn items.
284 assert.isTrue(
285 snapshot.projection.visibleTurnItems.some((row) => row.visibility === "inherited"),
286 );
287 }
288 }
289 }),
290 );
291β
292 it.effect("fails before the body when the schema rejects the snapshot, as encoding did", () =>
293 Effect.gen(function* () {
294 const projections = yield* ProjectionStore.ProjectionStoreV2;
295 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(PARENT);
296 const wire = projectThreadProjectionForWire(projection);
297 const [first, ...rest] = wire.turnItems;
298 const invalid = {
299 snapshotSequence,
300 projection: {
301 ...wire,
302 turnItems: [
303 { ...first!, status: "unknown" } as unknown as OrchestrationV2TurnItem,
304 ...rest,
305 ],
306 },
307 };
308 const notJson = NOT_JSON_VALUES.map((value) => ({ value })).map((answers) => ({
309 snapshotSequence,
310 projection: { ...wire, runtimeRequests: runtimeRequests([answers]) },
311 }));
312 for (const snapshot of [invalid, ...notJson]) {
313 assert.throws(() => referenceBody(snapshot));
314 const error = yield* encodeThreadSnapshotBody(snapshot).pipe(Effect.flip);
315 assert.isTrue(Schema.isSchemaError(error));
316 }
317 }),
318 );
319β
320 it.effect("keeps chunks bounded for large and deeply nested answers", () =>
321 Effect.gen(function* () {
322 const projections = yield* ProjectionStore.ProjectionStoreV2;
323 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(FORK);
324 // Deeper than a recursive writer, or one JSON.stringify call, can go: with and without bulk.
325 const nest = (leaf: unknown) => {
326 let deep = leaf;
327 for (let depth = 0; depth < 3_000; depth++) deep = depth % 2 === 0 ? [deep] : { deep };
328 return deep;
329 };
330 const snapshot = {
331 snapshotSequence,
332 projection: {
333 ...projectThreadProjectionForWire(projection),
334 // Each answer set is large or deep in its own way.
335 runtimeRequests: runtimeRequests([
336 { reply: { toJSON: null, text: `${TEXT}\n`.repeat(40_000) } },
337 { [TEXT.repeat(40_000)]: 0 },
338 // Under a chunk before escaping, six times that after: each NUL is written as \u0000.
339 { nul: "\u0000".repeat(200_000) },
340 { many: Array.from({ length: 200_000 }, (_, index) => ({ index, text: "x" })) },
341 { deep: nest(TEXT.repeat(40_000)) },
342 { deep: nest(TEXT) },
343 ]),
344 },
345 };
346 const streamed = yield* streamedBody(snapshot);
347 assert.isTrue(streamed.bytes.equals(referenceBody(snapshot)));
348 assert.isAtMost(streamed.largestChunk, 1024 * 1024);
349 }),
350 );
351β
352 it.effect("writes an answer too deep for JSON.stringify here, without failing mid-body", () =>
353 Effect.gen(function* () {
354 const projections = yield* ProjectionStore.ProjectionStoreV2;
355 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(FORK);
356 const snapshot = (deep: unknown) => ({
357 snapshotSequence,
358 projection: {
359 ...projectThreadProjectionForWire(projection),
360 runtimeRequests: runtimeRequests([{ deep }]),
361 },
362 });
363 // A two-byte string puts JSON.stringify on its recursive path, which this depth overflows.
364 let deep: unknown = "π".repeat(10);
365 let deepJson = JSON.stringify(deep);
366 for (let depth = 0; depth < 20_000; depth++) {
367 deep = depth % 2 === 0 ? [deep] : { deep };
368 deepJson = depth % 2 === 0 ? `[${deepJson}]` : `{"deep":${deepJson}}`;
369 }
370 assert.throws(() => JSON.stringify(deep), RangeError);
371 const expected = referenceBody(snapshot("placeholder"))
372 .toString("utf8")
373 .replace('"deep":"placeholder"', () => `"deep":${deepJson}`);
374 const streamed = yield* streamedBody(snapshot(deep));
375 assert.strictEqual(streamed.bytes.toString("utf8"), expected);
376 }),
377 );
378});