Open History to see the last commit
1import {
2 EventId,
3 ThreadId,
4 TurnItemId,
5 type OrchestrationV2ProjectedTurnItem,
6 type OrchestrationV2ThreadProjection,
7 type OrchestrationV2TurnItem,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "vite-plus/test";
10import * as DateTime from "effect/DateTime";
11
12import {
13 buildBoundedThreadStreamSnapshot,
14 decideThreadResume,
15 isThreadReplayRawPayloadSafe,
16 threadReplayEncodedBytes,
17 THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES,
18 THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
19 THREAD_RESUME_MAX_REPLAY_EVENTS,
20} from "./ThreadStream.ts";
21import { projectDomainEventForWire } from "./WireProjection.ts";
22
23const NOW = DateTime.makeUnsafe("2026-09-08T00:00:00.000Z");
24const THREAD_ID = ThreadId.make("thread-stream-test");
25const LARGE_PROJECTABLE_OUTPUT_BYTES = 10 * 1_048_576;
26const LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES = 10_486_214;
27// The first projected replay measured 821 bytes; leave room for small envelope additions.
28const MAX_PROJECTED_DYNAMIC_REPLAY_BYTES = 2_048;
29
30function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection {
31 const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
32 { length: itemCount },
33 (_, index) => {
34 const id = TurnItemId.make(`item-${index}`);
35 const item = {
36 id,
37 type: "command_execution",
38 threadId: THREAD_ID,
39 runId: null,
40 nodeId: null,
41 providerThreadId: null,
42 providerTurnId: null,
43 nativeItemRef: null,
44 parentItemId: null,
45 ordinal: index + 1,
46 status: "completed",
47 title: `Command ${index}`,
48 input: `command-${index}`,
49 output: `output-${index}`,
50 exitCode: 0,
51 startedAt: NOW,
52 completedAt: NOW,
53 updatedAt: NOW,
54 } satisfies OrchestrationV2TurnItem;
55 return {
56 position: index,
57 visibility: "local",
58 sourceThreadId: THREAD_ID,
59 sourceItemId: id,
60 item,
61 };
62 },
63 );
64 return {
65 thread: {
66 id: THREAD_ID,
67 projectId: "project-stream-test",
68 title: "Thread stream test",
69 providerInstanceId: "codex",
70 modelSelection: null,
71 runtimeMode: "full-access",
72 interactionMode: "default",
73 branch: null,
74 worktreePath: null,
75 activeProviderThreadId: null,
76 lineage: {
77 parentThreadId: null,
78 relationshipToParent: null,
79 rootThreadId: THREAD_ID,
80 },
81 forkedFrom: null,
82 createdBy: "user",
83 creationSource: "web",
84 createdAt: NOW,
85 updatedAt: NOW,
86 archivedAt: null,
87 settledOverride: null,
88 settledAt: null,
89 deletedAt: null,
90 },
91 runs: [],
92 attempts: [],
93 nodes: [],
94 subagents: [],
95 providerSessions: [],
96 providerThreads: [],
97 providerTurns: [],
98 runtimeRequests: [],
99 messages: [],
100 plans: [],
101 turnItems: visibleTurnItems.map((row) => row.item),
102 checkpointScopes: [],
103 checkpoints: [],
104 contextHandoffs: [],
105 contextTransfers: [],
106 visibleTurnItems,
107 updatedAt: NOW,
108 } as unknown as OrchestrationV2ThreadProjection;
109}
110
111describe("decideThreadResume", () => {
112 it("replays when the gap is zero", () => {
113 expect(
114 decideThreadResume({
115 afterSequence: 10,
116 highWater: 10,
117 replayEventCount: 0,
118 replayEncodedBytes: 0,
119 }),
120 ).toEqual({ mode: "replay", afterSequence: 10, throughSequence: 10 });
121 });
122
123 it("replays when the event count is within the bound", () => {
124 expect(
125 decideThreadResume({
126 afterSequence: 10,
127 highWater: 20_000,
128 replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS,
129 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
130 }),
131 ).toEqual({
132 mode: "replay",
133 afterSequence: 10,
134 throughSequence: 20_000,
135 });
136 });
137
138 it("falls back to a snapshot when the event count exceeds the bound", () => {
139 expect(
140 decideThreadResume({
141 afterSequence: 10,
142 highWater: 20_000,
143 replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS + 1,
144 replayEncodedBytes: 1,
145 }),
146 ).toEqual({ mode: "snapshot" });
147 });
148
149 it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
150 expect(
151 decideThreadResume({
152 afterSequence: 10,
153 highWater: 11,
154 replayEventCount: 1,
155 replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1,
156 }),
157 ).toEqual({ mode: "snapshot" });
158 });
159
160 it("rejects pathological raw payloads before decoding them", () => {
161 expect(isThreadReplayRawPayloadSafe(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES)).toBe(true);
162 expect(isThreadReplayRawPayloadSafe(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES + 1)).toBe(false);
163
164 // Raw safety and projected transport size are deliberately separate. A
165 // tiny projected replay is transport-safe even when its raw source is not.
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});