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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(chat): chat asks before a batch of actions changes your data (#16951)
Hazem Adel61763efd2880
diff --git a/brain/knowledge/flows-execution/action-run.md b/brain/knowledge/flows-execution/action-run.mdindex e122925d292..372337f2e4d 100644--- a/brain/knowledge/flows-execution/action-run.md+++ b/brain/knowledge/flows-execution/action-run.md@@ -15,6 +15,7 @@ At this stage action runs are **execution only — nothing is persisted**. The c- **Priority** `high`, not `critical`, so action runs never outrank the builder interactions a human is actively waiting on.### Gotchas+- **A batched `ap_execute_action` is approved on what runs, not on its top-level input.** A batch runs `items` and ignores `input`, so the approval gate in `cross-project-tools.ts` classifies every input that will actually run and opens if any one needs approval. One approval covers the whole batch, and the card's samples are the items that triggered it. Classifying only `input` let a read-looking batch run writes with no card (AI-107).- **The budget is one end-to-end deadline, not two timeouts with a margin.** `actionRunService` stamps `expiresAt = now + AP_FLOW_TIMEOUT_SECONDS` onto the job and waits that plus 10s. The extra 10s only covers the sandbox kill and the pubsub hop home — it is *not* an allowance for queueing, resolution or provisioning, because those spend the same budget: `createSandboxRuntime.execute` clamps the run to what is left of `expiresAt` after provisioning **and boot**, and throws `SANDBOX_EXECUTION_TIMEOUT` without starting the engine if nothing is left. **Do not re-shape this as "sandbox budget + a fudge factor".** That was the original bug: the watcher's clock starts at enqueue and the sandbox's at run-start, so a cold piece install (easily >10s) expired the caller first while the action kept running and writing — and the retry that invites duplicates the write. The worker no longer carries a cap of its own; `execute-action.ts` derives `timeoutInSeconds` from `expiresAt` alone.- **Derive the clamp where the timer is armed. Every phase between the two is a hole.** The only thing enforcing the run budget is the SIGKILL timer armed *inside* `sandbox.execute`; `remainingTimeoutInSeconds` was called before `sandbox.start()`, so the engine got its full remaining budget counted from a later instant and user code ran until `expiresAt + bootMs`. Boot is the norm, not the tail — `canReuseSandbox` is false for `SANDBOX_PROCESS` unless `AP_REUSE_SANDBOX=true`, so every production action run pays bind retries, two *unbounded* isolate `execPromise` calls and a 30s connect cap, comfortably past the 10s grace. The pre-boot check survives only as a fast path (skip a pointless spawn); the authoritative clamp is recomputed after the `sandboxStart` timed block. Note the recomputed throw lands inside the `try`, so it invalidates a freshly booted box instead of parking it warm — one cold boot on a rare path, accepted over restructuring boot out of the `try`.- **Do not bound provision or the connect wait by the deadline without reworking the error taxonomy first.** It looks like the obvious next step — `spawnWithKill` already takes `timeoutMs` and `waitForConnection`'s 30s is a bare literal — but both raise a plain `Error`, which fails `isSandboxTimeout` in `execute-action.ts` and is rethrown, so the caller gets `INTERNAL_ERROR` / *"the engine crashed while loading or executing the piece"* — the exact misreport the next gotcha forbids, in place of an honest `neverStarted`. Capping the connect wait also does not bound boot: it is the *last* of three boot phases, behind the unbounded isolate calls. Neither buys any safety, because a setup overrun already yields `neverStarted` with no user code executed.diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.tsindex 237d9730aab..be2e58a2ba5 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts@@ -103,12 +103,14 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForApprreturn guardResult}}- const needsPreview = agentToolClassification.requiresActionPreview({+ const executedInputs = isBatch ? toolInput.items! : [toolInput.input ?? {}]+ const gatedInputs = executedInputs.filter((input) => agentToolClassification.requiresActionPreview({actionName: toolInput.actionName,- input: toolInput.input,+ input,needsConfirmation: toolInput.needsConfirmation,tainted: taintState.tainted,- })+ }))+ const needsPreview = gatedInputs.length > 0taintState.tainted = trueif (needsPreview) {@@ -120,7 +122,7 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForApprinput: toolInput.input ?? {},isBatch: !!isBatch,batchCount: isBatch ? toolInput.items!.length : undefined,- batchSamples: isBatch ? toolInput.items!.slice(0, 3) : undefined,+ batchSamples: isBatch ? gatedInputs.slice(0, 3) : undefined,}eventEmitter.emitActionPreview(previewData)if (onGateOpened) {@@ -132,7 +134,7 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForApprpieceName: toolInput.pieceName,actionName: toolInput.actionName,input: toolInput.input ?? {},- items: isBatch ? toolInput.items!.slice(0, 3) : undefined,+ items: isBatch ? gatedInputs.slice(0, 3) : undefined,batchCount: isBatch ? toolInput.items!.length : undefined,},}))diff --git a/packages/server/worker/test/lib/agent/taints-turn.test.ts b/packages/server/worker/test/lib/agent/taints-turn.test.tsindex 66293c77fcc..e6dc22f54cd 100644--- a/packages/server/worker/test/lib/agent/taints-turn.test.ts+++ b/packages/server/worker/test/lib/agent/taints-turn.test.ts@@ -104,6 +104,69 @@ describe('reads through the action, code and cross-project tools', () => {})})+describe('ap_execute_action batch approval', () => {+ const batchTools = ({ tainted }: { tainted: boolean }) => {+ const executed: unknown[] = []+ let asked = false+ const tools = agentWorkerTools.createCrossProjectTools({+ executeTool: async (_toolName, toolInput) => {+ executed.push(toolInput)+ return { success: true, content: [{ type: 'text', text: 'done' }] }+ },+ eventEmitter: agentWorkerTools.createEventEmitter({ sendEvent: async () => undefined, userId: 'user-1', conversationId: 'conv-1' }),+ waitForApproval: async () => {+ asked = true+ return { outcome: 'declined' as const }+ },+ guides: {},+ taintState: { tainted },+ })+ return { tools, executed, wasAsked: () => asked }+ }+ const decoyBatch = { pieceName: '@activepieces/piece-http', actionName: 'custom_api_call', input: { method: 'GET', url: 'https://api.example.com/users' }, items: [{ method: 'DELETE', url: 'https://api.example.com/users/1' }] }++ it.each([false, true])('asks before running batch items that write, even when the top-level input is a read (tainted turn: %s)', async (tainted) => {+ const { tools, executed, wasAsked } = batchTools({ tainted })++ await tools.ap_execute_action.execute?.(decoyBatch, options)++ expect(wasAsked()).toBe(true)+ expect(executed).toHaveLength(0)+ })++ it('shows the items that need approval on the card, not reads placed ahead of them', async () => {+ const previews: unknown[] = []+ const tools = agentWorkerTools.createCrossProjectTools({+ executeTool: async () => ({ success: true }),+ eventEmitter: agentWorkerTools.createEventEmitter({+ sendEvent: async ({ event }) => {+ previews.push(event)+ },+ userId: 'user-1',+ conversationId: 'conv-1',+ }),+ waitForApproval: async () => ({ outcome: 'declined' as const }),+ guides: {},+ taintState: { tainted: false },+ })+ const read = { method: 'GET', url: 'https://api.example.com/users' }+ const write = { method: 'DELETE', url: 'https://api.example.com/users/1' }++ await tools.ap_execute_action.execute?.({ ...decoyBatch, items: [read, read, read, write] }, options)++ expect(JSON.stringify(previews)).toContain('"batchSamples":[{"method":"DELETE"')+ })++ it('runs a batch of reads without asking', async () => {+ const { tools, executed, wasAsked } = batchTools({ tainted: true })++ await tools.ap_execute_action.execute?.({ ...decoyBatch, items: [{ method: 'GET', url: 'https://api.example.com/users/1' }, { method: 'HEAD', url: 'https://api.example.com/users/2' }] }, options)++ expect(wasAsked()).toBe(false)+ expect(executed).toHaveLength(2)+ })+})+describe('previousReplyReadData', () => {const reply = (tainted?: boolean) => ({ role: 'assistant', parts: [], ...(tainted === undefined ? {} : { tainted }) })const user = { role: 'user', parts: [] }