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

main
ts 1,783 lines 58 KB
Raw
1 import { describe, expect, it } from "vite-plus/test";
2
3 import type * as EffectAcpSchema from "effect-acp/compat";
4
5 import {
6 decideToolCallUpdateEmission,
7 applyAcpAgentTerminalUpdate,
8 acpContentBlockDisplayText,
9 embeddedTerminalIdsFromSessionUpdate,
10 extractMcpToolCallIdentity,
11 mergeToolCallState,
12 parsePermissionRequest,
13 parseSessionModeState,
14 parseSessionUpdateEvent,
15 sessionModelStateFromInitialize,
16 sessionUpdateCountsAsLoadReplayActivity,
17 sessionUpdateIsReplay,
18 syntheticLoadSessionResponseFromInitialize,
19 toolCallProgressLength,
20 toolCallVisibleOutputChanged,
21 withTrackedPermissionToolCall,
22 type AcpToolCallState,
23 } from "./runtimeModel.ts";
24
25 describe("AcpRuntimeModel", () => {
26 it("parses session mode state from typed ACP session setup responses", () => {
27 const modeState = parseSessionModeState({
28 sessionId: "session-1",
29 modes: {
30 currentModeId: " code ",
31 availableModes: [
32 { id: " ask ", name: " Ask ", description: " Request approval " },
33 { id: " code ", name: " Code " },
34 ],
35 },
36 configOptions: [],
37 } satisfies EffectAcpSchema.NewSessionResponse);
38
39 expect(modeState).toEqual({
40 currentModeId: "code",
41 availableModes: [
42 { id: "ask", name: "Ask", description: "Request approval" },
43 { id: "code", name: "Code" },
44 ],
45 });
46 });
47
48 it("detects Grok session replay updates from _meta.isReplay", () => {
49 expect(
50 sessionUpdateIsReplay({
51 _meta: { isReplay: true },
52 sessionId: "session-1",
53 update: {
54 sessionUpdate: "agent_message_chunk",
55 content: { type: "text", text: "replayed" },
56 },
57 } satisfies EffectAcpSchema.SessionNotification),
58 ).toBe(true);
59 expect(
60 sessionUpdateIsReplay({
61 sessionId: "session-1",
62 update: {
63 sessionUpdate: "agent_message_chunk",
64 content: { type: "text", text: "live" },
65 },
66 } satisfies EffectAcpSchema.SessionNotification),
67 ).toBe(false);
68 });
69
70 it("ignores Grok keepalive chunks when tracking session/load replay activity", () => {
71 expect(
72 sessionUpdateCountsAsLoadReplayActivity({
73 sessionId: "session-1",
74 update: {
75 sessionUpdate: "agent_message_chunk",
76 content: { type: "text", text: "" },
77 },
78 } satisfies EffectAcpSchema.SessionNotification),
79 ).toBe(false);
80 expect(
81 sessionUpdateCountsAsLoadReplayActivity({
82 _meta: { isReplay: true },
83 sessionId: "session-1",
84 update: {
85 sessionUpdate: "tool_call",
86 toolCallId: "replay-tool",
87 title: "Replay",
88 kind: "search",
89 status: "completed",
90 },
91 } satisfies EffectAcpSchema.SessionNotification),
92 ).toBe(true);
93 });
94
95 it("ignores load-replay activity from other sessions while a load gate is active", () => {
96 expect(
97 sessionUpdateCountsAsLoadReplayActivity(
98 {
99 sessionId: "session-other",
100 update: {
101 sessionUpdate: "agent_message_chunk",
102 content: { type: "text", text: "unrelated" },
103 },
104 } satisfies EffectAcpSchema.SessionNotification,
105 "session-loading",
106 ),
107 ).toBe(false);
108 expect(
109 sessionUpdateCountsAsLoadReplayActivity(
110 {
111 sessionId: "session-loading",
112 update: {
113 sessionUpdate: "agent_message_chunk",
114 content: { type: "text", text: "replay" },
115 },
116 } satisfies EffectAcpSchema.SessionNotification,
117 "session-loading",
118 ),
119 ).toBe(true);
120 });
121
122 it("ignores malformed initialize mode state in synthetic load responses", () => {
123 const response = syntheticLoadSessionResponseFromInitialize({
124 protocolVersion: 1,
125 _meta: {
126 modeState: {
127 currentModeId: "code",
128 availableModes: [{ id: "code", name: 12 }],
129 },
130 },
131 } as EffectAcpSchema.InitializeResponse);
132
133 expect(response.modes).toBeUndefined();
134 expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
135 });
136
137 it("keeps initialize mode state whose modes have null descriptions", () => {
138 const response = syntheticLoadSessionResponseFromInitialize({
139 protocolVersion: 1,
140 _meta: {
141 modeState: {
142 currentModeId: "code",
143 availableModes: [
144 { id: "ask", name: "Ask", description: null },
145 { id: "code", name: "Code", description: "Edit files", _meta: null },
146 ],
147 _meta: null,
148 },
149 },
150 } satisfies EffectAcpSchema.InitializeResponse);
151
152 expect(parseSessionModeState(response)).toEqual({
153 currentModeId: "code",
154 availableModes: [
155 { id: "ask", name: "Ask" },
156 { id: "code", name: "Code", description: "Edit files" },
157 ],
158 });
159 });
160
161 it("reads initialize model state and ignores malformed model state", () => {
162 const modelState = {
163 currentModelId: "grok-4.7",
164 availableModels: [
165 {
166 modelId: "grok-4.7",
167 name: "Grok 4.7",
168 description: null,
169 _meta: { reasoningEfforts: [{ id: "high", default: true }] },
170 },
171 { modelId: "grok-4.6", name: "Grok 4.6" },
172 ],
173 };
174
175 expect(sessionModelStateFromInitialize({ protocolVersion: 1, _meta: { modelState } })).toEqual(
176 modelState,
177 );
178 expect(
179 sessionModelStateFromInitialize({
180 protocolVersion: 1,
181 _meta: {
182 modelState: { currentModelId: "grok-4.7", availableModels: [{ modelId: "grok-4.7" }] },
183 },
184 }),
185 ).toBeUndefined();
186 expect(
187 sessionModelStateFromInitialize({
188 protocolVersion: 1,
189 _meta: { modelState: { ...modelState, _meta: "not an object" } },
190 }),
191 ).toBeUndefined();
192 });
193
194 it("projects typed ACP tool call updates into runtime events", () => {
195 const created = parseSessionUpdateEvent({
196 sessionId: "session-1",
197 update: {
198 sessionUpdate: "tool_call",
199 toolCallId: "tool-1",
200 title: "Terminal",
201 kind: "execute",
202 status: "pending",
203 rawInput: {
204 executable: "bun",
205 args: ["run", "typecheck"],
206 },
207 content: [
208 {
209 type: "content",
210 content: {
211 type: "text",
212 text: "Running checks",
213 },
214 },
215 ],
216 },
217 } satisfies EffectAcpSchema.SessionNotification);
218
219 expect(created.events).toEqual([
220 {
221 _tag: "ToolCallUpdated",
222 toolCall: {
223 toolCallId: "tool-1",
224 kind: "execute",
225 title: "Ran command",
226 status: "pending",
227 command: "bun run typecheck",
228 detail: "bun run typecheck",
229 data: {
230 toolCallId: "tool-1",
231 kind: "execute",
232 title: "Terminal",
233 command: "bun run typecheck",
234 rawInput: {
235 executable: "bun",
236 args: ["run", "typecheck"],
237 },
238 content: [
239 {
240 type: "content",
241 content: {
242 type: "text",
243 text: "Running checks",
244 },
245 },
246 ],
247 },
248 },
249 rawPayload: {
250 sessionId: "session-1",
251 update: {
252 sessionUpdate: "tool_call",
253 toolCallId: "tool-1",
254 title: "Terminal",
255 kind: "execute",
256 status: "pending",
257 rawInput: {
258 executable: "bun",
259 args: ["run", "typecheck"],
260 },
261 content: [
262 {
263 type: "content",
264 content: {
265 type: "text",
266 text: "Running checks",
267 },
268 },
269 ],
270 },
271 },
272 },
273 ]);
274
275 const updated = parseSessionUpdateEvent({
276 sessionId: "session-1",
277 update: {
278 sessionUpdate: "tool_call_update",
279 toolCallId: "tool-1",
280 status: "completed",
281 rawOutput: { exitCode: 0 },
282 },
283 } satisfies EffectAcpSchema.SessionNotification);
284
285 expect(updated.events).toHaveLength(1);
286 expect(updated.events[0]?._tag).toBe("ToolCallUpdated");
287 const createdEvent = created.events[0];
288 const updatedEvent = updated.events[0];
289 if (createdEvent?._tag === "ToolCallUpdated" && updatedEvent?._tag === "ToolCallUpdated") {
290 expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
291 toolCallId: "tool-1",
292 status: "completed",
293 title: "Ran command",
294 detail: "bun run typecheck",
295 command: "bun run typecheck",
296 });
297 }
298 });
299
300 it("ends a tool call that ACP reports as cancelled", () => {
301 const toolCall = (status: EffectAcpSchema.ToolCallStatus) => {
302 const parsed = parseSessionUpdateEvent({
303 sessionId: "session-1",
304 update: {
305 sessionUpdate: status === "in_progress" ? "tool_call" : "tool_call_update",
306 toolCallId: "tool-1",
307 title: "Run `sleep 60`",
308 kind: "execute",
309 status,
310 },
311 } as EffectAcpSchema.SessionNotification);
312 const event = parsed.events[0];
313 if (event?._tag !== "ToolCallUpdated") {
314 throw new Error("expected a tool call update");
315 }
316 return event.toolCall;
317 };
318
319 const running = toolCall("in_progress");
320 const cancelled = mergeToolCallState(running, toolCall("cancelled"));
321 expect(cancelled.status).toBe("failed");
322 expect(
323 decideToolCallUpdateEmission({
324 previous: running,
325 next: cancelled,
326 lastEmittedDetailLength: 0,
327 skippedSinceEmit: 0,
328 }).emit,
329 ).toBe(true);
330 });
331
332 it("clears prior ACP locations when an update explicitly replaces them", () => {
333 const toolCall = (locations?: EffectAcpSchema.ToolCallLocation[] | null) => {
334 const parsed = parseSessionUpdateEvent({
335 sessionId: "session-1",
336 update: {
337 sessionUpdate: "tool_call_update",
338 toolCallId: "read-1",
339 ...(locations === undefined ? {} : { locations }),
340 },
341 } satisfies EffectAcpSchema.SessionNotification);
342 const event = parsed.events.find((candidate) => candidate._tag === "ToolCallUpdated");
343 if (!event || event._tag !== "ToolCallUpdated") {
344 throw new Error("expected a tool call update");
345 }
346 return event.toolCall;
347 };
348
349 const created = toolCall([{ path: "README" }]);
350 expect(mergeToolCallState(created, toolCall()).data.locations).toEqual([{ path: "README" }]);
351 const cleared = mergeToolCallState(created, toolCall([]));
352 expect(cleared.data.locations).toEqual([]);
353 expect(mergeToolCallState(created, toolCall(null)).data.locations).toEqual([]);
354 const emits = (previous: AcpToolCallState, next: AcpToolCallState) =>
355 decideToolCallUpdateEmission({
356 previous,
357 next,
358 lastEmittedDetailLength: 0,
359 skippedSinceEmit: 0,
360 }).emit;
361 expect(emits(created, cleared)).toBe(true);
362 expect(toolCallVisibleOutputChanged(created, cleared)).toBe(true);
363 const relocated = mergeToolCallState(cleared, toolCall([{ path: "/workspace/src/app.ts" }]));
364 expect(emits(cleared, relocated)).toBe(true);
365 expect(toolCallVisibleOutputChanged(cleared, relocated)).toBe(true);
366 const repeated = mergeToolCallState(relocated, toolCall([{ path: "/workspace/src/app.ts" }]));
367 expect(emits(relocated, repeated)).toBe(false);
368 expect(toolCallVisibleOutputChanged(relocated, repeated)).toBe(false);
369 });
370
371 it("clears explicitly nulled ACP v2 tool call fields and replaces raw input", () => {
372 const toolCall = (update: Omit<EffectAcpSchema.ToolCallUpdate, "toolCallId">) => {
373 const parsed = parseSessionUpdateEvent({
374 sessionId: "session-1",
375 update: { sessionUpdate: "tool_call_update", toolCallId: "call-1", ...update },
376 } satisfies EffectAcpSchema.SessionNotification);
377 const event = parsed.events.find((candidate) => candidate._tag === "ToolCallUpdated");
378 if (!event || event._tag !== "ToolCallUpdated") {
379 throw new Error("expected a tool call update");
380 }
381 return event.toolCall;
382 };
383
384 const created = toolCall({
385 name: "old-name",
386 title: "Old title",
387 kind: "read",
388 status: "in_progress",
389 content: [{ type: "content", content: { type: "text", text: "old output" } }],
390 rawInput: { path: "old.txt", obsolete: true },
391 _meta: { old: true },
392 });
393
394 expect(
395 mergeToolCallState(created, toolCall({ rawInput: { path: "new.txt" } })).data.rawInput,
396 ).toEqual({ path: "new.txt" });
397
398 const cleared = mergeToolCallState(
399 created,
400 toolCall({
401 name: null,
402 title: null,
403 kind: null,
404 status: null,
405 content: null,
406 rawInput: null,
407 _meta: null,
408 }),
409 );
410 const { name, title, kind, content, rawInput, meta } = cleared.data;
411 expect({ name, title, kind, content, rawInput, meta }).toEqual({});
412 expect({ kind: cleared.kind, title: cleared.title, status: cleared.status }).toEqual({});
413 });
414
415 it("forwards an empty ACP v1 plan to clear previous entries", () => {
416 const entries = [
417 [{ content: "Inspect state", priority: "high", status: "pending" }],
418 [],
419 ] as const;
420 const updates = entries.flatMap(
421 (plan) =>
422 parseSessionUpdateEvent({
423 sessionId: "session-1",
424 update: { sessionUpdate: "plan", entries: plan },
425 }).events,
426 );
427
428 expect(updates).toMatchObject([
429 {
430 _tag: "PlanUpdated",
431 payload: {
432 nativePlanId: "legacy",
433 kind: "items",
434 plan: [{ step: "Inspect state", status: "pending" }],
435 },
436 },
437 {
438 _tag: "PlanUpdated",
439 payload: { nativePlanId: "legacy", kind: "items", plan: [] },
440 },
441 ]);
442 });
443
444 it("projects typed ACP plan and content updates", () => {
445 const planResult = parseSessionUpdateEvent({
446 sessionId: "session-1",
447 update: {
448 sessionUpdate: "plan",
449 entries: [
450 { content: " Inspect state ", priority: "high", status: "completed" },
451 { content: "", priority: "medium", status: "in_progress" },
452 ],
453 },
454 } satisfies EffectAcpSchema.SessionNotification);
455
456 expect(planResult.events).toEqual([
457 {
458 _tag: "PlanUpdated",
459 payload: {
460 nativePlanId: "legacy",
461 kind: "items",
462 plan: [
463 { step: "Inspect state", status: "completed" },
464 { step: "Step 2", status: "inProgress" },
465 ],
466 },
467 rawPayload: {
468 sessionId: "session-1",
469 update: {
470 sessionUpdate: "plan",
471 entries: [
472 { content: " Inspect state ", priority: "high", status: "completed" },
473 { content: "", priority: "medium", status: "in_progress" },
474 ],
475 },
476 },
477 },
478 ]);
479
480 const contentResult = parseSessionUpdateEvent({
481 sessionId: "session-1",
482 update: {
483 sessionUpdate: "agent_message_chunk",
484 content: {
485 type: "text",
486 text: "hello from acp",
487 },
488 },
489 } satisfies EffectAcpSchema.SessionNotification);
490
491 expect(contentResult.events).toEqual([
492 {
493 _tag: "ContentDelta",
494 text: "hello from acp",
495 rawPayload: {
496 sessionId: "session-1",
497 update: {
498 sessionUpdate: "agent_message_chunk",
499 content: {
500 type: "text",
501 text: "hello from acp",
502 },
503 },
504 },
505 },
506 ]);
507 });
508
509 it("keeps permission request parsing compatible with loose extension payloads", () => {
510 const request = parsePermissionRequest({
511 sessionId: "session-1",
512 options: [
513 {
514 optionId: "allow-once",
515 name: "Allow once",
516 kind: "allow_once",
517 },
518 ],
519 toolCall: {
520 toolCallId: "tool-1",
521 title: "`cat package.json`",
522 kind: "execute",
523 status: "pending",
524 content: [
525 {
526 type: "content",
527 content: {
528 type: "text",
529 text: "Not in allowlist",
530 },
531 },
532 ],
533 },
534 });
535
536 expect(request).toMatchObject({
537 kind: "execute",
538 detail: "cat package.json",
539 toolCall: {
540 toolCallId: "tool-1",
541 kind: "execute",
542 status: "pending",
543 command: "cat package.json",
544 },
545 });
546 });
547
548 it("keeps an explicit permission request kind over the tracked tool call's kind", () => {
549 const request = withTrackedPermissionToolCall(
550 {
551 sessionId: "session-1",
552 options: [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }],
553 toolCall: { toolCallId: "tool-1", kind: "read" },
554 },
555 {
556 toolCallId: "tool-1",
557 kind: "execute",
558 data: { toolCallId: "tool-1", title: "git status", rawInput: { command: "git status" } },
559 },
560 );
561
562 expect(parsePermissionRequest(request)).toMatchObject({ kind: "read", detail: "git status" });
563 });
564
565 it("keeps explicitly cleared permission request fields over the tracked tool call", () => {
566 const request = withTrackedPermissionToolCall(
567 {
568 sessionId: "session-1",
569 options: [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }],
570 toolCall: { toolCallId: "tool-1", kind: null, title: null, rawInput: null },
571 },
572 {
573 toolCallId: "tool-1",
574 kind: "execute",
575 data: { toolCallId: "tool-1", title: "git status", rawInput: { command: "git status" } },
576 },
577 );
578
579 expect(parsePermissionRequest(request).kind).toBe("unknown");
580 });
581
582 it("bounds an oversized cumulative tool_call_update content buffer to a tail window", () => {
583 const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
584 "\n",
585 );
586 expect(hugeText.length).toBeGreaterThan(60_000);
587
588 const result = parseSessionUpdateEvent({
589 sessionId: "session-1",
590 update: {
591 // Real tool_call_update deltas omit title; raw content then supplies detail.
592 sessionUpdate: "tool_call_update",
593 toolCallId: "tool-1",
594 kind: "other",
595 status: "in_progress",
596 content: [{ type: "content", content: { type: "text", text: hugeText } }],
597 },
598 } satisfies EffectAcpSchema.SessionNotification);
599
600 expect(result.events).toHaveLength(1);
601 const event = result.events[0];
602 if (event?._tag !== "ToolCallUpdated") {
603 throw new Error("expected a ToolCallUpdated event");
604 }
605
606 expect(event.toolCall.detail).toBeDefined();
607 const detail = event.toolCall.detail!;
608 expect(detail.length).toBe(8_028);
609 expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
610 expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
611
612 const rawUpdate = (
613 event.rawPayload as {
614 readonly update: {
615 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
616 };
617 }
618 ).update;
619 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
620 expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
621 });
622
623 it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
624 let previous: AcpToolCallState | undefined;
625 let lastEmittedDetailLength: number | undefined;
626 let skippedSinceEmit = 0;
627 let emittedCount = 0;
628 let emittedBytes = 0;
629 let notificationBytes = 0;
630 let largestEmittedEventBytes = 0;
631 let finalDetail: string | undefined;
632 let cumulativeBuffer = "";
633
634 for (let i = 0; i < 1_000; i += 1) {
635 cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
636 const isLast = i === 999;
637
638 const notification = {
639 sessionId: "session-1",
640 update: {
641 sessionUpdate: "tool_call_update",
642 toolCallId: "tool-1",
643 kind: "other",
644 status: isLast ? "completed" : "in_progress",
645 content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
646 },
647 } satisfies EffectAcpSchema.SessionNotification;
648 notificationBytes += JSON.stringify(notification).length;
649
650 const { events } = parseSessionUpdateEvent(notification);
651
652 const event = events[0];
653 if (event?._tag !== "ToolCallUpdated") {
654 continue;
655 }
656
657 const merged = mergeToolCallState(previous, event.toolCall);
658 const decision = decideToolCallUpdateEmission({
659 previous,
660 next: merged,
661 lastEmittedDetailLength,
662 skippedSinceEmit,
663 });
664 previous = merged;
665 skippedSinceEmit = decision.skippedSinceEmit;
666 if (decision.emit) {
667 emittedCount += 1;
668 const eventBytes = JSON.stringify({
669 toolCall: merged,
670 rawPayload: event.rawPayload,
671 }).length;
672 emittedBytes += eventBytes;
673 largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
674 lastEmittedDetailLength = merged.detail?.length;
675 finalDetail = merged.detail;
676 }
677 }
678
679 expect(notificationBytes).toBeGreaterThan(31_000_000);
680
681 expect(emittedCount).toBe(114);
682 expect(largestEmittedEventBytes).toBeLessThan(25_000);
683 expect(emittedBytes).toBeLessThan(2_600_000);
684 expect(finalDetail).toBeDefined();
685 expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
686 });
687
688 it("keeps non-text tool call content entries in order when bounding oversized text", () => {
689 const hugePrefix = "x".repeat(25_000);
690 const hugeTail = "y".repeat(25_000);
691 const { events } = parseSessionUpdateEvent({
692 sessionId: "session-1",
693 update: {
694 sessionUpdate: "tool_call_update",
695 toolCallId: "tool-1",
696 kind: "edit",
697 status: "in_progress",
698 content: [
699 { type: "content", content: { type: "text", text: hugePrefix } },
700 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
701 { type: "content", content: { type: "text", text: hugeTail } },
702 { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
703 { type: "content", content: { type: "text", text: " " } },
704 ],
705 },
706 } satisfies EffectAcpSchema.SessionNotification);
707
708 const event = events[0];
709 if (event?._tag !== "ToolCallUpdated") {
710 throw new Error("expected a ToolCallUpdated event");
711 }
712 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
713 expect(content).toHaveLength(3);
714 expect(content[0]).toEqual({
715 type: "diff",
716 path: "/repo/file.ts",
717 oldText: "before",
718 newText: "after",
719 });
720 const lastEntry = content[1];
721 if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
722 throw new Error("expected a bounded text entry");
723 }
724 expect(lastEntry.content.text.length).toBeLessThan(8_100);
725 expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
726 expect(content[2]).toEqual({
727 type: "diff",
728 path: "/repo/other.ts",
729 oldText: "old",
730 newText: "new",
731 });
732 });
733
734 it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
735 const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
736 expect(padded.length).toBeGreaterThan(60_000);
737
738 const { events } = parseSessionUpdateEvent({
739 sessionId: "session-1",
740 update: {
741 sessionUpdate: "tool_call_update",
742 toolCallId: "tool-1",
743 kind: "other",
744 status: "in_progress",
745 content: [{ type: "content", content: { type: "text", text: padded } }],
746 },
747 } satisfies EffectAcpSchema.SessionNotification);
748
749 const event = events[0];
750 if (event?._tag !== "ToolCallUpdated") {
751 throw new Error("expected a ToolCallUpdated event");
752 }
753
754 expect(event.toolCall.detail).toBe("ok");
755 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
756 const textEntry = content[0];
757 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
758 throw new Error("expected a bounded text entry");
759 }
760 expect(textEntry.content.text).toBe("ok");
761
762 const rawUpdate = (
763 event.rawPayload as {
764 readonly update: {
765 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
766 };
767 }
768 ).update;
769 expect(rawUpdate.content[0]?.content.text).toBe("ok");
770 expect(JSON.stringify(event).length).toBeLessThan(padded.length);
771 });
772
773 describe("decideToolCallUpdateEmission", () => {
774 const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
775 ({
776 toolCallId: "tool-1",
777 title: "Grok Tool",
778 ...(status ? { status } : {}),
779 ...(detail ? { detail } : {}),
780 data: {},
781 }) satisfies AcpToolCallState;
782
783 it("always emits terminal (completed/failed) status updates regardless of growth", () => {
784 expect(
785 decideToolCallUpdateEmission({
786 previous: toolCall("same", "inProgress"),
787 next: toolCall("same", "completed"),
788 lastEmittedDetailLength: 4,
789 skippedSinceEmit: 0,
790 }),
791 ).toEqual({ emit: true, skippedSinceEmit: 0 });
792
793 expect(
794 decideToolCallUpdateEmission({
795 previous: toolCall("same", "inProgress"),
796 next: toolCall("same", "failed"),
797 lastEmittedDetailLength: 4,
798 skippedSinceEmit: 3,
799 }),
800 ).toEqual({ emit: true, skippedSinceEmit: 0 });
801 });
802
803 it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
804 const commandCall = (stdout: string): AcpToolCallState => ({
805 toolCallId: "tool-1",
806 title: "Ran command",
807 status: "inProgress",
808 command: "ls",
809 detail: "ls",
810 data: {
811 command: "ls",
812 content: [{ type: "content", content: { type: "text", text: stdout } }],
813 },
814 });
815
816 let previous: AcpToolCallState | undefined;
817 let lastEmittedDetailLength: number | undefined;
818 let skippedSinceEmit = 0;
819 const emissions: Array<boolean> = [];
820
821 for (let i = 1; i <= 12; i += 1) {
822 const next = commandCall("x".repeat(i));
823 const decision = decideToolCallUpdateEmission({
824 previous,
825 next,
826 lastEmittedDetailLength,
827 skippedSinceEmit,
828 });
829 emissions.push(decision.emit);
830 skippedSinceEmit = decision.skippedSinceEmit;
831 if (decision.emit) {
832 lastEmittedDetailLength = toolCallProgressLength(next);
833 }
834 previous = next;
835 }
836
837 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
838 expect(emittedIndices).toEqual([1, 11]);
839 });
840
841 it("coalesces small deltas but forces an emission after the coalesce limit", () => {
842 let lastEmittedDetailLength: number | undefined = 0;
843 let skippedSinceEmit = 0;
844 const emissions: Array<boolean> = [];
845 let previous: AcpToolCallState | undefined;
846
847 for (let i = 1; i <= 12; i += 1) {
848 const next = toolCall("x".repeat(i), "inProgress");
849 const decision = decideToolCallUpdateEmission({
850 previous,
851 next,
852 lastEmittedDetailLength,
853 skippedSinceEmit,
854 });
855 emissions.push(decision.emit);
856 skippedSinceEmit = decision.skippedSinceEmit;
857 if (decision.emit) {
858 lastEmittedDetailLength = next.detail?.length;
859 }
860 previous = next;
861 }
862
863 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
864 expect(emittedIndices).toEqual([1, 11]);
865 });
866
867 it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
868 let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
869 const lastEmittedDetailLength = previous.detail?.length;
870 let skippedSinceEmit = 0;
871
872 for (const detail of ["frame-b", "frame-c"]) {
873 const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
874 const decision = decideToolCallUpdateEmission({
875 previous,
876 next,
877 lastEmittedDetailLength,
878 skippedSinceEmit,
879 });
880 expect(decision.emit).toBe(false);
881 skippedSinceEmit = decision.skippedSinceEmit;
882 previous = next;
883 }
884
885 const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
886 expect(completed.detail).toBe("frame-c");
887 expect(
888 decideToolCallUpdateEmission({
889 previous,
890 next: completed,
891 lastEmittedDetailLength,
892 skippedSinceEmit,
893 }),
894 ).toEqual({ emit: true, skippedSinceEmit: 0 });
895 });
896 });
897
898 it("preserves message identity, usage, metadata, and non-text output", () => {
899 const message = parseSessionUpdateEvent({
900 sessionId: "session-1",
901 update: {
902 sessionUpdate: "agent_message_chunk",
903 messageId: "message-1",
904 content: {
905 type: "resource_link",
906 name: "report.txt",
907 title: "Report",
908 description: "Generated artifact",
909 uri: "file:///workspace/report.txt",
910 },
911 },
912 } satisfies EffectAcpSchema.SessionNotification);
913 const usage = parseSessionUpdateEvent({
914 sessionId: "session-1",
915 update: {
916 sessionUpdate: "usage_update",
917 used: 2_500,
918 size: 10_000,
919 cost: { amount: 0.42, currency: "USD" },
920 },
921 } satisfies EffectAcpSchema.SessionNotification);
922 const metadata = parseSessionUpdateEvent({
923 sessionId: "session-1",
924 update: {
925 sessionUpdate: "session_info_update",
926 title: " Native session ",
927 updatedAt: " 2026-08-23T00:00:00Z ",
928 },
929 } satisfies EffectAcpSchema.SessionNotification);
930
931 expect(message.events[0]).toMatchObject({
932 _tag: "ContentDelta",
933 messageId: "message-1",
934 text: "Report: Generated artifact\nfile:///workspace/report.txt",
935 });
936 expect(usage.events[0]).toMatchObject({
937 _tag: "UsageUpdated",
938 usage: {
939 usedTokens: 2_500,
940 maxTokens: 10_000,
941 cost: { amount: 0.42, currency: "USD" },
942 },
943 });
944 expect(metadata.events[0]).toMatchObject({
945 _tag: "SessionInfoUpdated",
946 metadata: {
947 title: "Native session",
948 updatedAt: "2026-08-23T00:00:00Z",
949 },
950 });
951 });
952
953 it("projects ACP v2 plan replacement and removal updates", () => {
954 const replaced = parseSessionUpdateEvent({
955 sessionId: "session-1",
956 update: {
957 sessionUpdate: "plan_update",
958 plan: {
959 type: "items",
960 planId: "plan-1",
961 entries: [
962 { content: " Inspect schema ", priority: "high", status: "completed" },
963 { content: "Ship integration", priority: "high", status: "in_progress" },
964 ],
965 },
966 },
967 } satisfies EffectAcpSchema.SessionNotification);
968 const removed = parseSessionUpdateEvent({
969 sessionId: "session-1",
970 update: { sessionUpdate: "plan_removed", planId: "plan-1" },
971 } satisfies EffectAcpSchema.SessionNotification);
972
973 expect(replaced.events[0]).toMatchObject({
974 _tag: "PlanUpdated",
975 payload: {
976 nativePlanId: "plan-1",
977 kind: "items",
978 plan: [
979 { step: "Inspect schema", status: "completed" },
980 { step: "Ship integration", status: "inProgress" },
981 ],
982 },
983 });
984 expect(removed.events[0]).toMatchObject({
985 _tag: "PlanUpdated",
986 payload: { nativePlanId: "plan-1", kind: "removed" },
987 });
988 });
989
990 it("preserves markdown, file, and future ACP plan variants by plan ID", () => {
991 const updates = [
992 {
993 sessionId: "session-1",
994 update: {
995 sessionUpdate: "plan_update",
996 plan: { type: "markdown", planId: "plan-markdown", content: "# Ship it" },
997 },
998 },
999 {
1000 sessionId: "session-1",
1001 update: {
1002 sessionUpdate: "plan_update",
1003 plan: { type: "file", planId: "plan-file", uri: "file:///workspace/PLAN.md" },
1004 },
1005 },
1006 {
1007 sessionId: "session-1",
1008 update: {
1009 sessionUpdate: "plan_update",
1010 plan: { type: "diagram", planId: "plan-future", nodes: [] },
1011 },
1012 },
1013 ] as const;
1014
1015 expect(updates.flatMap((update) => parseSessionUpdateEvent(update).events)).toMatchObject([
1016 {
1017 _tag: "PlanUpdated",
1018 payload: { nativePlanId: "plan-markdown", kind: "markdown", markdown: "# Ship it" },
1019 },
1020 {
1021 _tag: "PlanUpdated",
1022 payload: {
1023 nativePlanId: "plan-file",
1024 kind: "file",
1025 uri: "file:///workspace/PLAN.md",
1026 },
1027 },
1028 {
1029 _tag: "PlanUpdated",
1030 payload: { nativePlanId: "plan-future", kind: "unknown", contentType: "diagram" },
1031 },
1032 ]);
1033 });
1034
1035 it("turns future ACP content and session updates into explicit placeholders", () => {
1036 expect(
1037 acpContentBlockDisplayText({
1038 type: "_t3_unknown",
1039 originalType: "chart",
1040 raw: { type: "chart", points: [] },
1041 }),
1042 ).toBe("[Unsupported ACP content: chart]");
1043
1044 expect(
1045 parseSessionUpdateEvent({
1046 sessionId: "session-1",
1047 update: {
1048 sessionUpdate: "_t3_unknown",
1049 originalSessionUpdate: "timeline_update",
1050 raw: { sessionUpdate: "timeline_update", entries: [] },
1051 },
1052 }).events,
1053 ).toMatchObject([{ _tag: "UnknownUpdate", updateType: "timeline_update" }]);
1054 });
1055
1056 it("projects ACP v2 compaction lifecycle and prompt usage", () => {
1057 const compacting = parseSessionUpdateEvent({
1058 sessionId: "session-1",
1059 update: {
1060 sessionUpdate: "compaction_update",
1061 compactionId: "compact-1",
1062 status: "in_progress",
1063 },
1064 } satisfies EffectAcpSchema.SessionNotification);
1065 const compacted = parseSessionUpdateEvent({
1066 sessionId: "session-1",
1067 update: {
1068 sessionUpdate: "compaction_update",
1069 compactionId: "compact-1",
1070 status: "completed",
1071 summary: [{ type: "text", text: "Retained the implementation decisions." }],
1072 },
1073 } satisfies EffectAcpSchema.SessionNotification);
1074 const idle = parseSessionUpdateEvent({
1075 sessionId: "session-1",
1076 update: {
1077 sessionUpdate: "state_update",
1078 state: "idle",
1079 stopReason: "end_turn",
1080 usage: { totalTokens: 420, inputTokens: 300, outputTokens: 100, thoughtTokens: 20 },
1081 },
1082 } satisfies EffectAcpSchema.SessionNotification);
1083
1084 expect(compacting.events[0]).toMatchObject({
1085 _tag: "ToolCallUpdated",
1086 toolCall: {
1087 toolCallId: "acp-compaction:compact-1",
1088 kind: "think",
1089 title: "Compact context",
1090 status: "inProgress",
1091 },
1092 });
1093 expect(compacted.events[0]).toMatchObject({
1094 _tag: "ToolCallUpdated",
1095 toolCall: {
1096 toolCallId: "acp-compaction:compact-1",
1097 status: "completed",
1098 data: { rawOutput: "Retained the implementation decisions." },
1099 },
1100 });
1101 expect(idle.events).toEqual([]);
1102
1103 const toolCall = (update: EffectAcpSchema.SessionUpdate) => {
1104 const event = parseSessionUpdateEvent({ sessionId: "session-1", update }).events[0];
1105 if (event?._tag !== "ToolCallUpdated") throw new Error("expected a compaction tool call");
1106 return event.toolCall;
1107 };
1108 const draft = toolCall({
1109 sessionUpdate: "compaction_summary_chunk",
1110 compactionId: "compact-1",
1111 content: { type: "text", text: "Draft summary" },
1112 });
1113 const finish = (summary?: ReadonlyArray<EffectAcpSchema.ContentBlock> | null) =>
1114 mergeToolCallState(
1115 draft,
1116 toolCall({
1117 sessionUpdate: "compaction_update",
1118 compactionId: "compact-1",
1119 status: "completed",
1120 ...(summary === undefined ? {} : { summary }),
1121 }),
1122 ).data.rawOutput;
1123
1124 expect(finish()).toBe("Draft summary");
1125 expect([finish(null), finish([]), finish([{ type: "text", text: "" }])]).toEqual([
1126 undefined,
1127 undefined,
1128 undefined,
1129 ]);
1130
1131 const fail = (
1132 previous: ReturnType<typeof toolCall>,
1133 patch: Pick<
1134 Extract<EffectAcpSchema.SessionUpdate, { sessionUpdate: "compaction_update" }>,
1135 "summary" | "error"
1136 >,
1137 ) =>
1138 mergeToolCallState(
1139 previous,
1140 toolCall({
1141 sessionUpdate: "compaction_update",
1142 compactionId: "compact-1",
1143 status: "failed",
1144 ...patch,
1145 }),
1146 );
1147 const failed = fail(draft, { error: "Budget exhausted" });
1148 const summaryCleared = fail(failed, { summary: null });
1149 const errorCleared = fail(summaryCleared, { error: null });
1150 const fields = (state: ReturnType<typeof toolCall>) => [
1151 state.data.rawOutput,
1152 state.data.compactionError,
1153 ];
1154 expect(fields(failed)).toEqual(["Draft summary", "Budget exhausted"]);
1155 expect(fields(summaryCleared)).toEqual([undefined, "Budget exhausted"]);
1156 expect(fields(errorCleared)).toEqual([undefined, undefined]);
1157 expect(fields(fail(draft, { summary: null, error: "Budget exhausted" }))).toEqual([
1158 undefined,
1159 "Budget exhausted",
1160 ]);
1161 });
1162
1163 it("applies ACP v2 agent-owned terminal snapshots and output chunks", () => {
1164 const snapshot = applyAcpAgentTerminalUpdate(undefined, {
1165 sessionUpdate: "terminal_update",
1166 terminalId: "terminal-1",
1167 command: "pnpm test",
1168 cwd: "/workspace",
1169 output: { data: Buffer.from("first line\n").toString("base64") },
1170 });
1171 const chunked = applyAcpAgentTerminalUpdate(snapshot, {
1172 sessionUpdate: "terminal_output_chunk",
1173 terminalId: "terminal-1",
1174 data: Buffer.from("second line\n").toString("base64"),
1175 });
1176 const completed = applyAcpAgentTerminalUpdate(chunked, {
1177 sessionUpdate: "terminal_update",
1178 terminalId: "terminal-1",
1179 exitStatus: { exitCode: 0 },
1180 });
1181
1182 expect(completed).toEqual({
1183 command: "pnpm test",
1184 cwd: "/workspace",
1185 output: "first line\nsecond line\n",
1186 outputBytes: 23,
1187 exitStatus: { exitCode: 0 },
1188 });
1189 });
1190
1191 it("preserves UTF-8 characters split across ACP terminal output chunks", () => {
1192 const bytes = Buffer.from("A🙂B", "utf8");
1193 const first = applyAcpAgentTerminalUpdate(undefined, {
1194 sessionUpdate: "terminal_output_chunk",
1195 terminalId: "terminal-utf8",
1196 data: bytes.subarray(0, 3).toString("base64"),
1197 });
1198 const second = applyAcpAgentTerminalUpdate(first, {
1199 sessionUpdate: "terminal_output_chunk",
1200 terminalId: "terminal-utf8",
1201 data: bytes.subarray(3).toString("base64"),
1202 });
1203
1204 expect(first.output).toBe("A");
1205 expect(first.pendingOutputBytes).toBeDefined();
1206 expect(second.output).toBe("A🙂B");
1207 expect(second.pendingOutputBytes).toBeUndefined();
1208 });
1209
1210 it("trims full ACP terminal output by a further 1 MiB at a UTF-8 boundary", () => {
1211 const cap = 16 * 1024 * 1024;
1212 const step = 1024 * 1024;
1213 const chunk = (text: string | Uint8Array) => ({
1214 sessionUpdate: "terminal_output_chunk" as const,
1215 terminalId: "terminal-cap",
1216 data: Buffer.from(text).toString("base64"),
1217 });
1218 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1219 sessionUpdate: "terminal_update",
1220 terminalId: "terminal-cap",
1221 output: {
1222 data: Buffer.from(`${"a".repeat(step)}é${"a".repeat(cap - step - 3)}`).toString("base64"),
1223 },
1224 });
1225 expect(seeded.outputBytes).toBe(cap - 1);
1226
1227 const full = applyAcpAgentTerminalUpdate(seeded, chunk("b"));
1228 expect(full.outputBytes).toBe(cap);
1229 expect(full.output.length).toBe(cap - 1);
1230
1231 // The cut at one byte past the cap plus 1 MiB falls inside "é", so the whole character goes.
1232 const trimmed = applyAcpAgentTerminalUpdate(full, chunk("c"));
1233 expect(trimmed.outputBytes).toBe(cap - step - 1);
1234 expect(trimmed.output.length).toBe(cap - step - 1);
1235 expect(trimmed.output.slice(0, 2)).toBe("aa");
1236 expect(trimmed.output.slice(-3)).toBe("abc");
1237
1238 const appended = applyAcpAgentTerminalUpdate(trimmed, chunk("🙂"));
1239 expect(appended.output.slice(-5)).toBe("abc🙂");
1240 expect(appended.output.length).toBe(trimmed.output.length + 2);
1241 expect(appended.outputBytes).toBe(cap - step + 3);
1242
1243 expect(Buffer.byteLength(appended.output)).toBe(appended.outputBytes);
1244
1245 const refilled = applyAcpAgentTerminalUpdate(appended, chunk("x".repeat(step - 3)));
1246 expect(refilled.outputBytes).toBe(cap);
1247 const pending = applyAcpAgentTerminalUpdate(refilled, chunk(Buffer.from("🙂").subarray(0, 2)));
1248 const exited = applyAcpAgentTerminalUpdate(pending, {
1249 sessionUpdate: "terminal_update",
1250 terminalId: "terminal-cap",
1251 exitStatus: { exitCode: 1 },
1252 });
1253 expect(exited.output.slice(-4)).toBe("xxx\uFFFD");
1254 expect(exited.outputBytes).toBe(cap - step);
1255 expect(exited.outputBytes).toBe(Buffer.byteLength(exited.output));
1256
1257 const cleared = applyAcpAgentTerminalUpdate(exited, {
1258 sessionUpdate: "terminal_update",
1259 terminalId: "terminal-cap",
1260 output: null,
1261 });
1262 expect(cleared).toMatchObject({ output: "", outputBytes: 0, exitStatus: { exitCode: 1 } });
1263 });
1264
1265 it("drops malformed and oversized ACP terminal frames without decoding them", () => {
1266 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1267 sessionUpdate: "terminal_output_chunk",
1268 terminalId: "terminal-invalid",
1269 data: Buffer.from("kept").toString("base64"),
1270 });
1271
1272 expect(
1273 applyAcpAgentTerminalUpdate(seeded, {
1274 sessionUpdate: "terminal_output_chunk",
1275 terminalId: "terminal-invalid",
1276 data: "not base64!",
1277 }),
1278 ).toBe(seeded);
1279
1280 expect(
1281 applyAcpAgentTerminalUpdate(seeded, {
1282 sessionUpdate: "terminal_output_chunk",
1283 terminalId: "terminal-oversized",
1284 data: Buffer.alloc(16 * 1024 * 1024 + 1).toString("base64"),
1285 }),
1286 ).toBe(seeded);
1287 });
1288
1289 it("projects binary ACP content without retaining encoded payloads", () => {
1290 const encodedPayload = "sensitive-base64-payload";
1291 const binary = acpContentBlockDisplayText({
1292 type: "resource",
1293 resource: {
1294 blob: encodedPayload,
1295 mimeType: "application/octet-stream",
1296 uri: "file:///workspace/archive.bin",
1297 },
1298 });
1299 const image = acpContentBlockDisplayText({
1300 type: "image",
1301 data: encodedPayload,
1302 mimeType: "image/png",
1303 uri: "file:///workspace/image.png",
1304 });
1305 const audio = acpContentBlockDisplayText({
1306 type: "audio",
1307 data: encodedPayload,
1308 mimeType: "audio/wav",
1309 });
1310
1311 expect(binary).toBe(
1312 "[ACP binary resource (application/octet-stream): file:///workspace/archive.bin]",
1313 );
1314 expect(image).toBe("[ACP image (image/png): file:///workspace/image.png]");
1315 expect(audio).toBe("[ACP audio (audio/wav)]");
1316 expect(`${binary}${image}${audio}`).not.toContain(encodedPayload);
1317
1318 const toolUpdate = parseSessionUpdateEvent({
1319 sessionId: "session-1",
1320 update: {
1321 sessionUpdate: "tool_call",
1322 toolCallId: "tool-with-image",
1323 title: "Generated image",
1324 content: [
1325 {
1326 type: "content",
1327 content: {
1328 type: "image",
1329 data: encodedPayload,
1330 mimeType: "image/png",
1331 uri: `data:image/png;base64,${encodedPayload}`,
1332 },
1333 },
1334 ],
1335 },
1336 } satisfies EffectAcpSchema.SessionNotification);
1337 const toolEvent = toolUpdate.events.find((event) => event._tag === "ToolCallUpdated");
1338 expect(JSON.stringify(toolEvent?.toolCall)).not.toContain(encodedPayload);
1339 expect(toolUpdate.events[0]).toMatchObject({
1340 _tag: "ToolCallUpdated",
1341 toolCall: {
1342 data: {
1343 content: [
1344 { type: "content", content: { type: "text", text: "[ACP image (image/png)]" } },
1345 ],
1346 },
1347 },
1348 });
1349 });
1350 });
1351
1352 describe("extractMcpToolCallIdentity", () => {
1353 function toolCallFromUpdate(
1354 update: EffectAcpSchema.SessionNotification["update"],
1355 ): NonNullable<ReturnType<typeof parsePermissionRequest>["toolCall"]> {
1356 const parsed = parseSessionUpdateEvent({ sessionId: "session-1", update });
1357 const event = parsed.events.find(
1358 (
1359 candidate,
1360 ): candidate is Extract<(typeof parsed.events)[number], { _tag: "ToolCallUpdated" }> =>
1361 candidate._tag === "ToolCallUpdated",
1362 );
1363 if (event === undefined) throw new Error("expected a tool call event");
1364 return event.toolCall;
1365 }
1366
1367 it("recovers server and tool from codex-acp tagged execute calls", () => {
1368 const toolCall = toolCallFromUpdate({
1369 sessionUpdate: "tool_call",
1370 toolCallId: "exec-f4591587-0754-4bb4-990b-f2767894ba93",
1371 kind: "execute",
1372 title: "mcp.t3-code.orchestrator_capabilities",
1373 status: "in_progress",
1374 rawInput: { server: "t3-code", tool: "orchestrator_capabilities", arguments: {} },
1375 _meta: { is_mcp_tool_call: true },
1376 });
1377
1378 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1379 server: "t3-code",
1380 tool: "orchestrator_capabilities",
1381 });
1382 });
1383
1384 it("recovers server, tool, and arguments from Antigravity call_mcp_tool calls", () => {
1385 // agy 1.5.12 reaches MCP tools its context budget left out through call_mcp_tool.
1386 const toolCall = toolCallFromUpdate({
1387 sessionUpdate: "tool_call",
1388 toolCallId: "call_13347576314095519317",
1389 kind: "execute",
1390 title: "MCP Tool navigate_page",
1391 status: "in_progress",
1392 rawInput: {
1393 ServerName: "chrome-devtools",
1394 ToolName: "navigate_page",
1395 Arguments: { url: "https://example.com" },
1396 },
1397 });
1398
1399 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1400 server: "chrome-devtools",
1401 tool: "navigate_page",
1402 input: { url: "https://example.com" },
1403 });
1404 });
1405
1406 it("recovers T3 identity from acp-mcp-call fallback commands", () => {
1407 const toolCall = toolCallFromUpdate({
1408 sessionUpdate: "tool_call",
1409 toolCallId: "exec-1",
1410 kind: "execute",
1411 title: "Ran command",
1412 status: "in_progress",
1413 });
1414
1415 expect(
1416 extractMcpToolCallIdentity(toolCall, {
1417 embeddedTerminalCommands: [
1418 '/usr/bin/node /srv/t3/bin.ts acp-mcp-call delegate_task {"task":"x"}',
1419 ],
1420 }),
1421 ).toEqual({ server: "t3-code", tool: "delegate_task", input: { task: "x" } });
1422 });
1423
1424 it("recovers T3 identity from pi-acp title-only fallback execs", () => {
1425 const toolCall = toolCallFromUpdate({
1426 sessionUpdate: "tool_call",
1427 toolCallId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1428 kind: "execute",
1429 title:
1430 '"$T3_ACP_MCP_NODE" "$T3_ACP_MCP_ENTRYPOINT" acp-mcp-call orchestrator_capabilities \'{}\'',
1431 status: "in_progress",
1432 rawInput: null,
1433 content: [
1434 {
1435 type: "terminal",
1436 terminalId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1437 },
1438 ],
1439 });
1440
1441 expect(toolCall.title).toBe("Ran command");
1442 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1443 server: "t3-code",
1444 tool: "orchestrator_capabilities",
1445 input: {},
1446 });
1447 });
1448
1449 it("recovers T3 identity from server-namespaced titles across titleless updates", () => {
1450 const created = toolCallFromUpdate({
1451 sessionUpdate: "tool_call",
1452 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1453 kind: "other",
1454 title: "t3-code_orchestrator_capabilities",
1455 status: "pending",
1456 locations: [],
1457 rawInput: {},
1458 });
1459 const completed = toolCallFromUpdate({
1460 sessionUpdate: "tool_call_update",
1461 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1462 status: "completed",
1463 content: [{ type: "content", content: { type: "text", text: '{"ok":true}' } }],
1464 });
1465 const merged = mergeToolCallState(created, completed);
1466
1467 expect(merged.title).toBe(created.title);
1468 expect(extractMcpToolCallIdentity(merged)).toEqual({
1469 server: "t3-code",
1470 tool: "orchestrator_capabilities",
1471 });
1472 });
1473
1474 it("recovers T3 identity across the registry agents' naming conventions", () => {
1475 for (const title of [
1476 "t3-code___delegate_task",
1477 "t3-code-delegate_task",
1478 'mcp__t3_code__delegate_task: {"mode":"async"}',
1479 't3-code__delegate_task: {"mode":"async"}',
1480 "delegate_task_t3-code",
1481 "t3-code/delegate_task",
1482 "delegate_task",
1483 'delegate_task: {"mode":"async"}',
1484 // Kimi retitles with partial JSON and middle-truncates args over 50 characters.
1485 'delegate_task: {"mode":"async","task":"Ru',
1486 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}',
1487 // Antigravity: "Running <tool>" before agy 1.5.8, "Run mcp_<server>_<tool>" since, "?" on prompts.
1488 "Running delegate_task",
1489 "Run mcp_t3-code_delegate_task",
1490 "Run mcp_t3-code_delegate_task?",
1491 ]) {
1492 const toolCall = toolCallFromUpdate({
1493 sessionUpdate: "tool_call",
1494 toolCallId: "convention-1",
1495 kind: "other",
1496 title,
1497 status: "pending",
1498 });
1499 expect(extractMcpToolCallIdentity(toolCall), title).toEqual({
1500 server: "t3-code",
1501 tool: "delegate_task",
1502 });
1503 }
1504 });
1505
1506 it("recovers T3 identity from Hermes editor-renamed MCP tool titles", () => {
1507 const identityFor = (title: string) =>
1508 extractMcpToolCallIdentity(
1509 toolCallFromUpdate({
1510 sessionUpdate: "tool_call",
1511 toolCallId: "hermes-1",
1512 kind: "other",
1513 title,
1514 status: "pending",
1515 rawInput: { title: "Chart", html: "<p>hi</p>", height: 320 },
1516 }),
1517 );
1518
1519 expect(identityFor("mcp__editor_t3_code_f6129534__html_render")).toEqual({
1520 server: "t3-code",
1521 tool: "html_render",
1522 });
1523 expect(identityFor("mcp__editor_github_1234abcd__html_render")).toEqual({
1524 server: "editor_github_1234abcd",
1525 tool: "html_render",
1526 });
1527 });
1528
1529 it("recovers T3 identity from Kiro's @-scoped titles", () => {
1530 for (const tool of ["html_render", "t3_thread_read", "delegate_task"]) {
1531 const toolCall = toolCallFromUpdate({
1532 sessionUpdate: "tool_call",
1533 toolCallId: "kiro-1",
1534 kind: "other",
1535 title: `@t3-code/${tool}`,
1536 status: "pending",
1537 rawInput: { tool_id: `t3-code::${tool}`, arguments: { threadId: "thread-1" } },
1538 });
1539 expect(extractMcpToolCallIdentity(toolCall), tool).toEqual({ server: "t3-code", tool });
1540 }
1541 });
1542
1543 // regression: #33667 OMP mounts MCP tools as xd:// devices and calls them through `write`.
1544 it("recovers T3 identity from OMP xd:// device writes but not its doc reads", () => {
1545 const args = {
1546 html: '<svg width="320" height="120"><rect width="300" height="100" fill="#4f46e5"/></svg>',
1547 title: "Static SVG",
1548 };
1549 const result = {
1550 htmlRender: { attachmentId: "synthetic-attachment-html", title: "Static SVG", height: 136 },
1551 message: "Shown to the reader above your reply.",
1552 };
1553 const text = JSON.stringify(result);
1554 const created = toolCallFromUpdate({
1555 sessionUpdate: "tool_call",
1556 toolCallId: "toolu_015ATZG99gw99Rrp4htieLux",
1557 title: "Rendering static SVG",
1558 kind: "execute",
1559 status: "pending",
1560 rawInput: { path: "xd://mcp__t3_code_html_render", content: JSON.stringify(args) },
1561 });
1562 const completed = mergeToolCallState(
1563 created,
1564 toolCallFromUpdate({
1565 sessionUpdate: "tool_call_update",
1566 toolCallId: "toolu_015ATZG99gw99Rrp4htieLux",
1567 status: "completed",
1568 rawOutput: {
1569 content: [{ type: "text", text }],
1570 details: {
1571 xdev: {
1572 tool: "mcp__t3_code_html_render",
1573 mode: "execute",
1574 args,
1575 tier: "write",
1576 inner: {
1577 serverName: "t3-code",
1578 mcpToolName: "html_render",
1579 rawContent: [{ type: "text", text }],
1580 provider: "acp",
1581 providerName: "ACP Client",
1582 structuredContent: result,
1583 },
1584 },
1585 },
1586 },
1587 content: [{ type: "content", content: { type: "text", text } }],
1588 }),
1589 );
1590 const docRead = toolCallFromUpdate({
1591 sessionUpdate: "tool_call",
1592 toolCallId: "toolu_read",
1593 title: "Reading html_render schema",
1594 kind: "read",
1595 status: "pending",
1596 rawInput: { path: "xd://mcp__t3_code_html_render" },
1597 });
1598
1599 const expected = { server: "t3-code", tool: "html_render", input: args };
1600 expect(extractMcpToolCallIdentity(created), "pending write").toEqual(expected);
1601 expect(extractMcpToolCallIdentity(completed), "completed write").toEqual(expected);
1602 expect(extractMcpToolCallIdentity(docRead), "doc read").toBeUndefined();
1603 });
1604
1605 it("does not claim an agent's own tool that shares a T3 tool name", () => {
1606 const toolCall = toolCallFromUpdate({
1607 sessionUpdate: "tool_call",
1608 toolCallId: "own-delegate-1",
1609 kind: "execute",
1610 title: "delegate_task: 1 tasks: Run the terminal command 'echo child-result-42'",
1611 status: "pending",
1612 });
1613 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1614 });
1615
1616 it("recovers T3 identity from goose _meta despite LLM-rewritten titles", () => {
1617 // goose titles change asynchronously; only _meta.goose.toolCall is stable.
1618 const toolCall = toolCallFromUpdate({
1619 sessionUpdate: "tool_call",
1620 toolCallId: "goose-1",
1621 title: "Checking on the delegated task",
1622 status: "in_progress",
1623 _meta: {
1624 goose: {
1625 toolCall: { toolName: "t3-code__task_status", extensionName: "t3-code" },
1626 messageId: "message-1",
1627 },
1628 },
1629 });
1630
1631 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1632 server: "t3-code",
1633 tool: "task_status",
1634 });
1635 });
1636
1637 it("recovers T3 identity from qwen serverId meta regardless of prefix format", () => {
1638 // qwen-code 0.21.12 serverId asserts MCP origin even when tool prefixes change.
1639 const toolCall = toolCallFromUpdate({
1640 sessionUpdate: "tool_call",
1641 toolCallId: "qwen-meta-1",
1642 kind: "other",
1643 title: "unrelated display title",
1644 status: "pending",
1645 _meta: { toolName: "mcp::t3-code::t3_thread_send", serverId: "t3-code", provenance: "mcp" },
1646 });
1647
1648 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1649 server: "t3-code",
1650 tool: "t3_thread_send",
1651 });
1652 });
1653
1654 it.each([
1655 { _meta: { claudeCode: { toolName: "mcp__weather__get_weather" } } },
1656 { _meta: { toolName: "mcp::weather::get_weather", serverId: "weather" } },
1657 ])("recovers external MCP identity from provider metadata", (metadata) => {
1658 const toolCall = toolCallFromUpdate({
1659 sessionUpdate: "tool_call",
1660 toolCallId: "weather-call",
1661 title: "Checking the forecast",
1662 status: "in_progress",
1663 ...metadata,
1664 });
1665 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1666 server: "weather",
1667 tool: "get_weather",
1668 });
1669 });
1670
1671 it.each([
1672 { kind: "execute", toolName: "developer__shell", extensionName: "developer" },
1673 { kind: "edit", toolName: "developer__edit", extensionName: "developer" },
1674 { kind: "other", toolName: "weather__get_weather", extensionName: "weather" },
1675 ] as const)(
1676 "leaves goose $toolName unclassified so built-ins keep their projection",
1677 ({ kind, toolName, extensionName }) => {
1678 // goose tags built-in extensions exactly like user MCP servers.
1679 const toolCall = toolCallFromUpdate({
1680 sessionUpdate: "tool_call",
1681 toolCallId: "goose-builtin",
1682 kind,
1683 title: "developer: shell",
1684 status: "in_progress",
1685 _meta: { goose: { toolCall: { toolName, extensionName } } },
1686 });
1687 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1688 },
1689 );
1690
1691 it("uses the asserted server instead of a misleading T3 title", () => {
1692 const toolCall = toolCallFromUpdate({
1693 sessionUpdate: "tool_call",
1694 toolCallId: "foreign-1",
1695 kind: "other",
1696 title: "t3-code_delegate_task",
1697 status: "pending",
1698 _meta: { toolName: "delegate_task", serverId: "other-orchestrator" },
1699 });
1700
1701 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1702 server: "other-orchestrator",
1703 tool: "delegate_task",
1704 });
1705 });
1706
1707 it("does not brand path-like or unknown-tool titles", () => {
1708 for (const title of [
1709 "t3-code/README.md",
1710 "t3-code_not_a_real_tool",
1711 "Run mcp_t3-code_not_a_real_tool",
1712 "Run manage_task",
1713 ]) {
1714 const toolCall = toolCallFromUpdate({
1715 sessionUpdate: "tool_call",
1716 toolCallId: "path-1",
1717 kind: "other",
1718 title,
1719 status: "pending",
1720 });
1721 expect(extractMcpToolCallIdentity(toolCall), title).toBeUndefined();
1722 }
1723 });
1724
1725 it("leaves ordinary execute calls unidentified", () => {
1726 const toolCall = toolCallFromUpdate({
1727 sessionUpdate: "tool_call",
1728 toolCallId: "exec-2",
1729 kind: "execute",
1730 title: "cat package.json",
1731 status: "in_progress",
1732 rawInput: { command: "cat package.json" },
1733 });
1734
1735 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1736 expect(
1737 extractMcpToolCallIdentity(toolCall, { embeddedTerminalCommands: ["bash -lc ls"] }),
1738 ).toBeUndefined();
1739 });
1740
1741 it("does not treat generic raw server and tool fields as MCP provenance", () => {
1742 const toolCall = toolCallFromUpdate({
1743 sessionUpdate: "tool_call",
1744 toolCallId: "generic-1",
1745 kind: "other",
1746 title: "Deploy",
1747 status: "pending",
1748 rawInput: { server: "production", tool: "deploy" },
1749 });
1750
1751 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1752 });
1753 });
1754
1755 describe("embeddedTerminalIdsFromSessionUpdate", () => {
1756 it("collects terminal ids from tool_call content before the text rewrite", () => {
1757 expect(
1758 embeddedTerminalIdsFromSessionUpdate({
1759 sessionId: "session-1",
1760 update: {
1761 sessionUpdate: "tool_call_update",
1762 toolCallId: "call_1",
1763 status: "in_progress",
1764 content: [
1765 { type: "terminal", terminalId: "t3-term-9" },
1766 { type: "content", content: { type: "text", text: "noise" } },
1767 ],
1768 },
1769 }),
1770 ).toEqual({ toolCallId: "call_1", terminalIds: ["t3-term-9"] });
1771 expect(
1772 embeddedTerminalIdsFromSessionUpdate({
1773 sessionId: "session-1",
1774 update: {
1775 sessionUpdate: "tool_call",
1776 toolCallId: "call_2",
1777 title: "Tool",
1778 status: "pending",
1779 },
1780 }),
1781 ).toBeUndefined();
1782 });
1783 });