Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(chat): keep each turn's tool calls in history, so chat never claims a change it did not make (#16021)

Hazem Adel052872cdb731
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.md
index 4c1bb026ee1..734af3efb75 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -31,6 +31,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **Stream idle watchdog** (`STREAM_IDLE_TIMEOUT_MS` 90s, in `streamChunksToClient`): aborts the turn if the drain-stream reader is silent 90s. It must be SUSPENDED while legitimate silent work is in flight — pending tool calls AND in-flight reasoning (`reasoning-start`→`reasoning-end`). **Reasoning-awareness was missing and caused the bug where long "thinking" on the Expert tier randomly aborted a healthy turn** (a >90s gap between reasoning deltas looked like a wedge). Backstop for a genuine mid-reasoning wedge is `MAX_TURN_WALL_CLOCK_MS` (20 min).
### Gotchas
+- **A step's `response.messages` holds only that step's messages (AI SDK v7).** The older SDK made it cumulative, so `collectStepMessages` once took the last step; under v7 that saved only a turn's closing text and dropped every tool call and result. The next turn then saw replies like "New agent is updated" with no tool call behind them, and repeated the pattern by claiming changes it never made. It now joins every step, and `run-agent-turn-history.test.ts` runs a real `streamText` turn so a future SDK change to these semantics fails loudly.
- **Chat has no fixed step cap.** A chat turn is bounded by credits (checked after every step), the runaway-token ceiling (`RUNAWAY_TURN_CONTEXT_MULTIPLE` × the context window), the identical-failure guard and the 2-hour `MAX_AGENT_TURN_WALL_CLOCK_MS`, so it finishes long jobs. A saved agent's author-set `maxSteps` is still honored on its last step: an agent with structured output is forced to call `TASK_COMPLETION_TOOL_NAME` so the flow gets a result, and any other agent runs with `toolChoice: 'none'` plus a wrap-up note, so it replies with what's done and what's left. Never a silent stop or an error.
- **The streaming lock is per run, not per conversation.** A re-send can claim `activeRunId` before the first job reaches `getAgentConfig`. `agentHelpers.acquireStreamingLock` only lets the owning run set STREAMING; an older run gets `AGENT_RUN_SUPERSEDED` and the worker exits quietly, with no ERROR save and no events. A lock that ignored `runId` let the old run stream unowned while the new one was rejected as busy and marked ERROR, which is how users saw nothing after tapping a starter card twice.
- **A failed turn used to leave status ERROR with an empty reply.** The error text only travelled as a websocket `ERROR` event, so a reload, another tab, or a user who was away saw a dead conversation (and often no user message either when the job died inside `getAgentConfig`, before it persists the turn). The `execute-agent-run.ts` catch now sends `failure: { message, userMessage? }` on the empty `saveAgentMessages` call and `conversation-rpc.ts` appends it to `uiMessages` as an assistant text reply; `use-chat.ts` shows the Retry banner when a loaded conversation is ERROR. Stale STREAMING to IDLE recovery, a worker that never picks the job up, and `assertAgentMessageRateLimitNotExceeded` still leave no reply of their own.
diff --git a/packages/server/utils/src/agent-ai-utils.ts b/packages/server/utils/src/agent-ai-utils.ts
index 7cf901e05b2..1de77331448 100644
--- a/packages/server/utils/src/agent-ai-utils.ts
+++ b/packages/server/utils/src/agent-ai-utils.ts
@@ -85,15 +85,8 @@ function sanitizeTruncatedAssistantTail(messages: ModelMessage[]): ModelMessage[
return [...head, { ...last, content: sanitizedParts }]
}
-/**
- * The response messages of a streamText turn. Each step's `response.messages` is
- * CUMULATIVE — it already contains every prior step's assistant/tool messages — so the
- * last step holds the complete set. Flat-mapping all steps instead would re-emit earlier
- * steps in a 4,3,2,1 staircase, persisting (and re-sending to the model) the same tool
- * call and reasoning block multiple times. Take the last step only.
- */
function collectStepMessages(steps: Array<{ response: { messages: ModelMessage[] } }>): ModelMessage[] {
- return steps[steps.length - 1]?.response.messages ?? []
+ return steps.flatMap((step) => step.response.messages)
}
function estimateTokenCount({ messages, systemPromptLength }: { messages: ModelMessage[], systemPromptLength: number }): number {
diff --git a/packages/server/utils/test/agent-ai-utils.test.ts b/packages/server/utils/test/agent-ai-utils.test.ts
index f7fd823538c..e667920d606 100644
--- a/packages/server/utils/test/agent-ai-utils.test.ts
+++ b/packages/server/utils/test/agent-ai-utils.test.ts
@@ -130,20 +130,13 @@ describe('collectStepMessages', () => {
content: [{ type: 'text', text: 'That table does not exist yet — want me to create it?' }],
}
- it('returns the last step (which on this provider is cumulative — holds every earlier step)', () => {
- // The provider's `response.messages` is cumulative: each step already contains every prior
- // step's assistant/tool messages, so the LAST step holds the full set. Flat-mapping would
- // re-emit the earlier steps in a 4,3,2,1 staircase (the bug this guards against).
+ it('joins every step, since each step holds only its own messages', () => {
const steps = [
{ response: { messages: [listCall, listResult] } },
- { response: { messages: [listCall, listResult, finalText] } },
+ { response: { messages: [finalText] } },
]
- const result = agentAiUtils.collectStepMessages(steps)
- expect(result).toEqual([listCall, listResult, finalText])
- // The regression this guards: the tool call + its result must survive (the last step carries them).
- expect(result).toContainEqual(listResult)
- // And no duplication from flat-mapping the staircase.
- expect(result.filter((m) => m === listCall).length).toBe(1)
+
+ expect(agentAiUtils.collectStepMessages(steps)).toEqual([listCall, listResult, finalText])
})
it('returns an empty array when there are no steps', () => {
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
index b84d059a9cc..474b6530744 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
@@ -72,10 +72,6 @@ export async function runAgentTurn({ model, fastModel, provider, systemPrompt, m
const uiParts: PersistedAgentPart[] = []
const toolCalls: AgentTurnToolCall[] = []
let toolCallOrder = 0
- // The cumulative response.messages of the CURRENT streamText attempt, captured per-step in
- // onStepEnd (the reliable source — mirrors what we stream to the UI). Folded into
- // accumulatedResponseMessages on EVERY loop exit, so an abort/error break never drops the
- // steps that already happened (which previously left the saved LLM history as just [user]).
let currentAttemptMessages: ModelMessage[] = []
let streamError: Error | null = null
@@ -191,12 +187,7 @@ export async function runAgentTurn({ model, fastModel, provider, systemPrompt, m
},
onStepEnd: ({ content, response }) => {
uiParts.push(...agentAiUtils.buildStepParts({ content: content as ContentPartLike[] }))
- // Persist the LLM history incrementally (not just UI parts): a turn preempted or
- // cancelled mid-flight must leave its assistant + tool messages behind so the next
- // run inherits them instead of re-discovering from scratch. accumulatedResponseMessages
- // holds prior continuation attempts; this step's response.messages is cumulative for
- // the current attempt (collectStepMessages takes the last step).
- currentAttemptMessages = agentAiUtils.collectStepMessages([{ response }])
+ currentAttemptMessages = [...currentAttemptMessages, ...agentAiUtils.collectStepMessages([{ response }])]
const responseMessages = [...accumulatedResponseMessages, ...currentAttemptMessages]
onProgress({ uiParts: [...uiParts], responseMessages })
log.debug({ partCount: uiParts.length, phase: phaseState.phase }, 'Chat step finished')
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts
new file mode 100644
index 00000000000..3e7d1c8eede
--- /dev/null
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts
@@ -0,0 +1,124 @@
+import { AIProviderName } from '@activepieces/core-utils'
+import { ModelMessage, tool } from 'ai'
+import { convertArrayToReadableStream, MockLanguageModelV3 } from 'ai/test'
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+import { runAgentTurn } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'
+
+describe('the history a turn leaves behind', () => {
+ it('keeps the tool call and its result, so the next turn knows the change was made by a tool', async () => {
+ const progress: ModelMessage[][] = []
+
+ const turn = await runAgentTurn({
+ model: updateThenConfirm(),
+ provider: AIProviderName.ANTHROPIC,
+ systemPrompt: 'You are a test agent.',
+ messages: [{ role: 'user', content: 'Change the instructions of New agent to: Reply in Arabic.' }],
+ tools: {
+ ap_update_agent: tool({ description: 'change an agent', inputSchema: z.object({ instructions: z.string() }), execute: async () => ({ saved: true }) }),
+ },
+ allToolNames: ['ap_update_agent'],
+ tier: TIER,
+ modelId: TIER.modelId,
+ phaseState: { phase: 'build' },
+ abortSignal: new AbortController().signal,
+ log: SILENT_LOG,
+ creditsLeft: async () => 100,
+ sinks: {
+ drainStream: (result) => result.consumeStream(),
+ onProgress: ({ responseMessages }) => progress.push(responseMessages),
+ },
+ })
+
+ expect(rolesAndParts(turn.accumulatedResponseMessages)).toEqual(['assistant:tool-call', 'tool:tool-result', 'assistant:text'])
+ expect(rolesAndParts(progress[progress.length - 1])).toEqual(['assistant:tool-call', 'tool:tool-result', 'assistant:text'])
+ })
+
+ it('keeps every finished step when the turn is cancelled partway, not just the last one', async () => {
+ const controller = new AbortController()
+ let saves = 0
+
+ const turn = await runAgentTurn({
+ model: keepsUpdating(),
+ provider: AIProviderName.ANTHROPIC,
+ systemPrompt: 'You are a test agent.',
+ messages: [{ role: 'user', content: 'Update New agent three times.' }],
+ tools: {
+ ap_update_agent: tool({
+ description: 'change an agent',
+ inputSchema: z.object({ instructions: z.string() }),
+ execute: async () => {
+ saves++
+ if (saves === 3) {
+ controller.abort()
+ }
+ return { saved: true }
+ },
+ }),
+ },
+ allToolNames: ['ap_update_agent'],
+ tier: TIER,
+ modelId: TIER.modelId,
+ phaseState: { phase: 'build' },
+ abortSignal: controller.signal,
+ log: SILENT_LOG,
+ creditsLeft: async () => 100,
+ sinks: { drainStream: (result) => result.consumeStream() },
+ })
+
+ const toolCalls = turn.accumulatedResponseMessages.flatMap((message) => typeof message.content === 'string'
+ ? []
+ : message.content.flatMap((part) => part.type === 'tool-call' ? [part.toolCallId] : []))
+ expect(toolCalls).toEqual(['update-1', 'update-2'])
+ })
+})
+
+function rolesAndParts(messages: ModelMessage[]): string[] {
+ return messages.flatMap((message) => typeof message.content === 'string'
+ ? [`${message.role}:text`]
+ : message.content.map((part) => `${message.role}:${part.type}`))
+}
+
+function updateThenConfirm(): MockLanguageModelV3 {
+ let calls = 0
+ return new MockLanguageModelV3({
+ doStream: async () => {
+ calls++
+ return {
+ stream: convertArrayToReadableStream(calls === 1
+ ? [
+ { type: 'stream-start' as const, warnings: [] },
+ { type: 'tool-call' as const, toolCallId: 'update-1', toolName: 'ap_update_agent', input: '{"instructions":"Reply in Arabic."}' },
+ { type: 'finish' as const, finishReason: 'tool-calls' as const, usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } },
+ ]
+ : [
+ { type: 'stream-start' as const, warnings: [] },
+ { type: 'text-start' as const, id: 'done' },
+ { type: 'text-delta' as const, id: 'done', delta: 'Done, New agent now replies in Arabic.' },
+ { type: 'text-end' as const, id: 'done' },
+ { type: 'finish' as const, finishReason: 'stop' as const, usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } },
+ ]),
+ }
+ },
+ })
+}
+
+const TIER = { id: 'fast', thinkingBudget: 5_000, modelId: 'anthropic/claude-haiku-4.5' }
+
+const SILENT_LOG = { debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined }
+
+function keepsUpdating(): MockLanguageModelV3 {
+ let calls = 0
+ return new MockLanguageModelV3({
+ doStream: async () => {
+ calls++
+ return {
+ stream: convertArrayToReadableStream([
+ { type: 'stream-start' as const, warnings: [] },
+ { type: 'tool-call' as const, toolCallId: `update-${calls}`, toolName: 'ap_update_agent', input: '{"instructions":"again"}' },
+ { type: 'finish' as const, finishReason: 'tool-calls' as const, usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } },
+ ]),
+ }
+ },
+ })
+}