Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 MessageId,
6 ContextHandoffId,
7 ProviderThreadId,
8 NodeId,
9 EventId,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2DomainEvent,
16 type OrchestrationV2ThreadProjection,
17 type OrchestrationV2ThreadStreamItem,
18 OrchestrationV2TurnItem,
19 OrchestrationV2TurnItemJson,
20} from "@t3tools/contracts";
21import { describe, expect, it } from "@effect/vitest";
22import * as DateTime from "effect/DateTime";
23import * as Schema from "effect/Schema";
24
25import { coalesceLiveUpdatedEvents } from "./ThreadLiveEventCoalescer.ts";
26import {
27 makeLiveBodyDeduper,
28 projectTurnItemForWire,
29 projectTurnItemForDetail,
30 projectDomainEventForWire,
31} from "./WireProjection.ts";
32import { threadShellFromProjection } from "./ProjectionStore.ts";
33import { MAX_TOOL_OUTPUT_IMAGES, toolOutputImages } from "@t3tools/shared/toolOutput";
34
35const decodeTurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);
36const encodeTurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);
37const decodeTurnItemJson = Schema.decodeUnknownSync(OrchestrationV2TurnItemJson);
38
39const base = {
40 id: TurnItemId.make("tool-1"),
41 type: "dynamic_tool" as const,
42 threadId: ThreadId.make("thread-1"),
43 runId: null,
44 nodeId: null,
45 providerThreadId: null,
46 providerTurnId: null,
47 nativeItemRef: null,
48 parentItemId: null,
49 ordinal: 1,
50 status: "completed" as const,
51 title: "MCP tool",
52 toolName: "mcp__github__fetch_pr",
53 input: { pr: 42 },
54 startedAt: DateTime.makeUnsafe("2026-08-13T00:00:00.000Z"),
55 completedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"),
56 updatedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"),
57};
58
59describe("orchestration V2 wire projection", () => {
60 it("keeps copied handoff transcripts out of activity items and live events", () => {
61 const item = {
62 ...base,
63 type: "handoff" as const,
64 contextHandoffId: ContextHandoffId.make("handoff:wire"),
65 fromProviderThreadIds: [],
66 toProviderThreadId: ProviderThreadId.make("target"),
67 fromProviderInstanceIds: [],
68 toProviderInstanceId: ProviderInstanceId.make("codex"),
69 strategy: "full_thread_summary" as const,
70 summary: "PRIVATE_HANDOFF_TRANSCRIPT",
71 };
72 const projected = projectTurnItemForWire(item);
73 expect(projected).not.toHaveProperty("summary");
74 expect(decodeTurnItem(projected)).toMatchObject({ contextHandoffId: item.contextHandoffId });
75 const event = {
76 id: EventId.make("handoff:wire"),
77 type: "turn-item.updated" as const,
78 threadId: base.threadId,
79 occurredAt: base.updatedAt,
80 payload: item,
81 };
82 expect(JSON.stringify(projectDomainEventForWire(event))).not.toContain(item.summary);
83 expect(item.summary).toBe("PRIVATE_HANDOFF_TRANSCRIPT");
84 });
85
86 it("preserves image metadata through wire and JSON contracts while redacting output", () => {
87 const item = {
88 ...base,
89 toolName: "Read",
90 input: { file_path: "/workspace/reference.png" },
91 viewedImagePath: "/workspace/reference.png",
92 output: { data: "private-image-data" },
93 } satisfies OrchestrationV2TurnItem;
94 const projected = projectTurnItemForWire(item);
95 const live = decodeTurnItem(projected);
96 const encoded = encodeTurnItemJson(live);
97 const json = decodeTurnItemJson(encoded);
98 const decoded = decodeTurnItem(json);
99 expect(decoded).toMatchObject({ viewedImagePath: "/workspace/reference.png" });
100 expect(decoded).not.toHaveProperty("output");
101 expect(item.output.data).toBe("private-image-data");
102 });
103
104 it("keeps transcript bodies out of shell rows", () => {
105 const now = DateTime.makeUnsafe("2026-08-13T00:00:00.000Z");
106 const threadId = ThreadId.make("thread-shell-budget");
107 const projection = {
108 thread: {
109 createdBy: "user",
110 creationSource: "web",
111 id: threadId,
112 projectId: ProjectId.make("project-shell-budget"),
113 title: "Shell payload budget",
114 providerInstanceId: ProviderInstanceId.make("codex"),
115 modelSelection: null,
116 runtimeMode: "full-access",
117 interactionMode: "default",
118 branch: null,
119 worktreePath: null,
120 lineage: {
121 parentThreadId: null,
122 relationshipToParent: null,
123 rootThreadId: threadId,
124 },
125 forkedFrom: null,
126 activeProviderThreadId: null,
127 createdAt: now,
128 updatedAt: now,
129 archivedAt: null,
130 settledOverride: null,
131 settledAt: null,
132 deletedAt: null,
133 },
134 runs: [],
135 attempts: [],
136 runtimeRequests: [],
137 messages: [
138 {
139 id: MessageId.make("message-shell-budget"),
140 role: "assistant",
141 text: "x".repeat(1_000_000),
142 updatedAt: now,
143 },
144 ],
145 providerSessions: [],
146 providerThreads: [],
147 turnItems: [],
148 visibleTurnItems: [],
149 plans: [],
150 updatedAt: now,
151 } as unknown as OrchestrationV2ThreadProjection;
152
153 const shell = threadShellFromProjection(projection);
154
155 expect(shell.latestVisibleMessage).toBeNull();
156 expect(JSON.stringify(shell).length).toBeLessThan(2_000);
157 });
158
159 it("omits even small dynamic tool results while retaining input", () => {
160 const item = { ...base, output: { ok: true } } satisfies OrchestrationV2TurnItem;
161 expect(projectTurnItemForWire(item)).toEqual({ ...base, outputOmitted: true });
162 expect(item.output).toEqual({ ok: true });
163 });
164
165 it("uses encoded JSON bytes for strings near the dynamic-value limit", () => {
166 const small = '"'.repeat(8_191);
167 const large = '"'.repeat(8_192);
168 const smallItem = { ...base, input: small };
169 expect(projectTurnItemForWire(smallItem)).toEqual(smallItem);
170 const projected = projectTurnItemForWire({ ...base, input: large });
171 expect(projected.type === "dynamic_tool" ? projected.input : null).toEqual({
172 summary: '"'.repeat(159) + "…",
173 truncated: true,
174 });
175 });
176
177 it("truncates detail at a UTF-8 boundary without changing the source", () => {
178 const progress = "a".repeat(32_767) + "😀" + "x".repeat(100_000);
179 const item = {
180 ...base,
181 type: "subagent" as const,
182 subagentId: NodeId.make("child-agent"),
183 origin: "app_owned" as const,
184 driver: ProviderDriverKind.make("codex"),
185 providerInstanceId: ProviderInstanceId.make("codex"),
186 childThreadId: null,
187 prompt: "Inspect code",
188 result: null,
189 progress,
190 };
191 const projected = projectTurnItemForWire(item);
192 expect(projected.type === "subagent" ? projected.progress : null).toBe(
193 "a".repeat(32_767) + "\n… output truncated for transport",
194 );
195 expect(item.progress).toBe(progress);
196 });
197
198 it("leaves a screenshot's bytes out of the fetched tool output", () => {
199 const data = "A".repeat(600_000);
200 const item = {
201 ...base,
202 type: "dynamic_tool" as const,
203 toolName: "mcp__t3-code__device_screenshot",
204 input: { deviceId: "phone" },
205 output: {
206 content: [{ type: "image", source: { type: "base64", media_type: "image/png", data } }],
207 },
208 };
209 expect(projectTurnItemForDetail(item)).toMatchObject({
210 output: { content: [{ type: "image", mimeType: "image/png" }] },
211 });
212 expect(item.output.content[0]?.source.data).toBe(data);
213 });
214
215 it("keeps image markers when the rest of a tool output is too large to send", () => {
216 const image = {
217 type: "image",
218 source: { type: "base64", media_type: "image/png", data: "AAAA" },
219 };
220 const item = {
221 ...base,
222 type: "dynamic_tool" as const,
223 output: { content: [{ type: "text", text: "x".repeat(300_000) }, image] },
224 };
225 const projected = projectTurnItemForDetail(item);
226 const output = projected.type === "dynamic_tool" ? projected.output : null;
227 expect(Array.isArray(output) ? output.slice(1) : null).toEqual([
228 { type: "image", mimeType: "image/png" },
229 ]);
230 expect(JSON.stringify(output).length).toBeLessThan(270_000);
231 });
232
233 it("bounds a tool output made of many images", () => {
234 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
235 const item = {
236 ...base,
237 type: "dynamic_tool" as const,
238 output: Array.from({ length: 10_000 }, () => image),
239 };
240 const projected = projectTurnItemForDetail(item);
241 const output = projected.type === "dynamic_tool" ? projected.output : null;
242 expect(Array.isArray(output) ? output.length : null).toBe(1 + MAX_TOOL_OUTPUT_IMAGES);
243 expect(Array.isArray(output) ? String(output[0]?.text).length : null).toBeLessThan(263_000);
244 expect(toolOutputImages(output)).toHaveLength(MAX_TOOL_OUTPUT_IMAGES);
245 });
246
247 it("keeps failure evidence without retaining command output", () => {
248 const item = {
249 ...base,
250 type: "command_execution" as const,
251 input: "cat missing-file",
252 output: "cat: missing-file: No such file or directory",
253 };
254 const projected = projectTurnItemForWire(item);
255 expect(projected).not.toHaveProperty("output");
256 expect(projected).toMatchObject({ outputIndicatesFailure: true });
257 expect(projectTurnItemForWire(projected)).toEqual(projected);
258 expect(projectTurnItemForWire({ ...item, output: "", exitCode: 2 })).toMatchObject({
259 outputIndicatesFailure: true,
260 exitCode: 2,
261 });
262 });
263
264 it("omits inline file bodies but preserves file identity and change counts", () => {
265 const item = {
266 ...base,
267 type: "file_change" as const,
268 fileName: "src/main.ts",
269 additions: 3,
270 deletions: 1,
271 diffStr: "+new code",
272 oldStr: "old code",
273 newStr: "new code",
274 };
275 const projected = projectTurnItemForWire(item);
276 expect(projected).not.toHaveProperty("diffStr");
277 expect(projected).not.toHaveProperty("oldStr");
278 expect(projected).not.toHaveProperty("newStr");
279 expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });
280 expect(item.diffStr).toBe("+new code");
281 expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });
282 expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");
283 expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");
284 const { diffStr: _diff, ...contentOnly } = item;
285 expect(projectTurnItemForDetail(contentOnly)).toMatchObject({
286 oldStr: "old code",
287 newStr: "new code",
288 });
289 expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");
290 const failed = projectTurnItemForWire({
291 ...item,
292 status: "failed",
293 diffStr: "String to replace not found",
294 });
295 expect(failed).toMatchObject({ diffStr: "String to replace not found" });
296 expect(failed).not.toHaveProperty("newStr");
297 });
298
299 it("retains only result identities and failure metadata in live tool events", () => {
300 const output = {
301 isError: true,
302 structuredContent: { threadId: "child-thread", messageId: "message", text: "PRIVATE_BODY" },
303 content: [{ type: "text", text: "PRIVATE_BODY" }],
304 };
305 const event = {
306 id: EventId.make("result-event"),
307 type: "turn-item.updated" as const,
308 threadId: base.threadId,
309 occurredAt: base.updatedAt,
310 payload: { ...base, output },
311 };
312 const projected = projectDomainEventForWire(event);
313 expect(projected.payload).toMatchObject({
314 output: { isError: true, threadId: "child-thread", messageId: "message" },
315 });
316 expect(JSON.stringify(projected)).not.toContain("PRIVATE_BODY");
317 expect(event.payload.output).toBe(output);
318 expect(projectDomainEventForWire(projected)).toEqual(projected);
319 });
320});
321
322describe("live body deduper", () => {
323 const at = base.updatedAt;
324 const messageId = MessageId.make("message-live");
325 const event = (
326 sequence: number,
327 rest: Pick<OrchestrationV2DomainEvent, "type" | "payload">,
328 ): Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }> => ({
329 kind: "event",
330 sequence,
331 event: {
332 id: EventId.make(`event-${sequence}`),
333 threadId: base.threadId,
334 occurredAt: at,
335 ...rest,
336 } as OrchestrationV2DomainEvent,
337 });
338 const message = (sequence: number, text: string) =>
339 event(sequence, {
340 type: "message.updated",
341 payload: {
342 id: messageId,
343 threadId: base.threadId,
344 runId: null,
345 nodeId: null,
346 role: "assistant",
347 text,
348 attachments: [],
349 streaming: true,
350 createdBy: "agent",
351 creationSource: "provider",
352 createdAt: at,
353 updatedAt: at,
354 },
355 });
356 const reply = (sequence: number, text: string) =>
357 event(sequence, {
358 type: "turn-item.updated",
359 payload: {
360 ...base,
361 status: "running",
362 type: "assistant_message",
363 messageId,
364 text,
365 streaming: true,
366 },
367 });
368 const payloadOf = (item: OrchestrationV2ThreadStreamItem) =>
369 item.kind === "event" ? item.event.payload : undefined;
370
371 it("blanks a reply that repeats the message delivered before it, after coalescing", () => {
372 const delivered = coalesceLiveUpdatedEvents([
373 message(1, "a"),
374 reply(2, "a"),
375 message(3, "ab"),
376 reply(4, "ab"),
377 ]).map(makeLiveBodyDeduper());
378
379 expect(
380 delivered.map((item) => [item.kind === "event" && item.sequence, payloadOf(item)]),
381 ).toEqual([
382 [3, message(3, "ab").event.payload],
383 [4, { ...reply(4, "ab").event.payload, text: "", textOmitted: true }],
384 ]);
385 });
386
387 it("caps a large checkpoint's files for the wire and still dedupes its item", () => {
388 const files = Array.from({ length: 250 }, (_, index) => ({
389 path: `vendor/file-${index}.ts`,
390 kind: "modified",
391 additions: 2,
392 deletions: 1,
393 }));
394 const checkpointId = CheckpointId.make("checkpoint-large");
395 const scopeId = CheckpointScopeId.make("scope-large");
396 const captured = event(1, {
397 type: "checkpoint.captured",
398 payload: {
399 id: checkpointId,
400 threadId: base.threadId,
401 scopeId,
402 runId: null,
403 nodeId: NodeId.make("node-large"),
404 parentCheckpointId: null,
405 ordinalWithinScope: 1,
406 appRunOrdinal: null,
407 ref: CheckpointRef.make("refs/t3/checkpoints/large"),
408 status: "ready",
409 files,
410 capturedAt: at,
411 },
412 });
413 const item = event(2, {
414 type: "turn-item.updated",
415 payload: { ...base, type: "checkpoint", checkpointId, scopeId, files },
416 });
417 const dedupe = makeLiveBodyDeduper();
418 const [record, card] = [captured, item].map((streamed) =>
419 dedupe({ ...streamed, event: projectDomainEventForWire(streamed.event) }),
420 );
421
422 const filesTotal = { count: 250, additions: 500, deletions: 250 };
423 expect(payloadOf(record!)).toMatchObject({ files: files.slice(0, 200), filesTotal });
424 expect(payloadOf(card!)).toMatchObject({ files: [], filesOmitted: true, filesTotal });
425 });
426
427 it("ships a reply whole when its message arrives after it", () => {
428 const first = reply(1, "a");
429 expect([first, message(2, "a")].map(makeLiveBodyDeduper())[0]).toBe(first);
430 });
431});