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

ThreadStream.test.ts

360 lines11.8 KB

1import {
2 EventId,
3 OrchestrationV2ThreadStreamItem,
4 ThreadId,
5 TurnItemId,
6 type OrchestrationV2ProjectedTurnItem,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2TurnItem,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "vite-plus/test";
11import * as DateTime from "effect/DateTime";
12import * as Schema from "effect/Schema";
13import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
14​
15import {
16 buildBoundedThreadStreamSnapshot,
17 decideThreadResume,
18 isThreadReplayRawPayloadSafe,
19 threadReplayEncodedBytes,
20 THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES,
21 THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
22 THREAD_RESUME_MAX_REPLAY_EVENTS,
23} from "./ThreadStream.ts";
24import { projectDomainEventForWire } from "./WireProjection.ts";
25​
26const NOW = DateTime.makeUnsafe("2026-09-08T00:00:00.000Z");
27const THREAD_ID = ThreadId.make("thread-stream-test");
28const LARGE_PROJECTABLE_OUTPUT_BYTES = 10 * 1_048_576;
29const LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES = 10_486_214;
30const MAX_PROJECTED_DYNAMIC_REPLAY_BYTES = 2_048;
31​
32function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection {
33 const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
34 { length: itemCount },
35 (_, index) => {
36 const id = TurnItemId.make(`item-${index}`);
37 const item = {
38 id,
39 type: "command_execution",
40 threadId: THREAD_ID,
41 runId: null,
42 nodeId: null,
43 providerThreadId: null,
44 providerTurnId: null,
45 nativeItemRef: null,
46 parentItemId: null,
47 ordinal: index + 1,
48 status: "completed",
49 title: `Command ${index}`,
50 input: `command-${index}`,
51 output: `output-${index}`,
52 exitCode: 0,
53 startedAt: NOW,
54 completedAt: NOW,
55 updatedAt: NOW,
56 } satisfies OrchestrationV2TurnItem;
57 return {
58 position: index,
59 visibility: "local",
60 sourceThreadId: THREAD_ID,
61 sourceItemId: id,
62 item,
63 };
64 },
65 );
66 return {
67 thread: {
68 id: THREAD_ID,
69 projectId: "project-stream-test",
70 title: "Thread stream test",
71 providerInstanceId: "codex",
72 modelSelection: null,
73 runtimeMode: "full-access",
74 interactionMode: "default",
75 branch: null,
76 worktreePath: null,
77 activeProviderThreadId: null,
78 lineage: {
79 parentThreadId: null,
80 relationshipToParent: null,
81 rootThreadId: THREAD_ID,
82 },
83 forkedFrom: null,
84 createdBy: "user",
85 creationSource: "web",
86 createdAt: NOW,
87 updatedAt: NOW,
88 archivedAt: null,
89 settledOverride: null,
90 settledAt: null,
91 deletedAt: null,
92 },
93 runs: [],
94 attempts: [],
95 nodes: [],
96 subagents: [],
97 providerSessions: [],
98 providerThreads: [],
99 providerTurns: [],
100 runtimeRequests: [],
101 messages: [],
102 plans: [],
103 turnItems: visibleTurnItems.map((row) => row.item),
104 checkpointScopes: [],
105 checkpoints: [],
106 contextHandoffs: [],
107 contextTransfers: [],
108 visibleTurnItems,
109 updatedAt: NOW,
110 } as unknown as OrchestrationV2ThreadProjection;
112​
113describe("decideThreadResume", () => {
114 it("replays when the gap is zero", () => {
115 expect(
116 decideThreadResume({
117 afterSequence: 10,
118 highWater: 10,
119 replayEventCount: 0,
120 replayEncodedBytes: 0,
121 }),
122 ).toEqual({ mode: "replay", afterSequence: 10, throughSequence: 10 });
123 });
124​
125 it("replays when the event count is within the bound", () => {
126 expect(
127 decideThreadResume({
128 afterSequence: 10,
129 highWater: 20_000,
130 replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS,
131 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
132 }),
133 ).toEqual({
134 mode: "replay",
135 afterSequence: 10,
136 throughSequence: 20_000,
137 });
138 });
139​
140 it("falls back to a snapshot when the event count exceeds the bound", () => {
141 expect(
142 decideThreadResume({
143 afterSequence: 10,
144 highWater: 20_000,
145 replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS + 1,
146 replayEncodedBytes: 1,
147 }),
148 ).toEqual({ mode: "snapshot" });
149 });
150​
151 it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
152 expect(
153 decideThreadResume({
154 afterSequence: 10,
155 highWater: 11,
156 replayEventCount: 1,
157 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1,
158 }),
159 ).toEqual({ mode: "snapshot" });
160 });
161​
162 it("rejects pathological raw payloads before decoding them", () => {
163 expect(isThreadReplayRawPayloadSafe(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES)).toBe(true);
164 expect(isThreadReplayRawPayloadSafe(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES + 1)).toBe(false);
165​
166 expect(
167 decideThreadResume({
168 afterSequence: 9,
169 highWater: 10,
170 replayEventCount: 1,
171 replayEncodedBytes: 1,
172 }),
173 ).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 });
174 });
175​
176 it("falls back to a snapshot when the client cursor is ahead of the store", () => {
177 expect(
178 decideThreadResume({
179 afterSequence: 50,
180 highWater: 40,
181 replayEventCount: 0,
182 replayEncodedBytes: 0,
183 }),
184 ).toEqual({ mode: "snapshot" });
185 });
186​
187 it("counts UTF-8 bytes across projected stream items", () => {
188 expect(threadReplayEncodedBytes([{ value: "a" }, { value: "🦊" }])).toBe(
189 Buffer.byteLength('{"value":"a"}', "utf8") + Buffer.byteLength('{"value":"🦊"}', "utf8"),
190 );
191 });
192​
193 it("builds socket fallback snapshots with a bounded timeline and history cursor", () => {
194 const snapshot = buildBoundedThreadStreamSnapshot({
195 snapshotSequence: 44,
196 projection: timelineProjection(80),
197 });
198​
199 expect(snapshot.kind).toBe("snapshot");
200 expect(snapshot.snapshotSequence).toBe(44);
201 expect(snapshot.projection.visibleTurnItems).toHaveLength(75);
202 expect(snapshot.projection.turnItems).toHaveLength(75);
203 expect(snapshot.historyCursor).not.toBeNull();
204 expect(snapshot.hasMoreHistory).toBe(true);
205 expect(snapshot.latestLocalTurnOrdinal).toBe(80);
206 expect(snapshot.payloadBudgetExceeded).toBe(false);
207 });
208​
209 it("rejects a 10 MiB raw replay even when its projected form fits the wire budget", () => {
210 const item = {
211 id: TurnItemId.make("large-dynamic-tool"),
212 type: "dynamic_tool",
213 threadId: THREAD_ID,
214 runId: null,
215 nodeId: null,
216 providerThreadId: null,
217 providerTurnId: null,
218 nativeItemRef: null,
219 parentItemId: null,
220 ordinal: 1,
221 status: "completed",
222 title: "Large result",
223 toolName: "mcp__test__large_result",
224 input: { query: "small" },
225 output: { text: "x".repeat(LARGE_PROJECTABLE_OUTPUT_BYTES) },
226 startedAt: NOW,
227 completedAt: NOW,
228 updatedAt: NOW,
229 } satisfies OrchestrationV2TurnItem;
230 const event = {
231 id: EventId.make("large-dynamic-tool-event"),
232 type: "turn-item.updated" as const,
233 threadId: THREAD_ID,
234 occurredAt: NOW,
235 payload: item,
236 };
237 const rawReplay = [{ kind: "event" as const, sequence: 10, event }];
238 const projectedReplay = [
239 {
240 kind: "event" as const,
241 sequence: 10,
242 event: projectDomainEventForWire(event),
243 },
244 ];
245​
246 const rawPayloadBytes = Buffer.byteLength(JSON.stringify(event.payload), "utf8");
247 expect(rawPayloadBytes).toBe(LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES);
248 expect(rawPayloadBytes).toBeGreaterThan(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES);
249 expect(isThreadReplayRawPayloadSafe(rawPayloadBytes)).toBe(false);
250 expect(threadReplayEncodedBytes(rawReplay)).toBeGreaterThan(
251 THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
252 );
253 const projectedBytes = threadReplayEncodedBytes(projectedReplay);
254 expect(projectedBytes).toBeLessThanOrEqual(MAX_PROJECTED_DYNAMIC_REPLAY_BYTES);
255 expect(
256 decideThreadResume({
257 afterSequence: 9,
258 highWater: 10,
259 replayEventCount: projectedReplay.length,
260 replayEncodedBytes: projectedBytes,
261 }),
262 ).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 });
263 });
264});
265​
266describe("compact bounded snapshots", () => {
267 const FORK_PARENT = ThreadId.make("thread-stream-parent");
268 const decodeStreamItem = Schema.decodeUnknownSync(
269 Schema.toCodecJson(OrchestrationV2ThreadStreamItem),
270 );
271 const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadStreamItem));
272​
273 function forkProjection(): OrchestrationV2ThreadProjection {
274 const base = timelineProjection(6);
275 const local = base.visibleTurnItems.slice(3).map((row, index) => ({ ...row, position: index }));
276 const inherited = base.visibleTurnItems.slice(0, 3).map((row, index) => {
277 const item = { ...row.item, id: TurnItemId.make(`parent-${index}`), threadId: FORK_PARENT };
278 return {
279 position: index,
280 visibility: "inherited" as const,
281 sourceThreadId: FORK_PARENT,
282 sourceItemId: item.id,
283 item,
284 };
285 });
286 const request = {
287 ...base.turnItems[0]!,
288 id: TurnItemId.make("interrupt-request"),
289 type: "run_interrupt_request",
290 ordinal: 0,
291 message: "Stop",
292 } as unknown as OrchestrationV2TurnItem;
293 return {
294 ...base,
295 turnItems: [request, ...local.map((row) => row.item)],
296 visibleTurnItems: [...inherited, ...local].map((row, position) => ({ ...row, position })),
297 };
298 }
299​
300 it.each([
301 ["linear", () => timelineProjection(80)],
302 ["fork with retained interrupt request", forkProjection],
303 ])("restores the exact opted-out snapshot for %s threads", (_, makeProjection) => {
304 const base = makeProjection();
305 const projection = {
306 ...base,
307 thread: { ...base.thread, modelSelection: { instanceId: "codex", model: "gpt-5" } },
308 } as OrchestrationV2ThreadProjection;
309 const full = buildBoundedThreadStreamSnapshot({ snapshotSequence: 44, projection });
310 const compact = buildBoundedThreadStreamSnapshot({
311 snapshotSequence: 44,
312 projection,
313 compactTurnItems: true,
314 });
315​
316 expect("turnItemsOmitLocalVisible" in full).toBe(false);
317 expect(compact.turnItemsOmitLocalVisible).toBe(true);
318 expect(compact.projection.turnItems.length).toBeLessThan(full.projection.turnItems.length);
319 const { turnItemsOmitLocalVisible: _marker, ...compactFields } = compact;
320 expect({ ...compactFields, projection: full.projection }).toEqual(full);
321​
322 const decodedFull = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(full))));
323 const decodedCompact = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(compact))));
324 if (decodedFull.kind !== "snapshot" || decodedCompact.kind !== "snapshot") {
325 throw new Error("Expected snapshots");
326 }
327 expect(boundedSnapshotProjection(decodedCompact)).toEqual(decodedFull.projection);
328 });
329​
330 it("keeps the retained interrupt request outside the visible window", () => {
331 const compact = buildBoundedThreadStreamSnapshot({
332 snapshotSequence: 1,
333 projection: forkProjection(),
334 compactTurnItems: true,
335 });
336 expect(compact.projection.turnItems.map((item) => item.id)).toEqual(["interrupt-request"]);
337 expect(boundedSnapshotProjection(compact).turnItems.map((item) => String(item.id))).toEqual([
338 "item-3",
339 "item-4",
340 "item-5",
341 "interrupt-request",
342 ]);
343 });
344​
345 it("omits the marker when the window has no local rows", () => {
346 const fork = forkProjection();
347 const inheritedOnly = {
348 ...fork,
349 turnItems: fork.turnItems.slice(0, 1),
350 visibleTurnItems: fork.visibleTurnItems.slice(0, 3),
351 };
352 const compact = buildBoundedThreadStreamSnapshot({
353 snapshotSequence: 1,
354 projection: inheritedOnly,
355 compactTurnItems: true,
356 });
357 expect("turnItemsOmitLocalVisible" in compact).toBe(false);
358 expect(compact.projection.turnItems.map((item) => item.id)).toEqual(["interrupt-request"]);
359 });
360});