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): chat waits for your answer before making other changes (#16519)

Hazem Adel58b984412d9a
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts
index 926a8e12a90..7eb683dad5a 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts
@@ -7,12 +7,14 @@ import { wrapDeleteGate, wrapTestFlowGate } from './tools/flow-gate-tools'
import { createAgentSurfaceTools, createBuildPlanTools, createLocalTools, createStructuredOutputTool, createThinkingTools } from './tools/session-tools'
import { unwrapLazyToolChunk } from './tools/skill-tools'
import { createTaintState, extractResultText, extractUserFacingError, isSuccessResult, normalizePieceName, previousReplyReadData, TOOL_EXECUTION_TIMEOUT_MS, truncateLargeResult, withToolTimeout, wrapToolsWithTaint } from './tools/tool-primitives'
+import { wrapToolsWithUserWaitBarrier } from './tools/user-wait-barrier'
import { createImageTools, createProviderSearchTools, createScrapeTools, createSearchTools, createWebTools, falImageGenerator, providerImageGenerator } from './tools/web-media-tools'
export { AgentEventEmitter, GateDecision, TaintState } from './tools/tool-primitives'
export const agentWorkerTools = {
wrapToolsWithTaint,
+ wrapToolsWithUserWaitBarrier,
previousReplyReadData,
createTaintState,
createEventEmitter,
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
index 742baab5e55..6cc1d73c129 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
@@ -264,7 +264,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge
skip: (dryRun ?? false) || (discoveryOnly ?? false),
log,
run: (stepMcpToolSet) => {
- const baseTools = { ...allTools, ...agentWorkerTools.wrapToolsWithTaint({ tools: stepMcpToolSet, taintState }) }
+ const baseTools = agentWorkerTools.wrapToolsWithUserWaitBarrier({ tools: { ...allTools, ...agentWorkerTools.wrapToolsWithTaint({ tools: stepMcpToolSet, taintState }) } })
const taskTools = createTaskSubagentTools({
tools: baseTools, guides: config.guides, models: turnModels, researchModels: isNil(fastTurnModel) ? turnModels : [fastTurnModel], tier: config.tier,
taskPrompt: config.taskSystemPrompt, creditsLeftFor, eventEmitter, abortSignal: abortController.signal, log,
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/user-wait-barrier.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/user-wait-barrier.ts
new file mode 100644
index 00000000000..8a03e792e10
--- /dev/null
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/user-wait-barrier.ts
@@ -0,0 +1,110 @@
+import { partition } from '@activepieces/core-utils'
+import { ToolExecutionOptions, ToolSet } from 'ai'
+import { toolHasExecute } from './tool-primitives'
+
+export function wrapToolsWithUserWaitBarrier({ tools }: { tools: ToolSet }): ToolSet {
+ const barrier = createBarrier()
+ return Object.fromEntries(Object.entries(tools).map(([toolName, tool]) => {
+ if (!toolHasExecute(tool) || NEVER_HELD_TOOLS.has(toolName)) {
+ return [toolName, tool]
+ }
+ const originalExecute = tool.execute.bind(tool)
+ const claimKind = ASKS_USER_TOOLS.has(toolName) ? 'ask' : MAY_WAIT_FOR_USER_TOOLS.has(toolName) ? 'gate' : null
+ const execute = async (args: unknown, options?: ToolExecutionOptions<undefined>) => {
+ if (claimKind !== 'ask') {
+ const until = claimKind === 'gate' ? 'questions-answered' : 'all-answered'
+ if (!barrier.isAnswered(until) && await barrier.waitForUser({ until }) === 'after-question') {
+ return { content: [{ type: 'text', text: HELD_BEHIND_QUESTION_MESSAGE }] }
+ }
+ }
+ if (claimKind === null) {
+ return originalExecute(args, options)
+ }
+ const release = barrier.claim(claimKind)
+ try {
+ return await originalExecute(args, options)
+ }
+ finally {
+ release()
+ }
+ }
+ return [toolName, Object.assign({}, tool, { execute })]
+ }))
+}
+
+function createBarrier(): Barrier {
+ const openClaims = { ask: 0, gate: 0 }
+ let waiters: Waiter[] = []
+ const isAnswered = (until: WaitUntil) => until === 'questions-answered' ? openClaims.ask === 0 : openClaims.ask + openClaims.gate === 0
+ return {
+ isAnswered,
+ claim: (kind) => {
+ openClaims[kind] += 1
+ if (kind === 'ask') {
+ waiters = waiters.map((waiter) => ({ ...waiter, sawQuestion: true }))
+ }
+ let released = false
+ return () => {
+ if (released) {
+ return
+ }
+ released = true
+ openClaims[kind] -= 1
+ const [ready, stillWaiting] = partition(waiters, (waiter) => isAnswered(waiter.until))
+ waiters = stillWaiting
+ ready.forEach((waiter) => waiter.wake(waiter.sawQuestion ? 'after-question' : 'after-approval'))
+ }
+ },
+ waitForUser: ({ until }) => new Promise((wake) => {
+ waiters = [...waiters, { until, sawQuestion: openClaims.ask > 0, wake }]
+ }),
+ }
+}
+
+const ASKS_USER_TOOLS = new Set([
+ 'ap_show_questions',
+ 'ap_show_connection_required',
+ 'ap_show_connection_picker',
+ 'ap_show_project_picker',
+ 'ap_show_mcp_reconnect',
+])
+
+const MAY_WAIT_FOR_USER_TOOLS = new Set([
+ 'ap_test_flow',
+ 'ap_delete_records',
+ 'ap_delete_table',
+ 'ap_delete_flow',
+ 'ap_manage_fields',
+ 'ap_send_email',
+ 'ap_execute_action',
+ 'ap_remember',
+ 'ap_add_agent_tool',
+ 'ap_remove_agent_tool',
+ 'ap_update_agent',
+ 'ap_create_agent',
+])
+
+const NEVER_HELD_TOOLS = new Set([
+ 'ap_update_thinking_status',
+ 'ap_set_build_plan',
+ 'ap_show_quick_replies',
+ 'ap_show_showcase',
+])
+
+const HELD_BEHIND_QUESTION_MESSAGE = 'Not run: you asked the user a question in the same step. Their answer is in that question\'s result now. Redo this change if it still fits the answer.'
+
+type WaitResult = 'after-question' | 'after-approval'
+
+type WaitUntil = 'questions-answered' | 'all-answered'
+
+type Waiter = {
+ until: WaitUntil
+ sawQuestion: boolean
+ wake: (result: WaitResult) => void
+}
+
+type Barrier = {
+ isAnswered: (until: WaitUntil) => boolean
+ claim: (kind: 'ask' | 'gate') => () => void
+ waitForUser: (params: { until: WaitUntil }) => Promise<WaitResult>
+}
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/user-wait-barrier.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/user-wait-barrier.test.ts
new file mode 100644
index 00000000000..35527cd3ea6
--- /dev/null
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/user-wait-barrier.test.ts
@@ -0,0 +1,126 @@
+import { tool, ToolExecutionOptions } from 'ai'
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+import { wrapToolsWithUserWaitBarrier } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/user-wait-barrier'
+
+const OPTIONS: ToolExecutionOptions<undefined> = { toolCallId: 'call', messages: [], context: undefined }
+
+function deferred(): { promise: Promise<string>, resolve: (value: string) => void } {
+ let resolve: (value: string) => void = () => undefined
+ const promise = new Promise<string>((res) => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
+describe('wrapToolsWithUserWaitBarrier', () => {
+ it('holds a flow edit until a permission gate in the same turn is answered', async () => {
+ const approval = deferred()
+ const order: string[] = []
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_remember: tool({ inputSchema: z.object({}), execute: async () => {
+ const answer = await approval.promise
+ order.push(`remember:${answer}`)
+ return answer
+ } }),
+ ap_update_step: tool({ inputSchema: z.object({}), execute: async () => {
+ order.push('update_step')
+ return 'updated'
+ } }),
+ } })
+
+ const remember = tools.ap_remember.execute?.({}, OPTIONS)
+ const update = tools.ap_update_step.execute?.({}, OPTIONS)
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(order).toEqual([])
+
+ approval.resolve('approved')
+ await Promise.all([remember, update])
+ expect(order).toEqual(['remember:approved', 'update_step'])
+ })
+
+ it('hands an edit queued behind a question back to the agent once the user answers', async () => {
+ const answer = deferred()
+ let ran = false
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_show_questions: tool({ inputSchema: z.object({}), execute: async () => answer.promise }),
+ ap_update_step: tool({ inputSchema: z.object({}), execute: async () => {
+ ran = true
+ return 'updated'
+ } }),
+ } })
+
+ const question = tools.ap_show_questions.execute?.({}, OPTIONS)
+ const update = tools.ap_update_step.execute?.({}, OPTIONS)
+ answer.resolve('weekly')
+ const [, updateResult] = await Promise.all([question, update])
+
+ expect(ran).toBe(false)
+ expect(JSON.stringify(updateResult)).toContain('Redo this change')
+ })
+
+ it('lets edits run in the next step after the question was answered', async () => {
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_show_questions: tool({ inputSchema: z.object({}), execute: async () => 'weekly' }),
+ ap_update_step: tool({ inputSchema: z.object({}), execute: async () => 'updated' }),
+ } })
+
+ await tools.ap_show_questions.execute?.({}, OPTIONS)
+
+ expect(await tools.ap_update_step.execute?.({}, OPTIONS)).toBe('updated')
+ })
+
+ it('runs tools normally when nothing waits for the user', async () => {
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_update_step: tool({ inputSchema: z.object({}), execute: async () => 'updated' }),
+ } })
+
+ expect(await tools.ap_update_step.execute?.({}, OPTIONS)).toBe('updated')
+ })
+
+ it('hands an agent edit back when a question is already open, instead of saving it unanswered', async () => {
+ const answer = deferred()
+ let saved = false
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_show_questions: tool({ inputSchema: z.object({}), execute: async () => answer.promise }),
+ ap_update_agent: tool({ inputSchema: z.object({}), execute: async () => {
+ saved = true
+ return 'saved'
+ } }),
+ } })
+
+ const question = tools.ap_show_questions.execute?.({}, OPTIONS)
+ const update = tools.ap_update_agent.execute?.({}, OPTIONS)
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(saved).toBe(false)
+
+ answer.resolve('in Arabic')
+ const [, updateResult] = await Promise.all([question, update])
+ expect(saved).toBe(false)
+ expect(JSON.stringify(updateResult)).toContain('Redo this change')
+ })
+
+ it('hands back an edit queued behind an approval when a question opens while it waits', async () => {
+ const approval = deferred()
+ const answer = deferred()
+ let ran = false
+ const tools = wrapToolsWithUserWaitBarrier({ tools: {
+ ap_remember: tool({ inputSchema: z.object({}), execute: async () => approval.promise }),
+ ap_show_questions: tool({ inputSchema: z.object({}), execute: async () => answer.promise }),
+ ap_update_step: tool({ inputSchema: z.object({}), execute: async () => {
+ ran = true
+ return 'updated'
+ } }),
+ } })
+
+ const remember = tools.ap_remember.execute?.({}, OPTIONS)
+ const update = tools.ap_update_step.execute?.({}, OPTIONS)
+ const question = tools.ap_show_questions.execute?.({}, OPTIONS)
+ approval.resolve('approved')
+ answer.resolve('weekly')
+ const [, updateResult] = await Promise.all([remember, update, question])
+
+ expect(ran).toBe(false)
+ expect(JSON.stringify(updateResult)).toContain('Redo this change')
+ })
+})