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