@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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