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

runtimeModel.test.ts

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