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("uses encoded JSON bytes for strings near the dynamic-value limit", () => {
169 const small = '"'.repeat(8_191);
170 const large = '"'.repeat(8_192);
171 const smallItem = { ...base, input: small };
172 expect(projectTurnItemForWire(smallItem)).toEqual(smallItem);
173 const projected = projectTurnItemForWire({ ...base, input: large });
174 expect(projected.type === "dynamic_tool" ? projected.input : null).toEqual({
175 summary: '"'.repeat(159) + "…",
176 truncated: true,
177 });
178 });
179
180 it("truncates detail at a UTF-8 boundary without changing the source", () => {
181 const marker = "\n… output truncated for transport";
182 const prefixBytes = 32_768 - Buffer.byteLength(marker);
183 const progress = "a".repeat(prefixBytes - 1) + "😀" + "x".repeat(100_000);
184 const item = {
185 ...base,
186 type: "subagent" as const,
187 subagentId: NodeId.make("child-agent"),
188 origin: "app_owned" as const,
189 driver: ProviderDriverKind.make("codex"),
190 providerInstanceId: ProviderInstanceId.make("codex"),
191 childThreadId: null,
192 prompt: "漢".repeat(12_000),
193 result: null,
194 progress,
195 };
196 const projected = projectTurnItemForWire(item);
197 expect(projectTurnItemForWire(projected)).toEqual(projected);
198 expect(
199 Buffer.byteLength(projected.type === "subagent" ? projected.prompt : ""),
200 ).toBeLessThanOrEqual(32_768);
201 expect(projected.type === "subagent" ? projected.progress : null).toBe(
202 "a".repeat(prefixBytes - 1) + marker,
203 );
204 expect(item.progress).toBe(progress);
205 });
206
207 it("leaves a screenshot's bytes out of the fetched tool output", () => {
208 const data = "A".repeat(600_000);
209 const item = {
210 ...base,
211 type: "dynamic_tool" as const,
212 toolName: "mcp__t3-code__device_screenshot",
213 input: { deviceId: "phone" },
214 output: {
215 content: [{ type: "image", source: { type: "base64", media_type: "image/png", data } }],
216 },
217 };
218 expect(projectTurnItemForDetail(item)).toMatchObject({
219 output: { content: [{ type: "image", mimeType: "image/png" }] },
220 });
221 expect(item.output.content[0]?.source.data).toBe(data);
222 });
223
224 it("keeps image markers when the rest of a tool output is too large to send", () => {
225 const image = {
226 type: "image",
227 source: { type: "base64", media_type: "image/png", data: "AAAA" },
228 };
229 const item = {
230 ...base,
231 type: "dynamic_tool" as const,
232 output: { content: [{ type: "text", text: "x".repeat(300_000) }, image] },
233 };
234 const projected = projectTurnItemForDetail(item);
235 const output = projected.type === "dynamic_tool" ? projected.output : null;
236 expect(Array.isArray(output) ? output.slice(1) : null).toEqual([
237 { type: "image", mimeType: "image/png" },
238 ]);
239 expect(JSON.stringify(output).length).toBeLessThan(270_000);
240 });
241
242 it("bounds a tool output made of many images", () => {
243 const image = { type: "image", data: "AAAA", mimeType: "image/png" };
244 const item = {
245 ...base,
246 type: "dynamic_tool" as const,
247 output: Array.from({ length: 10_000 }, () => image),
248 };
249 const projected = projectTurnItemForDetail(item);
250 const output = projected.type === "dynamic_tool" ? projected.output : null;
251 expect(Array.isArray(output) ? output.length : null).toBe(1 + MAX_TOOL_OUTPUT_IMAGES);
252 expect(Array.isArray(output) ? String(output[0]?.text).length : null).toBeLessThan(263_000);
253 expect(toolOutputImages(output)).toHaveLength(MAX_TOOL_OUTPUT_IMAGES);
254 });
255
256 it("keeps failure evidence without retaining command output", () => {
257 const item = {
258 ...base,
259 type: "command_execution" as const,
260 input: "cat missing-file",
261 output: "cat: missing-file: No such file or directory",
262 };
263 const projected = projectTurnItemForWire(item);
264 expect(projected).not.toHaveProperty("output");
265 expect(projected).toMatchObject({ outputIndicatesFailure: true });
266 expect(projectTurnItemForWire(projected)).toEqual(projected);
267 expect(projectTurnItemForWire({ ...item, output: "", exitCode: 2 })).toMatchObject({
268 outputIndicatesFailure: true,
269 exitCode: 2,
270 });
271 });
272
273 it.each([
274 "logs/app.log:12: Error: ENOENT: no such file or directory",
275 "fixtures/ci.txt:3: Process exited with exit code 2",
276 ])("trusts a zero exit code over failure text in the output: %s", (output) => {
277 const projected = projectTurnItemForWire({
278 ...base,
279 type: "command_execution" as const,
280 input: "rg -n error logs fixtures",
281 output,
282 exitCode: 0,
283 });
284 expect(projected).not.toHaveProperty("outputIndicatesFailure");
285 expect(projected).toMatchObject({ exitCode: 0, outputOmitted: true });
286 });
287
288 it("omits inline file bodies but preserves file identity and change counts", () => {
289 const item = {
290 ...base,
291 type: "file_change" as const,
292 fileName: "src/main.ts",
293 additions: 3,
294 deletions: 1,
295 diffStr: "+new code",
296 oldStr: "old code",
297 newStr: "new code",
298 };
299 const projected = projectTurnItemForWire(item);
300 expect(projected).not.toHaveProperty("diffStr");
301 expect(projected).not.toHaveProperty("oldStr");
302 expect(projected).not.toHaveProperty("newStr");
303 expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });
304 expect(item.diffStr).toBe("+new code");
305 expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });
306 expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");
307 expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");
308 const { diffStr: _diff, ...contentOnly } = item;
309 expect(projectTurnItemForDetail(contentOnly)).toMatchObject({
310 oldStr: "old code",
311 newStr: "new code",
312 });
313 expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");
314 const failed = projectTurnItemForWire({
315 ...item,
316 status: "failed",
317 diffStr: "String to replace not found",
318 });
319 expect(failed).toMatchObject({ diffStr: "String to replace not found" });
320 expect(failed).not.toHaveProperty("newStr");
321 });
322
323 it("retains only result identities and failure metadata in live tool events", () => {
324 const output = {
325 isError: true,
326 structuredContent: { threadId: "child-thread", messageId: "message", text: "PRIVATE_BODY" },
327 content: [{ type: "text", text: "PRIVATE_BODY" }],
328 };
329 const event = {
330 id: EventId.make("result-event"),
331 type: "turn-item.updated" as const,
332 threadId: base.threadId,
333 occurredAt: base.updatedAt,
334 payload: { ...base, output },
335 };
336 const projected = projectDomainEventForWire(event);
337 expect(projected.payload).toMatchObject({
338 output: { isError: true, threadId: "child-thread", messageId: "message" },
339 });
340 expect(JSON.stringify(projected)).not.toContain("PRIVATE_BODY");
341 expect(event.payload.output).toBe(output);
342 expect(projectDomainEventForWire(projected)).toEqual(projected);
343 });
344
345 it("shares one wire projection per stored event", () => {
346 const tool: OrchestrationV2StoredEvent = {
347 sequence: 1,
348 commandId: null,
349 event: {
350 id: EventId.make("shared-tool-event"),
351 type: "turn-item.updated",
352 threadId: base.threadId,
353 occurredAt: base.updatedAt,
354 payload: { ...base, output: { content: [{ type: "text", text: "PRIVATE_BODY" }] } },
355 },
356 };
357 const projected = projectStoredEventForWire(tool);
358 expect(projected).toEqual({ ...tool, event: projectDomainEventForWire(tool.event) });
359 expect(projectStoredEventForWire(tool)).toBe(projected);
360 const detached: OrchestrationV2StoredEvent = {
361 sequence: 2,
362 commandId: null,
363 event: {
364 id: EventId.make("detached-event"),
365 type: "provider-session.detached",
366 threadId: base.threadId,
367 occurredAt: base.updatedAt,
368 payload: {
369 providerSessionId: ProviderSessionId.make("session"),
370 detachedAt: base.updatedAt,
371 },
372 },
373 };
374 expect(projectStoredEventForWire(detached)).toBe(detached);
375 });
376});
377
378describe("live body deduper", () => {
379 const at = base.updatedAt;
380 const messageId = MessageId.make("message-live");
381 const event = (
382 sequence: number,
383 rest: Pick<OrchestrationV2DomainEvent, "type" | "payload">,
384 ): Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }> => ({
385 kind: "event",
386 sequence,
387 event: {
388 id: EventId.make(`event-${sequence}`),
389 threadId: base.threadId,
390 occurredAt: at,
391 ...rest,
392 } as OrchestrationV2DomainEvent,
393 });
394 const message = (sequence: number, text: string) =>
395 event(sequence, {
396 type: "message.updated",
397 payload: {
398 id: messageId,
399 threadId: base.threadId,
400 runId: null,
401 nodeId: null,
402 role: "assistant",
403 text,
404 attachments: [],
405 streaming: true,
406 createdBy: "agent",
407 creationSource: "provider",
408 createdAt: at,
409 updatedAt: at,
410 },
411 });
412 const reply = (sequence: number, text: string) =>
413 event(sequence, {
414 type: "turn-item.updated",
415 payload: {
416 ...base,
417 status: "running",
418 type: "assistant_message",
419 messageId,
420 text,
421 streaming: true,
422 },
423 });
424 const payloadOf = (item: OrchestrationV2ThreadStreamItem) =>
425 item.kind === "event" ? item.event.payload : undefined;
426
427 it("blanks a reply that repeats the message delivered before it, after coalescing", () => {
428 const delivered = coalesceLiveUpdatedEvents([
429 message(1, "a"),
430 reply(2, "a"),
431 message(3, "ab"),
432 reply(4, "ab"),
433 ]).map(makeLiveBodyDeduper());
434
435 expect(
436 delivered.map((item) => [item.kind === "event" && item.sequence, payloadOf(item)]),
437 ).toEqual([
438 [3, message(3, "ab").event.payload],
439 [4, { ...reply(4, "ab").event.payload, text: "", textOmitted: true }],
440 ]);
441 });
442
443 it("caps a large checkpoint's files for the wire and still dedupes its item", () => {
444 const files = Array.from({ length: 250 }, (_, index) => ({
445 path: `vendor/file-${index}.ts`,
446 kind: "modified",
447 additions: 2,
448 deletions: 1,
449 }));
450 const checkpointId = CheckpointId.make("checkpoint-large");
451 const scopeId = CheckpointScopeId.make("scope-large");
452 const captured = event(1, {
453 type: "checkpoint.captured",
454 payload: {
455 id: checkpointId,
456 threadId: base.threadId,
457 scopeId,
458 runId: null,
459 nodeId: NodeId.make("node-large"),
460 parentCheckpointId: null,
461 ordinalWithinScope: 1,
462 appRunOrdinal: null,
463 ref: CheckpointRef.make("refs/t3/checkpoints/large"),
464 status: "ready",
465 files,
466 capturedAt: at,
467 },
468 });
469 const item = event(2, {
470 type: "turn-item.updated",
471 payload: { ...base, type: "checkpoint", checkpointId, scopeId, files },
472 });
473 const dedupe = makeLiveBodyDeduper();
474 const [record, card] = [captured, item].map((streamed) =>
475 dedupe({ ...streamed, event: projectDomainEventForWire(streamed.event) }),
476 );
477
478 const filesTotal = { count: 250, additions: 500, deletions: 250 };
479 expect(payloadOf(record!)).toMatchObject({ files: files.slice(0, 200), filesTotal });
480 expect(payloadOf(card!)).toMatchObject({ files: [], filesOmitted: true, filesTotal });
481 });
482
483 it("ships a reply whole when its message arrives after it", () => {
484 const first = reply(1, "a");
485 expect([first, message(2, "a")].map(makeLiveBodyDeduper())[0]).toBe(first);
486 });
487});