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