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.each([
265 "logs/app.log:12: Error: ENOENT: no such file or directory",
266 "fixtures/ci.txt:3: Process exited with exit code 2",
267 ])("trusts a zero exit code over failure text in the output: %s", (output) => {
268 const projected = projectTurnItemForWire({
269 ...base,
270 type: "command_execution" as const,
271 input: "rg -n error logs fixtures",
272 output,
273 exitCode: 0,
274 });
275 expect(projected).not.toHaveProperty("outputIndicatesFailure");
276 expect(projected).toMatchObject({ exitCode: 0, outputOmitted: true });
277 });
278
279 it("omits inline file bodies but preserves file identity and change counts", () => {
280 const item = {
281 ...base,
282 type: "file_change" as const,
283 fileName: "src/main.ts",
284 additions: 3,
285 deletions: 1,
286 diffStr: "+new code",
287 oldStr: "old code",
288 newStr: "new code",
289 };
290 const projected = projectTurnItemForWire(item);
291 expect(projected).not.toHaveProperty("diffStr");
292 expect(projected).not.toHaveProperty("oldStr");
293 expect(projected).not.toHaveProperty("newStr");
294 expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 });
295 expect(item.diffStr).toBe("+new code");
296 expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" });
297 expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr");
298 expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr");
299 const { diffStr: _diff, ...contentOnly } = item;
300 expect(projectTurnItemForDetail(contentOnly)).toMatchObject({
301 oldStr: "old code",
302 newStr: "new code",
303 });
304 expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr");
305 const failed = projectTurnItemForWire({
306 ...item,
307 status: "failed",
308 diffStr: "String to replace not found",
309 });
310 expect(failed).toMatchObject({ diffStr: "String to replace not found" });
311 expect(failed).not.toHaveProperty("newStr");
312 });
313
314 it("retains only result identities and failure metadata in live tool events", () => {
315 const output = {
316 isError: true,
317 structuredContent: { threadId: "child-thread", messageId: "message", text: "PRIVATE_BODY" },
318 content: [{ type: "text", text: "PRIVATE_BODY" }],
319 };
320 const event = {
321 id: EventId.make("result-event"),
322 type: "turn-item.updated" as const,
323 threadId: base.threadId,
324 occurredAt: base.updatedAt,
325 payload: { ...base, output },
326 };
327 const projected = projectDomainEventForWire(event);
328 expect(projected.payload).toMatchObject({
329 output: { isError: true, threadId: "child-thread", messageId: "message" },
330 });
331 expect(JSON.stringify(projected)).not.toContain("PRIVATE_BODY");
332 expect(event.payload.output).toBe(output);
333 expect(projectDomainEventForWire(projected)).toEqual(projected);
334 });
335});
336
337describe("live body deduper", () => {
338 const at = base.updatedAt;
339 const messageId = MessageId.make("message-live");
340 const event = (
341 sequence: number,
342 rest: Pick<OrchestrationV2DomainEvent, "type" | "payload">,
343 ): Extract<OrchestrationV2ThreadStreamItem, { kind: "event" }> => ({
344 kind: "event",
345 sequence,
346 event: {
347 id: EventId.make(`event-${sequence}`),
348 threadId: base.threadId,
349 occurredAt: at,
350 ...rest,
351 } as OrchestrationV2DomainEvent,
352 });
353 const message = (sequence: number, text: string) =>
354 event(sequence, {
355 type: "message.updated",
356 payload: {
357 id: messageId,
358 threadId: base.threadId,
359 runId: null,
360 nodeId: null,
361 role: "assistant",
362 text,
363 attachments: [],
364 streaming: true,
365 createdBy: "agent",
366 creationSource: "provider",
367 createdAt: at,
368 updatedAt: at,
369 },
370 });
371 const reply = (sequence: number, text: string) =>
372 event(sequence, {
373 type: "turn-item.updated",
374 payload: {
375 ...base,
376 status: "running",
377 type: "assistant_message",
378 messageId,
379 text,
380 streaming: true,
381 },
382 });
383 const payloadOf = (item: OrchestrationV2ThreadStreamItem) =>
384 item.kind === "event" ? item.event.payload : undefined;
385
386 it("blanks a reply that repeats the message delivered before it, after coalescing", () => {
387 const delivered = coalesceLiveUpdatedEvents([
388 message(1, "a"),
389 reply(2, "a"),
390 message(3, "ab"),
391 reply(4, "ab"),
392 ]).map(makeLiveBodyDeduper());
393
394 expect(
395 delivered.map((item) => [item.kind === "event" && item.sequence, payloadOf(item)]),
396 ).toEqual([
397 [3, message(3, "ab").event.payload],
398 [4, { ...reply(4, "ab").event.payload, text: "", textOmitted: true }],
399 ]);
400 });
401
402 it("caps a large checkpoint's files for the wire and still dedupes its item", () => {
403 const files = Array.from({ length: 250 }, (_, index) => ({
404 path: `vendor/file-${index}.ts`,
405 kind: "modified",
406 additions: 2,
407 deletions: 1,
408 }));
409 const checkpointId = CheckpointId.make("checkpoint-large");
410 const scopeId = CheckpointScopeId.make("scope-large");
411 const captured = event(1, {
412 type: "checkpoint.captured",
413 payload: {
414 id: checkpointId,
415 threadId: base.threadId,
416 scopeId,
417 runId: null,
418 nodeId: NodeId.make("node-large"),
419 parentCheckpointId: null,
420 ordinalWithinScope: 1,
421 appRunOrdinal: null,
422 ref: CheckpointRef.make("refs/t3/checkpoints/large"),
423 status: "ready",
424 files,
425 capturedAt: at,
426 },
427 });
428 const item = event(2, {
429 type: "turn-item.updated",
430 payload: { ...base, type: "checkpoint", checkpointId, scopeId, files },
431 });
432 const dedupe = makeLiveBodyDeduper();
433 const [record, card] = [captured, item].map((streamed) =>
434 dedupe({ ...streamed, event: projectDomainEventForWire(streamed.event) }),
435 );
436
437 const filesTotal = { count: 250, additions: 500, deletions: 250 };
438 expect(payloadOf(record!)).toMatchObject({ files: files.slice(0, 200), filesTotal });
439 expect(payloadOf(card!)).toMatchObject({ files: [], filesOmitted: true, filesTotal });
440 });
441
442 it("ships a reply whole when its message arrives after it", () => {
443 const first = reply(1, "a");
444 expect([first, message(2, "a")].map(makeLiveBodyDeduper())[0]).toBe(first);
445 });
446});