Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 MessageId,
6 ContextHandoffId,
7 ProviderSessionId,
8 ProviderThreadId,
9 NodeId,
10 EventId,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ThreadId,
15 TurnItemId,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2StoredEvent,
18 type OrchestrationV2ThreadProjection,
19 type OrchestrationV2ThreadStreamItem,
20 OrchestrationV2TurnItem,
21 OrchestrationV2TurnItemJson,
22} from "@t3tools/contracts";
23import { describe, expect, it } from "@effect/vitest";
24import * as DateTime from "effect/DateTime";
25import * as Schema from "effect/Schema";
26
27import { coalesceLiveUpdatedEvents } from "./ThreadLiveEventCoalescer.ts";
28import {
29 makeLiveBodyDeduper,
30 projectTurnItemForWire,
31 projectTurnItemForDetail,
32 projectDomainEventForWire,
33 projectStoredEventForWire,
34} from "./WireProjection.ts";
35import { threadShellFromProjection } from "./ProjectionStore.ts";
36import { MAX_TOOL_OUTPUT_IMAGES, toolOutputImages } from "@t3tools/shared/toolOutput";
37
38const decodeTurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);
39const encodeTurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);
40const decodeTurnItemJson = Schema.decodeUnknownSync(OrchestrationV2TurnItemJson);
41
42const base = {
43 id: TurnItemId.make("tool-1"),
44 type: "dynamic_tool" as const,
45 threadId: ThreadId.make("thread-1"),
46 runId: null,
47 nodeId: null,
48 providerThreadId: null,
49 providerTurnId: null,
50 nativeItemRef: null,
51 parentItemId: null,
52 ordinal: 1,
53 status: "completed" as const,
54 title: "MCP tool",
55 toolName: "mcp__github__fetch_pr",
56 input: { pr: 42 },
57 startedAt: DateTime.makeUnsafe("2026-08-13T00:00:00.000Z"),
58 completedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"),
59 updatedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"),
60};
61
62describe("orchestration V2 wire projection", () => {
63 it("keeps copied handoff transcripts out of activity items and live events", () => {
64 const item = {
65 ...base,
66 type: "handoff" as const,
67 contextHandoffId: ContextHandoffId.make("handoff:wire"),
68 fromProviderThreadIds: [],
69 toProviderThreadId: ProviderThreadId.make("target"),
70 fromProviderInstanceIds: [],
71 toProviderInstanceId: ProviderInstanceId.make("codex"),
72 strategy: "full_thread_summary" as const,
73 summary: "PRIVATE_HANDOFF_TRANSCRIPT",
74 };
75 const projected = projectTurnItemForWire(item);
76 expect(projected).not.toHaveProperty("summary");
77 expect(decodeTurnItem(projected)).toMatchObject({ contextHandoffId: item.contextHandoffId });
78 const event = {
79 id: EventId.make("handoff:wire"),
80 type: "turn-item.updated" as const,
81 threadId: base.threadId,
82 occurredAt: base.updatedAt,
83 payload: item,
84 };
85 expect(JSON.stringify(projectDomainEventForWire(event))).not.toContain(item.summary);
86 expect(item.summary).toBe("PRIVATE_HANDOFF_TRANSCRIPT");
87 });
88
89 it("preserves image metadata through wire and JSON contracts while redacting output", () => {
90 const item = {
91 ...base,
92 toolName: "Read",
93 input: { file_path: "/workspace/reference.png" },
94 viewedImagePath: "/workspace/reference.png",
95 output: { data: "private-image-data" },
96 } satisfies OrchestrationV2TurnItem;
97 const projected = projectTurnItemForWire(item);
98 const live = decodeTurnItem(projected);
99 const encoded = encodeTurnItemJson(live);
100 const json = decodeTurnItemJson(encoded);
101 const decoded = decodeTurnItem(json);
102 expect(decoded).toMatchObject({ viewedImagePath: "/workspace/reference.png" });
103 expect(decoded).not.toHaveProperty("output");
104 expect(item.output.data).toBe("private-image-data");
105 });
106
107 it("keeps transcript bodies out of shell rows", () => {
108 const now = DateTime.makeUnsafe("2026-08-13T00:00:00.000Z");
109 const threadId = ThreadId.make("thread-shell-budget");
110 const projection = {
111 thread: {
112 createdBy: "user",
113 creationSource: "web",
114 id: threadId,
115 projectId: ProjectId.make("project-shell-budget"),
116 title: "Shell payload budget",
117 providerInstanceId: ProviderInstanceId.make("codex"),
118 modelSelection: null,
119 runtimeMode: "full-access",
120 interactionMode: "default",
121 branch: null,
122 worktreePath: null,
123 lineage: {
124 parentThreadId: null,
125 relationshipToParent: null,
126 rootThreadId: threadId,
127 },
128 forkedFrom: null,
129 activeProviderThreadId: null,
130 createdAt: now,
131 updatedAt: now,
132 archivedAt: null,
133 settledOverride: null,
134 settledAt: null,
135 deletedAt: null,
136 },
137 runs: [],
138 attempts: [],
139 runtimeRequests: [],
140 messages: [
141 {
142 id: MessageId.make("message-shell-budget"),
143 role: "assistant",
144 text: "x".repeat(1_000_000),
145 updatedAt: now,
146 },
147 ],
148 providerSessions: [],
149 providerThreads: [],
150 turnItems: [],
151 visibleTurnItems: [],
152 plans: [],
153 updatedAt: now,
154 } as unknown as OrchestrationV2ThreadProjection;
155
156 const shell = threadShellFromProjection(projection);
157
158 expect(shell.latestVisibleMessage).toBeNull();
159 expect(JSON.stringify(shell).length).toBeLessThan(2_000);
160 });
161
162 it("omits even small dynamic tool results while retaining input", () => {
163 const item = { ...base, output: { ok: true } } satisfies OrchestrationV2TurnItem;
164 expect(projectTurnItemForWire(item)).toEqual({ ...base, outputOmitted: true });
165 expect(item.output).toEqual({ ok: true });
166 });
167
168 it("keeps a thread read's title and link beside a large omitted result", () => {
169 const thread = {
170 threadId: "thread-1",
171 title: "Recorded title",
172 link: "[Recorded title](t3-thread://v2/linked-environment/thread-1)",
173 };
174 const item = {
175 ...base,
176 toolName: "mcp__t3-code__t3_thread_read",
177 output: [{ type: "text", text: JSON.stringify({ thread, items: ["x".repeat(24_000)] }) }],
178 };
179 expect(projectTurnItemForWire(item)).toEqual({
180 ...item,
181 output: { thread },
182 outputOmitted: true,
183 });
184 });
185
186 it("uses encoded JSON bytes for strings near the dynamic-value limit", () => {
187 const small = '"'.repeat(8_191);
188 const large = '"'.repeat(8_192);
189 const smallItem = { ...base, input: small };
190 expect(projectTurnItemForWire(smallItem)).toEqual(smallItem);
191 const projected = projectTurnItemForWire({ ...base, input: large });
192 expect(projected.type === "dynamic_tool" ? projected.input : null).toEqual({
193 summary: '"'.repeat(159) + "…",
194 truncated: true,
195 });
196
197 const boundary = projectTurnItemForWire({
198 ...base,
199 input: { text: "a".repeat(149) + "😀" + "b".repeat(17_000) },
200 });
201 expect(boundary.type === "dynamic_tool" ? boundary.input : null).toEqual({
202 summary: '{"text":"' + "a".repeat(149) + "…",
203 truncated: true,
204 });
205 });
206
207 it("marks truncated command notices while preserving their detail on demand", () => {
208 const detail = `printf '${"é".repeat(20_000)}'`;
209 const item = {
210 ...base,
211 type: "notification",
212 source: { kind: "command" },
213 outcome: "completed",
214 summary: "Command finished",
215 detail,
216 } satisfies OrchestrationV2TurnItem;
217 const projected = decodeTurnItem(
218 decodeTurnItemJson(encodeTurnItemJson(projectTurnItemForWire(item))),
219 );
220
221 expect(projected).toMatchObject({
222 detailTruncated: true,
223 detail: expect.stringContaining("… output truncated for transport"),
224 });
225 expect(projectTurnItemForWire(projected)).toEqual(projected);
226 expect(projectTurnItemForDetail(item)).toEqual(item);
227 const short = { ...item, detail: "printf ok" };
228 expect(projectTurnItemForWire(short)).toBe(short);
229 });
230
231 it("truncates detail at a UTF-8 boundary without changing the source", () => {
232 const marker = "\n… output truncated for transport";
233 const prefixBytes = 32_768 - Buffer.byteLength(marker);
234 const progress = "a".repeat(prefixBytes - 1) + "😀" + "x".repeat(100_000);
235 const item = {
236 ...base,
237 type: "subagent" as const,
238 subagentId: NodeId.make("child-agent"),
239 origin: "app_owned" as const,
240 driver: ProviderDriverKind.make("codex"),
241 providerInstanceId: ProviderInstanceId.make("codex"),
242 childThreadId: null,
243 prompt: "漢".repeat(12_000),
244 result: null,
245 progress,
246 };
247 const projected = projectTurnItemForWire(item);
248 expect(projectTurnItemForWire(projected)).toEqual(projected);
249 expect(
250 Buffer.byteLength(projected.type === "subagent" ? projected.prompt : ""),
251 ).toBeLessThanOrEqual(32_768);
252 expect(projected.type === "subagent" ? projected.progress : null).toBe(
253 "a".repeat(prefixBytes - 1) + marker,
254 );
255 expect(item.progress).toBe(progress);
256
257 const literal = "a".repeat(prefixBytes - 3) + "\uFFFD";
258 const withLiteral = projectTurnItemForWire({ ...item, progress: literal + "x".repeat(100) });
259 expect(withLiteral.type === "subagent" ? withLiteral.progress : null).toBe(literal + marker);
260 });
261
262 it("leaves a screenshot's bytes out of the fetched tool output", () => {
263 const data = "A".repeat(600_000);
264 const item = {
265 ...base,
266 type: "dynamic_tool" as const,
267 toolName: "mcp__t3-code__device_screenshot",
268 input: { deviceId: "phone" },
269 output: {
270 content: [{ type: "image", source: { type: "base64", media_type: "image/png", data } }],
271 },
272 };
273 expect(projectTurnItemForDetail(item)).toMatchObject({
274 output: { content: [{ type: "image", mimeType: "image/png" }] },
275 });
276 expect(item.output.content[0]?.source.data).toBe(data);
277
278 const t3McpApp = {
279 attachmentId: "app-html",
280 server: "repro",
281 tool: "chart",
282 resourceUri: "ui://repro/chart",
283 };
284 const text = { type: "text", text: "Rendered chart" };
285 const appItem = {
286 ...item,
287 toolName: "repro.chart",
288 output: {
289 t3McpApp,
290 result: { content: [text, { type: "image", mimeType: "image/png", data }] },
291 },
292 };
293 expect(projectTurnItemForDetail(appItem)).toMatchObject({
294 output: { t3McpApp, result: { content: [text, { type: "image", mimeType: "image/png" }] } },
295 });
296 const largeOutput = projectTurnItemForDetail(appItem);
297 expect(
298 JSON.stringify(largeOutput.type === "dynamic_tool" ? largeOutput.output : null),
299 ).not.toContain(data);
300
301 const smallApp = {
302 t3McpApp,
303 result: { content: [text, { type: "image", mimeType: "image/png", data: "iVBORw0KGgo=" }] },
304 };
305 expect(projectTurnItemForDetail({ ...appItem, output: smallApp })).toMatchObject({
306 output: smallApp,
307 });
308
309 const forged = projectTurnItemForDetail({
310 ...appItem,
311 output: { t3McpApp: { ...t3McpApp, resourceUri: data }, result: { content: [text] } },
312 });
313 expect(
314 JSON.stringify(forged.type === "dynamic_tool" ? forged.output : null).length,
315 ).toBeLessThan(270_000);
316 });
317
318 it("keeps image markers when the rest of a tool output is too large to send", () => {
319 const image = {
320 type: "image",
321 source: { type: "base64", media_type: "image/png", data: "AAAA" },
322 };
323 const item = {
324 ...base,
325 type: "dynamic_tool" as const,
326 output: { content: [{ type: "text", text: "x".repeat(300_000) }, image] },
327 };
328 const projected = projectTurnItemForDetail(item);
329 const output = projected.type === "dynamic_tool" ? projected.output : null;
330 expect(Array.isArray(output) ? output.slice(1) : null).toEqual([
331 { type: "image", mimeType: "image/png" },
332 ]);
333 expect(JSON.stringify(output).length).toBeLessThan(270_000);
334 });
335
336 it("bounds a tool output made of many images", () => {
337 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
338 const item = {
339 ...base,
340 type: "dynamic_tool" as const,
341 output: Array.from({ length: 10_000 }, () => image),
342 };
343 const projected = projectTurnItemForDetail(item);
344 const output = projected.type === "dynamic_tool" ? projected.output : null;
345 expect(Array.isArray(output) ? output.length : null).toBe(1 + MAX_TOOL_OUTPUT_IMAGES);
346 expect(Array.isArray(output) ? String(output[0]?.text).length : null).toBeLessThan(263_000);
347 expect(toolOutputImages(output)).toHaveLength(MAX_TOOL_OUTPUT_IMAGES);
348 });
349
350 it("keeps failure evidence without retaining command output", () => {
351 const item = {
352 ...base,
353 type: "command_execution" as const,
354 input: "cat missing-file",
355 output: "cat: missing-file: No such file or directory",
356 };
357 const projected = projectTurnItemForWire(item);
358 expect(projected).not.toHaveProperty("output");
359 expect(projected).toMatchObject({ outputIndicatesFailure: true });
360 expect(projectTurnItemForWire(projected)).toEqual(projected);
361 expect(projectTurnItemForWire({ ...item, output: "", exitCode: 2 })).toMatchObject({
362 outputIndicatesFailure: true,
363 exitCode: 2,
364 });
365 });
366
367 it.each([
368 "logs/app.log:12: Error: ENOENT: no such file or directory",
369 "fixtures/ci.txt:3: Process exited with exit code 2",
370 ])("trusts a zero exit code over failure text in the output: %s", (output) => {
371 const projected = projectTurnItemForWire({
372 ...base,
373 type: "command_execution" as const,
374 input: "rg -n error logs fixtures",
375 output,
376 exitCode: 0,
377 });
378 expect(projected).not.toHaveProperty("outputIndicatesFailure");
379 expect(projected).toMatchObject({ exitCode: 0, outputOmitted: true });
380 });
381
382 it("omits inline file bodies but preserves file identity and change counts", () => {
383 const item = {
384 ...base,
385 type: "file_change" as const,
386 fileName: "src/main.ts",
387 additions: 3,
388 deletions: 1,
389 diffStr: "+new code",
390 oldStr: "old code",
391 newStr: "new code",
392 };
393 const projected = projectTurnItemForWire(item);
394 expect(projected).not.toHaveProperty("diffStr");
395 expect(projected).not.toHaveProperty("oldStr");
396 expect(projected).not.toHaveProperty("newStr");
397 expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });
398 expect(item.diffStr).toBe("+new code");
399 expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });
400 expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");
401 expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");
402 const { diffStr: _diff, ...contentOnly } = item;
403 expect(projectTurnItemForDetail(contentOnly)).toMatchObject({
404 oldStr: "old code",
405 newStr: "new code",
406 });
407 expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");
408 const failed = projectTurnItemForWire({
409 ...item,
410 status: "failed",
411 diffStr: "String to replace not found",
412 });
413 expect(failed).toMatchObject({ diffStr: "String to replace not found" });
414 expect(failed).not.toHaveProperty("newStr");
415 });
416
417 it("retains only result identities and failure metadata in live tool events", () => {
418 const output = {
419 isError: true,
420 structuredContent: { threadId: "child-thread", messageId: "message", text: "PRIVATE_BODY" },
421 content: [{ type: "text", text: "PRIVATE_BODY" }],
422 };
423 const event = {
424 id: EventId.make("result-event"),
425 type: "turn-item.updated" as const,
426 threadId: base.threadId,
427 occurredAt: base.updatedAt,
428 payload: { ...base, output },
429 };
430 const projected = projectDomainEventForWire(event);
431 expect(projected.payload).toMatchObject({
432 output: { isError: true, threadId: "child-thread", messageId: "message" },
433 });
434 expect(JSON.stringify(projected)).not.toContain("PRIVATE_BODY");
435 expect(event.payload.output).toBe(output);
436 expect(projectDomainEventForWire(projected)).toEqual(projected);
437 });
438
439 it("shares one wire projection per stored event", () => {
440 const tool: OrchestrationV2StoredEvent = {
441 sequence: 1,
442 commandId: null,
443 event: {
444 id: EventId.make("shared-tool-event"),
445 type: "turn-item.updated",
446 threadId: base.threadId,
447 occurredAt: base.updatedAt,
448 payload: { ...base, output: { content: [{ type: "text", text: "PRIVATE_BODY" }] } },
449 },
450 };
451 const projected = projectStoredEventForWire(tool);
452 expect(projected).toEqual({ ...tool, event: projectDomainEventForWire(tool.event) });
453 expect(projectStoredEventForWire(tool)).toBe(projected);
454 const detached: OrchestrationV2StoredEvent = {
455 sequence: 2,
456 commandId: null,
457 event: {
458 id: EventId.make("detached-event"),
459 type: "provider-session.detached",
460 threadId: base.threadId,
461 occurredAt: base.updatedAt,
462 payload: {
463 providerSessionId: ProviderSessionId.make("session"),
464 detachedAt: base.updatedAt,
465 },
466 },
467 };
468 expect(projectStoredEventForWire(detached)).toBe(detached);
469 });
470});
471
472describe("live body deduper", () => {
473 const at = base.updatedAt;
474 const messageId = MessageId.make("message-live");
475 const event = (
476 sequence: number,
477 rest: Pick<OrchestrationV2DomainEvent, "type" | "payload">,
478 ): Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }> => ({
479 kind: "event",
480 sequence,
481 event: {
482 id: EventId.make(`event-${sequence}`),
483 threadId: base.threadId,
484 occurredAt: at,
485 ...rest,
486 } as OrchestrationV2DomainEvent,
487 });
488 const message = (sequence: number, text: string) =>
489 event(sequence, {
490 type: "message.updated",
491 payload: {
492 id: messageId,
493 threadId: base.threadId,
494 runId: null,
495 nodeId: null,
496 role: "assistant",
497 text,
498 attachments: [],
499 streaming: true,
500 createdBy: "agent",
501 creationSource: "provider",
502 createdAt: at,
503 updatedAt: at,
504 },
505 });
506 const reply = (sequence: number, text: string) =>
507 event(sequence, {
508 type: "turn-item.updated",
509 payload: {
510 ...base,
511 status: "running",
512 type: "assistant_message",
513 messageId,
514 text,
515 streaming: true,
516 },
517 });
518 const payloadOf = (item: OrchestrationV2ThreadStreamItem) =>
519 item.kind === "event" ? item.event.payload : undefined;
520
521 it("blanks a reply that repeats the message delivered before it, after coalescing", () => {
522 const delivered = coalesceLiveUpdatedEvents([
523 message(1, "a"),
524 reply(2, "a"),
525 message(3, "ab"),
526 reply(4, "ab"),
527 ]).map(makeLiveBodyDeduper());
528
529 expect(
530 delivered.map((item) => [item.kind === "event" && item.sequence, payloadOf(item)]),
531 ).toEqual([
532 [3, message(3, "ab").event.payload],
533 [4, { ...reply(4, "ab").event.payload, text: "", textOmitted: true }],
534 ]);
535 });
536
537 it("caps a large checkpoint's files for the wire and still dedupes its item", () => {
538 const files = Array.from({ length: 250 }, (_, index) => ({
539 path: `vendor/file-${index}.ts`,
540 kind: "modified",
541 additions: 2,
542 deletions: 1,
543 }));
544 const checkpointId = CheckpointId.make("checkpoint-large");
545 const scopeId = CheckpointScopeId.make("scope-large");
546 const captured = event(1, {
547 type: "checkpoint.captured",
548 payload: {
549 id: checkpointId,
550 threadId: base.threadId,
551 scopeId,
552 runId: null,
553 nodeId: NodeId.make("node-large"),
554 parentCheckpointId: null,
555 ordinalWithinScope: 1,
556 appRunOrdinal: null,
557 ref: CheckpointRef.make("refs/t3/checkpoints/large"),
558 status: "ready",
559 files,
560 capturedAt: at,
561 },
562 });
563 const item = event(2, {
564 type: "turn-item.updated",
565 payload: { ...base, type: "checkpoint", checkpointId, scopeId, files },
566 });
567 const dedupe = makeLiveBodyDeduper();
568 const [record, card] = [captured, item].map((streamed) =>
569 dedupe({ ...streamed, event: projectDomainEventForWire(streamed.event) }),
570 );
571
572 const filesTotal = { count: 250, additions: 500, deletions: 250 };
573 expect(payloadOf(record!)).toMatchObject({ files: files.slice(0, 200), filesTotal });
574 expect(payloadOf(card!)).toMatchObject({ files: [], filesOmitted: true, filesTotal });
575 });
576
577 it("ships a reply whole when its message arrives after it", () => {
578 const first = reply(1, "a");
579 expect([first, message(2, "a")].map(makeLiveBodyDeduper())[0]).toBe(first);
580 });
581});