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