Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtimeModel.test.ts

1,447 lines46.4 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import type * as EffectAcpSchema from "effect-acp/compat";
4​
5import {
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 type AcpToolCallState,
21} from "./runtimeModel.ts";
22​
23describe("AcpRuntimeModel", () => {
24 it("parses session mode state from typed ACP session setup responses", () => {
25 const modeState = parseSessionModeState({
26 sessionId: "session-1",
27 modes: {
28 currentModeId: " code ",
29 availableModes: [
30 { id: " ask ", name: " Ask ", description: " Request approval " },
31 { id: " code ", name: " Code " },
32 ],
33 },
34 configOptions: [],
35 } satisfies EffectAcpSchema.NewSessionResponse);
36​
37 expect(modeState).toEqual({
38 currentModeId: "code",
39 availableModes: [
40 { id: "ask", name: "Ask", description: "Request approval" },
41 { id: "code", name: "Code" },
42 ],
43 });
44 });
45​
46 it("detects Grok session replay updates from _meta.isReplay", () => {
47 expect(
48 sessionUpdateIsReplay({
49 _meta: { isReplay: true },
50 sessionId: "session-1",
51 update: {
52 sessionUpdate: "agent_message_chunk",
53 content: { type: "text", text: "replayed" },
54 },
55 } satisfies EffectAcpSchema.SessionNotification),
56 ).toBe(true);
57 expect(
58 sessionUpdateIsReplay({
59 sessionId: "session-1",
60 update: {
61 sessionUpdate: "agent_message_chunk",
62 content: { type: "text", text: "live" },
63 },
64 } satisfies EffectAcpSchema.SessionNotification),
65 ).toBe(false);
66 });
67​
68 it("ignores Grok keepalive chunks when tracking session/load replay activity", () => {
69 expect(
70 sessionUpdateCountsAsLoadReplayActivity({
71 sessionId: "session-1",
72 update: {
73 sessionUpdate: "agent_message_chunk",
74 content: { type: "text", text: "" },
75 },
76 } satisfies EffectAcpSchema.SessionNotification),
77 ).toBe(false);
78 expect(
79 sessionUpdateCountsAsLoadReplayActivity({
80 _meta: { isReplay: true },
81 sessionId: "session-1",
82 update: {
83 sessionUpdate: "tool_call",
84 toolCallId: "replay-tool",
85 title: "Replay",
86 kind: "search",
87 status: "completed",
88 },
89 } satisfies EffectAcpSchema.SessionNotification),
90 ).toBe(true);
91 });
92​
93 it("ignores load-replay activity from other sessions while a load gate is active", () => {
94 expect(
95 sessionUpdateCountsAsLoadReplayActivity(
96 {
97 sessionId: "session-other",
98 update: {
99 sessionUpdate: "agent_message_chunk",
100 content: { type: "text", text: "unrelated" },
101 },
102 } satisfies EffectAcpSchema.SessionNotification,
103 "session-loading",
104 ),
105 ).toBe(false);
106 expect(
107 sessionUpdateCountsAsLoadReplayActivity(
108 {
109 sessionId: "session-loading",
110 update: {
111 sessionUpdate: "agent_message_chunk",
112 content: { type: "text", text: "replay" },
113 },
114 } satisfies EffectAcpSchema.SessionNotification,
115 "session-loading",
116 ),
117 ).toBe(true);
118 });
119​
120 it("ignores malformed initialize mode state in synthetic load responses", () => {
121 const response = syntheticLoadSessionResponseFromInitialize({
122 protocolVersion: 1,
123 _meta: {
124 modeState: {
125 currentModeId: "code",
126 availableModes: [{ id: "code", name: 12 }],
127 },
128 },
129 } as EffectAcpSchema.InitializeResponse);
130​
131 expect(response.modes).toBeUndefined();
132 expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
133 });
134​
135 it("keeps initialize mode state whose modes have null descriptions", () => {
136 const response = syntheticLoadSessionResponseFromInitialize({
137 protocolVersion: 1,
138 _meta: {
139 modeState: {
140 currentModeId: "code",
141 availableModes: [
142 { id: "ask", name: "Ask", description: null },
143 { id: "code", name: "Code", description: "Edit files", _meta: null },
144 ],
145 _meta: null,
146 },
147 },
148 } satisfies EffectAcpSchema.InitializeResponse);
149​
150 expect(parseSessionModeState(response)).toEqual({
151 currentModeId: "code",
152 availableModes: [
153 { id: "ask", name: "Ask" },
154 { id: "code", name: "Code", description: "Edit files" },
155 ],
156 });
157 });
158​
159 it("reads initialize model state and ignores malformed model state", () => {
160 const modelState = {
161 currentModelId: "grok-4.7",
162 availableModels: [
163 {
164 modelId: "grok-4.7",
165 name: "Grok 4.7",
166 description: null,
167 _meta: { reasoningEfforts: [{ id: "high", default: true }] },
168 },
169 { modelId: "grok-4.6", name: "Grok 4.6" },
170 ],
171 };
172​
173 expect(sessionModelStateFromInitialize({ protocolVersion: 1, _meta: { modelState } })).toEqual(
174 modelState,
175 );
176 expect(
177 sessionModelStateFromInitialize({
178 protocolVersion: 1,
179 _meta: {
180 modelState: { currentModelId: "grok-4.7", availableModels: [{ modelId: "grok-4.7" }] },
181 },
182 }),
183 ).toBeUndefined();
184 expect(
185 sessionModelStateFromInitialize({
186 protocolVersion: 1,
187 _meta: { modelState: { ...modelState, _meta: "not an object" } },
188 }),
189 ).toBeUndefined();
190 });
191​
192 it("projects typed ACP tool call updates into runtime events", () => {
193 const created = parseSessionUpdateEvent({
194 sessionId: "session-1",
195 update: {
196 sessionUpdate: "tool_call",
197 toolCallId: "tool-1",
198 title: "Terminal",
199 kind: "execute",
200 status: "pending",
201 rawInput: {
202 executable: "bun",
203 args: ["run", "typecheck"],
204 },
205 content: [
206 {
207 type: "content",
208 content: {
209 type: "text",
210 text: "Running checks",
211 },
212 },
213 ],
214 },
215 } satisfies EffectAcpSchema.SessionNotification);
216​
217 expect(created.events).toEqual([
218 {
219 _tag: "ToolCallUpdated",
220 toolCall: {
221 toolCallId: "tool-1",
222 kind: "execute",
223 title: "Ran command",
224 status: "pending",
225 command: "bun run typecheck",
226 detail: "bun run typecheck",
227 data: {
228 toolCallId: "tool-1",
229 kind: "execute",
230 title: "Terminal",
231 command: "bun run typecheck",
232 rawInput: {
233 executable: "bun",
234 args: ["run", "typecheck"],
235 },
236 content: [
237 {
238 type: "content",
239 content: {
240 type: "text",
241 text: "Running checks",
242 },
243 },
244 ],
245 },
246 },
247 rawPayload: {
248 sessionId: "session-1",
249 update: {
250 sessionUpdate: "tool_call",
251 toolCallId: "tool-1",
252 title: "Terminal",
253 kind: "execute",
254 status: "pending",
255 rawInput: {
256 executable: "bun",
257 args: ["run", "typecheck"],
258 },
259 content: [
260 {
261 type: "content",
262 content: {
263 type: "text",
264 text: "Running checks",
265 },
266 },
267 ],
268 },
269 },
270 },
271 ]);
272​
273 const updated = parseSessionUpdateEvent({
274 sessionId: "session-1",
275 update: {
276 sessionUpdate: "tool_call_update",
277 toolCallId: "tool-1",
278 status: "completed",
279 rawOutput: { exitCode: 0 },
280 },
281 } satisfies EffectAcpSchema.SessionNotification);
282​
283 expect(updated.events).toHaveLength(1);
284 expect(updated.events[0]?._tag).toBe("ToolCallUpdated");
285 const createdEvent = created.events[0];
286 const updatedEvent = updated.events[0];
287 if (createdEvent?._tag === "ToolCallUpdated" && updatedEvent?._tag === "ToolCallUpdated") {
288 expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
289 toolCallId: "tool-1",
290 status: "completed",
291 title: "Ran command",
292 detail: "bun run typecheck",
293 command: "bun run typecheck",
294 });
295 }
296 });
297​
298 it("clears prior ACP locations when an update explicitly replaces them", () => {
299 const toolCall = (locations?: EffectAcpSchema.ToolCallLocation[] | null) => {
300 const parsed = parseSessionUpdateEvent({
301 sessionId: "session-1",
302 update: {
303 sessionUpdate: "tool_call_update",
304 toolCallId: "read-1",
305 kind: "read",
306 ...(locations === undefined ? {} : { locations }),
307 },
308 } satisfies EffectAcpSchema.SessionNotification);
309 const event = parsed.events.find((candidate) => candidate._tag === "ToolCallUpdated");
310 if (!event || event._tag !== "ToolCallUpdated") {
311 throw new Error("expected a tool call update");
312 }
313 return event.toolCall;
314 };
315​
316 const created = toolCall([{ path: "README" }]);
317 expect(mergeToolCallState(created, toolCall()).data.locations).toEqual([{ path: "README" }]);
318 const cleared = mergeToolCallState(created, toolCall([]));
319 expect(cleared.data.locations).toEqual([]);
320 expect(mergeToolCallState(created, toolCall(null)).data.locations).toEqual([]);
321 expect(
322 decideToolCallUpdateEmission({
323 previous: created,
324 next: cleared,
325 lastEmittedDetailLength: 0,
326 skippedSinceEmit: 0,
327 }).emit,
328 ).toBe(true);
329 });
330​
331 it("projects typed ACP plan and content updates", () => {
332 const planResult = parseSessionUpdateEvent({
333 sessionId: "session-1",
334 update: {
335 sessionUpdate: "plan",
336 entries: [
337 { content: " Inspect state ", priority: "high", status: "completed" },
338 { content: "", priority: "medium", status: "in_progress" },
339 ],
340 },
341 } satisfies EffectAcpSchema.SessionNotification);
342​
343 expect(planResult.events).toEqual([
344 {
345 _tag: "PlanUpdated",
346 payload: {
347 nativePlanId: "legacy",
348 kind: "items",
349 plan: [
350 { step: "Inspect state", status: "completed" },
351 { step: "Step 2", status: "inProgress" },
352 ],
353 },
354 rawPayload: {
355 sessionId: "session-1",
356 update: {
357 sessionUpdate: "plan",
358 entries: [
359 { content: " Inspect state ", priority: "high", status: "completed" },
360 { content: "", priority: "medium", status: "in_progress" },
361 ],
362 },
363 },
364 },
365 ]);
366​
367 const contentResult = parseSessionUpdateEvent({
368 sessionId: "session-1",
369 update: {
370 sessionUpdate: "agent_message_chunk",
371 content: {
372 type: "text",
373 text: "hello from acp",
374 },
375 },
376 } satisfies EffectAcpSchema.SessionNotification);
377​
378 expect(contentResult.events).toEqual([
379 {
380 _tag: "ContentDelta",
381 text: "hello from acp",
382 rawPayload: {
383 sessionId: "session-1",
384 update: {
385 sessionUpdate: "agent_message_chunk",
386 content: {
387 type: "text",
388 text: "hello from acp",
389 },
390 },
391 },
392 },
393 ]);
394 });
395​
396 it("keeps permission request parsing compatible with loose extension payloads", () => {
397 const request = parsePermissionRequest({
398 sessionId: "session-1",
399 options: [
400 {
401 optionId: "allow-once",
402 name: "Allow once",
403 kind: "allow_once",
404 },
405 ],
406 toolCall: {
407 toolCallId: "tool-1",
408 title: "`cat package.json`",
409 kind: "execute",
410 status: "pending",
411 content: [
412 {
413 type: "content",
414 content: {
415 type: "text",
416 text: "Not in allowlist",
417 },
418 },
419 ],
420 },
421 });
422​
423 expect(request).toMatchObject({
424 kind: "execute",
425 detail: "cat package.json",
426 toolCall: {
427 toolCallId: "tool-1",
428 kind: "execute",
429 status: "pending",
430 command: "cat package.json",
431 },
432 });
433 });
434​
435 it("bounds an oversized cumulative tool_call_update content buffer to a tail window", () => {
436 // Mirrors Grok's ACP CLI resending the ENTIRE accumulated terminal output on every
437 // tool_call_update notification instead of a delta (see upstream #6556).
438 const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
439 "\n",
440 );
441 expect(hugeText.length).toBeGreaterThan(60_000);
442​
443 const result = parseSessionUpdateEvent({
444 sessionId: "session-1",
445 update: {
446 // Real ACP `tool_call_update` deltas typically omit `title` (already established by
447 // the initial `tool_call`); that is also the shape that surfaces raw content as detail.
448 sessionUpdate: "tool_call_update",
449 toolCallId: "tool-1",
450 kind: "other",
451 status: "in_progress",
452 content: [{ type: "content", content: { type: "text", text: hugeText } }],
453 },
454 } satisfies EffectAcpSchema.SessionNotification);
455​
456 expect(result.events).toHaveLength(1);
457 const event = result.events[0];
458 if (event?._tag !== "ToolCallUpdated") {
459 throw new Error("expected a ToolCallUpdated event");
460 }
461​
462 expect(event.toolCall.detail).toBeDefined();
463 const detail = event.toolCall.detail!;
464 expect(detail.length).toBe(8_028);
465 expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
466 expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
467​
468 const rawUpdate = (
469 event.rawPayload as {
470 readonly update: {
471 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
472 };
473 }
474 ).update;
475 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
476 expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
477 });
478​
479 it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
480 let previous: AcpToolCallState | undefined;
481 let lastEmittedDetailLength: number | undefined;
482 let skippedSinceEmit = 0;
483 let emittedCount = 0;
484 let emittedBytes = 0;
485 let notificationBytes = 0;
486 let largestEmittedEventBytes = 0;
487 let finalDetail: string | undefined;
488 let cumulativeBuffer = "";
489​
490 for (let i = 0; i < 1_000; i += 1) {
491 cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
492 const isLast = i === 999;
493​
494 const notification = {
495 sessionId: "session-1",
496 update: {
497 sessionUpdate: "tool_call_update",
498 toolCallId: "tool-1",
499 kind: "other",
500 status: isLast ? "completed" : "in_progress",
501 content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
502 },
503 } satisfies EffectAcpSchema.SessionNotification;
504 notificationBytes += JSON.stringify(notification).length;
505​
506 const { events } = parseSessionUpdateEvent(notification);
507​
508 const event = events[0];
509 if (event?._tag !== "ToolCallUpdated") {
510 continue;
511 }
512​
513 const merged = mergeToolCallState(previous, event.toolCall);
514 const decision = decideToolCallUpdateEmission({
515 previous,
516 next: merged,
517 lastEmittedDetailLength,
518 skippedSinceEmit,
519 });
520 previous = merged;
521 skippedSinceEmit = decision.skippedSinceEmit;
522 if (decision.emit) {
523 emittedCount += 1;
524 const eventBytes = JSON.stringify({
525 toolCall: merged,
526 rawPayload: event.rawPayload,
527 }).length;
528 emittedBytes += eventBytes;
529 largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
530 lastEmittedDetailLength = merged.detail?.length;
531 finalDetail = merged.detail;
532 }
533 }
534​
535 expect(notificationBytes).toBeGreaterThan(31_000_000);
536​
537 expect(emittedCount).toBe(114);
538 expect(largestEmittedEventBytes).toBeLessThan(25_000);
539 expect(emittedBytes).toBeLessThan(2_600_000);
540 expect(finalDetail).toBeDefined();
541 expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
542 });
543​
544 it("keeps non-text tool call content entries in order when bounding oversized text", () => {
545 const hugePrefix = "x".repeat(25_000);
546 const hugeTail = "y".repeat(25_000);
547 const { events } = parseSessionUpdateEvent({
548 sessionId: "session-1",
549 update: {
550 sessionUpdate: "tool_call_update",
551 toolCallId: "tool-1",
552 kind: "edit",
553 status: "in_progress",
554 content: [
555 { type: "content", content: { type: "text", text: hugePrefix } },
556 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
557 { type: "content", content: { type: "text", text: hugeTail } },
558 { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
559 { type: "content", content: { type: "text", text: " " } },
560 ],
561 },
562 } satisfies EffectAcpSchema.SessionNotification);
563​
564 const event = events[0];
565 if (event?._tag !== "ToolCallUpdated") {
566 throw new Error("expected a ToolCallUpdated event");
567 }
568 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
569 expect(content).toHaveLength(3);
570 expect(content[0]).toEqual({
571 type: "diff",
572 path: "/repo/file.ts",
573 oldText: "before",
574 newText: "after",
575 });
576 const lastEntry = content[1];
577 if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
578 throw new Error("expected a bounded text entry");
579 }
580 expect(lastEntry.content.text.length).toBeLessThan(8_100);
581 expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
582 expect(content[2]).toEqual({
583 type: "diff",
584 path: "/repo/other.ts",
585 oldText: "old",
586 newText: "new",
587 });
588 });
589​
590 it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
591 const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
592 expect(padded.length).toBeGreaterThan(60_000);
593​
594 const { events } = parseSessionUpdateEvent({
595 sessionId: "session-1",
596 update: {
597 sessionUpdate: "tool_call_update",
598 toolCallId: "tool-1",
599 kind: "other",
600 status: "in_progress",
601 content: [{ type: "content", content: { type: "text", text: padded } }],
602 },
603 } satisfies EffectAcpSchema.SessionNotification);
604​
605 const event = events[0];
606 if (event?._tag !== "ToolCallUpdated") {
607 throw new Error("expected a ToolCallUpdated event");
608 }
609​
610 expect(event.toolCall.detail).toBe("ok");
611 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
612 const textEntry = content[0];
613 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
614 throw new Error("expected a bounded text entry");
615 }
616 expect(textEntry.content.text).toBe("ok");
617​
618 const rawUpdate = (
619 event.rawPayload as {
620 readonly update: {
621 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
622 };
623 }
624 ).update;
625 expect(rawUpdate.content[0]?.content.text).toBe("ok");
626 expect(JSON.stringify(event).length).toBeLessThan(padded.length);
627 });
628​
629 describe("decideToolCallUpdateEmission", () => {
630 const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
631 ({
632 toolCallId: "tool-1",
633 title: "Grok Tool",
634 ...(status ? { status } : {}),
635 ...(detail ? { detail } : {}),
636 data: {},
637 }) satisfies AcpToolCallState;
638​
639 it("always emits terminal (completed/failed) status updates regardless of growth", () => {
640 expect(
641 decideToolCallUpdateEmission({
642 previous: toolCall("same", "inProgress"),
643 next: toolCall("same", "completed"),
644 lastEmittedDetailLength: 4,
645 skippedSinceEmit: 0,
646 }),
647 ).toEqual({ emit: true, skippedSinceEmit: 0 });
648​
649 expect(
650 decideToolCallUpdateEmission({
651 previous: toolCall("same", "inProgress"),
652 next: toolCall("same", "failed"),
653 lastEmittedDetailLength: 4,
654 skippedSinceEmit: 3,
655 }),
656 ).toEqual({ emit: true, skippedSinceEmit: 0 });
657 });
658​
659 it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
660 const commandCall = (stdout: string): AcpToolCallState => ({
661 toolCallId: "tool-1",
662 title: "Ran command",
663 status: "inProgress",
664 command: "ls",
665 detail: "ls",
666 data: {
667 command: "ls",
668 content: [{ type: "content", content: { type: "text", text: stdout } }],
669 },
670 });
671​
672 let previous: AcpToolCallState | undefined;
673 let lastEmittedDetailLength: number | undefined;
674 let skippedSinceEmit = 0;
675 const emissions: Array<boolean> = [];
676​
677 for (let i = 1; i <= 12; i += 1) {
678 const next = commandCall("x".repeat(i));
679 const decision = decideToolCallUpdateEmission({
680 previous,
681 next,
682 lastEmittedDetailLength,
683 skippedSinceEmit,
684 });
685 emissions.push(decision.emit);
686 skippedSinceEmit = decision.skippedSinceEmit;
687 if (decision.emit) {
688 lastEmittedDetailLength = toolCallProgressLength(next);
689 }
690 previous = next;
691 }
692​
693 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
694 expect(emittedIndices).toEqual([1, 11]);
695 });
696​
697 it("coalesces small deltas but forces an emission after the coalesce limit", () => {
698 let lastEmittedDetailLength: number | undefined = 0;
699 let skippedSinceEmit = 0;
700 const emissions: Array<boolean> = [];
701 let previous: AcpToolCallState | undefined;
702​
703 for (let i = 1; i <= 12; i += 1) {
704 const next = toolCall("x".repeat(i), "inProgress");
705 const decision = decideToolCallUpdateEmission({
706 previous,
707 next,
708 lastEmittedDetailLength,
709 skippedSinceEmit,
710 });
711 emissions.push(decision.emit);
712 skippedSinceEmit = decision.skippedSinceEmit;
713 if (decision.emit) {
714 lastEmittedDetailLength = next.detail?.length;
715 }
716 previous = next;
717 }
718​
719 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
720 expect(emittedIndices).toEqual([1, 11]);
721 });
722​
723 it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
724 let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
725 const lastEmittedDetailLength = previous.detail?.length;
726 let skippedSinceEmit = 0;
727​
728 for (const detail of ["frame-b", "frame-c"]) {
729 const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
730 const decision = decideToolCallUpdateEmission({
731 previous,
732 next,
733 lastEmittedDetailLength,
734 skippedSinceEmit,
735 });
736 expect(decision.emit).toBe(false);
737 skippedSinceEmit = decision.skippedSinceEmit;
738 previous = next;
739 }
740​
741 const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
742 expect(completed.detail).toBe("frame-c");
743 expect(
744 decideToolCallUpdateEmission({
745 previous,
746 next: completed,
747 lastEmittedDetailLength,
748 skippedSinceEmit,
749 }),
750 ).toEqual({ emit: true, skippedSinceEmit: 0 });
751 });
752 });
753​
754 it("preserves message identity, usage, metadata, and non-text output", () => {
755 const message = parseSessionUpdateEvent({
756 sessionId: "session-1",
757 update: {
758 sessionUpdate: "agent_message_chunk",
759 messageId: "message-1",
760 content: {
761 type: "resource_link",
762 name: "report.txt",
763 title: "Report",
764 description: "Generated artifact",
765 uri: "file:///workspace/report.txt",
766 },
767 },
768 } satisfies EffectAcpSchema.SessionNotification);
769 const usage = parseSessionUpdateEvent({
770 sessionId: "session-1",
771 update: {
772 sessionUpdate: "usage_update",
773 used: 2_500,
774 size: 10_000,
775 cost: { amount: 0.42, currency: "USD" },
776 },
777 } satisfies EffectAcpSchema.SessionNotification);
778 const metadata = parseSessionUpdateEvent({
779 sessionId: "session-1",
780 update: {
781 sessionUpdate: "session_info_update",
782 title: " Native session ",
783 updatedAt: " 2026-08-23T00:00:00Z ",
784 },
785 } satisfies EffectAcpSchema.SessionNotification);
786​
787 expect(message.events[0]).toMatchObject({
788 _tag: "ContentDelta",
789 messageId: "message-1",
790 text: "Report: Generated artifact\nfile:///workspace/report.txt",
791 });
792 expect(usage.events[0]).toMatchObject({
793 _tag: "UsageUpdated",
794 usage: {
795 usedTokens: 2_500,
796 maxTokens: 10_000,
797 cost: { amount: 0.42, currency: "USD" },
798 },
799 });
800 expect(metadata.events[0]).toMatchObject({
801 _tag: "SessionInfoUpdated",
802 metadata: {
803 title: "Native session",
804 updatedAt: "2026-08-23T00:00:00Z",
805 },
806 });
807 });
808​
809 it("projects ACP v2 plan replacement and removal updates", () => {
810 const replaced = parseSessionUpdateEvent({
811 sessionId: "session-1",
812 update: {
813 sessionUpdate: "plan_update",
814 plan: {
815 type: "items",
816 planId: "plan-1",
817 entries: [
818 { content: " Inspect schema ", priority: "high", status: "completed" },
819 { content: "Ship integration", priority: "high", status: "in_progress" },
820 ],
821 },
822 },
823 } satisfies EffectAcpSchema.SessionNotification);
824 const removed = parseSessionUpdateEvent({
825 sessionId: "session-1",
826 update: { sessionUpdate: "plan_removed", planId: "plan-1" },
827 } satisfies EffectAcpSchema.SessionNotification);
828​
829 expect(replaced.events[0]).toMatchObject({
830 _tag: "PlanUpdated",
831 payload: {
832 nativePlanId: "plan-1",
833 kind: "items",
834 plan: [
835 { step: "Inspect schema", status: "completed" },
836 { step: "Ship integration", status: "inProgress" },
837 ],
838 },
839 });
840 expect(removed.events[0]).toMatchObject({
841 _tag: "PlanUpdated",
842 payload: { nativePlanId: "plan-1", kind: "removed" },
843 });
844 });
845​
846 it("preserves markdown, file, and future ACP plan variants by plan ID", () => {
847 const updates = [
848 {
849 sessionId: "session-1",
850 update: {
851 sessionUpdate: "plan_update",
852 plan: { type: "markdown", planId: "plan-markdown", content: "# Ship it" },
853 },
854 },
855 {
856 sessionId: "session-1",
857 update: {
858 sessionUpdate: "plan_update",
859 plan: { type: "file", planId: "plan-file", uri: "file:///workspace/PLAN.md" },
860 },
861 },
862 {
863 sessionId: "session-1",
864 update: {
865 sessionUpdate: "plan_update",
866 plan: { type: "diagram", planId: "plan-future", nodes: [] },
867 },
868 },
869 ] as const;
870​
871 expect(updates.flatMap((update) => parseSessionUpdateEvent(update).events)).toMatchObject([
872 {
873 _tag: "PlanUpdated",
874 payload: { nativePlanId: "plan-markdown", kind: "markdown", markdown: "# Ship it" },
875 },
876 {
877 _tag: "PlanUpdated",
878 payload: {
879 nativePlanId: "plan-file",
880 kind: "file",
881 uri: "file:///workspace/PLAN.md",
882 },
883 },
884 {
885 _tag: "PlanUpdated",
886 payload: { nativePlanId: "plan-future", kind: "unknown", contentType: "diagram" },
887 },
888 ]);
889 });
890​
891 it("turns future ACP content and session updates into explicit placeholders", () => {
892 expect(
893 acpContentBlockDisplayText({
894 type: "_t3_unknown",
895 originalType: "chart",
896 raw: { type: "chart", points: [] },
897 }),
898 ).toBe("[Unsupported ACP content: chart]");
899​
900 expect(
901 parseSessionUpdateEvent({
902 sessionId: "session-1",
903 update: {
904 sessionUpdate: "_t3_unknown",
905 originalSessionUpdate: "timeline_update",
906 raw: { sessionUpdate: "timeline_update", entries: [] },
907 },
908 }).events,
909 ).toMatchObject([{ _tag: "UnknownUpdate", updateType: "timeline_update" }]);
910 });
911​
912 it("projects ACP v2 compaction lifecycle and prompt usage", () => {
913 const compacting = parseSessionUpdateEvent({
914 sessionId: "session-1",
915 update: {
916 sessionUpdate: "compaction_update",
917 compactionId: "compact-1",
918 status: "in_progress",
919 },
920 } satisfies EffectAcpSchema.SessionNotification);
921 const compacted = parseSessionUpdateEvent({
922 sessionId: "session-1",
923 update: {
924 sessionUpdate: "compaction_update",
925 compactionId: "compact-1",
926 status: "completed",
927 summary: [{ type: "text", text: "Retained the implementation decisions." }],
928 },
929 } satisfies EffectAcpSchema.SessionNotification);
930 const idle = parseSessionUpdateEvent({
931 sessionId: "session-1",
932 update: {
933 sessionUpdate: "state_update",
934 state: "idle",
935 stopReason: "end_turn",
936 usage: { totalTokens: 420, inputTokens: 300, outputTokens: 100, thoughtTokens: 20 },
937 },
938 } satisfies EffectAcpSchema.SessionNotification);
939​
940 expect(compacting.events[0]).toMatchObject({
941 _tag: "ToolCallUpdated",
942 toolCall: {
943 toolCallId: "acp-compaction:compact-1",
944 kind: "think",
945 title: "Compact context",
946 status: "inProgress",
947 },
948 });
949 expect(compacted.events[0]).toMatchObject({
950 _tag: "ToolCallUpdated",
951 toolCall: {
952 toolCallId: "acp-compaction:compact-1",
953 status: "completed",
954 data: { rawOutput: "Retained the implementation decisions." },
955 },
956 });
957 expect(idle.events[0]).toMatchObject({
958 _tag: "UsageUpdated",
959 usage: { usedTokens: 420 },
960 });
961 });
962​
963 it("applies ACP v2 agent-owned terminal snapshots and output chunks", () => {
964 const snapshot = applyAcpAgentTerminalUpdate(undefined, {
965 sessionUpdate: "terminal_update",
966 terminalId: "terminal-1",
967 command: "pnpm test",
968 cwd: "/workspace",
969 output: { data: Buffer.from("first line\n").toString("base64") },
970 });
971 const chunked = applyAcpAgentTerminalUpdate(snapshot, {
972 sessionUpdate: "terminal_output_chunk",
973 terminalId: "terminal-1",
974 data: Buffer.from("second line\n").toString("base64"),
975 });
976 const completed = applyAcpAgentTerminalUpdate(chunked, {
977 sessionUpdate: "terminal_update",
978 terminalId: "terminal-1",
979 exitStatus: { exitCode: 0 },
980 });
981​
982 expect(completed).toEqual({
983 command: "pnpm test",
984 cwd: "/workspace",
985 output: "first line\nsecond line\n",
986 outputBytes: 23,
987 exitStatus: { exitCode: 0 },
988 });
989 });
990​
991 it("preserves UTF-8 characters split across ACP terminal output chunks", () => {
992 const bytes = Buffer.from("AπŸ™‚B", "utf8");
993 const first = applyAcpAgentTerminalUpdate(undefined, {
994 sessionUpdate: "terminal_output_chunk",
995 terminalId: "terminal-utf8",
996 data: bytes.subarray(0, 3).toString("base64"),
997 });
998 const second = applyAcpAgentTerminalUpdate(first, {
999 sessionUpdate: "terminal_output_chunk",
1000 terminalId: "terminal-utf8",
1001 data: bytes.subarray(3).toString("base64"),
1002 });
1003​
1004 expect(first.output).toBe("A");
1005 expect(first.pendingOutputBytes).toBeDefined();
1006 expect(second.output).toBe("AπŸ™‚B");
1007 expect(second.pendingOutputBytes).toBeUndefined();
1008 });
1009​
1010 it("keeps the newest 16 MiB of ACP terminal output at a UTF-8 boundary", () => {
1011 const cap = 16 * 1024 * 1024;
1012 const chunk = (text: string | Uint8Array) => ({
1013 sessionUpdate: "terminal_output_chunk" as const,
1014 terminalId: "terminal-cap",
1015 data: Buffer.from(text).toString("base64"),
1016 });
1017 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1018 sessionUpdate: "terminal_update",
1019 terminalId: "terminal-cap",
1020 output: { data: Buffer.from(`Γ©${"a".repeat(cap - 3)}`).toString("base64") },
1021 });
1022 expect(seeded.outputBytes).toBe(cap - 1);
1023​
1024 // One byte over the cap falls inside "Γ©", so the whole character is dropped.
1025 const trimmed = applyAcpAgentTerminalUpdate(seeded, chunk("bc"));
1026 expect(trimmed.output.length).toBe(cap - 1);
1027 expect(trimmed.output.slice(0, 2)).toBe("aa");
1028 expect(trimmed.output.slice(-3)).toBe("abc");
1029 expect(trimmed.outputBytes).toBe(cap - 1);
1030​
1031 const emoji = applyAcpAgentTerminalUpdate(trimmed, chunk("πŸ™‚"));
1032 expect(emoji.output.slice(-5)).toBe("abcπŸ™‚");
1033 expect(emoji.outputBytes).toBe(cap);
1034 expect(Buffer.byteLength(emoji.output)).toBe(cap);
1035​
1036 // Exit flushes an incomplete trailing character and trims again.
1037 const pending = applyAcpAgentTerminalUpdate(emoji, chunk(Buffer.from("πŸ™‚").subarray(0, 2)));
1038 const exited = applyAcpAgentTerminalUpdate(pending, {
1039 sessionUpdate: "terminal_update",
1040 terminalId: "terminal-cap",
1041 exitStatus: { exitCode: 1 },
1042 });
1043 expect(exited.output.slice(-4)).toBe("cπŸ™‚\uFFFD");
1044 expect(exited.outputBytes).toBe(Buffer.byteLength(exited.output));
1045 expect(exited.outputBytes).toBeLessThanOrEqual(cap);
1046​
1047 const cleared = applyAcpAgentTerminalUpdate(exited, {
1048 sessionUpdate: "terminal_update",
1049 terminalId: "terminal-cap",
1050 output: null,
1051 });
1052 expect(cleared).toMatchObject({ output: "", outputBytes: 0, exitStatus: { exitCode: 1 } });
1053 });
1054​
1055 it("drops malformed and oversized ACP terminal frames without decoding them", () => {
1056 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1057 sessionUpdate: "terminal_output_chunk",
1058 terminalId: "terminal-invalid",
1059 data: Buffer.from("kept").toString("base64"),
1060 });
1061​
1062 expect(
1063 applyAcpAgentTerminalUpdate(seeded, {
1064 sessionUpdate: "terminal_output_chunk",
1065 terminalId: "terminal-invalid",
1066 data: "not base64!",
1067 }),
1068 ).toBe(seeded);
1069​
1070 expect(
1071 applyAcpAgentTerminalUpdate(seeded, {
1072 sessionUpdate: "terminal_output_chunk",
1073 terminalId: "terminal-oversized",
1074 data: Buffer.alloc(16 * 1024 * 1024 + 1).toString("base64"),
1075 }),
1076 ).toBe(seeded);
1077 });
1078​
1079 it("projects binary ACP content without retaining encoded payloads", () => {
1080 const encodedPayload = "sensitive-base64-payload";
1081 const binary = acpContentBlockDisplayText({
1082 type: "resource",
1083 resource: {
1084 blob: encodedPayload,
1085 mimeType: "application/octet-stream",
1086 uri: "file:///workspace/archive.bin",
1087 },
1088 });
1089 const image = acpContentBlockDisplayText({
1090 type: "image",
1091 data: encodedPayload,
1092 mimeType: "image/png",
1093 uri: "file:///workspace/image.png",
1094 });
1095 const audio = acpContentBlockDisplayText({
1096 type: "audio",
1097 data: encodedPayload,
1098 mimeType: "audio/wav",
1099 });
1100​
1101 expect(binary).toBe(
1102 "[ACP binary resource (application/octet-stream): file:///workspace/archive.bin]",
1103 );
1104 expect(image).toBe("[ACP image (image/png): file:///workspace/image.png]");
1105 expect(audio).toBe("[ACP audio (audio/wav)]");
1106 expect(`${binary}${image}${audio}`).not.toContain(encodedPayload);
1107​
1108 const toolUpdate = parseSessionUpdateEvent({
1109 sessionId: "session-1",
1110 update: {
1111 sessionUpdate: "tool_call",
1112 toolCallId: "tool-with-image",
1113 title: "Generated image",
1114 content: [
1116 type: "content",
1117 content: {
1118 type: "image",
1119 data: encodedPayload,
1120 mimeType: "image/png",
1121 uri: `data:image/png;base64,${encodedPayload}`,
1122 },
1123 },
1124 ],
1125 },
1126 } satisfies EffectAcpSchema.SessionNotification);
1127 const toolEvent = toolUpdate.events.find((event) => event._tag === "ToolCallUpdated");
1128 expect(JSON.stringify(toolEvent?.toolCall)).not.toContain(encodedPayload);
1129 expect(toolUpdate.events[0]).toMatchObject({
1130 _tag: "ToolCallUpdated",
1131 toolCall: {
1132 data: {
1133 content: [
1134 { type: "content", content: { type: "text", text: "[ACP image (image/png)]" } },
1135 ],
1136 },
1137 },
1138 });
1139 });
1140});
1141​
1142describe("extractMcpToolCallIdentity", () => {
1143 function toolCallFromUpdate(
1144 update: EffectAcpSchema.SessionNotification["update"],
1145 ): NonNullable<ReturnType<typeof parsePermissionRequest>["toolCall"]> {
1146 const parsed = parseSessionUpdateEvent({ sessionId: "session-1", update });
1147 const event = parsed.events.find(
1149 candidate,
1150 ): candidate is Extract<(typeof parsed.events)[number], { _tag: "ToolCallUpdated" }> =>
1151 candidate._tag === "ToolCallUpdated",
1152 );
1153 if (event === undefined) throw new Error("expected a tool call event");
1154 return event.toolCall;
1156​
1157 it("recovers server and tool from codex-acp tagged execute calls", () => {
1158 const toolCall = toolCallFromUpdate({
1159 sessionUpdate: "tool_call",
1160 toolCallId: "exec-f4591587-0754-4bb4-990b-f2767894ba93",
1161 kind: "execute",
1162 title: "mcp.t3-code.orchestrator_capabilities",
1163 status: "in_progress",
1164 rawInput: { server: "t3-code", tool: "orchestrator_capabilities", arguments: {} },
1165 _meta: { is_mcp_tool_call: true },
1166 });
1167​
1168 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1169 server: "t3-code",
1170 tool: "orchestrator_capabilities",
1171 });
1172 });
1173​
1174 it("recovers T3 identity from acp-mcp-call fallback commands", () => {
1175 const toolCall = toolCallFromUpdate({
1176 sessionUpdate: "tool_call",
1177 toolCallId: "exec-1",
1178 kind: "execute",
1179 title: "Ran command",
1180 status: "in_progress",
1181 });
1182​
1183 expect(
1184 extractMcpToolCallIdentity(toolCall, {
1185 embeddedTerminalCommands: [
1186 '/usr/bin/node /srv/t3/bin.ts acp-mcp-call delegate_task {"task":"x"}',
1187 ],
1188 }),
1189 ).toEqual({ server: "t3-code", tool: "delegate_task", input: { task: "x" } });
1190 });
1191​
1192 it("recovers T3 identity from pi-acp title-only fallback execs", () => {
1193 const toolCall = toolCallFromUpdate({
1194 sessionUpdate: "tool_call",
1195 toolCallId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1196 kind: "execute",
1197 title:
1198 '"$T3_ACP_MCP_NODE" "$T3_ACP_MCP_ENTRYPOINT" acp-mcp-call orchestrator_capabilities \'{}\'',
1199 status: "in_progress",
1200 rawInput: null,
1201 content: [
1203 type: "terminal",
1204 terminalId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1205 },
1206 ],
1207 });
1208​
1209 expect(toolCall.title).toBe("Ran command");
1210 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1211 server: "t3-code",
1212 tool: "orchestrator_capabilities",
1213 input: {},
1214 });
1215 });
1216​
1217 it("recovers T3 identity from server-namespaced titles across titleless updates", () => {
1218 const created = toolCallFromUpdate({
1219 sessionUpdate: "tool_call",
1220 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1221 kind: "other",
1222 title: "t3-code_orchestrator_capabilities",
1223 status: "pending",
1224 locations: [],
1225 rawInput: {},
1226 });
1227 const completed = toolCallFromUpdate({
1228 sessionUpdate: "tool_call_update",
1229 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1230 status: "completed",
1231 content: [{ type: "content", content: { type: "text", text: '{"ok":true}' } }],
1232 });
1233 const merged = mergeToolCallState(created, completed);
1234​
1235 expect(extractMcpToolCallIdentity(merged)).toEqual({
1236 server: "t3-code",
1237 tool: "orchestrator_capabilities",
1238 });
1239 });
1240​
1241 it("recovers T3 identity across the registry agents' naming conventions", () => {
1242 for (const title of [
1243 "t3-code___delegate_task",
1244 "t3-code-delegate_task",
1245 'mcp__t3_code__delegate_task: {"mode":"async"}',
1246 't3-code__delegate_task: {"mode":"async"}',
1247 "delegate_task_t3-code",
1248 "t3-code/delegate_task",
1249 "delegate_task",
1250 'delegate_task: {"mode":"async"}',
1251 // Kimi retitles on every streamed args chunk with the raw partial JSON,
1252 // and middle-truncates args longer than 50 characters.
1253 'delegate_task: {"mode":"async","task":"Ru',
1254 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}',
1255 ]) {
1256 const toolCall = toolCallFromUpdate({
1257 sessionUpdate: "tool_call",
1258 toolCallId: "convention-1",
1259 kind: "other",
1260 title,
1261 status: "pending",
1262 });
1263 expect(extractMcpToolCallIdentity(toolCall), title).toEqual({
1264 server: "t3-code",
1265 tool: "delegate_task",
1266 });
1268 });
1269​
1270 it("does not claim an agent's own tool that shares a T3 tool name", () => {
1271 // Hermes' built-in delegate_task, titled "<tool>: <description>" like all its calls.
1272 const toolCall = toolCallFromUpdate({
1273 sessionUpdate: "tool_call",
1274 toolCallId: "own-delegate-1",
1275 kind: "execute",
1276 title: "delegate_task: 1 tasks: Run the terminal command 'echo child-result-42'",
1277 status: "pending",
1278 });
1279 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1280 });
1281​
1282 it("recovers T3 identity from goose _meta despite LLM-rewritten titles", () => {
1283 // goose enriches titles asynchronously, so only _meta.goose.toolCall is
1284 // stable; shape from crates/goose/src/acp/server/tool_calls/conversion.rs.
1285 const toolCall = toolCallFromUpdate({
1286 sessionUpdate: "tool_call",
1287 toolCallId: "goose-1",
1288 title: "Checking on the delegated task",
1289 status: "in_progress",
1290 _meta: {
1291 goose: {
1292 toolCall: { toolName: "t3-code__task_status", extensionName: "t3-code" },
1293 messageId: "message-1",
1294 },
1295 },
1296 });
1297​
1298 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1299 server: "t3-code",
1300 tool: "task_status",
1301 });
1302 });
1303​
1304 it("recovers T3 identity from qwen serverId meta regardless of prefix format", () => {
1305 // qwen-code 0.21.12 emits _meta.serverId + _meta.toolName; serverId is an
1306 // explicit origin assertion, so a known tool suffix suffices even if the
1307 // prefix format changes.
1308 const toolCall = toolCallFromUpdate({
1309 sessionUpdate: "tool_call",
1310 toolCallId: "qwen-meta-1",
1311 kind: "other",
1312 title: "unrelated display title",
1313 status: "pending",
1314 _meta: { toolName: "mcp::t3-code::t3_thread_send", serverId: "t3-code", provenance: "mcp" },
1315 });
1316​
1317 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1318 server: "t3-code",
1319 tool: "t3_thread_send",
1320 });
1321 });
1322​
1323 it.each([
1324 { _meta: { claudeCode: { toolName: "mcp__weather__get_weather" } } },
1325 { _meta: { toolName: "mcp::weather::get_weather", serverId: "weather" } },
1326 ])("recovers external MCP identity from provider metadata", (metadata) => {
1327 const toolCall = toolCallFromUpdate({
1328 sessionUpdate: "tool_call",
1329 toolCallId: "weather-call",
1330 title: "Checking the forecast",
1331 status: "in_progress",
1332 ...metadata,
1333 });
1334 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1335 server: "weather",
1336 tool: "get_weather",
1337 });
1338 });
1339​
1340 it.each([
1341 { kind: "execute", toolName: "developer__shell", extensionName: "developer" },
1342 { kind: "edit", toolName: "developer__edit", extensionName: "developer" },
1343 { kind: "other", toolName: "weather__get_weather", extensionName: "weather" },
1344 ] as const)(
1345 "leaves goose $toolName unclassified so built-ins keep their projection",
1346 ({ kind, toolName, extensionName }) => {
1347 // goose tags built-in extensions exactly like user MCP servers.
1348 const toolCall = toolCallFromUpdate({
1349 sessionUpdate: "tool_call",
1350 toolCallId: "goose-builtin",
1351 kind,
1352 title: "developer: shell",
1353 status: "in_progress",
1354 _meta: { goose: { toolCall: { toolName, extensionName } } },
1355 });
1356 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1357 },
1358 );
1359​
1360 it("uses the asserted server instead of a misleading T3 title", () => {
1361 const toolCall = toolCallFromUpdate({
1362 sessionUpdate: "tool_call",
1363 toolCallId: "foreign-1",
1364 kind: "other",
1365 title: "t3-code_delegate_task",
1366 status: "pending",
1367 _meta: { toolName: "delegate_task", serverId: "other-orchestrator" },
1368 });
1369​
1370 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1371 server: "other-orchestrator",
1372 tool: "delegate_task",
1373 });
1374 });
1375​
1376 it("does not brand path-like or unknown-tool titles", () => {
1377 for (const title of ["t3-code/README.md", "t3-code_not_a_real_tool"]) {
1378 const toolCall = toolCallFromUpdate({
1379 sessionUpdate: "tool_call",
1380 toolCallId: "path-1",
1381 kind: "other",
1382 title,
1383 status: "pending",
1384 });
1385 expect(extractMcpToolCallIdentity(toolCall), title).toBeUndefined();
1387 });
1388​
1389 it("leaves ordinary execute calls unidentified", () => {
1390 const toolCall = toolCallFromUpdate({
1391 sessionUpdate: "tool_call",
1392 toolCallId: "exec-2",
1393 kind: "execute",
1394 title: "cat package.json",
1395 status: "in_progress",
1396 rawInput: { command: "cat package.json" },
1397 });
1398​
1399 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1400 expect(
1401 extractMcpToolCallIdentity(toolCall, { embeddedTerminalCommands: ["bash -lc ls"] }),
1402 ).toBeUndefined();
1403 });
1404​
1405 it("does not treat generic raw server and tool fields as MCP provenance", () => {
1406 const toolCall = toolCallFromUpdate({
1407 sessionUpdate: "tool_call",
1408 toolCallId: "generic-1",
1409 kind: "other",
1410 title: "Deploy",
1411 status: "pending",
1412 rawInput: { server: "production", tool: "deploy" },
1413 });
1414​
1415 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1416 });
1417});
1418​
1419describe("embeddedTerminalIdsFromSessionUpdate", () => {
1420 it("collects terminal ids from tool_call content before the text rewrite", () => {
1421 expect(
1422 embeddedTerminalIdsFromSessionUpdate({
1423 sessionId: "session-1",
1424 update: {
1425 sessionUpdate: "tool_call_update",
1426 toolCallId: "call_1",
1427 status: "in_progress",
1428 content: [
1429 { type: "terminal", terminalId: "t3-term-9" },
1430 { type: "content", content: { type: "text", text: "noise" } },
1431 ],
1432 },
1433 }),
1434 ).toEqual({ toolCallId: "call_1", terminalIds: ["t3-term-9"] });
1435 expect(
1436 embeddedTerminalIdsFromSessionUpdate({
1437 sessionId: "session-1",
1438 update: {
1439 sessionUpdate: "tool_call",
1440 toolCallId: "call_2",
1441 title: "Tool",
1442 status: "pending",
1443 },
1444 }),
1445 ).toBeUndefined();
1446 });
1447});