Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import type * as EffectAcpSchema from "effect-acp/schema";
4
5import {
6 decideToolCallUpdateEmission,
7 extractModelConfigId,
8 mergeToolCallState,
9 parsePermissionRequest,
10 parseSessionModeState,
11 parseSessionUpdateEvent,
12 sessionUpdateIsReplay,
13 syntheticLoadSessionResponseFromInitialize,
14 toolCallProgressLength,
15 type AcpToolCallState,
16} from "./AcpRuntimeModel.ts";
17
18describe("AcpRuntimeModel", () => {
19 it("parses session mode state from typed ACP session setup responses", () => {
20 const modeState = parseSessionModeState({
21 sessionId: "session-1",
22 modes: {
23 currentModeId: " code ",
24 availableModes: [
25 { id: " ask ", name: " Ask ", description: " Request approval " },
26 { id: " code ", name: " Code " },
27 ],
28 },
29 configOptions: [],
30 } satisfies EffectAcpSchema.NewSessionResponse);
31
32 expect(modeState).toEqual({
33 currentModeId: "code",
34 availableModes: [
35 { id: "ask", name: "Ask", description: "Request approval" },
36 { id: "code", name: "Code" },
37 ],
38 });
39 });
40
41 it("extracts the model config id from typed ACP config options", () => {
42 const modelConfigId = extractModelConfigId({
43 sessionId: "session-1",
44 configOptions: [
45 {
46 id: "approval",
47 name: "Approval Mode",
48 category: "permission",
49 type: "select",
50 currentValue: "ask",
51 options: [{ value: "ask", name: "Ask" }],
52 },
53 {
54 id: "model",
55 name: "Model",
56 category: "model",
57 type: "select",
58 currentValue: "default",
59 options: [{ value: "default", name: "Auto" }],
60 },
61 ],
62 } satisfies EffectAcpSchema.NewSessionResponse);
63
64 expect(modelConfigId).toBe("model");
65 });
66
67 it("detects Grok session replay updates from _meta.isReplay", () => {
68 expect(
69 sessionUpdateIsReplay({
70 _meta: { isReplay: true },
71 sessionId: "session-1",
72 update: {
73 sessionUpdate: "agent_message_chunk",
74 content: { type: "text", text: "replayed" },
75 },
76 } satisfies EffectAcpSchema.SessionNotification),
77 ).toBe(true);
78 expect(
79 sessionUpdateIsReplay({
80 sessionId: "session-1",
81 update: {
82 sessionUpdate: "agent_message_chunk",
83 content: { type: "text", text: "live" },
84 },
85 } satisfies EffectAcpSchema.SessionNotification),
86 ).toBe(false);
87 });
88
89 it("builds a synthetic load response from initialize model state", () => {
90 const response = syntheticLoadSessionResponseFromInitialize({
91 protocolVersion: 1,
92 _meta: {
93 modelState: {
94 currentModelId: "grok-build",
95 availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
96 },
97 },
98 } satisfies EffectAcpSchema.InitializeResponse);
99
100 expect(response.models?.currentModelId).toBe("grok-build");
101 expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
102 });
103
104 it("accepts initialize model descriptions with null", () => {
105 const response = syntheticLoadSessionResponseFromInitialize({
106 protocolVersion: 1,
107 _meta: {
108 modelState: {
109 currentModelId: "grok-build",
110 availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
111 },
112 },
113 } satisfies EffectAcpSchema.InitializeResponse);
114
115 expect(response.models?.availableModels[0]?.description).toBeNull();
116 });
117
118 it("ignores malformed initialize model state in synthetic load responses", () => {
119 const response = syntheticLoadSessionResponseFromInitialize({
120 protocolVersion: 1,
121 _meta: {
122 modelState: {
123 currentModelId: "grok-build",
124 availableModels: [null],
125 },
126 modeState: {
127 currentModeId: "code",
128 availableModes: [{ id: "code", name: 12 }],
129 },
130 },
131 } as EffectAcpSchema.InitializeResponse);
132
133 expect(response.models).toBeUndefined();
134 expect(response.modes).toBeUndefined();
135 expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
136 });
137
138 it("builds a synthetic load response with initialize mode state", () => {
139 const response = syntheticLoadSessionResponseFromInitialize({
140 protocolVersion: 1,
141 _meta: {
142 modeState: {
143 currentModeId: "code",
144 availableModes: [
145 { id: "ask", name: "Ask" },
146 { id: "code", name: "Code" },
147 ],
148 },
149 },
150 } satisfies EffectAcpSchema.InitializeResponse);
151
152 expect(response.modes?.currentModeId).toBe("code");
153 expect(response.modes?.availableModes).toHaveLength(2);
154 });
155
156 it("projects typed ACP tool call updates into runtime events", () => {
157 const created = parseSessionUpdateEvent({
158 sessionId: "session-1",
159 update: {
160 sessionUpdate: "tool_call",
161 toolCallId: "tool-1",
162 title: "Terminal",
163 kind: "execute",
164 status: "pending",
165 rawInput: {
166 executable: "bun",
167 args: ["run", "typecheck"],
168 },
169 content: [
170 {
171 type: "content",
172 content: {
173 type: "text",
174 text: "Running checks",
175 },
176 },
177 ],
178 },
179 } satisfies EffectAcpSchema.SessionNotification);
180
181 expect(created.events).toEqual([
182 {
183 _tag: "ToolCallUpdated",
184 toolCall: {
185 toolCallId: "tool-1",
186 kind: "execute",
187 title: "Ran command",
188 status: "pending",
189 command: "bun run typecheck",
190 detail: "bun run typecheck",
191 data: {
192 toolCallId: "tool-1",
193 kind: "execute",
194 command: "bun run typecheck",
195 rawInput: {
196 executable: "bun",
197 args: ["run", "typecheck"],
198 },
199 content: [
200 {
201 type: "content",
202 content: {
203 type: "text",
204 text: "Running checks",
205 },
206 },
207 ],
208 },
209 },
210 rawPayload: {
211 sessionId: "session-1",
212 update: {
213 sessionUpdate: "tool_call",
214 toolCallId: "tool-1",
215 title: "Terminal",
216 kind: "execute",
217 status: "pending",
218 rawInput: {
219 executable: "bun",
220 args: ["run", "typecheck"],
221 },
222 content: [
223 {
224 type: "content",
225 content: {
226 type: "text",
227 text: "Running checks",
228 },
229 },
230 ],
231 },
232 },
233 },
234 ]);
235
236 const updated = parseSessionUpdateEvent({
237 sessionId: "session-1",
238 update: {
239 sessionUpdate: "tool_call_update",
240 toolCallId: "tool-1",
241 status: "completed",
242 rawOutput: { exitCode: 0 },
243 },
244 } satisfies EffectAcpSchema.SessionNotification);
245
246 expect(updated.events).toHaveLength(1);
247 expect(updated.events[0]?._tag).toBe("ToolCallUpdated");
248 const createdEvent = created.events[0];
249 const updatedEvent = updated.events[0];
250 if (createdEvent?._tag === "ToolCallUpdated" && updatedEvent?._tag === "ToolCallUpdated") {
251 expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
252 toolCallId: "tool-1",
253 status: "completed",
254 title: "Ran command",
255 detail: "bun run typecheck",
256 command: "bun run typecheck",
257 });
258 }
259 });
260
261 it("trims padded current mode updates before emitting a mode change", () => {
262 const result = parseSessionUpdateEvent({
263 sessionId: "session-1",
264 update: {
265 sessionUpdate: "current_mode_update",
266 currentModeId: " code ",
267 },
268 } satisfies EffectAcpSchema.SessionNotification);
269
270 expect(result.modeId).toBe("code");
271 expect(result.events).toEqual([
272 {
273 _tag: "ModeChanged",
274 modeId: "code",
275 },
276 ]);
277 });
278
279 it("projects typed ACP plan and content updates", () => {
280 const planResult = parseSessionUpdateEvent({
281 sessionId: "session-1",
282 update: {
283 sessionUpdate: "plan",
284 entries: [
285 { content: " Inspect state ", priority: "high", status: "completed" },
286 { content: "", priority: "medium", status: "in_progress" },
287 ],
288 },
289 } satisfies EffectAcpSchema.SessionNotification);
290
291 expect(planResult.events).toEqual([
292 {
293 _tag: "PlanUpdated",
294 payload: {
295 plan: [
296 { step: "Inspect state", status: "completed" },
297 { step: "Step 2", status: "inProgress" },
298 ],
299 },
300 rawPayload: {
301 sessionId: "session-1",
302 update: {
303 sessionUpdate: "plan",
304 entries: [
305 { content: " Inspect state ", priority: "high", status: "completed" },
306 { content: "", priority: "medium", status: "in_progress" },
307 ],
308 },
309 },
310 },
311 ]);
312
313 const contentResult = parseSessionUpdateEvent({
314 sessionId: "session-1",
315 update: {
316 sessionUpdate: "agent_message_chunk",
317 content: {
318 type: "text",
319 text: "hello from acp",
320 },
321 },
322 } satisfies EffectAcpSchema.SessionNotification);
323
324 expect(contentResult.events).toEqual([
325 {
326 _tag: "ContentDelta",
327 text: "hello from acp",
328 rawPayload: {
329 sessionId: "session-1",
330 update: {
331 sessionUpdate: "agent_message_chunk",
332 content: {
333 type: "text",
334 text: "hello from acp",
335 },
336 },
337 },
338 },
339 ]);
340 });
341
342 it("keeps thought chunks separate from assistant text", () => {
343 const notification = {
344 sessionId: "session-1",
345 update: {
346 sessionUpdate: "agent_thought_chunk",
347 content: { type: "text", text: "Inspect the current implementation first." },
348 },
349 } satisfies EffectAcpSchema.SessionNotification;
350
351 expect(parseSessionUpdateEvent(notification).events).toEqual([
352 {
353 _tag: "ThoughtDelta",
354 text: "Inspect the current implementation first.",
355 rawPayload: notification,
356 },
357 ]);
358 });
359
360 it("preserves native command inputs and empty command lists", () => {
361 const availableCommands = [
362 { name: "plan", description: "Plan a task", input: { hint: "task" } },
363 { name: "logout", description: "Sign out" },
364 ] satisfies ReadonlyArray<EffectAcpSchema.AvailableCommand>;
365
366 for (const commands of [availableCommands, []]) {
367 const notification = {
368 sessionId: "session-1",
369 update: { sessionUpdate: "available_commands_update", availableCommands: commands },
370 } satisfies EffectAcpSchema.SessionNotification;
371 expect(parseSessionUpdateEvent(notification).events).toEqual([
372 {
373 _tag: "AvailableCommandsUpdated",
374 availableCommands: commands,
375 rawPayload: notification,
376 },
377 ]);
378 }
379 });
380
381 it("keeps permission request parsing compatible with loose extension payloads", () => {
382 const request = parsePermissionRequest({
383 sessionId: "session-1",
384 options: [
385 {
386 optionId: "allow-once",
387 name: "Allow once",
388 kind: "allow_once",
389 },
390 ],
391 toolCall: {
392 toolCallId: "tool-1",
393 title: "`cat package.json`",
394 kind: "execute",
395 status: "pending",
396 content: [
397 {
398 type: "content",
399 content: {
400 type: "text",
401 text: "Not in allowlist",
402 },
403 },
404 ],
405 },
406 });
407
408 expect(request).toMatchObject({
409 kind: "execute",
410 detail: "cat package.json",
411 toolCall: {
412 toolCallId: "tool-1",
413 kind: "execute",
414 status: "pending",
415 command: "cat package.json",
416 },
417 });
418 });
419
420 it("bounds an oversized cumulative tool_call_update content buffer to a tail window", () => {
421 // Mirrors Grok's ACP CLI resending the ENTIRE accumulated terminal output on every
422 // tool_call_update notification instead of a delta (see upstream #6556).
423 const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
424 "\n",
425 );
426 expect(hugeText.length).toBeGreaterThan(60_000);
427
428 const result = parseSessionUpdateEvent({
429 sessionId: "session-1",
430 update: {
431 // Real ACP `tool_call_update` deltas typically omit `title` (already established by
432 // the initial `tool_call`); that is also the shape that surfaces raw content as detail.
433 sessionUpdate: "tool_call_update",
434 toolCallId: "tool-1",
435 kind: "other",
436 status: "in_progress",
437 content: [{ type: "content", content: { type: "text", text: hugeText } }],
438 },
439 } satisfies EffectAcpSchema.SessionNotification);
440
441 expect(result.events).toHaveLength(1);
442 const event = result.events[0];
443 if (event?._tag !== "ToolCallUpdated") {
444 throw new Error("expected a ToolCallUpdated event");
445 }
446
447 expect(event.toolCall.detail).toBeDefined();
448 const detail = event.toolCall.detail!;
449 // 8000 chars of tail plus the truncation marker, regardless of input size.
450 expect(detail.length).toBe(8_028);
451 expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
452 expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
453
454 // The raw payload threaded through for logging/persistence must not smuggle the full
455 // cumulative buffer back in either.
456 const rawUpdate = (
457 event.rawPayload as {
458 readonly update: {
459 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
460 };
461 }
462 ).update;
463 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
464 expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
465 });
466
467 it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
468 let previous: AcpToolCallState | undefined;
469 let lastEmittedDetailLength: number | undefined;
470 let skippedSinceEmit = 0;
471 let emittedCount = 0;
472 let emittedBytes = 0;
473 let notificationBytes = 0;
474 let largestEmittedEventBytes = 0;
475 let finalDetail: string | undefined;
476 let cumulativeBuffer = "";
477
478 for (let i = 0; i < 1_000; i += 1) {
479 // Grok resends the FULL accumulated buffer, not a delta, on every redraw.
480 cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
481 const isLast = i === 999;
482
483 const notification = {
484 sessionId: "session-1",
485 update: {
486 sessionUpdate: "tool_call_update",
487 toolCallId: "tool-1",
488 kind: "other",
489 status: isLast ? "completed" : "in_progress",
490 content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
491 },
492 } satisfies EffectAcpSchema.SessionNotification;
493 notificationBytes += JSON.stringify(notification).length;
494
495 const { events } = parseSessionUpdateEvent(notification);
496
497 const event = events[0];
498 if (event?._tag !== "ToolCallUpdated") {
499 continue;
500 }
501
502 const merged = mergeToolCallState(previous, event.toolCall);
503 const decision = decideToolCallUpdateEmission({
504 previous,
505 next: merged,
506 lastEmittedDetailLength,
507 skippedSinceEmit,
508 });
509 previous = merged;
510 skippedSinceEmit = decision.skippedSinceEmit;
511 if (decision.emit) {
512 emittedCount += 1;
513 const eventBytes = JSON.stringify({
514 toolCall: merged,
515 rawPayload: event.rawPayload,
516 }).length;
517 emittedBytes += eventBytes;
518 largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
519 lastEmittedDetailLength = merged.detail?.length;
520 finalDetail = merged.detail;
521 }
522 }
523
524 // The flood as the CLI sends it: 1000 cumulative redraws, ~31.6 MB of JSON.
525 expect(notificationBytes).toBeGreaterThan(31_000_000);
526
527 // 1000 cumulative redraws collapse into a fixed, small number of runtime events...
528 expect(emittedCount).toBe(114);
529 // ...each individually bounded, no matter how long the tool call runs...
530 expect(largestEmittedEventBytes).toBeLessThan(25_000);
531 // ...so the whole flooding tool call costs ~2.5 MB of runtime events instead of ~31.6 MB.
532 expect(emittedBytes).toBeLessThan(2_600_000);
533 // ...while the FINAL state (forced by the completed status) still reflects the real,
534 // latest output rather than a stale coalesced value.
535 expect(finalDetail).toBeDefined();
536 expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
537 });
538
539 it("keeps non-text tool call content entries in order when bounding oversized text", () => {
540 const hugePrefix = "x".repeat(25_000);
541 const hugeTail = "y".repeat(25_000);
542 const { events } = parseSessionUpdateEvent({
543 sessionId: "session-1",
544 update: {
545 sessionUpdate: "tool_call_update",
546 toolCallId: "tool-1",
547 kind: "edit",
548 status: "in_progress",
549 content: [
550 { type: "content", content: { type: "text", text: hugePrefix } },
551 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
552 { type: "content", content: { type: "text", text: hugeTail } },
553 { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
554 { type: "content", content: { type: "text", text: " " } },
555 ],
556 },
557 } satisfies EffectAcpSchema.SessionNotification);
558
559 const event = events[0];
560 if (event?._tag !== "ToolCallUpdated") {
561 throw new Error("expected a ToolCallUpdated event");
562 }
563 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
564 expect(content).toHaveLength(3);
565 expect(content[0]).toEqual({
566 type: "diff",
567 path: "/repo/file.ts",
568 oldText: "before",
569 newText: "after",
570 });
571 const lastEntry = content[1];
572 if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
573 throw new Error("expected a bounded text entry");
574 }
575 expect(lastEntry.content.text.length).toBeLessThan(8_100);
576 expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
577 expect(content[2]).toEqual({
578 type: "diff",
579 path: "/repo/other.ts",
580 oldText: "old",
581 newText: "new",
582 });
583 });
584
585 it("keeps a retained tail on the original text entries around non-text content", () => {
586 const prefix = "a".repeat(4_000);
587 const suffix = "b".repeat(5_000);
588 const { events } = parseSessionUpdateEvent({
589 sessionId: "session-1",
590 update: {
591 sessionUpdate: "tool_call_update",
592 toolCallId: "tool-1",
593 kind: "edit",
594 status: "in_progress",
595 content: [
596 { type: "content", content: { type: "text", text: prefix } },
597 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
598 { type: "content", content: { type: "text", text: suffix } },
599 ],
600 },
601 } satisfies EffectAcpSchema.SessionNotification);
602
603 const event = events[0];
604 if (event?._tag !== "ToolCallUpdated") {
605 throw new Error("expected a ToolCallUpdated event");
606 }
607 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
608 expect(content).toHaveLength(3);
609 const firstText = content[0];
610 if (firstText?.type !== "content" || firstText.content.type !== "text") {
611 throw new Error("expected a bounded prefix text entry");
612 }
613 expect(firstText.content.text.startsWith("[Earlier output truncated]")).toBe(true);
614 expect(firstText.content.text.endsWith("a".repeat(100))).toBe(true);
615 expect(content[1]).toEqual({
616 type: "diff",
617 path: "/repo/file.ts",
618 oldText: "before",
619 newText: "after",
620 });
621 expect(content[2]).toEqual({
622 type: "content",
623 content: { type: "text", text: suffix },
624 });
625 });
626
627 it("bounds oversized whitespace-only tool call content that has no trimmed text", () => {
628 // Whitespace-only entries are skipped when extracting display text (`chunks.length === 0`)
629 // and used to be returned unchanged, which let a redrawing terminal persist unbounded
630 // buffers on `toolCall.data.content` and `rawPayload`.
631 const hugeWhitespace = " \n\t".repeat(30_000);
632 expect(hugeWhitespace.length).toBeGreaterThan(60_000);
633
634 const { events } = parseSessionUpdateEvent({
635 sessionId: "session-1",
636 update: {
637 sessionUpdate: "tool_call_update",
638 toolCallId: "tool-1",
639 kind: "other",
640 status: "in_progress",
641 content: [{ type: "content", content: { type: "text", text: hugeWhitespace } }],
642 },
643 } satisfies EffectAcpSchema.SessionNotification);
644
645 const event = events[0];
646 if (event?._tag !== "ToolCallUpdated") {
647 throw new Error("expected a ToolCallUpdated event");
648 }
649
650 expect(event.toolCall.detail).toBeUndefined();
651 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
652 const textEntry = content[0];
653 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
654 throw new Error("expected a bounded text entry");
655 }
656 expect(textEntry.content.text.length).toBeLessThan(8_100);
657 expect(textEntry.content.text.startsWith("[Earlier output truncated]")).toBe(true);
658
659 const rawUpdate = (
660 event.rawPayload as {
661 readonly update: {
662 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
663 };
664 }
665 ).update;
666 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
667 expect(JSON.stringify(event).length).toBeLessThan(hugeWhitespace.length);
668 });
669
670 it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
671 const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
672 expect(padded.length).toBeGreaterThan(60_000);
673
674 const { events } = parseSessionUpdateEvent({
675 sessionId: "session-1",
676 update: {
677 sessionUpdate: "tool_call_update",
678 toolCallId: "tool-1",
679 kind: "other",
680 status: "in_progress",
681 content: [{ type: "content", content: { type: "text", text: padded } }],
682 },
683 } satisfies EffectAcpSchema.SessionNotification);
684
685 const event = events[0];
686 if (event?._tag !== "ToolCallUpdated") {
687 throw new Error("expected a ToolCallUpdated event");
688 }
689
690 expect(event.toolCall.detail).toBe("ok");
691 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
692 const textEntry = content[0];
693 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
694 throw new Error("expected a bounded text entry");
695 }
696 expect(textEntry.content.text).toBe("ok");
697
698 const rawUpdate = (
699 event.rawPayload as {
700 readonly update: {
701 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
702 };
703 }
704 ).update;
705 expect(rawUpdate.content[0]?.content.text).toBe("ok");
706 expect(JSON.stringify(event).length).toBeLessThan(padded.length);
707 });
708
709 describe("decideToolCallUpdateEmission", () => {
710 const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
711 ({
712 toolCallId: "tool-1",
713 title: "Grok Tool",
714 ...(status ? { status } : {}),
715 ...(detail ? { detail } : {}),
716 data: {},
717 }) satisfies AcpToolCallState;
718
719 it("emits the first in-progress tool_call even when it has no detail", () => {
720 expect(
721 decideToolCallUpdateEmission({
722 previous: undefined,
723 next: { toolCallId: "tool-1", title: "Grok Tool", status: "pending", data: {} },
724 lastEmittedDetailLength: undefined,
725 skippedSinceEmit: 0,
726 }),
727 ).toEqual({ emit: true, skippedSinceEmit: 0 });
728 });
729
730 it("always emits terminal (completed/failed) status updates regardless of growth", () => {
731 expect(
732 decideToolCallUpdateEmission({
733 previous: toolCall("same", "inProgress"),
734 next: toolCall("same", "completed"),
735 lastEmittedDetailLength: 4,
736 skippedSinceEmit: 0,
737 }),
738 ).toEqual({ emit: true, skippedSinceEmit: 0 });
739
740 expect(
741 decideToolCallUpdateEmission({
742 previous: toolCall("same", "inProgress"),
743 next: toolCall("same", "failed"),
744 lastEmittedDetailLength: 4,
745 skippedSinceEmit: 3,
746 }),
747 ).toEqual({ emit: true, skippedSinceEmit: 0 });
748 });
749
750 it("skips updates whose bounded detail did not change", () => {
751 const previous = toolCall("frame 1", "inProgress");
752 expect(
753 decideToolCallUpdateEmission({
754 previous,
755 next: previous,
756 lastEmittedDetailLength: 7,
757 skippedSinceEmit: 0,
758 }),
759 ).toEqual({ emit: false, skippedSinceEmit: 0 });
760 });
761
762 it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
763 const commandCall = (stdout: string): AcpToolCallState => ({
764 toolCallId: "tool-1",
765 title: "Ran command",
766 status: "inProgress",
767 command: "ls",
768 detail: "ls",
769 data: {
770 command: "ls",
771 content: [{ type: "content", content: { type: "text", text: stdout } }],
772 },
773 });
774
775 let previous: AcpToolCallState | undefined;
776 let lastEmittedDetailLength: number | undefined;
777 let skippedSinceEmit = 0;
778 const emissions: Array<boolean> = [];
779
780 for (let i = 1; i <= 12; i += 1) {
781 const next = commandCall("x".repeat(i));
782 const decision = decideToolCallUpdateEmission({
783 previous,
784 next,
785 lastEmittedDetailLength,
786 skippedSinceEmit,
787 });
788 emissions.push(decision.emit);
789 skippedSinceEmit = decision.skippedSinceEmit;
790 if (decision.emit) {
791 lastEmittedDetailLength = toolCallProgressLength(next);
792 }
793 previous = next;
794 }
795
796 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
797 expect(emittedIndices).toEqual([1, 11]);
798 });
799
800 it("emits pending to inProgress status changes even when detail and output are unchanged", () => {
801 expect(
802 decideToolCallUpdateEmission({
803 previous: toolCall("same", "pending"),
804 next: toolCall("same", "inProgress"),
805 lastEmittedDetailLength: 4,
806 skippedSinceEmit: 0,
807 }),
808 ).toEqual({ emit: true, skippedSinceEmit: 0 });
809 });
810
811 it("emits immediately when the title changes, even with no growth", () => {
812 const decision = decideToolCallUpdateEmission({
813 previous: { toolCallId: "tool-1", title: "Reading file", detail: "x", data: {} },
814 next: { toolCallId: "tool-1", title: "Ran command", detail: "x", data: {} },
815 lastEmittedDetailLength: 1,
816 skippedSinceEmit: 0,
817 });
818 expect(decision).toEqual({ emit: true, skippedSinceEmit: 0 });
819 });
820
821 it("coalesces small deltas but forces an emission after the coalesce limit", () => {
822 let lastEmittedDetailLength: number | undefined = 0;
823 let skippedSinceEmit = 0;
824 const emissions: Array<boolean> = [];
825 let previous: AcpToolCallState | undefined;
826
827 for (let i = 1; i <= 12; i += 1) {
828 // Grows by 1 char per update — well under the 256-char growth threshold, so this
829 // exercises the coalesce-count fallback rather than the growth-based trigger.
830 const next = toolCall("x".repeat(i), "inProgress");
831 const decision = decideToolCallUpdateEmission({
832 previous,
833 next,
834 lastEmittedDetailLength,
835 skippedSinceEmit,
836 });
837 emissions.push(decision.emit);
838 skippedSinceEmit = decision.skippedSinceEmit;
839 if (decision.emit) {
840 lastEmittedDetailLength = next.detail?.length;
841 }
842 previous = next;
843 }
844
845 // First update always emits (no previous state yet); after that, small per-update
846 // growth should be coalesced until the coalesce limit forces a periodic emission.
847 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
848 expect(emittedIndices).toEqual([1, 11]);
849 });
850
851 it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
852 let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
853 const lastEmittedDetailLength = previous.detail?.length;
854 let skippedSinceEmit = 0;
855
856 for (const detail of ["frame-b", "frame-c"]) {
857 const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
858 const decision = decideToolCallUpdateEmission({
859 previous,
860 next,
861 lastEmittedDetailLength,
862 skippedSinceEmit,
863 });
864 expect(decision.emit).toBe(false);
865 skippedSinceEmit = decision.skippedSinceEmit;
866 previous = next;
867 }
868
869 const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
870 expect(completed.detail).toBe("frame-c");
871 expect(
872 decideToolCallUpdateEmission({
873 previous,
874 next: completed,
875 lastEmittedDetailLength,
876 skippedSinceEmit,
877 }),
878 ).toEqual({ emit: true, skippedSinceEmit: 0 });
879 });
880 });
881});