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 permission request parsing compatible with loose extension payloads", () => {
343 const request = parsePermissionRequest({
344 sessionId: "session-1",
345 options: [
346 {
347 optionId: "allow-once",
348 name: "Allow once",
349 kind: "allow_once",
350 },
351 ],
352 toolCall: {
353 toolCallId: "tool-1",
354 title: "`cat package.json`",
355 kind: "execute",
356 status: "pending",
357 content: [
358 {
359 type: "content",
360 content: {
361 type: "text",
362 text: "Not in allowlist",
363 },
364 },
365 ],
366 },
367 });
368
369 expect(request).toMatchObject({
370 kind: "execute",
371 detail: "cat package.json",
372 toolCall: {
373 toolCallId: "tool-1",
374 kind: "execute",
375 status: "pending",
376 command: "cat package.json",
377 },
378 });
379 });
380
381 it("bounds an oversized cumulative tool_call_update content buffer to a tail window", () => {
382 // Mirrors Grok's ACP CLI resending the ENTIRE accumulated terminal output on every
383 // tool_call_update notification instead of a delta (see upstream #6556).
384 const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
385 "\n",
386 );
387 expect(hugeText.length).toBeGreaterThan(60_000);
388
389 const result = parseSessionUpdateEvent({
390 sessionId: "session-1",
391 update: {
392 // Real ACP `tool_call_update` deltas typically omit `title` (already established by
393 // the initial `tool_call`); that is also the shape that surfaces raw content as detail.
394 sessionUpdate: "tool_call_update",
395 toolCallId: "tool-1",
396 kind: "other",
397 status: "in_progress",
398 content: [{ type: "content", content: { type: "text", text: hugeText } }],
399 },
400 } satisfies EffectAcpSchema.SessionNotification);
401
402 expect(result.events).toHaveLength(1);
403 const event = result.events[0];
404 if (event?._tag !== "ToolCallUpdated") {
405 throw new Error("expected a ToolCallUpdated event");
406 }
407
408 expect(event.toolCall.detail).toBeDefined();
409 const detail = event.toolCall.detail!;
410 // 8000 chars of tail plus the truncation marker, regardless of input size.
411 expect(detail.length).toBe(8_028);
412 expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
413 expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
414
415 // The raw payload threaded through for logging/persistence must not smuggle the full
416 // cumulative buffer back in either.
417 const rawUpdate = (
418 event.rawPayload as {
419 readonly update: {
420 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
421 };
422 }
423 ).update;
424 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
425 expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
426 });
427
428 it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
429 let previous: AcpToolCallState | undefined;
430 let lastEmittedDetailLength: number | undefined;
431 let skippedSinceEmit = 0;
432 let emittedCount = 0;
433 let emittedBytes = 0;
434 let notificationBytes = 0;
435 let largestEmittedEventBytes = 0;
436 let finalDetail: string | undefined;
437 let cumulativeBuffer = "";
438
439 for (let i = 0; i < 1_000; i += 1) {
440 // Grok resends the FULL accumulated buffer, not a delta, on every redraw.
441 cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
442 const isLast = i === 999;
443
444 const notification = {
445 sessionId: "session-1",
446 update: {
447 sessionUpdate: "tool_call_update",
448 toolCallId: "tool-1",
449 kind: "other",
450 status: isLast ? "completed" : "in_progress",
451 content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
452 },
453 } satisfies EffectAcpSchema.SessionNotification;
454 notificationBytes += JSON.stringify(notification).length;
455
456 const { events } = parseSessionUpdateEvent(notification);
457
458 const event = events[0];
459 if (event?._tag !== "ToolCallUpdated") {
460 continue;
461 }
462
463 const merged = mergeToolCallState(previous, event.toolCall);
464 const decision = decideToolCallUpdateEmission({
465 previous,
466 next: merged,
467 lastEmittedDetailLength,
468 skippedSinceEmit,
469 });
470 previous = merged;
471 skippedSinceEmit = decision.skippedSinceEmit;
472 if (decision.emit) {
473 emittedCount += 1;
474 const eventBytes = JSON.stringify({
475 toolCall: merged,
476 rawPayload: event.rawPayload,
477 }).length;
478 emittedBytes += eventBytes;
479 largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
480 lastEmittedDetailLength = merged.detail?.length;
481 finalDetail = merged.detail;
482 }
483 }
484
485 // The flood as the CLI sends it: 1000 cumulative redraws, ~31.6 MB of JSON.
486 expect(notificationBytes).toBeGreaterThan(31_000_000);
487
488 // 1000 cumulative redraws collapse into a fixed, small number of runtime events...
489 expect(emittedCount).toBe(114);
490 // ...each individually bounded, no matter how long the tool call runs...
491 expect(largestEmittedEventBytes).toBeLessThan(25_000);
492 // ...so the whole flooding tool call costs ~2.5 MB of runtime events instead of ~31.6 MB.
493 expect(emittedBytes).toBeLessThan(2_600_000);
494 // ...while the FINAL state (forced by the completed status) still reflects the real,
495 // latest output rather than a stale coalesced value.
496 expect(finalDetail).toBeDefined();
497 expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
498 });
499
500 it("keeps non-text tool call content entries in order when bounding oversized text", () => {
501 const hugePrefix = "x".repeat(25_000);
502 const hugeTail = "y".repeat(25_000);
503 const { events } = parseSessionUpdateEvent({
504 sessionId: "session-1",
505 update: {
506 sessionUpdate: "tool_call_update",
507 toolCallId: "tool-1",
508 kind: "edit",
509 status: "in_progress",
510 content: [
511 { type: "content", content: { type: "text", text: hugePrefix } },
512 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
513 { type: "content", content: { type: "text", text: hugeTail } },
514 { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
515 { type: "content", content: { type: "text", text: " " } },
516 ],
517 },
518 } satisfies EffectAcpSchema.SessionNotification);
519
520 const event = events[0];
521 if (event?._tag !== "ToolCallUpdated") {
522 throw new Error("expected a ToolCallUpdated event");
523 }
524 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
525 expect(content).toHaveLength(3);
526 expect(content[0]).toEqual({
527 type: "diff",
528 path: "/repo/file.ts",
529 oldText: "before",
530 newText: "after",
531 });
532 const lastEntry = content[1];
533 if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
534 throw new Error("expected a bounded text entry");
535 }
536 expect(lastEntry.content.text.length).toBeLessThan(8_100);
537 expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
538 expect(content[2]).toEqual({
539 type: "diff",
540 path: "/repo/other.ts",
541 oldText: "old",
542 newText: "new",
543 });
544 });
545
546 it("keeps a retained tail on the original text entries around non-text content", () => {
547 const prefix = "a".repeat(4_000);
548 const suffix = "b".repeat(5_000);
549 const { events } = parseSessionUpdateEvent({
550 sessionId: "session-1",
551 update: {
552 sessionUpdate: "tool_call_update",
553 toolCallId: "tool-1",
554 kind: "edit",
555 status: "in_progress",
556 content: [
557 { type: "content", content: { type: "text", text: prefix } },
558 { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
559 { type: "content", content: { type: "text", text: suffix } },
560 ],
561 },
562 } satisfies EffectAcpSchema.SessionNotification);
563
564 const event = events[0];
565 if (event?._tag !== "ToolCallUpdated") {
566 throw new Error("expected a ToolCallUpdated event");
567 }
568 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
569 expect(content).toHaveLength(3);
570 const firstText = content[0];
571 if (firstText?.type !== "content" || firstText.content.type !== "text") {
572 throw new Error("expected a bounded prefix text entry");
573 }
574 expect(firstText.content.text.startsWith("[Earlier output truncated]")).toBe(true);
575 expect(firstText.content.text.endsWith("a".repeat(100))).toBe(true);
576 expect(content[1]).toEqual({
577 type: "diff",
578 path: "/repo/file.ts",
579 oldText: "before",
580 newText: "after",
581 });
582 expect(content[2]).toEqual({
583 type: "content",
584 content: { type: "text", text: suffix },
585 });
586 });
587
588 it("bounds oversized whitespace-only tool call content that has no trimmed text", () => {
589 // Whitespace-only entries are skipped when extracting display text (`chunks.length === 0`)
590 // and used to be returned unchanged, which let a redrawing terminal persist unbounded
591 // buffers on `toolCall.data.content` and `rawPayload`.
592 const hugeWhitespace = " \n\t".repeat(30_000);
593 expect(hugeWhitespace.length).toBeGreaterThan(60_000);
594
595 const { events } = parseSessionUpdateEvent({
596 sessionId: "session-1",
597 update: {
598 sessionUpdate: "tool_call_update",
599 toolCallId: "tool-1",
600 kind: "other",
601 status: "in_progress",
602 content: [{ type: "content", content: { type: "text", text: hugeWhitespace } }],
603 },
604 } satisfies EffectAcpSchema.SessionNotification);
605
606 const event = events[0];
607 if (event?._tag !== "ToolCallUpdated") {
608 throw new Error("expected a ToolCallUpdated event");
609 }
610
611 expect(event.toolCall.detail).toBeUndefined();
612 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
613 const textEntry = content[0];
614 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
615 throw new Error("expected a bounded text entry");
616 }
617 expect(textEntry.content.text.length).toBeLessThan(8_100);
618 expect(textEntry.content.text.startsWith("[Earlier output truncated]")).toBe(true);
619
620 const rawUpdate = (
621 event.rawPayload as {
622 readonly update: {
623 readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
624 };
625 }
626 ).update;
627 expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
628 expect(JSON.stringify(event).length).toBeLessThan(hugeWhitespace.length);
629 });
630
631 it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
632 const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
633 expect(padded.length).toBeGreaterThan(60_000);
634
635 const { events } = parseSessionUpdateEvent({
636 sessionId: "session-1",
637 update: {
638 sessionUpdate: "tool_call_update",
639 toolCallId: "tool-1",
640 kind: "other",
641 status: "in_progress",
642 content: [{ type: "content", content: { type: "text", text: padded } }],
643 },
644 } satisfies EffectAcpSchema.SessionNotification);
645
646 const event = events[0];
647 if (event?._tag !== "ToolCallUpdated") {
648 throw new Error("expected a ToolCallUpdated event");
649 }
650
651 expect(event.toolCall.detail).toBe("ok");
652 const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
653 const textEntry = content[0];
654 if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
655 throw new Error("expected a bounded text entry");
656 }
657 expect(textEntry.content.text).toBe("ok");
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).toBe("ok");
667 expect(JSON.stringify(event).length).toBeLessThan(padded.length);
668 });
669
670 describe("decideToolCallUpdateEmission", () => {
671 const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
672 ({
673 toolCallId: "tool-1",
674 title: "Grok Tool",
675 ...(status ? { status } : {}),
676 ...(detail ? { detail } : {}),
677 data: {},
678 }) satisfies AcpToolCallState;
679
680 it("emits the first in-progress tool_call even when it has no detail", () => {
681 expect(
682 decideToolCallUpdateEmission({
683 previous: undefined,
684 next: { toolCallId: "tool-1", title: "Grok Tool", status: "pending", data: {} },
685 lastEmittedDetailLength: undefined,
686 skippedSinceEmit: 0,
687 }),
688 ).toEqual({ emit: true, skippedSinceEmit: 0 });
689 });
690
691 it("always emits terminal (completed/failed) status updates regardless of growth", () => {
692 expect(
693 decideToolCallUpdateEmission({
694 previous: toolCall("same", "inProgress"),
695 next: toolCall("same", "completed"),
696 lastEmittedDetailLength: 4,
697 skippedSinceEmit: 0,
698 }),
699 ).toEqual({ emit: true, skippedSinceEmit: 0 });
700
701 expect(
702 decideToolCallUpdateEmission({
703 previous: toolCall("same", "inProgress"),
704 next: toolCall("same", "failed"),
705 lastEmittedDetailLength: 4,
706 skippedSinceEmit: 3,
707 }),
708 ).toEqual({ emit: true, skippedSinceEmit: 0 });
709 });
710
711 it("skips updates whose bounded detail did not change", () => {
712 const previous = toolCall("frame 1", "inProgress");
713 expect(
714 decideToolCallUpdateEmission({
715 previous,
716 next: previous,
717 lastEmittedDetailLength: 7,
718 skippedSinceEmit: 0,
719 }),
720 ).toEqual({ emit: false, skippedSinceEmit: 0 });
721 });
722
723 it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
724 const commandCall = (stdout: string): AcpToolCallState => ({
725 toolCallId: "tool-1",
726 title: "Ran command",
727 status: "inProgress",
728 command: "ls",
729 detail: "ls",
730 data: {
731 command: "ls",
732 content: [{ type: "content", content: { type: "text", text: stdout } }],
733 },
734 });
735
736 let previous: AcpToolCallState | undefined;
737 let lastEmittedDetailLength: number | undefined;
738 let skippedSinceEmit = 0;
739 const emissions: Array<boolean> = [];
740
741 for (let i = 1; i <= 12; i += 1) {
742 const next = commandCall("x".repeat(i));
743 const decision = decideToolCallUpdateEmission({
744 previous,
745 next,
746 lastEmittedDetailLength,
747 skippedSinceEmit,
748 });
749 emissions.push(decision.emit);
750 skippedSinceEmit = decision.skippedSinceEmit;
751 if (decision.emit) {
752 lastEmittedDetailLength = toolCallProgressLength(next);
753 }
754 previous = next;
755 }
756
757 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
758 expect(emittedIndices).toEqual([1, 11]);
759 });
760
761 it("emits pending to inProgress status changes even when detail and output are unchanged", () => {
762 expect(
763 decideToolCallUpdateEmission({
764 previous: toolCall("same", "pending"),
765 next: toolCall("same", "inProgress"),
766 lastEmittedDetailLength: 4,
767 skippedSinceEmit: 0,
768 }),
769 ).toEqual({ emit: true, skippedSinceEmit: 0 });
770 });
771
772 it("emits immediately when the title changes, even with no growth", () => {
773 const decision = decideToolCallUpdateEmission({
774 previous: { toolCallId: "tool-1", title: "Reading file", detail: "x", data: {} },
775 next: { toolCallId: "tool-1", title: "Ran command", detail: "x", data: {} },
776 lastEmittedDetailLength: 1,
777 skippedSinceEmit: 0,
778 });
779 expect(decision).toEqual({ emit: true, skippedSinceEmit: 0 });
780 });
781
782 it("coalesces small deltas but forces an emission after the coalesce limit", () => {
783 let lastEmittedDetailLength: number | undefined = 0;
784 let skippedSinceEmit = 0;
785 const emissions: Array<boolean> = [];
786 let previous: AcpToolCallState | undefined;
787
788 for (let i = 1; i <= 12; i += 1) {
789 // Grows by 1 char per update — well under the 256-char growth threshold, so this
790 // exercises the coalesce-count fallback rather than the growth-based trigger.
791 const next = toolCall("x".repeat(i), "inProgress");
792 const decision = decideToolCallUpdateEmission({
793 previous,
794 next,
795 lastEmittedDetailLength,
796 skippedSinceEmit,
797 });
798 emissions.push(decision.emit);
799 skippedSinceEmit = decision.skippedSinceEmit;
800 if (decision.emit) {
801 lastEmittedDetailLength = next.detail?.length;
802 }
803 previous = next;
804 }
805
806 // First update always emits (no previous state yet); after that, small per-update
807 // growth should be coalesced until the coalesce limit forces a periodic emission.
808 const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
809 expect(emittedIndices).toEqual([1, 11]);
810 });
811
812 it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
813 let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
814 const lastEmittedDetailLength = previous.detail?.length;
815 let skippedSinceEmit = 0;
816
817 for (const detail of ["frame-b", "frame-c"]) {
818 const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
819 const decision = decideToolCallUpdateEmission({
820 previous,
821 next,
822 lastEmittedDetailLength,
823 skippedSinceEmit,
824 });
825 expect(decision.emit).toBe(false);
826 skippedSinceEmit = decision.skippedSinceEmit;
827 previous = next;
828 }
829
830 const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
831 expect(completed.detail).toBe("frame-c");
832 expect(
833 decideToolCallUpdateEmission({
834 previous,
835 next: completed,
836 lastEmittedDetailLength,
837 skippedSinceEmit,
838 }),
839 ).toEqual({ emit: true, skippedSinceEmit: 0 });
840 });
841 });
842});