Open History to see the last commit
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;
111}
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 expect(snapshot.payloadBudgetExceeded).toBe(false);
165 });
166
167 it("rejects a 10 MiB raw replay even when its projected form fits the wire budget", () => {
168 const item = {
169 id: TurnItemId.make("large-dynamic-tool"),
170 type: "dynamic_tool",
171 threadId: THREAD_ID,
172 runId: null,
173 nodeId: null,
174 providerThreadId: null,
175 providerTurnId: null,
176 nativeItemRef: null,
177 parentItemId: null,
178 ordinal: 1,
179 status: "completed",
180 title: "Large result",
181 toolName: "mcp__test__large_result",
182 input: { query: "small" },
183 output: { text: "x".repeat(LARGE_PROJECTABLE_OUTPUT_BYTES) },
184 startedAt: NOW,
185 completedAt: NOW,
186 updatedAt: NOW,
187 } satisfies OrchestrationV2TurnItem;
188 const event = {
189 id: EventId.make("large-dynamic-tool-event"),
190 type: "turn-item.updated" as const,
191 threadId: THREAD_ID,
192 occurredAt: NOW,
193 payload: item,
194 };
195 const rawReplay = [{ kind: "event" as const, sequence: 10, event }];
196 const projectedReplay = [
197 {
198 kind: "event" as const,
199 sequence: 10,
200 event: projectDomainEventForWire(event),
201 },
202 ];
203
204 const rawPayloadBytes = Buffer.byteLength(JSON.stringify(event.payload), "utf8");
205 expect(rawPayloadBytes).toBe(LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES);
206 expect(rawPayloadBytes).toBeGreaterThan(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES);
207 expect(isThreadReplayRawPayloadSafe(rawPayloadBytes)).toBe(false);
208 expect(threadReplayEncodedBytes(rawReplay)).toBeGreaterThan(
209 THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
210 );
211 const projectedBytes = threadReplayEncodedBytes(projectedReplay);
212 expect(projectedBytes).toBeLessThanOrEqual(MAX_PROJECTED_DYNAMIC_REPLAY_BYTES);
213 expect(
214 decideThreadResume({
215 afterSequence: 9,
216 highWater: 10,
217 replayEventCount: projectedReplay.length,
218 replayEncodedBytes: projectedBytes,
219 }),
220 ).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 });
221 });
222});
223
224describe("compact bounded snapshots", () => {
225 const FORK_PARENT = ThreadId.make("thread-stream-parent");
226 const decodeStreamItem = Schema.decodeUnknownSync(
227 Schema.toCodecJson(OrchestrationV2ThreadStreamItem),
228 );
229 const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadStreamItem));
230
231 function forkProjection(): OrchestrationV2ThreadProjection {
232 const base = timelineProjection(6);
233 const local = base.visibleTurnItems.slice(3).map((row, index) => ({ ...row, position: index }));
234 const inherited = base.visibleTurnItems.slice(0, 3).map((row, index) => {
235 const item = { ...row.item, id: TurnItemId.make(`parent-${index}`), threadId: FORK_PARENT };
236 return {
237 position: index,
238 visibility: "inherited" as const,
239 sourceThreadId: FORK_PARENT,
240 sourceItemId: item.id,
241 item,
242 };
243 });
244 const request = {
245 ...base.turnItems[0]!,
246 id: TurnItemId.make("interrupt-request"),
247 type: "run_interrupt_request",
248 ordinal: 0,
249 message: "Stop",
250 } as unknown as OrchestrationV2TurnItem;
251 return {
252 ...base,
253 turnItems: [request, ...local.map((row) => row.item)],
254 visibleTurnItems: [...inherited, ...local].map((row, position) => ({ ...row, position })),
255 };
256 }
257
258 it.each([
259 ["linear", () => timelineProjection(80)],
260 ["fork with retained interrupt request", forkProjection],
261 ])("restores the exact opted-out snapshot for %s threads", (_, makeProjection) => {
262 const base = makeProjection();
263 const projection = {
264 ...base,
265 thread: { ...base.thread, modelSelection: { instanceId: "codex", model: "gpt-5" } },
266 } as OrchestrationV2ThreadProjection;
267 const full = buildBoundedThreadStreamSnapshot({ snapshotSequence: 44, projection });
268 const compact = buildBoundedThreadStreamSnapshot({
269 snapshotSequence: 44,
270 projection,
271 compactTurnItems: true,
272 });
273
274 expect("turnItemsOmitLocalVisible" in full).toBe(false);
275 expect(compact.turnItemsOmitLocalVisible).toBe(true);
276 expect(compact.projection.turnItems.length).toBeLessThan(full.projection.turnItems.length);
277 const { turnItemsOmitLocalVisible: _marker, ...compactFields } = compact;
278 expect({ ...compactFields, projection: full.projection }).toEqual(full);
279
280 const decodedFull = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(full))));
281 const decodedCompact = decodeStreamItem(JSON.parse(JSON.stringify(encodeStreamItem(compact))));
282 if (decodedFull.kind !== "snapshot" || decodedCompact.kind !== "snapshot") {
283 throw new Error("Expected snapshots");
284 }
285 expect(boundedSnapshotProjection(decodedCompact)).toEqual(decodedFull.projection);
286 });
287});