Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(grok): bound cumulative tool output updates (#7279)

Lars Nieuwenhuisafc8342801d4
diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts
index 7682c5f5f..dc0dd6e04 100644
--- a/apps/server/src/provider/acp/AcpRuntimeModel.test.ts
+++ b/apps/server/src/provider/acp/AcpRuntimeModel.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import type * as EffectAcpSchema from "effect-acp/schema";
import {
+ decideToolCallUpdateEmission,
extractModelConfigId,
mergeToolCallState,
parsePermissionRequest,
@@ -10,6 +11,7 @@ import {
parseSessionUpdateEvent,
sessionUpdateIsReplay,
syntheticLoadSessionResponseFromInitialize,
+ type AcpToolCallState,
} from "./AcpRuntimeModel.ts";
describe("AcpRuntimeModel", () => {
@@ -374,4 +376,281 @@ describe("AcpRuntimeModel", () => {
},
});
});
+
+ it("bounds an oversized cumulative tool_call_update content buffer to a tail window", () => {
+ // Mirrors Grok's ACP CLI resending the ENTIRE accumulated terminal output on every
+ // tool_call_update notification instead of a delta (see upstream #6556).
+ const hugeText = Array.from({ length: 2_000 }, (_, i) => `line ${i}: ${"x".repeat(50)}`).join(
+ "\n",
+ );
+ expect(hugeText.length).toBeGreaterThan(60_000);
+
+ const result = parseSessionUpdateEvent({
+ sessionId: "session-1",
+ update: {
+ // Real ACP `tool_call_update` deltas typically omit `title` (already established by
+ // the initial `tool_call`); that is also the shape that surfaces raw content as detail.
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-1",
+ kind: "other",
+ status: "in_progress",
+ content: [{ type: "content", content: { type: "text", text: hugeText } }],
+ },
+ } satisfies EffectAcpSchema.SessionNotification);
+
+ expect(result.events).toHaveLength(1);
+ const event = result.events[0];
+ if (event?._tag !== "ToolCallUpdated") {
+ throw new Error("expected a ToolCallUpdated event");
+ }
+
+ expect(event.toolCall.detail).toBeDefined();
+ const detail = event.toolCall.detail!;
+ // 8000 chars of tail plus the truncation marker, regardless of input size.
+ expect(detail.length).toBe(8_028);
+ expect(detail.startsWith("[Earlier output truncated]")).toBe(true);
+ expect(detail.endsWith(hugeText.slice(-100))).toBe(true);
+
+ // The raw payload threaded through for logging/persistence must not smuggle the full
+ // cumulative buffer back in either.
+ const rawUpdate = (
+ event.rawPayload as {
+ readonly update: {
+ readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
+ };
+ }
+ ).update;
+ expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
+ expect(JSON.stringify(event).length).toBeLessThan(hugeText.length);
+ });
+
+ it("coalesces 1000 rapid cumulative tool_call_update notifications for a redrawing progress bar", () => {
+ let previous: AcpToolCallState | undefined;
+ let lastEmittedDetailLength: number | undefined;
+ let skippedSinceEmit = 0;
+ let emittedCount = 0;
+ let emittedBytes = 0;
+ let notificationBytes = 0;
+ let largestEmittedEventBytes = 0;
+ let finalDetail: string | undefined;
+ let cumulativeBuffer = "";
+
+ for (let i = 0; i < 1_000; i += 1) {
+ // Grok resends the FULL accumulated buffer, not a delta, on every redraw.
+ cumulativeBuffer += `frame ${i}: ${"#".repeat(50)}\n`;
+ const isLast = i === 999;
+
+ const notification = {
+ sessionId: "session-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-1",
+ kind: "other",
+ status: isLast ? "completed" : "in_progress",
+ content: [{ type: "content", content: { type: "text", text: cumulativeBuffer } }],
+ },
+ } satisfies EffectAcpSchema.SessionNotification;
+ notificationBytes += JSON.stringify(notification).length;
+
+ const { events } = parseSessionUpdateEvent(notification);
+
+ const event = events[0];
+ if (event?._tag !== "ToolCallUpdated") {
+ continue;
+ }
+
+ const merged = mergeToolCallState(previous, event.toolCall);
+ const decision = decideToolCallUpdateEmission({
+ previous,
+ next: merged,
+ lastEmittedDetailLength,
+ skippedSinceEmit,
+ });
+ previous = merged;
+ skippedSinceEmit = decision.skippedSinceEmit;
+ if (decision.emit) {
+ emittedCount += 1;
+ const eventBytes = JSON.stringify({
+ toolCall: merged,
+ rawPayload: event.rawPayload,
+ }).length;
+ emittedBytes += eventBytes;
+ largestEmittedEventBytes = Math.max(largestEmittedEventBytes, eventBytes);
+ lastEmittedDetailLength = merged.detail?.length;
+ finalDetail = merged.detail;
+ }
+ }
+
+ // The flood as the CLI sends it: 1000 cumulative redraws, ~31.6 MB of JSON.
+ expect(notificationBytes).toBeGreaterThan(31_000_000);
+
+ // 1000 cumulative redraws collapse into a fixed, small number of runtime events...
+ expect(emittedCount).toBe(114);
+ // ...each individually bounded, no matter how long the tool call runs...
+ expect(largestEmittedEventBytes).toBeLessThan(25_000);
+ // ...so the whole flooding tool call costs ~2.5 MB of runtime events instead of ~31.6 MB.
+ expect(emittedBytes).toBeLessThan(2_600_000);
+ // ...while the FINAL state (forced by the completed status) still reflects the real,
+ // latest output rather than a stale coalesced value.
+ expect(finalDetail).toBeDefined();
+ expect(finalDetail?.endsWith(`frame 999: ${"#".repeat(50)}`)).toBe(true);
+ });
+
+ it("keeps non-text tool call content entries in order when bounding oversized text", () => {
+ const hugePrefix = "x".repeat(25_000);
+ const hugeTail = "y".repeat(25_000);
+ const { events } = parseSessionUpdateEvent({
+ sessionId: "session-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-1",
+ kind: "edit",
+ status: "in_progress",
+ content: [
+ { type: "content", content: { type: "text", text: hugePrefix } },
+ { type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
+ { type: "content", content: { type: "text", text: hugeTail } },
+ { type: "diff", path: "/repo/other.ts", oldText: "old", newText: "new" },
+ { type: "content", content: { type: "text", text: " " } },
+ ],
+ },
+ } satisfies EffectAcpSchema.SessionNotification);
+
+ const event = events[0];
+ if (event?._tag !== "ToolCallUpdated") {
+ throw new Error("expected a ToolCallUpdated event");
+ }
+ const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
+ expect(content).toHaveLength(3);
+ expect(content[0]).toEqual({
+ type: "diff",
+ path: "/repo/file.ts",
+ oldText: "before",
+ newText: "after",
+ });
+ const lastEntry = content[1];
+ if (lastEntry?.type !== "content" || lastEntry.content.type !== "text") {
+ throw new Error("expected a bounded text entry");
+ }
+ expect(lastEntry.content.text.length).toBeLessThan(8_100);
+ expect(lastEntry.content.text.endsWith(hugeTail.slice(-100))).toBe(true);
+ expect(content[2]).toEqual({
+ type: "diff",
+ path: "/repo/other.ts",
+ oldText: "old",
+ newText: "new",
+ });
+ });
+
+ describe("decideToolCallUpdateEmission", () => {
+ const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
+ ({
+ toolCallId: "tool-1",
+ title: "Grok Tool",
+ ...(status ? { status } : {}),
+ ...(detail ? { detail } : {}),
+ data: {},
+ }) satisfies AcpToolCallState;
+
+ it("always emits terminal (completed/failed) status updates regardless of growth", () => {
+ expect(
+ decideToolCallUpdateEmission({
+ previous: toolCall("same", "inProgress"),
+ next: toolCall("same", "completed"),
+ lastEmittedDetailLength: 4,
+ skippedSinceEmit: 0,
+ }),
+ ).toEqual({ emit: true, skippedSinceEmit: 0 });
+
+ expect(
+ decideToolCallUpdateEmission({
+ previous: toolCall("same", "inProgress"),
+ next: toolCall("same", "failed"),
+ lastEmittedDetailLength: 4,
+ skippedSinceEmit: 3,
+ }),
+ ).toEqual({ emit: true, skippedSinceEmit: 0 });
+ });
+
+ it("skips updates whose bounded detail did not change", () => {
+ expect(
+ decideToolCallUpdateEmission({
+ previous: toolCall("frame 1", "inProgress"),
+ next: toolCall("frame 1", "inProgress"),
+ lastEmittedDetailLength: 7,
+ skippedSinceEmit: 0,
+ }),
+ ).toEqual({ emit: false, skippedSinceEmit: 0 });
+ });
+
+ it("emits immediately when the title changes, even with no growth", () => {
+ const decision = decideToolCallUpdateEmission({
+ previous: { toolCallId: "tool-1", title: "Reading file", detail: "x", data: {} },
+ next: { toolCallId: "tool-1", title: "Ran command", detail: "x", data: {} },
+ lastEmittedDetailLength: 1,
+ skippedSinceEmit: 0,
+ });
+ expect(decision).toEqual({ emit: true, skippedSinceEmit: 0 });
+ });
+
+ it("coalesces small deltas but forces an emission after the coalesce limit", () => {
+ let lastEmittedDetailLength: number | undefined = 0;
+ let skippedSinceEmit = 0;
+ const emissions: Array<boolean> = [];
+ let previous: AcpToolCallState | undefined;
+
+ for (let i = 1; i <= 12; i += 1) {
+ // Grows by 1 char per update — well under the 256-char growth threshold, so this
+ // exercises the coalesce-count fallback rather than the growth-based trigger.
+ const next = toolCall("x".repeat(i), "inProgress");
+ const decision = decideToolCallUpdateEmission({
+ previous,
+ next,
+ lastEmittedDetailLength,
+ skippedSinceEmit,
+ });
+ emissions.push(decision.emit);
+ skippedSinceEmit = decision.skippedSinceEmit;
+ if (decision.emit) {
+ lastEmittedDetailLength = next.detail?.length;
+ }
+ previous = next;
+ }
+
+ // First update always emits (no previous state yet); after that, small per-update
+ // growth should be coalesced until the coalesce limit forces a periodic emission.
+ const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
+ expect(emittedIndices).toEqual([1, 11]);
+ });
+
+ it("retains the latest replacement snapshot when equal-length updates are coalesced", () => {
+ let previous: AcpToolCallState = toolCall("frame-a", "inProgress");
+ const lastEmittedDetailLength = previous.detail?.length;
+ let skippedSinceEmit = 0;
+
+ for (const detail of ["frame-b", "frame-c"]) {
+ const next = mergeToolCallState(previous, toolCall(detail, "inProgress"));
+ const decision = decideToolCallUpdateEmission({
+ previous,
+ next,
+ lastEmittedDetailLength,
+ skippedSinceEmit,
+ });
+ expect(decision.emit).toBe(false);
+ skippedSinceEmit = decision.skippedSinceEmit;
+ previous = next;
+ }
+
+ const completed = mergeToolCallState(previous, toolCall(undefined, "completed"));
+ expect(completed.detail).toBe("frame-c");
+ expect(
+ decideToolCallUpdateEmission({
+ previous,
+ next: completed,
+ lastEmittedDetailLength,
+ skippedSinceEmit,
+ }),
+ ).toEqual({ emit: true, skippedSinceEmit: 0 });
+ });
+ });
});
diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts
index e6bfc127e..2e561c4cc 100644
--- a/apps/server/src/provider/acp/AcpRuntimeModel.ts
+++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts
@@ -264,25 +264,97 @@ function extractToolCallCommand(rawInput: unknown, title: string | undefined): s
return extractCommandFromTitle(title);
}
+// Some ACP agents (observed with Grok's CLI) resend the ENTIRE accumulated tool-call
+// output on every `tool_call_update` notification instead of a delta, so a redrawing
+// terminal progress bar can balloon a single tool call to hundreds of KB per update at
+// several updates per second. Cap what we retain/emit to a bounded tail so one busy tool
+// call cannot flood runtime event ingestion. We always keep the tail: `tool_call_update`
+// deltas routinely omit `kind`, so there is no reliable way to tell a redrawing terminal
+// from another tool here, and the end is the useful part of any live-growing output.
+const TOOL_CALL_CONTENT_MAX_CHARS = 8_000;
+const TOOL_CALL_CONTENT_TRUNCATION_MARKER = "[Earlier output truncated]\n\n";
+
+function boundToolCallOutputText(text: string): string {
+ if (text.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
+ return text;
+ }
+ const tail = text.slice(text.length - TOOL_CALL_CONTENT_MAX_CHARS);
+ return `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${tail}`;
+}
+
+const RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"] as const;
+
+// `rawOutput` is provider-defined and, for terminal-shaped tools, mirrors the same
+// cumulative text-growth problem as `content` (see the comment above). Bound its known
+// text-bearing fields the same way so a chatty provider cannot smuggle unbounded output
+// through this field instead.
+function boundToolCallRawOutput(rawOutput: unknown): unknown {
+ if (!isRecord(rawOutput)) {
+ return rawOutput;
+ }
+ let changed = false;
+ const bounded: Record<string, unknown> = { ...rawOutput };
+ for (const field of RAW_OUTPUT_TEXT_FIELDS) {
+ const value = rawOutput[field];
+ if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
+ bounded[field] = boundToolCallOutputText(value);
+ changed = true;
+ }
+ }
+ return changed ? bounded : rawOutput;
+}
+
+interface ExtractedToolCallContent {
+ readonly text: string | undefined;
+ readonly content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | undefined;
+}
+
+function toolCallContentText(entry: EffectAcpSchema.ToolCallContent): string | undefined {
+ if (entry.type !== "content" || entry.content.type !== "text") {
+ return undefined;
+ }
+ return entry.content.text;
+}
+
function extractTextContentFromToolCallContent(
content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
-): string | undefined {
- if (!content) return undefined;
+): ExtractedToolCallContent {
+ if (!content) {
+ return { text: undefined, content: undefined };
+ }
const chunks: Array<string> = [];
for (const entry of content) {
- if (entry.type !== "content") {
- continue;
- }
- const nestedContent = entry.content;
- if (nestedContent.type !== "text") {
- continue;
- }
- const text = nestedContent.text.trim();
- if (text.length > 0) {
+ const text = toolCallContentText(entry)?.trim();
+ if (text) {
chunks.push(text);
}
}
- return chunks.length > 0 ? chunks.join("\n") : undefined;
+ if (chunks.length === 0) {
+ return { text: undefined, content };
+ }
+ const joined = chunks.join("\n");
+ if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
+ return { text: joined, content };
+ }
+ const bounded = boundToolCallOutputText(joined);
+ // Collapse the text entries into a single bounded one at the final contributing text entry,
+ // and leave every other entry kind (diffs, images, resource links) in its original relative
+ // order. The retained tail came from that text entry, so placing it there also preserves its
+ // ordering relative to interleaved non-text content and ignores later blank text entries.
+ const lastContributingTextIndex = content.reduce(
+ (lastIndex, entry, index) => (toolCallContentText(entry)?.trim() ? index : lastIndex),
+ -1,
+ );
+ const boundedContent = content.flatMap((entry, index) => {
+ if (toolCallContentText(entry) === undefined) {
+ return [entry];
+ }
+ if (index !== lastContributingTextIndex) {
+ return [];
+ }
+ return [{ type: "content", content: { type: "text", text: bounded } } as const];
+ });
+ return { text: bounded, content: boundedContent };
}
function normalizeToolKind(kind: unknown): string | undefined {
@@ -326,7 +398,8 @@ function makeToolCallState(
}
const title = input.title?.trim() || undefined;
const command = extractToolCallCommand(input.rawInput, title);
- const textContent = extractTextContentFromToolCallContent(input.content);
+ const extractedContent = extractTextContentFromToolCallContent(input.content);
+ const textContent = extractedContent.text;
const normalizedTitle =
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
? title
@@ -343,10 +416,10 @@ function makeToolCallState(
data.rawInput = input.rawInput;
}
if (input.rawOutput !== undefined) {
- data.rawOutput = input.rawOutput;
+ data.rawOutput = boundToolCallRawOutput(input.rawOutput);
}
if (input.content !== undefined) {
- data.content = input.content;
+ data.content = extractedContent.content ?? input.content;
}
if (input.locations !== undefined) {
data.locations = input.locations;
@@ -424,6 +497,53 @@ export function mergeToolCallState(
};
}
+// Even with bounded content (see TOOL_CALL_CONTENT_MAX_CHARS above), a redrawing terminal
+// can still shift its bounded tail window on nearly every notification, which would emit
+// a runtime event per redraw. Coalesce those: only emit early when the tool call's detail
+// has grown meaningfully since the last emission, otherwise batch up to a small number of
+// skipped updates before emitting anyway, so the UI still gets periodic progress and the
+// final (completed/failed) state is always emitted immediately.
+const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
+const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
+
+export interface AcpToolCallEmitDecisionInput {
+ readonly previous: AcpToolCallState | undefined;
+ readonly next: AcpToolCallState;
+ readonly lastEmittedDetailLength: number | undefined;
+ readonly skippedSinceEmit: number;
+}
+
+export interface AcpToolCallEmitDecision {
+ readonly emit: boolean;
+ readonly skippedSinceEmit: number;
+}
+
+export function decideToolCallUpdateEmission(
+ input: AcpToolCallEmitDecisionInput,
+): AcpToolCallEmitDecision {
+ const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
+ if (next.status === "completed" || next.status === "failed") {
+ return { emit: true, skippedSinceEmit: 0 };
+ }
+ if (!next.detail) {
+ return { emit: false, skippedSinceEmit };
+ }
+ if (previous === undefined || previous.title !== next.title) {
+ return { emit: true, skippedSinceEmit: 0 };
+ }
+ if (previous.detail === next.detail) {
+ return { emit: false, skippedSinceEmit };
+ }
+ const grewMeaningfully =
+ lastEmittedDetailLength === undefined ||
+ Math.abs(next.detail.length - lastEmittedDetailLength) >=
+ TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
+ if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
+ return { emit: true, skippedSinceEmit: 0 };
+ }
+ return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
+}
+
export function parsePermissionRequest(
params: EffectAcpSchema.RequestPermissionRequest,
): AcpPermissionRequest {
@@ -505,6 +625,33 @@ export function syntheticLoadSessionResponseFromInitialize(
};
}
+// The parsed AcpToolCallState already carries bounded content (see makeToolCallState /
+// extractTextContentFromToolCallContent above), but the raw JSON-RPC notification is also
+// threaded through as `rawPayload` for logging/debugging and ends up persisted on the
+// runtime event. Substitute the same bounded `content`/`rawOutput` there so an oversized
+// cumulative update cannot smuggle the unbounded buffer back in through the raw payload.
+function boundToolCallRawPayload(
+ params: EffectAcpSchema.SessionNotification,
+ update: AcpToolCallUpdate,
+ toolCall: AcpToolCallState,
+): unknown {
+ const boundedContent = toolCall.data.content;
+ const boundedRawOutput = toolCall.data.rawOutput;
+ const contentBounded = update.content !== undefined && boundedContent !== update.content;
+ const rawOutputBounded = update.rawOutput !== undefined && boundedRawOutput !== update.rawOutput;
+ if (!contentBounded && !rawOutputBounded) {
+ return params;
+ }
+ return {
+ ...params,
+ update: {
+ ...update,
+ ...(contentBounded ? { content: boundedContent } : {}),
+ ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
+ },
+ };
+}
+
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
readonly modeId?: string;
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
@@ -548,7 +695,7 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
events.push({
_tag: "ToolCallUpdated",
toolCall,
- rawPayload: params,
+ rawPayload: boundToolCallRawPayload(params, upd, toolCall),
});
}
break;
@@ -559,7 +706,7 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
events.push({
_tag: "ToolCallUpdated",
toolCall,
- rawPayload: params,
+ rawPayload: boundToolCallRawPayload(params, upd, toolCall),
});
}
break;
diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts
index 09fce6d56..0dcf72895 100644
--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts
+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts
@@ -23,6 +23,7 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
collectSessionConfigOptionValues,
+ decideToolCallUpdateEmission,
extractModelConfigId,
findSessionConfigOption,
mergeToolCallState,
@@ -36,6 +37,12 @@ import {
type AcpToolCallState,
} from "./AcpRuntimeModel.ts";
+interface AcpToolCallTrackedState {
+ readonly state: AcpToolCallState;
+ readonly lastEmittedDetailLength: number | undefined;
+ readonly skippedSinceEmit: number;
+}
+
function formatConfigOptionValue(value: string | boolean): string {
return JSON.stringify(value);
}
@@ -279,7 +286,7 @@ export const make = (
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
- const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
+ const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());
const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
@@ -851,7 +858,7 @@ const handleSessionUpdate = ({
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
- readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
+ readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly assistantItemRuntimeId: string;
readonly params: EffectAcpSchema.SessionNotification;
@@ -869,18 +876,31 @@ const handleSessionUpdate = ({
queue,
assistantSegmentRef,
});
- const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
- const previous = current.get(event.toolCall.toolCallId);
+ const { merged, decision } = yield* Ref.modify(toolCallsRef, (current) => {
+ const tracked = current.get(event.toolCall.toolCallId);
+ const previous = tracked?.state;
const nextToolCall = mergeToolCallState(previous, event.toolCall);
+ const decision = decideToolCallUpdateEmission({
+ previous,
+ next: nextToolCall,
+ lastEmittedDetailLength: tracked?.lastEmittedDetailLength,
+ skippedSinceEmit: tracked?.skippedSinceEmit ?? 0,
+ });
const next = new Map(current);
if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
next.delete(nextToolCall.toolCallId);
} else {
- next.set(nextToolCall.toolCallId, nextToolCall);
+ next.set(nextToolCall.toolCallId, {
+ state: nextToolCall,
+ lastEmittedDetailLength: decision.emit
+ ? nextToolCall.detail?.length
+ : tracked?.lastEmittedDetailLength,
+ skippedSinceEmit: decision.skippedSinceEmit,
+ });
}
- return [{ previous, merged: nextToolCall }, next] as const;
+ return [{ merged: nextToolCall, decision }, next] as const;
});
- if (!shouldEmitToolCallUpdate(previous, merged)) {
+ if (!decision.emit) {
continue;
}
yield* Queue.offer(queue, {
@@ -926,19 +946,6 @@ function updateModeState(modeState: AcpSessionModeState, nextModeId: string): Ac
: modeState;
}
-function shouldEmitToolCallUpdate(
- previous: AcpToolCallState | undefined,
- next: AcpToolCallState,
-): boolean {
- if (next.status === "completed" || next.status === "failed") {
- return true;
- }
- if (!next.detail) {
- return false;
- }
- return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
-}
-
const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
`assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;