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

ThreadStream.test.ts

286 lines9.3 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 event count is within the bound", () => {
115 expect(
116 decideThreadResume({
117 afterSequence: 10,
118 highWater: 20_000,
119 replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS,
120 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
121 }),
122 ).toEqual({
123 mode: "replay",
124 afterSequence: 10,
125 throughSequence: 20_000,
126 });
127 });
128​
129 it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
130 expect(
131 decideThreadResume({
132 afterSequence: 10,
133 highWater: 11,
134 replayEventCount: 1,
135 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1,
136 }),
137 ).toEqual({ mode: "snapshot" });
138 });
139​
140 it("falls back to a snapshot when the client cursor is ahead of the store", () => {
141 expect(
142 decideThreadResume({
143 afterSequence: 50,
144 highWater: 40,
145 replayEventCount: 0,
146 replayEncodedBytes: 0,
147 }),
148 ).toEqual({ mode: "snapshot" });
149 });
150​
151 it("builds socket fallback snapshots with a bounded timeline and history cursor", () => {
152 const snapshot = buildBoundedThreadStreamSnapshot({
153 snapshotSequence: 44,
154 projection: timelineProjection(80),
155 });
156​
157 expect(snapshot.kind).toBe("snapshot");
158 expect(snapshot.snapshotSequence).toBe(44);
159 expect(snapshot.projection.visibleTurnItems).toHaveLength(75);
160 expect(snapshot.projection.turnItems).toHaveLength(75);
161 expect(snapshot.historyCursor).not.toBeNull();
162 expect(snapshot.hasMoreHistory).toBe(true);
163 expect(snapshot.latestLocalTurnOrdinal).toBe(80);
164 });
165​
166 it("rejects a 10 MiB raw replay even when its projected form fits the wire budget", () => {
167 const item = {
168 id: TurnItemId.make("large-dynamic-tool"),
169 type: "dynamic_tool",
170 threadId: THREAD_ID,
171 runId: null,
172 nodeId: null,
173 providerThreadId: null,
174 providerTurnId: null,
175 nativeItemRef: null,
176 parentItemId: null,
177 ordinal: 1,
178 status: "completed",
179 title: "Large result",
180 toolName: "mcp__test__large_result",
181 input: { query: "small" },
182 output: { text: "x".repeat(LARGE_PROJECTABLE_OUTPUT_BYTES) },
183 startedAt: NOW,
184 completedAt: NOW,
185 updatedAt: NOW,
186 } satisfies OrchestrationV2TurnItem;
187 const event = {
188 id: EventId.make("large-dynamic-tool-event"),
189 type: "turn-item.updated" as const,
190 threadId: THREAD_ID,
191 occurredAt: NOW,
192 payload: item,
193 };
194 const rawReplay = [{ kind: "event" as const, sequence: 10, event }];
195 const projectedReplay = [
196 {
197 kind: "event" as const,
198 sequence: 10,
199 event: projectDomainEventForWire(event),
200 },
201 ];
202​
203 const rawPayloadBytes = Buffer.byteLength(JSON.stringify(event.payload), "utf8");
204 expect(rawPayloadBytes).toBe(LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES);
205 expect(rawPayloadBytes).toBeGreaterThan(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES);
206 expect(isThreadReplayRawPayloadSafe(rawPayloadBytes)).toBe(false);
207 expect(threadReplayEncodedBytes(rawReplay)).toBeGreaterThan(
208 THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
209 );
210 const projectedBytes = threadReplayEncodedBytes(projectedReplay);
211 expect(projectedBytes).toBeLessThanOrEqual(MAX_PROJECTED_DYNAMIC_REPLAY_BYTES);
212 expect(
213 decideThreadResume({
214 afterSequence: 9,
215 highWater: 10,
216 replayEventCount: projectedReplay.length,
217 replayEncodedBytes: projectedBytes,
218 }),
219 ).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 });
220 });
221});
222​
223describe("compact bounded snapshots", () => {
224 const FORK_PARENT = ThreadId.make("thread-stream-parent");
225 const decodeStreamItem = Schema.decodeUnknownSync(
226 Schema.toCodecJson(OrchestrationV2ThreadStreamItem),
227 );
228 const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadStreamItem));
229​
230 function forkProjection(): OrchestrationV2ThreadProjection {
231 const base = timelineProjection(6);
232 const local = base.visibleTurnItems.slice(3).map((row, index) => ({ ...row, position: index }));
233 const inherited = base.visibleTurnItems.slice(0, 3).map((row, index) => {
234 const item = { ...row.item, id: TurnItemId.make(`parent-${index}`), threadId: FORK_PARENT };
235 return {
236 position: index,
237 visibility: "inherited" as const,
238 sourceThreadId: FORK_PARENT,
239 sourceItemId: item.id,
240 item,
241 };
242 });
243 const request = {
244 ...base.turnItems[0]!,
245 id: TurnItemId.make("interrupt-request"),
246 type: "run_interrupt_request",
247 ordinal: 0,
248 message: "Stop",
249 } as unknown as OrchestrationV2TurnItem;
250 return {
251 ...base,
252 turnItems: [request, ...local.map((row) => row.item)],
253 visibleTurnItems: [...inherited, ...local].map((row, position) => ({ ...row, position })),
254 };
255 }
256​
257 it.each([
258 ["linear", () => timelineProjection(80)],
259 ["fork with retained interrupt request", forkProjection],
260 ])("restores the exact opted-out snapshot for %s threads", (_, makeProjection) => {
261 const base = makeProjection();
262 const projection = {
263 ...base,
264 thread: { ...base.thread, modelSelection: { instanceId: "codex", model: "gpt-5" } },
265 } as OrchestrationV2ThreadProjection;
266 const full = buildBoundedThreadStreamSnapshot({ snapshotSequence: 44, projection });
267 const compact = buildBoundedThreadStreamSnapshot({
268 snapshotSequence: 44,
269 projection,
270 compactTurnItems: true,
271 });
272​
273 expect("turnItemsOmitLocalVisible" in full).toBe(false);
274 expect(compact.turnItemsOmitLocalVisible).toBe(true);
275 expect(compact.projection.turnItems.length).toBeLessThan(full.projection.turnItems.length);
276 const { turnItemsOmitLocalVisible: _marker, ...compactFields } = compact;
277 expect({ ...compactFields, projection: full.projection }).toEqual(full);
278​
279 const decodedFull = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(full))));
280 const decodedCompact = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(compact))));
281 if (decodedFull.kind !== "snapshot" || decodedCompact.kind !== "snapshot") {
282 throw new Error("Expected snapshots");
283 }
284 expect(boundedSnapshotProjection(decodedCompact)).toEqual(decodedFull.projection);
285 });
286});