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): ask before a live test when the write check can't run (#16855)

Hazem Adel464d46808f28
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.md
index c440c2c83f4..2aa23d97ce1 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -45,7 +45,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **A built flow ends with a "Turn it on?" card, never an auto-publish**: an audit found 40% of built-but-unpublished flows ended on "open it to review", some claiming LIVE. Chat never publishes on its own; only a yes to the card calls `ap_lock_and_publish` (`build_flow.md` "Turn it on?"). Pinned by the `build-then-ask-turn-it-on` fixture (`askedToTurnItOn`, `noLiveClaimWithoutPublish`). The live-claim check is a regex plus "was `ap_lock_and_publish` called", so it cannot see whether publish succeeded.
- **Server-managed connections**: the LLM never sees connection externalIds; `ap_execute_action` auto-fills them from a Redis store.
- **Prompt-injection taint**: a per-turn `taintState` flips to `tainted` once the turn reads outside or user data (MCP tools, web/search/scrape, `ap_explore_data`, `ap_execute_action`, `ap_run_code`, `ap_list_across_projects`, configured tools). It forces the action-preview gate on non-read-only actions, makes saved-agent edits (`ap_update_agent`, `ap_add_agent_tool`, `ap_remove_agent_tool`, `ap_create_agent`) ask for approval on the action card instead of refusing, and makes `ap_remember` ask before saving (memory reaches every future conversation). It carries one message: each saved reply stores `tainted` (this reply's own reads, via `createTaintState`), and the next message starts from it. Deletes are confirmed always, not by taint.
-- **Write-check gate**: before a live `ap_test_flow`, `__flow_write_check` RPC flags write/destructive PIECE steps; read-only flows run ungated; gate fails open on RPC error.
+- **Write-check gate**: before a live `ap_test_flow`, `__flow_write_check` RPC flags write/destructive PIECE steps; read-only flows run ungated; if the check itself errors, the approval card still shows (fails closed).
- **Chat follows the plan on Cloud and Enterprise.** `chatVisibility` returns `plan.chatEnabled` on both, and Community and embedded sessions never see chat. Chat reaches a Cloud user only through `CHAT_ENABLED` on their Autumn plan, which `toPlatformPlanFlags` writes to `chatEnabled`; the code has no Cloud override.
- **Flow correctness is 100% prompt/guide-driven — nothing in code enforces it.** The "#1 silent bug" ("Class A"): the agent frames a *recurring* automation as a *one-time task* and omits any anti-reprocessing step, so run N+1 redoes run N's work (re-pays, re-sends). It's a design-time reasoning gap, not a testing gap — `ap_test_flow` runs ONCE, so a single test looks perfect; the bug only shows on the 2nd run. Fix lives in the prompt (`chat-system-prompt.md` `<decision_framework>` + `build_flow.md` "Recurring flows must not reprocess") + capability eval fixtures with a `recurring_avoids_reprocessing` judge dimension. The platform already has every primitive (Tables New-Record webhook, polling `DedupeStrategy`, `_dedupe_key`, Store, update/delete-record); the agent just wasn't reaching for them. Watch the `build_flow.md` "don't over-build" bias — it once actively discouraged the fix.
- **Compaction runs inside the 60s `getAgentConfig` RPC, so it must stay bounded.** The summarizer call is capped at `SUMMARY_OUTPUT_RESERVE_TOKENS` and aborted after `COMPACTION_TIMEOUT_MS` (35s). On failure the previous summary is kept and `buildCompactedPayload` still fits the history to the budget, flagging trimmed messages to the model. An unbounded summary once ran for 2.5 min and failed the turn as `RPC [getAgentConfig] failed (timeout: 60000ms)`.
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts
index 9b89f2d4b74..2c59ef998f5 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts
@@ -1,4 +1,4 @@
-import { isObject, tryCatch } from '@activepieces/core-utils'
+import { isNil, isObject, tryCatch } from '@activepieces/core-utils'
import { ToolExecutionOptions } from 'ai'
import { AgentEventEmitter, GateDecision, gateNoResponseMessage, toolHasExecute } from './tool-primitives'
@@ -22,14 +22,16 @@ export function wrapTestFlowGate({ mcpTools, checkFlowWrites, waitForApproval, s
if (flowId && gateId) {
const { data: check, error } = await tryCatch(() => checkFlowWrites(flowId))
if (error) {
- log?.warn({ error, flow: { id: flowId } }, 'ap_test_flow write-check failed, running test without confirmation gate')
+ log?.warn({ error, flow: { id: flowId } }, 'ap_test_flow write-check failed, asking for approval before the live test')
}
- else if (isObject(check) && check['hasWrites'] === true) {
- const writeSteps = Array.isArray(check['writeSteps']) ? check['writeSteps'].filter((s): s is string => typeof s === 'string') : []
- const flowName = typeof check['flowName'] === 'string' ? check['flowName'] : 'this flow'
+ const writeCheck = isObject(check) ? check : {}
+ const mustConfirm = !isNil(error) || writeCheck['hasWrites'] === true
+ if (mustConfirm) {
+ const writeSteps = Array.isArray(writeCheck['writeSteps']) ? writeCheck['writeSteps'].filter((s): s is string => typeof s === 'string') : []
+ const flowName = typeof writeCheck['flowName'] === 'string' ? `"${writeCheck['flowName']}"` : 'this flow'
const gateLabel = writeSteps.length > 0
- ? `Run a live test of "${flowName}" — performs: ${writeSteps.join(', ')}`
- : `Run a live test of "${flowName}"`
+ ? `Run a live test of ${flowName} — performs: ${writeSteps.join(', ')}`
+ : `Run a live test of ${flowName}`
// Render the confirmation card in the live session (and persist it for refresh).
// Without the emit the gate would block silently until the approval timeout.
eventEmitter.emitActionPreview({
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/test-flow-gate.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/test-flow-gate.test.ts
new file mode 100644
index 00000000000..d9cbdd5ca5d
--- /dev/null
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/test-flow-gate.test.ts
@@ -0,0 +1,55 @@
+import { isObject } from '@activepieces/core-utils'
+import { describe, expect, it, vi } from 'vitest'
+import { agentWorkerTools, GateDecision } from '../../../../../../src/lib/execute/jobs/ee/agent/agent-worker-tools'
+import { toolHasExecute } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/tool-primitives'
+
+describe('wrapTestFlowGate', () => {
+ it('asks the user before a live test when the write check fails, and does not run it when they decline', async () => {
+ const { testFlow, runTest, waitForApproval } = setup({ checkFlowWrites: async () => {
+ throw new Error('rpc timeout')
+ } })
+
+ const result = await testFlow({ flowId: 'flow-1' }, { toolCallId: 'call-1' })
+
+ expect(waitForApproval).toHaveBeenCalledWith({ gateId: 'call-1' })
+ expect(runTest).not.toHaveBeenCalled()
+ expect(JSON.stringify(result)).toContain('cancelled')
+ })
+
+ it('runs a read-only flow without asking', async () => {
+ const { testFlow, runTest, waitForApproval } = setup({ checkFlowWrites: async () => ({ hasWrites: false }) })
+
+ await testFlow({ flowId: 'flow-1' }, { toolCallId: 'call-1' })
+
+ expect(waitForApproval).not.toHaveBeenCalled()
+ expect(runTest).toHaveBeenCalledTimes(1)
+ })
+})
+
+function setup({ checkFlowWrites }: { checkFlowWrites: (flowId: string) => Promise<unknown> }): {
+ testFlow: (args: unknown, options: { toolCallId: string }) => Promise<unknown>
+ runTest: ReturnType<typeof vi.fn>
+ waitForApproval: ReturnType<typeof vi.fn>
+} {
+ const runTest = vi.fn(async () => TOOL_RESULT)
+ const waitForApproval = vi.fn(async (): Promise<GateDecision> => ({ outcome: 'declined' }))
+ const eventEmitter = agentWorkerTools.createEventEmitter({
+ sendEvent: async () => undefined,
+ userId: 'user-1',
+ conversationId: 'conv-1',
+ })
+ const wrapped = agentWorkerTools.wrapTestFlowGate({
+ mcpTools: { ap_test_flow: { execute: runTest } },
+ checkFlowWrites,
+ waitForApproval,
+ storePendingGate: async () => undefined,
+ eventEmitter,
+ })
+ const testFlow = wrapped['ap_test_flow']
+ if (!isObject(testFlow) || !toolHasExecute(testFlow)) {
+ throw new Error('ap_test_flow was not wrapped')
+ }
+ return { testFlow: testFlow.execute, runTest, waitForApproval }
+}
+
+const TOOL_RESULT = { content: [{ type: 'text', text: 'done' }] }