Open History to see the last commit
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 const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
437 "\n",
438 );
439 expect(hugeText.length).toBeGreaterThan(60_000);
440β
441 const result = parseSessionUpdateEvent({
442 sessionId: "session-1",
443 update: {
444 // Real tool_call_update deltas omit title; raw content then supplies detail.
445 sessionUpdate: "tool_call_update",
446 toolCallId: "tool-1",
447 kind: "other",
448 status: "in_progress",
449 content: [{ type: "content", content: { type: "text", text: hugeText } }],
450 },
451 } satisfies EffectAcpSchema.SessionNotification);
452β
453 expect(result.events).toHaveLength(1);
454 const event = result.events[0];
455 if (event?._tag !== "ToolCallUpdated") {
456 throw new Error("expected a ToolCallUpdated event");
457 }
458β
459 expect(event.toolCall.detail).toBeDefined();
460 const detail = event.toolCall.detail!;
461 expect(detail.length).toBe(8_028);
462 expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
463 expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
464β
465 const rawUpdate = (
466 event.rawPayload as {
467 readonly update: {
468 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
469 };
470 }
471 ).update;
472 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
473 expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
474 });
475β
476 it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
477 let previous: AcpToolCallState | undefined;
478 let lastEmittedDetailLength: number | undefined;
479 let skippedSinceEmit = 0;
480 let emittedCount = 0;
481 let emittedBytes = 0;
482 let notificationBytes = 0;
483 let largestEmittedEventBytes = 0;
484 let finalDetail: string | undefined;
485 let cumulativeBuffer = "";
486β
487 for (let i = 0; i < 1_000; i += 1) {
488 cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
489 const isLast = i === 999;
490β
491 const notification = {
492 sessionId: "session-1",
493 update: {
494 sessionUpdate: "tool_call_update",
495 toolCallId: "tool-1",
496 kind: "other",
497 status: isLast ? "completed" : "in_progress",
498 content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
499 },
500 } satisfies EffectAcpSchema.SessionNotification;
501 notificationBytes += JSON.stringify(notification).length;
502β
503 const { events } = parseSessionUpdateEvent(notification);
504β
505 const event = events[0];
506 if (event?._tag !== "ToolCallUpdated") {
507 continue;
508 }
509β
510 const merged = mergeToolCallState(previous, event.toolCall);
511 const decision = decideToolCallUpdateEmission({
512 previous,
513 next: merged,
514 lastEmittedDetailLength,
515 skippedSinceEmit,
516 });
517 previous = merged;
518 skippedSinceEmit = decision.skippedSinceEmit;
519 if (decision.emit) {
520 emittedCount += 1;
521 const eventBytes = JSON.stringify({
522 toolCall: merged,
523 rawPayload: event.rawPayload,
524 }).length;
525 emittedBytes += eventBytes;
526 largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
527 lastEmittedDetailLength = merged.detail?.length;
528 finalDetail = merged.detail;
529 }
530 }
531β
532 expect(notificationBytes).toBeGreaterThan(31_000_000);
533β
534 expect(emittedCount).toBe(114);
535 expect(largestEmittedEventBytes).toBeLessThan(25_000);
536 expect(emittedBytes).toBeLessThan(2_600_000);
537 expect(finalDetail).toBeDefined();
538 expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
539 });
540β
541 it("keeps non-text tool call content entries in order when bounding oversized text", () => {
542 const hugePrefix = "x".repeat(25_000);
543 const hugeTail = "y".repeat(25_000);
544 const { events } = parseSessionUpdateEvent({
545 sessionId: "session-1",
546 update: {
547 sessionUpdate: "tool_call_update",
548 toolCallId: "tool-1",
549 kind: "edit",
550 status: "in_progress",
551 content: [
552 { type: "content", content: { type: "text", text: hugePrefix } },
553 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
554 { type: "content", content: { type: "text", text: hugeTail } },
555 { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
556 { type: "content", content: { type: "text", text: " " } },
557 ],
558 },
559 } satisfies EffectAcpSchema.SessionNotification);
560β
561 const event = events[0];
562 if (event?._tag !== "ToolCallUpdated") {
563 throw new Error("expected a ToolCallUpdated event");
564 }
565 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
566 expect(content).toHaveLength(3);
567 expect(content[0]).toEqual({
568 type: "diff",
569 path: "/repo/file.ts",
570 oldText: "before",
571 newText: "after",
572 });
573 const lastEntry = content[1];
574 if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
575 throw new Error("expected a bounded text entry");
576 }
577 expect(lastEntry.content.text.length).toBeLessThan(8_100);
578 expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
579 expect(content[2]).toEqual({
580 type: "diff",
581 path: "/repo/other.ts",
582 oldText: "old",
583 newText: "new",
584 });
585 });
586β
587 it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
588 const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
589 expect(padded.length).toBeGreaterThan(60_000);
590β
591 const { events } = parseSessionUpdateEvent({
592 sessionId: "session-1",
593 update: {
594 sessionUpdate: "tool_call_update",
595 toolCallId: "tool-1",
596 kind: "other",
597 status: "in_progress",
598 content: [{ type: "content", content: { type: "text", text: padded } }],
599 },
600 } satisfies EffectAcpSchema.SessionNotification);
601β
602 const event = events[0];
603 if (event?._tag !== "ToolCallUpdated") {
604 throw new Error("expected a ToolCallUpdated event");
605 }
606β
607 expect(event.toolCall.detail).toBe("ok");
608 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
609 const textEntry = content[0];
610 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
611 throw new Error("expected a bounded text entry");
612 }
613 expect(textEntry.content.text).toBe("ok");
614β
615 const rawUpdate = (
616 event.rawPayload as {
617 readonly update: {
618 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
619 };
620 }
621 ).update;
622 expect(rawUpdate.content[0]?.content.text).toBe("ok");
623 expect(JSON.stringify(event).length).toBeLessThan(padded.length);
624 });
625β
626 describe("decideToolCallUpdateEmission", () => {
627 const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
628 ({
629 toolCallId: "tool-1",
630 title: "Grok Tool",
631 ...(status ? { status } : {}),
632 ...(detail ? { detail } : {}),
633 data: {},
634 }) satisfies AcpToolCallState;
635β
636 it("always emits terminal (completed/failed) status updates regardless of growth", () => {
637 expect(
638 decideToolCallUpdateEmission({
639 previous: toolCall("same", "inProgress"),
640 next: toolCall("same", "completed"),
641 lastEmittedDetailLength: 4,
642 skippedSinceEmit: 0,
643 }),
644 ).toEqual({ emit: true, skippedSinceEmit: 0 });
645β
646 expect(
647 decideToolCallUpdateEmission({
648 previous: toolCall("same", "inProgress"),
649 next: toolCall("same", "failed"),
650 lastEmittedDetailLength: 4,
651 skippedSinceEmit: 3,
652 }),
653 ).toEqual({ emit: true, skippedSinceEmit: 0 });
654 });
655β
656 it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
657 const commandCall = (stdout: string): AcpToolCallState => ({
658 toolCallId: "tool-1",
659 title: "Ran command",
660 status: "inProgress",
661 command: "ls",
662 detail: "ls",
663 data: {
664 command: "ls",
665 content: [{ type: "content", content: { type: "text", text: stdout } }],
666 },
667 });
668β
669 let previous: AcpToolCallState | undefined;
670 let lastEmittedDetailLength: number | undefined;
671 let skippedSinceEmit = 0;
672 const emissions: Array<boolean> = [];
673β
674 for (let i = 1; i <= 12; i += 1) {
675 const next = commandCall("x".repeat(i));
676 const decision = decideToolCallUpdateEmission({
677 previous,
678 next,
679 lastEmittedDetailLength,
680 skippedSinceEmit,
681 });
682 emissions.push(decision.emit);
683 skippedSinceEmit = decision.skippedSinceEmit;
684 if (decision.emit) {
685 lastEmittedDetailLength = toolCallProgressLength(next);
686 }
687 previous = next;
688 }
689β
690 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
691 expect(emittedIndices).toEqual([1, 11]);
692 });
693β
694 it("coalesces small deltas but forces an emission after the coalesce limit", () => {
695 let lastEmittedDetailLength: number | undefined = 0;
696 let skippedSinceEmit = 0;
697 const emissions: Array<boolean> = [];
698 let previous: AcpToolCallState | undefined;
699β
700 for (let i = 1; i <= 12; i += 1) {
701 const next = toolCall("x".repeat(i), "inProgress");
702 const decision = decideToolCallUpdateEmission({
703 previous,
704 next,
705 lastEmittedDetailLength,
706 skippedSinceEmit,
707 });
708 emissions.push(decision.emit);
709 skippedSinceEmit = decision.skippedSinceEmit;
710 if (decision.emit) {
711 lastEmittedDetailLength = next.detail?.length;
712 }
713 previous = next;
714 }
715β
716 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
717 expect(emittedIndices).toEqual([1, 11]);
718 });
719β
720 it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
721 let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
722 const lastEmittedDetailLength = previous.detail?.length;
723 let skippedSinceEmit = 0;
724β
725 for (const detail of ["frame-b", "frame-c"]) {
726 const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
727 const decision = decideToolCallUpdateEmission({
728 previous,
729 next,
730 lastEmittedDetailLength,
731 skippedSinceEmit,
732 });
733 expect(decision.emit).toBe(false);
734 skippedSinceEmit = decision.skippedSinceEmit;
735 previous = next;
736 }
737β
738 const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
739 expect(completed.detail).toBe("frame-c");
740 expect(
741 decideToolCallUpdateEmission({
742 previous,
743 next: completed,
744 lastEmittedDetailLength,
745 skippedSinceEmit,
746 }),
747 ).toEqual({ emit: true, skippedSinceEmit: 0 });
748 });
749 });
750β
751 it("preserves message identity, usage, metadata, and non-text output", () => {
752 const message = parseSessionUpdateEvent({
753 sessionId: "session-1",
754 update: {
755 sessionUpdate: "agent_message_chunk",
756 messageId: "message-1",
757 content: {
758 type: "resource_link",
759 name: "report.txt",
760 title: "Report",
761 description: "Generated artifact",
762 uri: "file:///workspace/report.txt",
763 },
764 },
765 } satisfies EffectAcpSchema.SessionNotification);
766 const usage = parseSessionUpdateEvent({
767 sessionId: "session-1",
768 update: {
769 sessionUpdate: "usage_update",
770 used: 2_500,
771 size: 10_000,
772 cost: { amount: 0.42, currency: "USD" },
773 },
774 } satisfies EffectAcpSchema.SessionNotification);
775 const metadata = parseSessionUpdateEvent({
776 sessionId: "session-1",
777 update: {
778 sessionUpdate: "session_info_update",
779 title: " Native session ",
780 updatedAt: " 2026-08-23T00:00:00Z ",
781 },
782 } satisfies EffectAcpSchema.SessionNotification);
783β
784 expect(message.events[0]).toMatchObject({
785 _tag: "ContentDelta",
786 messageId: "message-1",
787 text: "Report: Generated artifact\nfile:///workspace/report.txt",
788 });
789 expect(usage.events[0]).toMatchObject({
790 _tag: "UsageUpdated",
791 usage: {
792 usedTokens: 2_500,
793 maxTokens: 10_000,
794 cost: { amount: 0.42, currency: "USD" },
795 },
796 });
797 expect(metadata.events[0]).toMatchObject({
798 _tag: "SessionInfoUpdated",
799 metadata: {
800 title: "Native session",
801 updatedAt: "2026-08-23T00:00:00Z",
802 },
803 });
804 });
805β
806 it("projects ACP v2 plan replacement and removal updates", () => {
807 const replaced = parseSessionUpdateEvent({
808 sessionId: "session-1",
809 update: {
810 sessionUpdate: "plan_update",
811 plan: {
812 type: "items",
813 planId: "plan-1",
814 entries: [
815 { content: " Inspect schema ", priority: "high", status: "completed" },
816 { content: "Ship integration", priority: "high", status: "in_progress" },
817 ],
818 },
819 },
820 } satisfies EffectAcpSchema.SessionNotification);
821 const removed = parseSessionUpdateEvent({
822 sessionId: "session-1",
823 update: { sessionUpdate: "plan_removed", planId: "plan-1" },
824 } satisfies EffectAcpSchema.SessionNotification);
825β
826 expect(replaced.events[0]).toMatchObject({
827 _tag: "PlanUpdated",
828 payload: {
829 nativePlanId: "plan-1",
830 kind: "items",
831 plan: [
832 { step: "Inspect schema", status: "completed" },
833 { step: "Ship integration", status: "inProgress" },
834 ],
835 },
836 });
837 expect(removed.events[0]).toMatchObject({
838 _tag: "PlanUpdated",
839 payload: { nativePlanId: "plan-1", kind: "removed" },
840 });
841 });
842β
843 it("preserves markdown, file, and future ACP plan variants by plan ID", () => {
844 const updates = [
845 {
846 sessionId: "session-1",
847 update: {
848 sessionUpdate: "plan_update",
849 plan: { type: "markdown", planId: "plan-markdown", content: "# Ship it" },
850 },
851 },
852 {
853 sessionId: "session-1",
854 update: {
855 sessionUpdate: "plan_update",
856 plan: { type: "file", planId: "plan-file", uri: "file:///workspace/PLAN.md" },
857 },
858 },
859 {
860 sessionId: "session-1",
861 update: {
862 sessionUpdate: "plan_update",
863 plan: { type: "diagram", planId: "plan-future", nodes: [] },
864 },
865 },
866 ] as const;
867β
868 expect(updates.flatMap((update) => parseSessionUpdateEvent(update).events)).toMatchObject([
869 {
870 _tag: "PlanUpdated",
871 payload: { nativePlanId: "plan-markdown", kind: "markdown", markdown: "# Ship it" },
872 },
873 {
874 _tag: "PlanUpdated",
875 payload: {
876 nativePlanId: "plan-file",
877 kind: "file",
878 uri: "file:///workspace/PLAN.md",
879 },
880 },
881 {
882 _tag: "PlanUpdated",
883 payload: { nativePlanId: "plan-future", kind: "unknown", contentType: "diagram" },
884 },
885 ]);
886 });
887β
888 it("turns future ACP content and session updates into explicit placeholders", () => {
889 expect(
890 acpContentBlockDisplayText({
891 type: "_t3_unknown",
892 originalType: "chart",
893 raw: { type: "chart", points: [] },
894 }),
895 ).toBe("[Unsupported ACP content: chart]");
896β
897 expect(
898 parseSessionUpdateEvent({
899 sessionId: "session-1",
900 update: {
901 sessionUpdate: "_t3_unknown",
902 originalSessionUpdate: "timeline_update",
903 raw: { sessionUpdate: "timeline_update", entries: [] },
904 },
905 }).events,
906 ).toMatchObject([{ _tag: "UnknownUpdate", updateType: "timeline_update" }]);
907 });
908β
909 it("projects ACP v2 compaction lifecycle and prompt usage", () => {
910 const compacting = parseSessionUpdateEvent({
911 sessionId: "session-1",
912 update: {
913 sessionUpdate: "compaction_update",
914 compactionId: "compact-1",
915 status: "in_progress",
916 },
917 } satisfies EffectAcpSchema.SessionNotification);
918 const compacted = parseSessionUpdateEvent({
919 sessionId: "session-1",
920 update: {
921 sessionUpdate: "compaction_update",
922 compactionId: "compact-1",
923 status: "completed",
924 summary: [{ type: "text", text: "Retained the implementation decisions." }],
925 },
926 } satisfies EffectAcpSchema.SessionNotification);
927 const idle = parseSessionUpdateEvent({
928 sessionId: "session-1",
929 update: {
930 sessionUpdate: "state_update",
931 state: "idle",
932 stopReason: "end_turn",
933 usage: { totalTokens: 420, inputTokens: 300, outputTokens: 100, thoughtTokens: 20 },
934 },
935 } satisfies EffectAcpSchema.SessionNotification);
936β
937 expect(compacting.events[0]).toMatchObject({
938 _tag: "ToolCallUpdated",
939 toolCall: {
940 toolCallId: "acp-compaction:compact-1",
941 kind: "think",
942 title: "Compact context",
943 status: "inProgress",
944 },
945 });
946 expect(compacted.events[0]).toMatchObject({
947 _tag: "ToolCallUpdated",
948 toolCall: {
949 toolCallId: "acp-compaction:compact-1",
950 status: "completed",
951 data: { rawOutput: "Retained the implementation decisions." },
952 },
953 });
954 expect(idle.events[0]).toMatchObject({
955 _tag: "UsageUpdated",
956 usage: { usedTokens: 420 },
957 });
958 });
959β
960 it("applies ACP v2 agent-owned terminal snapshots and output chunks", () => {
961 const snapshot = applyAcpAgentTerminalUpdate(undefined, {
962 sessionUpdate: "terminal_update",
963 terminalId: "terminal-1",
964 command: "pnpm test",
965 cwd: "/workspace",
966 output: { data: Buffer.from("first line\n").toString("base64") },
967 });
968 const chunked = applyAcpAgentTerminalUpdate(snapshot, {
969 sessionUpdate: "terminal_output_chunk",
970 terminalId: "terminal-1",
971 data: Buffer.from("second line\n").toString("base64"),
972 });
973 const completed = applyAcpAgentTerminalUpdate(chunked, {
974 sessionUpdate: "terminal_update",
975 terminalId: "terminal-1",
976 exitStatus: { exitCode: 0 },
977 });
978β
979 expect(completed).toEqual({
980 command: "pnpm test",
981 cwd: "/workspace",
982 output: "first line\nsecond line\n",
983 outputBytes: 23,
984 exitStatus: { exitCode: 0 },
985 });
986 });
987β
988 it("preserves UTF-8 characters split across ACP terminal output chunks", () => {
989 const bytes = Buffer.from("AπB", "utf8");
990 const first = applyAcpAgentTerminalUpdate(undefined, {
991 sessionUpdate: "terminal_output_chunk",
992 terminalId: "terminal-utf8",
993 data: bytes.subarray(0, 3).toString("base64"),
994 });
995 const second = applyAcpAgentTerminalUpdate(first, {
996 sessionUpdate: "terminal_output_chunk",
997 terminalId: "terminal-utf8",
998 data: bytes.subarray(3).toString("base64"),
999 });
1000β
1001 expect(first.output).toBe("A");
1002 expect(first.pendingOutputBytes).toBeDefined();
1003 expect(second.output).toBe("AπB");
1004 expect(second.pendingOutputBytes).toBeUndefined();
1005 });
1006β
1007 it("keeps the newest 16 MiB of ACP terminal output at a UTF-8 boundary", () => {
1008 const cap = 16 * 1024 * 1024;
1009 const chunk = (text: string | Uint8Array) => ({
1010 sessionUpdate: "terminal_output_chunk" as const,
1011 terminalId: "terminal-cap",
1012 data: Buffer.from(text).toString("base64"),
1013 });
1014 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1015 sessionUpdate: "terminal_update",
1016 terminalId: "terminal-cap",
1017 output: { data: Buffer.from(`Γ©${"a".repeat(cap - 3)}`).toString("base64") },
1018 });
1019 expect(seeded.outputBytes).toBe(cap - 1);
1020β
1021 // One byte over the cap falls inside "Γ©", so the whole character is dropped.
1022 const trimmed = applyAcpAgentTerminalUpdate(seeded, chunk("bc"));
1023 expect(trimmed.output.length).toBe(cap - 1);
1024 expect(trimmed.output.slice(0, 2)).toBe("aa");
1025 expect(trimmed.output.slice(-3)).toBe("abc");
1026 expect(trimmed.outputBytes).toBe(cap - 1);
1027β
1028 const emoji = applyAcpAgentTerminalUpdate(trimmed, chunk("π"));
1029 expect(emoji.output.slice(-5)).toBe("abcπ");
1030 expect(emoji.outputBytes).toBe(cap);
1031 expect(Buffer.byteLength(emoji.output)).toBe(cap);
1032β
1033 // Exit flushes an incomplete trailing character and trims again.
1034 const pending = applyAcpAgentTerminalUpdate(emoji, chunk(Buffer.from("π").subarray(0, 2)));
1035 const exited = applyAcpAgentTerminalUpdate(pending, {
1036 sessionUpdate: "terminal_update",
1037 terminalId: "terminal-cap",
1038 exitStatus: { exitCode: 1 },
1039 });
1040 expect(exited.output.slice(-4)).toBe("cπ\uFFFD");
1041 expect(exited.outputBytes).toBe(Buffer.byteLength(exited.output));
1042 expect(exited.outputBytes).toBeLessThanOrEqual(cap);
1043β
1044 const cleared = applyAcpAgentTerminalUpdate(exited, {
1045 sessionUpdate: "terminal_update",
1046 terminalId: "terminal-cap",
1047 output: null,
1048 });
1049 expect(cleared).toMatchObject({ output: "", outputBytes: 0, exitStatus: { exitCode: 1 } });
1050 });
1051β
1052 it("drops malformed and oversized ACP terminal frames without decoding them", () => {
1053 const seeded = applyAcpAgentTerminalUpdate(undefined, {
1054 sessionUpdate: "terminal_output_chunk",
1055 terminalId: "terminal-invalid",
1056 data: Buffer.from("kept").toString("base64"),
1057 });
1058β
1059 expect(
1060 applyAcpAgentTerminalUpdate(seeded, {
1061 sessionUpdate: "terminal_output_chunk",
1062 terminalId: "terminal-invalid",
1063 data: "not base64!",
1064 }),
1065 ).toBe(seeded);
1066β
1067 expect(
1068 applyAcpAgentTerminalUpdate(seeded, {
1069 sessionUpdate: "terminal_output_chunk",
1070 terminalId: "terminal-oversized",
1071 data: Buffer.alloc(16 * 1024 * 1024 + 1).toString("base64"),
1072 }),
1073 ).toBe(seeded);
1074 });
1075β
1076 it("projects binary ACP content without retaining encoded payloads", () => {
1077 const encodedPayload = "sensitive-base64-payload";
1078 const binary = acpContentBlockDisplayText({
1079 type: "resource",
1080 resource: {
1081 blob: encodedPayload,
1082 mimeType: "application/octet-stream",
1083 uri: "file:///workspace/archive.bin",
1084 },
1085 });
1086 const image = acpContentBlockDisplayText({
1087 type: "image",
1088 data: encodedPayload,
1089 mimeType: "image/png",
1090 uri: "file:///workspace/image.png",
1091 });
1092 const audio = acpContentBlockDisplayText({
1093 type: "audio",
1094 data: encodedPayload,
1095 mimeType: "audio/wav",
1096 });
1097β
1098 expect(binary).toBe(
1099 "[ACP binary resource (application/octet-stream): file:///workspace/archive.bin]",
1100 );
1101 expect(image).toBe("[ACP image (image/png): file:///workspace/image.png]");
1102 expect(audio).toBe("[ACP audio (audio/wav)]");
1103 expect(`${binary}${image}${audio}`).not.toContain(encodedPayload);
1104β
1105 const toolUpdate = parseSessionUpdateEvent({
1106 sessionId: "session-1",
1107 update: {
1108 sessionUpdate: "tool_call",
1109 toolCallId: "tool-with-image",
1110 title: "Generated image",
1111 content: [
1112 {
1113 type: "content",
1114 content: {
1115 type: "image",
1116 data: encodedPayload,
1117 mimeType: "image/png",
1118 uri: `data:image/png;base64,${encodedPayload}`,
1119 },
1120 },
1121 ],
1122 },
1123 } satisfies EffectAcpSchema.SessionNotification);
1124 const toolEvent = toolUpdate.events.find((event) => event._tag === "ToolCallUpdated");
1125 expect(JSON.stringify(toolEvent?.toolCall)).not.toContain(encodedPayload);
1126 expect(toolUpdate.events[0]).toMatchObject({
1127 _tag: "ToolCallUpdated",
1128 toolCall: {
1129 data: {
1130 content: [
1131 { type: "content", content: { type: "text", text: "[ACP image (image/png)]" } },
1132 ],
1133 },
1134 },
1135 });
1136 });
1137});
1138β
1139describe("extractMcpToolCallIdentity", () => {
1140 function toolCallFromUpdate(
1141 update: EffectAcpSchema.SessionNotification["update"],
1142 ): NonNullable<ReturnType<typeof parsePermissionRequest>["toolCall"]> {
1143 const parsed = parseSessionUpdateEvent({ sessionId: "session-1", update });
1144 const event = parsed.events.find(
1145 (
1146 candidate,
1147 ): candidate is Extract<(typeof parsed.events)[number], { _tag: "ToolCallUpdated" }> =>
1148 candidate._tag === "ToolCallUpdated",
1149 );
1150 if (event === undefined) throw new Error("expected a tool call event");
1151 return event.toolCall;
1152 }
1153β
1154 it("recovers server and tool from codex-acp tagged execute calls", () => {
1155 const toolCall = toolCallFromUpdate({
1156 sessionUpdate: "tool_call",
1157 toolCallId: "exec-f4591587-0754-4bb4-990b-f2767894ba93",
1158 kind: "execute",
1159 title: "mcp.t3-code.orchestrator_capabilities",
1160 status: "in_progress",
1161 rawInput: { server: "t3-code", tool: "orchestrator_capabilities", arguments: {} },
1162 _meta: { is_mcp_tool_call: true },
1163 });
1164β
1165 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1166 server: "t3-code",
1167 tool: "orchestrator_capabilities",
1168 });
1169 });
1170β
1171 it("recovers T3 identity from acp-mcp-call fallback commands", () => {
1172 const toolCall = toolCallFromUpdate({
1173 sessionUpdate: "tool_call",
1174 toolCallId: "exec-1",
1175 kind: "execute",
1176 title: "Ran command",
1177 status: "in_progress",
1178 });
1179β
1180 expect(
1181 extractMcpToolCallIdentity(toolCall, {
1182 embeddedTerminalCommands: [
1183 '/usr/bin/node /srv/t3/bin.ts acp-mcp-call delegate_task {"task":"x"}',
1184 ],
1185 }),
1186 ).toEqual({ server: "t3-code", tool: "delegate_task", input: { task: "x" } });
1187 });
1188β
1189 it("recovers T3 identity from pi-acp title-only fallback execs", () => {
1190 const toolCall = toolCallFromUpdate({
1191 sessionUpdate: "tool_call",
1192 toolCallId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1193 kind: "execute",
1194 title:
1195 '"$T3_ACP_MCP_NODE" "$T3_ACP_MCP_ENTRYPOINT" acp-mcp-call orchestrator_capabilities \'{}\'',
1196 status: "in_progress",
1197 rawInput: null,
1198 content: [
1199 {
1200 type: "terminal",
1201 terminalId: "call_JdxnvzjHHrbvyASTLVekLYWV|fc_08f5a805a7159aa6016a7ec4afad548191",
1202 },
1203 ],
1204 });
1205β
1206 expect(toolCall.title).toBe("Ran command");
1207 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1208 server: "t3-code",
1209 tool: "orchestrator_capabilities",
1210 input: {},
1211 });
1212 });
1213β
1214 it("recovers T3 identity from server-namespaced titles across titleless updates", () => {
1215 const created = toolCallFromUpdate({
1216 sessionUpdate: "tool_call",
1217 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1218 kind: "other",
1219 title: "t3-code_orchestrator_capabilities",
1220 status: "pending",
1221 locations: [],
1222 rawInput: {},
1223 });
1224 const completed = toolCallFromUpdate({
1225 sessionUpdate: "tool_call_update",
1226 toolCallId: "chatcmpl-tool-b2a6142ee1a510a5",
1227 status: "completed",
1228 content: [{ type: "content", content: { type: "text", text: '{"ok":true}' } }],
1229 });
1230 const merged = mergeToolCallState(created, completed);
1231β
1232 expect(extractMcpToolCallIdentity(merged)).toEqual({
1233 server: "t3-code",
1234 tool: "orchestrator_capabilities",
1235 });
1236 });
1237β
1238 it("recovers T3 identity across the registry agents' naming conventions", () => {
1239 for (const title of [
1240 "t3-code___delegate_task",
1241 "t3-code-delegate_task",
1242 'mcp__t3_code__delegate_task: {"mode":"async"}',
1243 't3-code__delegate_task: {"mode":"async"}',
1244 "delegate_task_t3-code",
1245 "t3-code/delegate_task",
1246 "delegate_task",
1247 'delegate_task: {"mode":"async"}',
1248 // Kimi retitles with partial JSON and middle-truncates args over 50 characters.
1249 'delegate_task: {"mode":"async","task":"Ru',
1250 'delegate_task: {"mode":"async","task":"Ru...cho child-result-42\'"}',
1251 ]) {
1252 const toolCall = toolCallFromUpdate({
1253 sessionUpdate: "tool_call",
1254 toolCallId: "convention-1",
1255 kind: "other",
1256 title,
1257 status: "pending",
1258 });
1259 expect(extractMcpToolCallIdentity(toolCall), title).toEqual({
1260 server: "t3-code",
1261 tool: "delegate_task",
1262 });
1263 }
1264 });
1265β
1266 it("does not claim an agent's own tool that shares a T3 tool name", () => {
1267 const toolCall = toolCallFromUpdate({
1268 sessionUpdate: "tool_call",
1269 toolCallId: "own-delegate-1",
1270 kind: "execute",
1271 title: "delegate_task: 1 tasks: Run the terminal command 'echo child-result-42'",
1272 status: "pending",
1273 });
1274 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1275 });
1276β
1277 it("recovers T3 identity from goose _meta despite LLM-rewritten titles", () => {
1278 // goose titles change asynchronously; only _meta.goose.toolCall is stable.
1279 const toolCall = toolCallFromUpdate({
1280 sessionUpdate: "tool_call",
1281 toolCallId: "goose-1",
1282 title: "Checking on the delegated task",
1283 status: "in_progress",
1284 _meta: {
1285 goose: {
1286 toolCall: { toolName: "t3-code__task_status", extensionName: "t3-code" },
1287 messageId: "message-1",
1288 },
1289 },
1290 });
1291β
1292 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1293 server: "t3-code",
1294 tool: "task_status",
1295 });
1296 });
1297β
1298 it("recovers T3 identity from qwen serverId meta regardless of prefix format", () => {
1299 // qwen-code 0.21.12 serverId asserts MCP origin even when tool prefixes change.
1300 const toolCall = toolCallFromUpdate({
1301 sessionUpdate: "tool_call",
1302 toolCallId: "qwen-meta-1",
1303 kind: "other",
1304 title: "unrelated display title",
1305 status: "pending",
1306 _meta: { toolName: "mcp::t3-code::t3_thread_send", serverId: "t3-code", provenance: "mcp" },
1307 });
1308β
1309 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1310 server: "t3-code",
1311 tool: "t3_thread_send",
1312 });
1313 });
1314β
1315 it.each([
1316 { _meta: { claudeCode: { toolName: "mcp__weather__get_weather" } } },
1317 { _meta: { toolName: "mcp::weather::get_weather", serverId: "weather" } },
1318 ])("recovers external MCP identity from provider metadata", (metadata) => {
1319 const toolCall = toolCallFromUpdate({
1320 sessionUpdate: "tool_call",
1321 toolCallId: "weather-call",
1322 title: "Checking the forecast",
1323 status: "in_progress",
1324 ...metadata,
1325 });
1326 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1327 server: "weather",
1328 tool: "get_weather",
1329 });
1330 });
1331β
1332 it.each([
1333 { kind: "execute", toolName: "developer__shell", extensionName: "developer" },
1334 { kind: "edit", toolName: "developer__edit", extensionName: "developer" },
1335 { kind: "other", toolName: "weather__get_weather", extensionName: "weather" },
1336 ] as const)(
1337 "leaves goose $toolName unclassified so built-ins keep their projection",
1338 ({ kind, toolName, extensionName }) => {
1339 // goose tags built-in extensions exactly like user MCP servers.
1340 const toolCall = toolCallFromUpdate({
1341 sessionUpdate: "tool_call",
1342 toolCallId: "goose-builtin",
1343 kind,
1344 title: "developer: shell",
1345 status: "in_progress",
1346 _meta: { goose: { toolCall: { toolName, extensionName } } },
1347 });
1348 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1349 },
1350 );
1351β
1352 it("uses the asserted server instead of a misleading T3 title", () => {
1353 const toolCall = toolCallFromUpdate({
1354 sessionUpdate: "tool_call",
1355 toolCallId: "foreign-1",
1356 kind: "other",
1357 title: "t3-code_delegate_task",
1358 status: "pending",
1359 _meta: { toolName: "delegate_task", serverId: "other-orchestrator" },
1360 });
1361β
1362 expect(extractMcpToolCallIdentity(toolCall)).toEqual({
1363 server: "other-orchestrator",
1364 tool: "delegate_task",
1365 });
1366 });
1367β
1368 it("does not brand path-like or unknown-tool titles", () => {
1369 for (const title of ["t3-code/README.md", "t3-code_not_a_real_tool"]) {
1370 const toolCall = toolCallFromUpdate({
1371 sessionUpdate: "tool_call",
1372 toolCallId: "path-1",
1373 kind: "other",
1374 title,
1375 status: "pending",
1376 });
1377 expect(extractMcpToolCallIdentity(toolCall), title).toBeUndefined();
1378 }
1379 });
1380β
1381 it("leaves ordinary execute calls unidentified", () => {
1382 const toolCall = toolCallFromUpdate({
1383 sessionUpdate: "tool_call",
1384 toolCallId: "exec-2",
1385 kind: "execute",
1386 title: "cat package.json",
1387 status: "in_progress",
1388 rawInput: { command: "cat package.json" },
1389 });
1390β
1391 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1392 expect(
1393 extractMcpToolCallIdentity(toolCall, { embeddedTerminalCommands: ["bash -lc ls"] }),
1394 ).toBeUndefined();
1395 });
1396β
1397 it("does not treat generic raw server and tool fields as MCP provenance", () => {
1398 const toolCall = toolCallFromUpdate({
1399 sessionUpdate: "tool_call",
1400 toolCallId: "generic-1",
1401 kind: "other",
1402 title: "Deploy",
1403 status: "pending",
1404 rawInput: { server: "production", tool: "deploy" },
1405 });
1406β
1407 expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined();
1408 });
1409});
1410β
1411describe("embeddedTerminalIdsFromSessionUpdate", () => {
1412 it("collects terminal ids from tool_call content before the text rewrite", () => {
1413 expect(
1414 embeddedTerminalIdsFromSessionUpdate({
1415 sessionId: "session-1",
1416 update: {
1417 sessionUpdate: "tool_call_update",
1418 toolCallId: "call_1",
1419 status: "in_progress",
1420 content: [
1421 { type: "terminal", terminalId: "t3-term-9" },
1422 { type: "content", content: { type: "text", text: "noise" } },
1423 ],
1424 },
1425 }),
1426 ).toEqual({ toolCallId: "call_1", terminalIds: ["t3-term-9"] });
1427 expect(
1428 embeddedTerminalIdsFromSessionUpdate({
1429 sessionId: "session-1",
1430 update: {
1431 sessionUpdate: "tool_call",
1432 toolCallId: "call_2",
1433 title: "Tool",
1434 status: "pending",
1435 },
1436 }),
1437 ).toBeUndefined();
1438 });
1439});