From d1f9254ae5498f63cb241b87a469159e2a0af9d4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 24 Nov 2026 23:57:12 -0800 Subject: [PATCH 01/10] feat(workflows): side-effect-free dry runs `sim workflows run --dry` (v2 execute `run.dry`, manual runs only) runs the saved draft without sending its writes. Every tool call not declared `read` (table writes, sends, HTTP calls, custom tools, and every MCP tool, which declares no effect) is answered with a placeholder shaped like the tool's outputs and listed in the run result's `sideEffects.stubbed` with the request it would have sent: an in-process operation's input or an HTTP call's method, URL and body, with the credentials the call resolved and the run's resolved secrets redacted. Reads, model calls, conditions and credential resolution run for real. Function blocks run their code and are listed in `sideEffects.unchecked`. Mothership and Pi blocks, which act outside the tool seam, and Human in the loop and Wait blocks, whose paused run would resume without the dry run, are answered whole. Dry runs are logged under the `test` trigger and are synchronous only (no stream, async or waitTimeoutSeconds). The interception is one check in `executeToolImplementation`, after credentials resolve and before dispatch, so block and Agent tool calls are covered alike. The policy rides on the execution context as `sideEffects`, which every child inherits: Workflow blocks, custom blocks, and workflows or custom blocks an Agent calls as tools, so a child's writes stay stubbed. `run.allowBlocks` (`--allow `) sends one block's writes for real and lists them in `sideEffects.allowed`; `run.mocks` (`--mock =`) answers a block with a fixed output through the existing mock seam, with or without `--dry`. Both resolve blocks by id, name or key like `--stop-after`. Workflow tests now answer the writes their mocks do not with the same placeholders. A failed dry run's `next` rerun keeps `--dry`. The source primers, `sim workflows source --help`, `run --help`, the CLI, build-and-run and coding-agent docs, and the integration skills now test with `--dry`. --- .agents/skills/add-integration/SKILL.md | 1 + .agents/skills/add-tools/SKILL.md | 5 + .agents/skills/validate-integration/SKILL.md | 3 + .../api-reference/build-and-run-workflows.mdx | 9 +- apps/docs/content/docs/cli/index.mdx | 2 +- apps/docs/content/docs/cli/reference.mdx | 5 + apps/docs/content/docs/cli/workflows.mdx | 5 + .../docs/workflows/code/coding-agents.mdx | 4 +- apps/docs/openapi-v2-workflows.json | 164 +++++++++ .../workflows/[workflowId]/execute/route.ts | 7 + apps/sim/executor/execution/block-executor.ts | 11 + apps/sim/executor/execution/executor.ts | 1 + apps/sim/executor/execution/types.ts | 41 +++ .../workflow/custom-block-tool-runner.ts | 7 +- .../sim/executor/handlers/workflow/handler.ts | 2 + .../executor/handlers/workflow/tool-runner.ts | 3 +- apps/sim/executor/types.ts | 3 + .../contracts/mothership-management-tools.ts | 2 +- apps/sim/lib/api/contracts/v2/workflows.ts | 88 ++++- apps/sim/lib/workflow-tests/session.ts | 20 +- .../application/dry-run.integration.ts | 346 ++++++++++++++++++ .../application/execute-manual-workflow.ts | 61 ++- .../application/run-workflow-for-test.ts | 7 +- apps/sim/lib/workflows/dry-run/block-mocks.ts | 27 ++ apps/sim/lib/workflows/dry-run/index.ts | 7 + apps/sim/lib/workflows/dry-run/samples.ts | 19 + .../sim/lib/workflows/dry-run/side-effects.ts | 147 ++++++++ .../lib/workflows/executor/execute-service.ts | 44 ++- .../workflows/executor/execute-workflow.ts | 4 + .../lib/workflows/executor/execution-core.ts | 5 + apps/sim/tools/index.test.ts | 17 + apps/sim/tools/index.ts | 28 ++ apps/sim/tools/side-effects.test.ts | 39 ++ apps/sim/tools/side-effects.ts | 117 ++++++ .../src/commands/protocol/source-loop-help.ts | 9 +- .../src/commands/protocol/source-primer.ts | 18 +- .../src/commands/protocol/workflow-dir.ts | 2 +- .../protocol/workflow-run-follow.test.ts | 143 ++++++++ .../commands/protocol/workflow-run-follow.ts | 142 ++++++- packages/sim-cli/src/contract/commands.ts | 5 +- packages/sim-cli/src/generated/v2-api.ts | 34 +- packages/sim-cli/src/runtime/run-next.ts | 7 +- 42 files changed, 1549 insertions(+), 62 deletions(-) create mode 100644 apps/sim/lib/workflows/application/dry-run.integration.ts create mode 100644 apps/sim/lib/workflows/dry-run/block-mocks.ts create mode 100644 apps/sim/lib/workflows/dry-run/index.ts create mode 100644 apps/sim/lib/workflows/dry-run/samples.ts create mode 100644 apps/sim/lib/workflows/dry-run/side-effects.ts create mode 100644 apps/sim/tools/side-effects.test.ts create mode 100644 apps/sim/tools/side-effects.ts diff --git a/.agents/skills/add-integration/SKILL.md b/.agents/skills/add-integration/SKILL.md index 6f15c8e6eef..c5d27a389a4 100644 --- a/.agents/skills/add-integration/SKILL.md +++ b/.agents/skills/add-integration/SKILL.md @@ -606,6 +606,7 @@ If creating V2 versions (API-aligned outputs): - [ ] Verified `tools.config.params` correctly maps and coerces all param types - [ ] Verified every tool output and `transformResponse` path against documented or live-verified JSON responses - [ ] If any response schema remained unknown, explicitly told the user instead of guessing +- [ ] Ran the block in a workflow with `sim workflows run --dry`: each write is in `sideEffects.stubbed` with the documented request, and each read ran for real (send one write for real only with `--allow ` against a test resource) - [ ] `{Service}BlockMeta` exported with at least 7 templates, each having `icon`, `title`, `prompt`, `modules`, `category`, and `tags` ## File Handling diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 7f45f81e0f7..16076789154 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -220,6 +220,11 @@ search that returns no email or phone, and an email verifier. `read`, fails the audit unless the `effect` line carries `// tool-effect: ` on one of the two lines above it; use it only for a genuine exception such as a GET that writes in `postProcess`. - A factory that builds tools from definitions takes `effect` per definition and passes it through. +- Prove the labels with a dry run: put the block in a workflow and run + `sim workflows run --dry --input '{…}'`. Each `write` call must appear in the result's + `sideEffects.stubbed` with the request you expect (an HTTP tool's `method`, `url` and `body`, or an + in-process operation's input, credentials redacted), and each `read` must run for real and return + live data. A write missing from `stubbed` was sent; a read listed there is labelled `write`. ## Critical Rules for Parameters diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index a9d69a3823e..1bf7479c9a1 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -82,6 +82,9 @@ For **every** tool file, check: `add-tools` → Declaring the effect) - [ ] Any `// tool-effect: ` sits on a genuine verb/label exception, and `bun run check:tool-effects` passes +- [ ] A dry run (`sim workflows run --dry --input '{…}'` on a workflow using the + block) lists every write operation in `sideEffects.stubbed` with the request the API docs + expect, and every read runs for real (rules: `add-tools` → Declaring the effect) ### Params - [ ] All required API params are marked `required: true` diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index 5d1768a9ca6..898b961adb2 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"`. Manual runs are synchronous or streamed, never `async`. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and Function blocks run for real and are listed under `sideEffects.unchecked`. Dry runs are logged under the `test` trigger. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. @@ -174,12 +174,12 @@ Run the saved draft with `run.source: "manual"`. Manual runs are synchronous or curl -sS --fail-with-body -X POST \ "$BASE_URL/api/v2/workflows/$WORKFLOW_ID/execute" \ -H "X-API-Key: $SIM_API_KEY" -H 'Content-Type: application/json' \ - -d '{"run": {"source": "manual"}, "input": {"ticketId": "T-123"}}' + -d '{"run": {"source": "manual", "dry": true}, "input": {"ticketId": "T-123"}}' ``` ```bash - sim workflows run "$WORKFLOW_ID" --manual --input '{"ticketId": "T-123"}' + sim workflows run "$WORKFLOW_ID" --dry --input '{"ticketId": "T-123"}' ``` @@ -193,6 +193,9 @@ Narrow a test run with these options: | Stop after one block | `run.stopAfterBlockId` | `--stop-after ` | | Rerun from a block, reusing an earlier run's upstream outputs | `run.entry: {type: "block", blockId, sourceRunId}` | `--from-block --source-run ` | | Rerun one block only | Block entry plus `stopAfterBlockId` naming the same block | `--from-block` and `--stop-after` with the same block | +| Send one block's writes for real during a dry run | `run.allowBlocks: [""]` | `--allow ` | +| Answer a block with a fixed output, to steer a branch | `run.mocks: {"": {...}}` | `--mock ='{...}'` | +| Run everything for real | omit `run.dry` | `--manual` | `stopAfterBlockId` cannot name a block inside a loop or parallel. A run that routes away from the stop block fails as soon as that is decided. diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index d44f4e9b9ee..f8e60ffd8b6 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -77,7 +77,7 @@ b8c0d247-9e13-4a86-97f5-2ad4e1638c09 Weekly digest /Reporting no 18 sim workflows run 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --input '{"ticketId":"T-4821"}' ``` -Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `. To execute the current saved workflow state, use `sim workflows run --manual`. +Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `. To execute the current saved workflow state, use `sim workflows run --manual`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. ## How commands are shaped diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 9d740bd6ba2..a6c8ba7f449 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,6 +8516,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8531,6 +8534,8 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run and are listed in sideEffects.unchecked. Child workflows run dry too. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. + The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 2db4c32aecb..9b3397b30e0 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,6 +833,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -848,6 +851,8 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run and are listed in sideEffects.unchecked. Child workflows run dry too. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. + The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index 42ec35a8469..fd82d6293a7 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -21,11 +21,13 @@ Point the agent at `.sim/AGENTS.md` before it edits. 3. Run one chained command, then fix whatever it reports in the next step: ```bash - sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --manual --input '{...}' + sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --dry --input '{...}' ``` A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. `check` also type-checks the directory, so the chain needs no separate `tsc`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. + `run --dry` tests the saved draft without sending its writes: each write returns a placeholder and is listed under `sideEffects` with the request it would have sent, so the agent checks payloads instead of cleaning up rows or messages. `--allow ` sends one block's writes for real against a test resource, and `--manual` runs everything for real. + For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). ## Look things up diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index e1f7b4cc243..c6578ce0971 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17204,6 +17204,143 @@ "title": "Execution error", "description": "Structured in-band failure details for a workflow run." }, + "WorkflowRunSideEffects": { + "type": "object", + "properties": { + "stubbed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow; empty when the call named no block." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "tool": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Tool the block (or an Agent) called; null when the whole block was answered instead of run." + }, + "request": { + "anyOf": [ + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Request field." + } + }, + { + "type": "null" + } + ], + "description": "What the call would have sent: an in-process operation's input, or an HTTP call's `method`, `url` and `body` (never headers). For a block answered whole, its logged inputs. Credentials and resolved secrets are redacted; null when the run could not prove none remain." + }, + "returned": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Placeholder field." + }, + "description": "Placeholder output the block or tool call returned to the run instead." + } + }, + "required": ["workflowId", "blockId", "block", "tool", "request", "returned"], + "additionalProperties": false + }, + "description": "Writes that were not sent, in the order the run reached them." + }, + "allowed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow; empty when the call named no block." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "tool": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Tool sent; null when the whole block ran." + } + }, + "required": ["workflowId", "blockId", "block", "tool"], + "additionalProperties": false + }, + "description": "Writes sent for real because `run.allowBlocks` named their block." + }, + "unchecked": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow; empty when the call named no block." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "reason": { + "type": "string", + "description": "Why the run cannot see what this block changed." + } + }, + "required": ["workflowId", "blockId", "block", "reason"], + "additionalProperties": false + }, + "description": "Blocks that ran for real whose own effects the run cannot see: Function blocks, whose code may make network calls." + }, + "omitted": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Entries left out once a list held 50." + } + }, + "required": ["stubbed", "allowed", "unchecked", "omitted"], + "additionalProperties": false, + "title": "Workflow run side effects", + "description": "What a dry run did with each write it reached." + }, "WorkflowRunResult": { "type": "object", "properties": { @@ -17325,6 +17462,10 @@ } ], "description": "Where the run waits when `status` is `paused`; null otherwise." + }, + "sideEffects": { + "description": "What a dry run (`run.dry`) did with each write it reached; absent otherwise.", + "$ref": "#/components/schemas/WorkflowRunSideEffects" } }, "required": [ @@ -17523,6 +17664,29 @@ "description": "Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.", "type": "string", "minLength": 1 + }, + "dry": { + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Reads, model calls, conditions and credential resolution run for real, and so do Function blocks, listed in `sideEffects.unchecked`. Child workflows inherit it. Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "type": "boolean" + }, + "allowBlocks": { + "description": "Blocks (id, display name or reference key) whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block cannot be allowed.", + "maxItems": 50, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mocks": { + "description": "Blocks (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. With or without `dry`.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Output object that answers the block instead of its handler." + } } }, "required": ["source"], diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index 2d54ea85391..9cd459aedf5 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -138,6 +138,7 @@ function presentRun(result: ExecuteWorkflowServiceRun) { endedAt: result.endedAt, durationMs: result.durationMs, executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), + ...(result.sideEffects ? { sideEffects: result.sideEffects } : {}), output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, paused: presentV2RunPause(result.paused), @@ -549,6 +550,9 @@ export const POST = withRouteHandler( blockId: manualRun.entry.blockId, sourceRunId: manualRun.entry.sourceRunId, stopAfterBlockId: manualRun.stopAfterBlockId, + dry: manualRun.dry, + allowBlocks: manualRun.allowBlocks, + mocks: manualRun.mocks, }, request: req, }) @@ -562,6 +566,9 @@ export const POST = withRouteHandler( triggerBlockId: manualRun.entry?.blockId, useMockPayload: manualRun.entry?.useMockPayload === true, stopAfterBlockId: manualRun.stopAfterBlockId, + dry: manualRun.dry, + allowBlocks: manualRun.allowBlocks, + mocks: manualRun.mocks, }, request: req, }) diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index 96dcc1f1061..9b06ddc165e 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -285,6 +285,14 @@ export class BlockExecutor { const testHooks = this.contextExtensions.testHooks const mockedBlockId = node.metadata.originalBlockId ?? block.id const isMocked = !isSentinel && testHooks?.mocksBlock(mockedBlockId) === true + const sideEffects = this.contextExtensions.sideEffects + const site = { + workflowId: blockCtx.workflowId, + blockId: mockedBlockId, + blockName: block.metadata?.name ?? mockedBlockId, + blockType: block.metadata?.id ?? '', + } + const isStubbed = !isSentinel && !isMocked && sideEffects?.stubsBlock(site) === true try { /** * Only the handler call is retried. A streaming handler returns before any @@ -303,6 +311,9 @@ export class BlockExecutor { inputDisplayRegistry ) } + if (isStubbed && sideEffects) { + return Promise.resolve(sideEffects.stubBlock({ ...site, input: blockLog?.input ?? {} })) + } const invocationMetadata = retry ? { ...nodeMetadata, retry } : nodeMetadata return handler.executeWithNode ? handler.executeWithNode(blockCtx, block, resolvedInputs, invocationMetadata) diff --git a/apps/sim/executor/execution/executor.ts b/apps/sim/executor/execution/executor.ts index b2f20695c85..da887cd2a68 100644 --- a/apps/sim/executor/execution/executor.ts +++ b/apps/sim/executor/execution/executor.ts @@ -470,6 +470,7 @@ export class DAGExecutor { enforceCredentialAccess: this.contextExtensions.enforceCredentialAccess, piiBlockOutputRedaction: this.contextExtensions.piiBlockOutputRedaction, testHooks: this.contextExtensions.testHooks, + sideEffects: this.contextExtensions.sideEffects, blockStates: state.getBlockStates(), blockLogs: restoredBlockLogs, /* diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 36265be745e..8e8a2cecd81 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -318,6 +318,46 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } +/** Where a call that may change state outside the run was made: a block of one executing workflow. */ +export interface SideEffectSite { + workflowId: string + /** The workflow block id, never a parallel-branch clone id; empty when the caller named none. */ + blockId: string + blockName: string + blockType: string +} + +/** A write tool call the run answers instead of sending, with the request it would have sent. */ +export interface StubbedToolCall extends SideEffectSite { + toolId: string + /** The request with credentials and resolved secrets redacted; null when it could not be. */ + request: Record | null +} + +/** A block the run answers instead of running its handler, with the inputs its log shows. */ +export interface StubbedBlockCall extends SideEffectSite { + input: Record +} + +/** + * How a run treats work that may change state outside it: a dry run, or a workflow test's + * unmocked writes. Unlike {@link ExecutionTestHooks}, every child execution inherits it, including + * a custom block's source workflow and a workflow or custom block an Agent calls as a tool, so a + * child's writes follow the run that started it. `tools/index.ts` consults it for every tool call + * not declared `read` (an MCP tool declares nothing, so every one), after credentials resolve and + * before anything is sent; the block executor consults it before each block's handler. + */ +export interface SideEffectPolicy { + /** Whether this write tool call is sent for real; a sent call is recorded with why it was. */ + sendsWrite(call: SideEffectSite & { toolId: string }): boolean + /** Records a write that was not sent and returns the placeholder output answering it. */ + stubWrite(call: StubbedToolCall): Record + /** Whether this block is answered with a placeholder instead of running its handler. */ + stubsBlock(block: SideEffectSite): boolean + /** Records a block that did not run and returns the placeholder output answering it. */ + stubBlock(call: StubbedBlockCall): NormalizedBlockOutput +} + export interface ContextExtensions { workspaceId?: string executionId?: string @@ -418,6 +458,7 @@ export interface ContextExtensions { stopAfterBlockId?: string testHooks?: ExecutionTestHooks + sideEffects?: SideEffectPolicy /** * Ordered list of workflow IDs in the current call chain, used for cycle detection. diff --git a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts index 407b64e5f5d..2f525085dfb 100644 --- a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts +++ b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts @@ -4,7 +4,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { isPlainRecord, isRecordLike } from '@sim/utils/object' import type { BillingAttributionSnapshot } from '@/lib/billing/core/attribution' -import type { PiiBlockOutputRedaction } from '@/executor/execution/types' +import type { PiiBlockOutputRedaction, SideEffectPolicy } from '@/executor/execution/types' import { WorkflowBlockHandler } from '@/executor/handlers/workflow/handler' import type { ExecutionContext, @@ -82,6 +82,8 @@ export function buildCustomBlockExecutionContext( piiBlockOutputRedaction?: PiiBlockOutputRedaction /** The invoking run's unrecorded model spend, which a child billed on its log adds to. */ unrecordedModelCost?: UnrecordedModelCost + /** The invoking run's side-effect policy, which the child's writes follow. */ + sideEffects?: SideEffectPolicy } ): ExecutionContext { // Prefer the invoking agent run's ids so correlation and cancellation both @@ -105,6 +107,7 @@ export function buildCustomBlockExecutionContext( environmentVariables: options.environmentVariables, piiBlockOutputRedaction: options.piiBlockOutputRedaction, unrecordedModelCost: options.unrecordedModelCost, + sideEffects: options.sideEffects, blockStates: new Map(), executedBlocks: new Set(), blockLogs: [], @@ -145,6 +148,7 @@ export async function runCustomBlockTool( abortSignal?: AbortSignal resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry principal?: WorkflowExecutionPrincipal + sideEffects?: SideEffectPolicy } = {} ): Promise { if (!params.blockType) { @@ -156,6 +160,7 @@ export async function runCustomBlockTool( abortSignal: options.abortSignal, resolvedSecretTraceRegistry: options.resolvedSecretTraceRegistry, principal: options.principal, + sideEffects: options.sideEffects, }) const block: SerializedBlock = { id: generateId(), diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index a2d8bc4cf4c..a3715fa11e6 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -931,6 +931,8 @@ export class WorkflowBlockHandler implements BlockHandler { // A workflow test's mocks and spies reach every child it runs, except a custom // block's: that workflow is the publisher's, so the test mocks the block whole. testHooks: isCustomBlock ? undefined : ctx.testHooks, + // A dry run's writes stay stubbed in every child, a custom block's included. + sideEffects: ctx.sideEffects, callChain: childCallChain, // A custom block's own session markers and the parent's live stream, fanned // out together — see `childCallbacks` above for why this is not two spreads. diff --git a/apps/sim/executor/handlers/workflow/tool-runner.ts b/apps/sim/executor/handlers/workflow/tool-runner.ts index c506fc97f92..25a09d367ba 100644 --- a/apps/sim/executor/handlers/workflow/tool-runner.ts +++ b/apps/sim/executor/handlers/workflow/tool-runner.ts @@ -6,7 +6,7 @@ import { isRecordLike } from '@sim/utils/object' import { calculateCostSummary } from '@/lib/logs/execution/logging-factory' import type { TraceSpan } from '@/lib/logs/types' import { ChildWorkflowError } from '@/executor/errors/child-workflow-error' -import type { PiiBlockOutputRedaction } from '@/executor/execution/types' +import type { PiiBlockOutputRedaction, SideEffectPolicy } from '@/executor/execution/types' import { buildCustomBlockExecutionContext, type CustomBlockExecutorContext, @@ -100,6 +100,7 @@ export async function runWorkflowTool( principal?: WorkflowExecutionPrincipal piiBlockOutputRedaction?: PiiBlockOutputRedaction unrecordedModelCost?: UnrecordedModelCost + sideEffects?: SideEffectPolicy } ): Promise { if (!params.workflowId) { diff --git a/apps/sim/executor/types.ts b/apps/sim/executor/types.ts index 75cc34c5811..c589d8b7e6a 100644 --- a/apps/sim/executor/types.ts +++ b/apps/sim/executor/types.ts @@ -11,6 +11,7 @@ import type { ParentIteration, PiiBlockOutputRedaction, SerializableExecutionState, + SideEffectPolicy, } from '@/executor/execution/types' import type { ResolvedSecretTraceProvenanceV1, @@ -451,6 +452,8 @@ export interface ExecutionContext { workflowId: string /** Set during a workflow test run; Agent tool calls consult it before calling the tool. */ testHooks?: ExecutionTestHooks + /** Set during a dry run or workflow test; inherited by every child execution. */ + sideEffects?: SideEffectPolicy workspaceId?: string executionId?: string largeValueExecutionIds?: string[] diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index e4d60e2a1a2..60ef983d2d0 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run, while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 29e3ded0daa..79f762fff5b 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1702,6 +1702,31 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .describe( 'Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.' ), + dry: z + .boolean() + .optional() + .describe( + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Reads, model calls, conditions and credential resolution run for real, and so do Function blocks, listed in `sideEffects.unchecked`. Child workflows inherit it. Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + ), + allowBlocks: z + .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) + .max(50) + .optional() + .describe( + 'Blocks (id, display name or reference key) whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block cannot be allowed.' + ), + mocks: z + .record( + z.string(), + z.unknown().describe('Output object that answers the block instead of its handler.') + ) + .optional() + .refine((mocks) => mocks === undefined || Object.keys(mocks).length <= 50, { + message: 'run.mocks names at most 50 blocks', + }) + .describe( + 'Blocks (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. With or without `dry`.' + ), }) .strict(), ]) @@ -1951,6 +1976,64 @@ const v2WorkflowRunPausePointSchema = z description: 'One point at which a paused run waits.', }) +const sideEffectBlockFields = { + workflowId: z + .string() + .describe('Workflow whose block it was: the run workflow, or a child workflow it called.'), + blockId: z.string().describe('Block id in that workflow; empty when the call named no block.'), + block: z.string().describe('Block display name.'), +} + +const v2RunSideEffectsSchema = z + .object({ + stubbed: z + .array( + z.object({ + ...sideEffectBlockFields, + tool: z + .string() + .nullable() + .describe( + 'Tool the block (or an Agent) called; null when the whole block was answered instead of run.' + ), + request: z + .record(z.string(), z.unknown().describe('Request field.')) + .nullable() + .describe( + "What the call would have sent: an in-process operation's input, or an HTTP call's `method`, `url` and `body` (never headers). For a block answered whole, its logged inputs. Credentials and resolved secrets are redacted; null when the run could not prove none remain." + ), + returned: z + .record(z.string(), z.unknown().describe('Placeholder field.')) + .describe('Placeholder output the block or tool call returned to the run instead.'), + }) + ) + .describe('Writes that were not sent, in the order the run reached them.'), + allowed: z + .array( + z.object({ + ...sideEffectBlockFields, + tool: z.string().nullable().describe('Tool sent; null when the whole block ran.'), + }) + ) + .describe('Writes sent for real because `run.allowBlocks` named their block.'), + unchecked: z + .array( + z.object({ + ...sideEffectBlockFields, + reason: z.string().describe('Why the run cannot see what this block changed.'), + }) + ) + .describe( + 'Blocks that ran for real whose own effects the run cannot see: Function blocks, whose code may make network calls.' + ), + omitted: z.number().int().nonnegative().describe('Entries left out once a list held 50.'), + }) + .meta({ + id: 'WorkflowRunSideEffects', + title: 'Workflow run side effects', + description: 'What a dry run did with each write it reached.', + }) + /** * The run result resource. In-band run failures are `status: 'failed'` * with a structured `error` — never an HTTP error: **a `runId` means 200/202 + @@ -1997,6 +2080,9 @@ export const v2ExecuteWorkflowDataSchema = z }) .nullable() .describe('Where the run waits when `status` is `paused`; null otherwise.'), + sideEffects: v2RunSideEffectsSchema + .optional() + .describe('What a dry run (`run.dry`) did with each write it reached; absent otherwise.'), }) .meta({ id: 'WorkflowRunResult', @@ -2090,7 +2176,7 @@ export const v2ResumeWorkflowQueuedSchema = v2ExecuteWorkflowQueuedSchema export type V2ResumeWorkflowQueued = z.output export const v2ResumeWorkflowDataSchema = v2ExecuteWorkflowDataSchema - .omit({ executionTimeoutSeconds: true }) + .omit({ executionTimeoutSeconds: true, sideEffects: true }) .extend({ error: v2ExecutionErrorSchema .omit({ rerunFromBlockId: true }) diff --git a/apps/sim/lib/workflow-tests/session.ts b/apps/sim/lib/workflow-tests/session.ts index 65340e4b364..f925a4189d5 100644 --- a/apps/sim/lib/workflow-tests/session.ts +++ b/apps/sim/lib/workflow-tests/session.ts @@ -21,13 +21,12 @@ import { type WorkflowTestRunResult, type WorkflowTestVersion, } from '@/lib/workflows/application/run-workflow-for-test' -import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' +import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run' import { loadDeployedWorkflowState, loadWorkflowFromNormalizedTables, } from '@/lib/workflows/persistence/utils' import { getActiveWorkflowName, listActiveWorkflowsNamed } from '@/lib/workflows/queries' -import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload' import { resolveTriggerRunOptions } from '@/lib/workflows/triggers/run-options' import { AGENT, normalizeName } from '@/executor/constants' import type { TestWorkflowBlock } from '@/executor/execution/types' @@ -35,7 +34,6 @@ import type { ExecutionResult } from '@/executor/types' import { hasExecutionResult, readAttemptedExecutionId } from '@/executor/utils/errors' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' -import { getToolOutputsMetadata } from '@/tools/metadata-outputs' import { hasToolId } from '@/tools/tool-ids' /** How long one `testNext` broker call waits before answering `waiting`, well under the broker timeout. */ @@ -192,19 +190,6 @@ function sameTool(mockToolId: string, toolId: string): boolean { ) } -/** Placeholder output shaped like a block's real one, for its configured operation. */ -function sampleBlockOutput(block: TestWorkflowBlock | undefined): Record { - if (!block) return {} - const subBlocks: Record = {} - for (const [key, value] of Object.entries(block.params)) subBlocks[key] = { value } - return generateMockPayloadFromOutputsDefinition(getEffectiveBlockOutputs(block.type, subBlocks)) -} - -function sampleToolOutput(toolId: string): Record { - const outputs = getToolOutputsMetadata(toolId) - return outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} -} - interface ToolMock { /** The Agent block it answers for; null answers every Agent. */ blockId: string | null @@ -473,6 +458,7 @@ class TestWorkflowRun { const { blockId, blockName, input, branchIndex } = parked.call const key = this.matcher.mockKey(blockId) if (!key) throw new Error(`Block ${blockName} was parked without a mock`) + const block = this.matcher.block(blockId) return { kind: 'mock', runId: this.id, @@ -480,7 +466,7 @@ class TestWorkflowRun { key, block: blockName, input, - sample: sampleBlockOutput(this.matcher.block(blockId)), + sample: block ? sampleBlockOutput(block) : {}, ...(branchIndex !== undefined ? { branchIndex } : {}), } } diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts new file mode 100644 index 00000000000..56c3315732d --- /dev/null +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -0,0 +1,346 @@ +/** + * Dry runs against real PostgreSQL, through the manual run use case: a dry run writes no table row + * and sends no HTTP request, and reports both writes with the payloads they would have sent (the + * run's secrets redacted) under the `test` trigger; an allowed block writes for real while reads + * run for real; a child workflow's write stays stubbed; and a mocked block steers a branch. + */ +import { db } from '@sim/db' +import { + permissions, + user, + userStats, + userTableDefinitions, + userTableRows, + workflow, + workflowExecutionLogs, + workflowExecutionSnapshots, + workspace, + workspaceEnvironment, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory' +import { sleep } from '@sim/utils/helpers' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, SubBlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { closeRedisConnection } from '@/lib/core/config/redis' +import { encryptSecret } from '@/lib/core/security/encryption' +import { + type ExecuteManualWorkflowInput, + executeManualWorkflowOperation, +} from '@/lib/workflows/application/execute-manual-workflow' +import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' +import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' + +const ownerId = generateId() +const workspaceId = generateId() +const parentId = generateId() +const childId = generateId() +const branchingId = generateId() +const tableId = generateId() +const SECRET = `dry-secret-${generateId()}` +const principal = createDelegatedPrincipal({ + subjectUserId: ownerId, + workspaceId, + audience: 'sim:workflows', +}) + +/** Block ids are global keys, so each block gets a fresh one; tests address blocks by name. */ +function block( + name: string, + type: string, + values: Record = {} +): BlockState { + return { + id: generateId(), + type, + name, + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: Object.fromEntries( + Object.entries(values).map(([key, value]) => [key, { id: key, type: 'short-input', value }]) + ), + } +} + +/** A graph of `blocks`, wired by `[source, target, sourceHandle?]` block names. */ +function graph( + blocks: BlockState[], + edges: Array<[string, string, string?]> +): { state: WorkflowState; idOf: (name: string) => string } { + const idOf = (name: string) => { + const found = blocks.find((entry) => entry.name === name) + if (!found) throw new Error(`No block ${name}`) + return found.id + } + const state: WorkflowState = { + blocks: Object.fromEntries(blocks.map((entry) => [entry.id, entry])), + edges: edges.map(([source, target, handle]) => ({ + id: generateId(), + source: idOf(source), + target: idOf(target), + ...(handle ? { sourceHandle: handle } : {}), + })), + loops: {}, + parallels: {}, + } + return { state, idOf } +} + +const upsertLead = (id: string, email: string) => + block(id, 'table', { + operation: 'upsert_row', + tableSelector: tableId, + data: JSON.stringify({ email, score: 82 }), + }) + +/** A POST to a host that never resolves: sent, it fails the run. Its body carries a secret. */ +const notify = (id: string) => + block(id, 'api', { + url: 'http://dry-run.invalid/hook', + method: 'POST', + body: JSON.stringify({ email: 'a@b.co', note: 'key={{DRY_SECRET}}' }), + }) + +/** Start → lookup (read) → save (table upsert) → notify (HTTP POST) → child (Workflow block). */ +const parent = graph( + [ + block('start', 'start_trigger'), + block('lookup', 'table', { operation: 'query_rows', tableSelector: tableId }), + upsertLead('save', 'a@b.co'), + notify('notify'), + block('child', 'workflow', { workflowId: childId }), + ], + [ + ['start', 'lookup'], + ['lookup', 'save'], + ['save', 'notify'], + ['notify', 'child'], + ] +) + +const child = graph( + [block('start', 'start_trigger'), upsertLead('childsave', 'child@b.co')], + [['start', 'childsave']] +) + +/** Start → lookup → gate: over 50 rows goes to `big`, else to `small`; both are POSTs. */ +const gate = block('gate', 'condition') +gate.subBlocks.conditions = { + id: 'conditions', + type: 'condition-input', + value: JSON.stringify([ + { id: `${gate.id}-if`, title: 'if', value: ' > 50' }, + { id: `${gate.id}-else`, title: 'else', value: '' }, + ]), +} +const branching = graph( + [ + block('start', 'start_trigger'), + block('lookup', 'table', { operation: 'query_rows', tableSelector: tableId }), + gate, + notify('big'), + notify('small'), + ], + [ + ['start', 'lookup'], + ['lookup', 'gate'], + ['gate', 'big', `condition-${gate.id}-if`], + ['gate', 'small', `condition-${gate.id}-else`], + ] +) + +async function run( + workflowId: string, + options: Partial = {} +): Promise { + const executionId = generateId() + const result = await executeManualWorkflowOperation.execute({ + principal, + input: { + workflowId, + requestId: generateId(), + executionId, + input: {}, + mode: 'sync', + requestHeaders: new Headers(), + useMockPayload: false, + ...options, + }, + }) + if (!result.ok || !('status' in result)) { + throw new Error(`Run did not settle: ${JSON.stringify(result)}`) + } + const deadline = Date.now() + 10_000 + while ((await getWorkflowExecutionLogStatus(executionId, workflowId)) !== result.status) { + if (Date.now() >= deadline) throw new Error('Run did not persist its terminal log') + await sleep(25) + } + return result +} + +async function rowEmails(): Promise { + const rows = await db + .select({ data: userTableRows.data }) + .from(userTableRows) + .where(eq(userTableRows.tableId, tableId)) + return rows.map((row) => JSON.stringify(row.data)) +} + +async function triggerOf(executionId: string): Promise { + const [log] = await db + .select({ trigger: workflowExecutionLogs.trigger }) + .from(workflowExecutionLogs) + .where(eq(workflowExecutionLogs.executionId, executionId)) + return log?.trigger +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Dry run fixture', + email: `${ownerId}@dry-run.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ id: generateId(), userId: ownerId }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Dry run fixture', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId: ownerId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + await db.insert(workspaceEnvironment).values({ + id: generateId(), + workspaceId, + variables: { DRY_SECRET: (await encryptSecret(SECRET)).encrypted }, + }) + await db.insert(userTableDefinitions).values({ + id: tableId, + workspaceId, + name: 'leads', + createdBy: ownerId, + schema: { + columns: [ + { id: 'col_email', name: 'email', type: 'string', required: true, unique: true }, + { id: 'col_score', name: 'score', type: 'number' }, + ], + }, + }) + for (const [id, state] of [ + [parentId, parent], + [childId, child], + [branchingId, branching], + ] as const) { + await db.insert(workflow).values({ + id, + userId: ownerId, + workspaceId, + name: `Dry run ${id}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const saved = await saveWorkflowToNormalizedTables(id, state.state) + expect(saved.success, saved.error).toBe(true) + } +}) + +afterAll(async () => { + const workflowIds = [parentId, childId, branchingId] + await db + .delete(workflowExecutionLogs) + .where(inArray(workflowExecutionLogs.workflowId, workflowIds)) + await db + .delete(workflowExecutionSnapshots) + .where(inArray(workflowExecutionSnapshots.workflowId, workflowIds)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) + await closeRedisConnection() + await db.$client.end() +}) + +describe('a dry run', () => { + it('writes no row and sends no request, and reports each write it held back', async () => { + const result = await run(parentId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(await rowEmails()).toEqual([]) + expect(await triggerOf(result.executionId)).toBe('test') + + const stubbed = result.sideEffects?.stubbed ?? [] + expect(stubbed.map((entry) => [entry.workflowId, entry.block, entry.tool])).toEqual([ + [parentId, 'save', 'table_upsert_row'], + [parentId, 'notify', 'http_request'], + [childId, 'childsave', 'table_upsert_row'], + ]) + expect(stubbed[0].request).toMatchObject({ + tableId, + data: { email: 'a@b.co', score: 82 }, + }) + expect(stubbed[1].request).toMatchObject({ + method: 'POST', + url: 'http://dry-run.invalid/hook', + body: { email: 'a@b.co' }, + }) + expect(JSON.stringify(stubbed[1].request)).not.toContain(SECRET) + expect(stubbed[2].request).toMatchObject({ data: { email: 'child@b.co' } }) + expect(result.sideEffects?.allowed).toEqual([]) + }) + + it('sends an allowed block’s write and still runs reads for real', async () => { + const allowed = await run(parentId, { dry: true, allowBlocks: ['save'] }) + + expect(allowed.status, JSON.stringify(allowed.error)).toBe('completed') + expect(await rowEmails()).toEqual([expect.stringContaining('a@b.co')]) + expect(allowed.sideEffects?.allowed).toEqual([ + { + workflowId: parentId, + blockId: parent.idOf('save'), + block: 'save', + tool: 'table_upsert_row', + }, + ]) + expect(allowed.sideEffects?.stubbed.map((entry) => entry.block)).toEqual([ + 'notify', + 'childsave', + ]) + + const reread = await run(parentId, { dry: true, selectedOutputs: ['lookup.rows'] }) + expect(JSON.stringify(reread.blockOutputs?.['lookup.rows'])).toContain('a@b.co') + expect(await rowEmails()).toHaveLength(1) + }) + + it('takes the branch a mocked block steers it to', async () => { + const unmocked = await run(branchingId, { dry: true }) + expect(unmocked.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['small']) + + const mocked = await run(branchingId, { + dry: true, + mocks: { lookup: { rows: [], rowCount: 0, totalCount: 99 } }, + }) + expect(mocked.status, JSON.stringify(mocked.error)).toBe('completed') + expect(mocked.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['big']) + }) + + it('refuses to allow a block outside a dry run, or one the draft does not have', async () => { + await expect(run(parentId, { allowBlocks: ['save'] })).rejects.toThrow( + 'run.allowBlocks requires run.dry' + ) + await expect(run(parentId, { dry: true, allowBlocks: ['nope'] })).rejects.toThrow( + /run\.allowBlocks "nope" is not a block/ + ) + }) +}) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index bd69f895b17..8c0e1afc404 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,4 +1,5 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' +import { isPlainRecord } from '@sim/utils/object' import { formatQuotedNameList } from '@sim/utils/string' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' @@ -11,6 +12,11 @@ import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/aut import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import type { ExecuteWorkflowInput } from '@/lib/workflows/application/execute-workflow' import { workflowOperations } from '@/lib/workflows/application/operations' +import { + createBlockMockHooks, + DryRunSideEffects, + PAUSING_BLOCK_TYPES, +} from '@/lib/workflows/dry-run' import { type ExecuteWorkflowServiceResult, executeWorkflowService, @@ -29,6 +35,12 @@ interface ManualExecutionInput extends Omit } export interface ExecuteManualWorkflowInput extends ManualExecutionInput { @@ -154,6 +166,53 @@ function resolveStopAfterBlock( return blockId } +/** + * The dry run and block mocks a manual run asked for, their blocks resolved like + * {@link resolveBlockSelector}. A dry run is logged under the `test` trigger, never as a manual + * run, and returns its side effects with the result it waits for, so it cannot stream or detach. + */ +function resolveRunOverrides(state: ManualWorkflowState, input: ManualExecutionInput) { + if (input.allowBlocks?.length && !input.dry) { + throw new OrchestrationError('validation', 'run.allowBlocks requires run.dry') + } + if (input.dry && (input.mode === 'stream' || input.detachable)) { + throw new OrchestrationError( + 'validation', + 'run.dry returns its side effects with the run result, so it cannot be combined with stream or waitTimeoutSeconds' + ) + } + const allowBlockIds = new Set() + for (const selector of input.allowBlocks ?? []) { + const blockId = resolveBlockSelector(state, selector, 'run.allowBlocks') + if (PAUSING_BLOCK_TYPES.has(state.blocks[blockId].type)) { + throw new OrchestrationError( + 'validation', + `run.allowBlocks "${selector}" pauses the run, which would resume without the dry run; mock its output with run.mocks instead.` + ) + } + allowBlockIds.add(blockId) + } + const mocks = new Map>() + for (const [selector, output] of Object.entries(input.mocks ?? {})) { + if (!isPlainRecord(output)) { + throw new OrchestrationError( + 'validation', + `run.mocks "${selector}" must be an object, the output the block returns` + ) + } + const blockId = resolveBlockSelector(state, selector, 'run.mocks') + if (mocks.has(blockId)) { + throw new OrchestrationError('validation', `run.mocks names block "${blockId}" twice`) + } + mocks.set(blockId, output) + } + return { + triggerType: input.dry ? ('test' as const) : ('manual' as const), + dryRun: input.dry ? new DryRunSideEffects({ allowBlockIds, pausingBlocks: 'stub' }) : undefined, + testHooks: mocks.size > 0 ? createBlockMockHooks(mocks) : undefined, + } +} + function listTriggers(options: ReturnType): string { return options.map((option) => `${option.triggerBlockId} (${option.blockName})`).join(', ') } @@ -167,6 +226,7 @@ function executionServiceInput(params: { stopAfterBlockId: string | undefined }) { return { + ...resolveRunOverrides(params.draftState, params.input), workflowId: params.context.workflowId, principal: params.principal, userId: requirePrincipalSubjectUserId(params.principal), @@ -191,7 +251,6 @@ function executionServiceInput(params: { requestHeaders: params.input.requestHeaders, includeThinking: params.input.includeThinking, includeToolCalls: params.input.includeToolCalls, - triggerType: 'manual' as const, useDraftState: true, draftState: params.draftState, } diff --git a/apps/sim/lib/workflows/application/run-workflow-for-test.ts b/apps/sim/lib/workflows/application/run-workflow-for-test.ts index 448eb42bce9..067c893e2c8 100644 --- a/apps/sim/lib/workflows/application/run-workflow-for-test.ts +++ b/apps/sim/lib/workflows/application/run-workflow-for-test.ts @@ -16,6 +16,7 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { generateRequestId } from '@/lib/core/utils/request' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { resolveTriggerExecution } from '@/lib/workflows/application/run-workflow-from-copilot' +import { DryRunSideEffects } from '@/lib/workflows/dry-run' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import type { ExecutionTestHooks } from '@/executor/execution/types' import type { ExecutionResult } from '@/executor/types' @@ -43,8 +44,9 @@ export interface RunWorkflowForTestInput { /** * One workflow run inside a workflow test: the workflow's single runnable trigger, the - * test's input, and its mocks installed as executor test hooks. Billed and logged like any - * run, under the `test` trigger. + * test's input, and its mocks installed as executor test hooks. A write the test does not mock + * is not sent: as in a dry run, it is answered with a placeholder shaped like the tool's output. + * Billed and logged like any run, under the `test` trigger. * * A step of the `workflow_tests.run` operation, which authorized the caller's write access to * the workspace before any test ran; nothing else may call it. Each nested run is not @@ -136,6 +138,7 @@ export async function runWorkflowForTest( abortSignal: input.abortSignal, billingAttribution, testHooks: input.testHooks, + sideEffects: new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'run' }), }, executionId ) diff --git a/apps/sim/lib/workflows/dry-run/block-mocks.ts b/apps/sim/lib/workflows/dry-run/block-mocks.ts new file mode 100644 index 00000000000..fa85e2221b4 --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/block-mocks.ts @@ -0,0 +1,27 @@ +import type { ExecutionTestHooks } from '@/executor/execution/types' +import type { NormalizedBlockOutput } from '@/executor/types' + +/** + * Test hooks that answer each block in `outputs` (keyed by workflow block id) with its output + * instead of running its handler (`run.mocks`). Normalization, logging and edges run as for any + * mocked block. Child workflows inherit the hooks, where these ids name no block. + */ +export function createBlockMockHooks( + outputs: ReadonlyMap +): ExecutionTestHooks { + return { + enterWorkflow: async () => {}, + mocksBlock: (blockId) => outputs.has(blockId), + resolveMock: async (call) => { + const output = outputs.get(call.blockId) + if (!output) throw new Error(`Block ${call.blockName} has no mock`) + return output + }, + mocksTool: () => false, + resolveToolMock: async (call) => { + throw new Error(`Tool ${call.toolId} has no mock`) + }, + spiesBlock: () => false, + recordSpy: () => {}, + } +} diff --git a/apps/sim/lib/workflows/dry-run/index.ts b/apps/sim/lib/workflows/dry-run/index.ts new file mode 100644 index 00000000000..2d4cb5bfeb7 --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/index.ts @@ -0,0 +1,7 @@ +export { createBlockMockHooks } from './block-mocks' +export { sampleBlockOutput, sampleToolOutput } from './samples' +export { + DryRunSideEffects, + PAUSING_BLOCK_TYPES, + type SideEffectsSummary, +} from './side-effects' diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts new file mode 100644 index 00000000000..886b4bc2f4e --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -0,0 +1,19 @@ +import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' +import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload' +import { getToolOutputsMetadata } from '@/tools/metadata-outputs' + +/** Placeholder output shaped like a block's real one, for the operation its params configure. */ +export function sampleBlockOutput(block: { + type: string + params: Record +}): Record { + const subBlocks: Record = {} + for (const [key, value] of Object.entries(block.params)) subBlocks[key] = { value } + return generateMockPayloadFromOutputsDefinition(getEffectiveBlockOutputs(block.type, subBlocks)) +} + +/** Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. */ +export function sampleToolOutput(toolId: string): Record { + const outputs = getToolOutputsMetadata(toolId) + return outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} +} diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts new file mode 100644 index 00000000000..9031bcea9d5 --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -0,0 +1,147 @@ +import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run/samples' +import { BlockType, HUMAN_IN_THE_LOOP_BLOCK_TYPES } from '@/executor/constants' +import type { + SideEffectPolicy, + SideEffectSite, + StubbedBlockCall, + StubbedToolCall, +} from '@/executor/execution/types' +import type { NormalizedBlockOutput } from '@/executor/types' + +/** Each list keeps at most this many entries; `omitted` counts the rest. */ +const MAX_RECORDED = 50 + +/** + * The one tool a dry run sends although it is a `write`: `function_execute` runs a Function + * block's code, which is the workflow's own logic rather than a side effect, so it runs and the + * block is listed as unchecked (its code can make network calls the run cannot see). + */ +const WORKFLOW_CODE_TOOL_ID = 'function_execute' + +/** Blocks whose handlers change state outside the tool seam, so a dry run answers them whole. */ +const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) + +/** + * Blocks that pause the run. A paused run resumes later without its dry run, so a dry run + * answers them whole and never pauses; they cannot be allowed. + */ +export const PAUSING_BLOCK_TYPES: ReadonlySet = new Set([ + ...HUMAN_IN_THE_LOOP_BLOCK_TYPES, + BlockType.WAIT, +]) + +interface RecordedSite { + workflowId: string + blockId: string + block: string +} + +/** A write the run did not send: the request it would have sent and the placeholder it got. */ +interface StubbedSideEffect extends RecordedSite { + /** The tool called; null when the whole block was answered instead of run. */ + tool: string | null + request: Record | null + returned: Record +} + +/** A write sent for real because its block was allowed. */ +interface AllowedSideEffect extends RecordedSite { + tool: string | null +} + +/** A block that ran for real whose effects the run cannot see. */ +interface UncheckedSideEffect extends RecordedSite { + reason: string +} + +/** What a dry run did with each write it reached; each list holds at most {@link MAX_RECORDED}. */ +export interface SideEffectsSummary { + stubbed: StubbedSideEffect[] + allowed: AllowedSideEffect[] + unchecked: UncheckedSideEffect[] + /** Entries left out of the lists above once they were full. */ + omitted: number +} + +function recordedSite(site: SideEffectSite): RecordedSite { + return { workflowId: site.workflowId, blockId: site.blockId, block: site.blockName } +} + +/** + * The side-effect policy of a dry run (`run.dry`) and of a workflow test's unmocked writes: every + * write tool call is answered with a placeholder shaped like the tool's output and recorded with + * the request it would have sent, except an allowed block's, which are sent and recorded. Reads + * always run. `pausingBlocks: 'stub'` also answers {@link PAUSING_BLOCK_TYPES} whole. + */ +export class DryRunSideEffects implements SideEffectPolicy { + private readonly stubbed: StubbedSideEffect[] = [] + private readonly allowed: AllowedSideEffect[] = [] + private readonly unchecked = new Map() + private omitted = 0 + + constructor( + private readonly options: { + /** Top-level workflow blocks whose writes are sent. */ + allowBlockIds: ReadonlySet + pausingBlocks: 'run' | 'stub' + } + ) {} + + private record(list: T[], entry: T): void { + if (list.length < MAX_RECORDED) list.push(entry) + else this.omitted++ + } + + sendsWrite(call: SideEffectSite & { toolId: string }): boolean { + if (call.toolId === WORKFLOW_CODE_TOOL_ID) { + const key = `${call.workflowId}:${call.blockId}` + if (this.unchecked.has(key)) return true + if (this.unchecked.size < MAX_RECORDED) { + this.unchecked.set(key, { + ...recordedSite(call), + reason: 'Its code ran for real; network calls it makes are not stubbed', + }) + } else this.omitted++ + return true + } + if (!this.options.allowBlockIds.has(call.blockId)) return false + this.record(this.allowed, { ...recordedSite(call), tool: call.toolId }) + return true + } + + stubWrite(call: StubbedToolCall): Record { + const returned = sampleToolOutput(call.toolId) + this.record(this.stubbed, { + ...recordedSite(call), + tool: call.toolId, + request: call.request, + returned, + }) + return returned + } + + stubsBlock(block: SideEffectSite): boolean { + if (this.options.pausingBlocks === 'stub' && PAUSING_BLOCK_TYPES.has(block.blockType)) { + return true + } + if (!SELF_DIRECTED_BLOCK_TYPES.has(block.blockType)) return false + if (!this.options.allowBlockIds.has(block.blockId)) return true + this.record(this.allowed, { ...recordedSite(block), tool: null }) + return false + } + + stubBlock(call: StubbedBlockCall): NormalizedBlockOutput { + const returned = sampleBlockOutput({ type: call.blockType, params: call.input }) + this.record(this.stubbed, { ...recordedSite(call), tool: null, request: call.input, returned }) + return returned + } + + summary(): SideEffectsSummary { + return { + stubbed: [...this.stubbed], + allowed: [...this.allowed], + unchecked: [...this.unchecked.values()], + omitted: this.omitted, + } + } +} diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index aadcba4b1f2..2377438d370 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -22,6 +22,7 @@ import { LoggingSession } from '@/lib/logs/execution/logging-session' import type { TraceSpan } from '@/lib/logs/types' import { MAX_MCP_WORKFLOW_RESPONSE_BYTES } from '@/lib/mcp/constants' import { hydrateUserFilesWithBase64 } from '@/lib/uploads/utils/user-file-base64.server' +import type { DryRunSideEffects, SideEffectsSummary } from '@/lib/workflows/dry-run' import { enqueueWorkflowExecution } from '@/lib/workflows/executor/enqueue-execution' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core' @@ -52,7 +53,11 @@ import { import { workflowHasResponseBlock } from '@/lib/workflows/utils' import { normalizeName } from '@/executor/constants' import { ExecutionSnapshot } from '@/executor/execution/snapshot' -import type { ExecutionMetadata, SerializableExecutionState } from '@/executor/execution/types' +import type { + ExecutionMetadata, + ExecutionTestHooks, + SerializableExecutionState, +} from '@/executor/execution/types' import type { BlockLog, NormalizedBlockOutput } from '@/executor/types' import { classifyExecutionError, @@ -154,6 +159,14 @@ export interface ExecuteWorkflowServiceParams { } /** Saved block after which execution stops, validated by the application use case. */ stopAfterBlockId?: string + /** + * A dry run: writes are answered with placeholders, and what each would have sent is returned + * as the run's `sideEffects`. Requires `useDraftState` and a `sync` or non-detachable + * `sync-result-stream` run, the modes that return the run's result. + */ + dryRun?: DryRunSideEffects + /** Blocks answered with fixed outputs instead of running, built by the application use case. */ + testHooks?: ExecutionTestHooks } export interface ExecuteWorkflowServiceFailure { @@ -189,6 +202,8 @@ export interface ExecuteWorkflowServiceRun { executionTimeoutMs: number /** Where a `paused` run waits; absent otherwise. */ paused?: RunPause | null + /** What a dry run did with each write it reached; absent for any other run. */ + sideEffects?: SideEffectsSummary } /** A run's result before the applied timeout is stamped onto it. */ @@ -334,6 +349,8 @@ export async function executeWorkflowService( runFromBlock, stopAfterBlockId, detachable = false, + dryRun, + testHooks, } = params let reqLogger = logger.withMetadata({ requestId, workflowId, userId }) @@ -357,6 +374,12 @@ export async function executeWorkflowService( if (draftState && !useDraftState) { throw new Error('A preloaded draft state requires manual execution state') } + if ((dryRun || testHooks) && !useDraftState) { + throw new Error('Dry runs and block mocks require manual execution state') + } + if (dryRun && (mode === 'stream' || detachable)) { + throw new Error('A dry run returns its side effects with the result it waits for') + } if (detachable && (mode !== 'sync-result-stream' || abortSignal)) { throw new Error('A detachable run returns its pending result and outlives its request') } @@ -450,6 +473,8 @@ export async function executeWorkflowService( executionId, requestId, checkDeployment: !useDraftState, + // A draft run is unmetered like the editor's, under `manual` or, for a dry run, `test`. + ...(useDraftState ? { checkRateLimit: false } : {}), rateLimitCounter: detachable ? 'async' : rateLimitCounter, loggingSession, useAuthenticatedUserAsActor, @@ -671,6 +696,7 @@ export async function executeWorkflowService( pinnedDeploymentVersionId: deploymentVersionId, runFromBlock, stopAfterBlockId, + testHooks, onStream, onBlockComplete: (blockId, data) => onBlockComplete(blockId, data.output, data.outputBlockId), @@ -776,6 +802,8 @@ export async function executeWorkflowService( runFromBlock, stopAfterBlockId, draftState, + testHooks, + sideEffects: dryRun, }) await handlePostExecutionPauseState({ result, workflowId, executionId, loggingSession }) @@ -980,8 +1008,18 @@ export async function executeWorkflowService( } const pending = runSynchronousWorkflow().then( - (result): ExecuteWorkflowServiceTerminalResult => - result.ok ? { ...result, executionTimeoutMs } : result + async (result): Promise => + result.ok + ? { + ...result, + executionTimeoutMs, + ...(dryRun + ? { + sideEffects: await compactServiceOutput(dryRun.summary(), compactionContext), + } + : {}), + } + : result ) if (mode === 'sync-result-stream') { /** Keep the claim until the pending run can prove whether durable ownership exists. */ diff --git a/apps/sim/lib/workflows/executor/execute-workflow.ts b/apps/sim/lib/workflows/executor/execute-workflow.ts index 6d227db04fb..6f66c39675b 100644 --- a/apps/sim/lib/workflows/executor/execute-workflow.ts +++ b/apps/sim/lib/workflows/executor/execute-workflow.ts @@ -18,6 +18,7 @@ import type { ExecutionMetadata, ExecutionTestHooks, SerializableExecutionState, + SideEffectPolicy, } from '@/executor/execution/types' import type { ExecutionResult, StreamingExecution } from '@/executor/types' import { attachExecutionResult, hasExecutionResult } from '@/executor/utils/errors' @@ -66,6 +67,8 @@ export interface ExecuteWorkflowOptions { stopAfterBlockId?: string /** Workflow test run: mocked blocks await these hooks instead of running. */ testHooks?: ExecutionTestHooks + /** A dry run's or workflow test's handling of writes; every child execution inherits it. */ + sideEffects?: SideEffectPolicy /** Run-from-block configuration using a prior execution snapshot. */ runFromBlock?: { startBlockId: string @@ -233,6 +236,7 @@ export async function executeWorkflow( abortSignal: streamConfig?.abortSignal, stopAfterBlockId: streamConfig?.stopAfterBlockId, testHooks: streamConfig?.testHooks, + sideEffects: streamConfig?.sideEffects, trustedInitialResolvedSecretTraceProvenance: streamConfig?.trustedInitialResolvedSecretTraceProvenance, runFromBlock: streamConfig?.runFromBlock, diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index 709587b26b4..b47074ca6b0 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -62,6 +62,7 @@ import type { ExecutionTestHooks, IterationContext, SerializableExecutionState, + SideEffectPolicy, } from '@/executor/execution/types' import type { ExecutionResult, StartBlockRunMetadata } from '@/executor/types' import { hasExecutionResult } from '@/executor/utils/errors' @@ -147,6 +148,8 @@ export interface ExecuteWorkflowCoreOptions { base64MaxBytes?: number stopAfterBlockId?: string testHooks?: ExecutionTestHooks + /** A dry run's or workflow test's handling of writes; every child execution inherits it. */ + sideEffects?: SideEffectPolicy /** Trusted encrypted provenance captured by a server-only pre-execution boundary. */ trustedInitialResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceV1 /** Immutable deployment admitted by the durable parent log for a resumed execution. */ @@ -665,6 +668,7 @@ async function executeWorkflowCoreImpl( includeFileBase64, base64MaxBytes, testHooks, + sideEffects, runFromBlock, resumeDeploymentVersionId, draftState, @@ -1329,6 +1333,7 @@ async function executeWorkflowCoreImpl( base64MaxBytes, stopAfterBlockId: resolvedStopAfterBlockId, ...(testHooks ? { testHooks } : {}), + ...(sideEffects ? { sideEffects } : {}), onChildWorkflowInstanceReady, callChain: metadata.callChain, // The live block stream has a single known, authenticated Sim viewer only on diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index 91176fb8694..032cc4601c0 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -77,6 +77,7 @@ import { executeVantaTool } from '@/lib/internal/vanta/execute-tool' import { buildDirectVideoRequest } from '@/lib/internal/video/direct-request' import { buildFalVideoRequest } from '@/lib/internal/video/fal-request' import { projectToolResultForCopilot } from '@/lib/mothership/request/tools/resolved-secret-result' +import { DryRunSideEffects } from '@/lib/workflows/dry-run' import { VideoGeneratorV2Block, VideoGeneratorV3Block } from '@/blocks/blocks/video_generator' import { ANONYMOUS_SECRET_TRACE_REPLACEMENT, @@ -7490,6 +7491,22 @@ describe('MCP Tool Execution', () => { }) }) + it('stubs an MCP tool in a dry run, since it declares no effect', async () => { + const dryRun = new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'stub' }) + + const result = await executeTool( + 'mcp-123-delete_file', + { path: '/test', _context: { blockId: 'agent-1' } }, + { executionContext: createToolExecutionContext({ sideEffects: dryRun }) } + ) + + expect(mockExecuteInternalToolOperation).not.toHaveBeenCalled() + expect(result.success).toBe(true) + expect(dryRun.summary().stubbed).toEqual([ + expect.objectContaining({ blockId: 'agent-1', tool: 'mcp-123-delete_file' }), + ]) + }) + it('preserves MCP operation error envelopes', async () => { const fetchSpy = vi.spyOn(globalThis, 'fetch') mockExecuteInternalToolOperation.mockResolvedValueOnce( diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index d11ec711921..b996485f7fc 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -133,6 +133,7 @@ import { readRequestedDeadline, } from '@/tools/request-transport' import { AWS_CREDENTIAL_OAUTH, AWS_SESSION_SIGNED_TOOL_IDS } from '@/tools/shared/saved-credentials' +import { answerUnsentWrite, describeToolRequest } from '@/tools/side-effects' import type { BYOKProviderId, CredentialParamSource, @@ -1916,6 +1917,16 @@ async function executeToolImplementation( logger.error(`Custom tool not found: ${normalizedToolId}`, { requestId }) } } else if (isMcpTool(normalizedToolId)) { + // An MCP tool declares no effect, so a dry run never sends one. + const unsent = answerUnsentWrite({ + toolId: normalizedToolId, + params, + executionContext, + registry: resolvedSecretTraceRegistry, + describeRequest: () => + Object.fromEntries(Object.entries(params).filter(([key]) => !key.startsWith('_'))), + }) + if (unsent) return unsent return await executeMcpTool( normalizedToolId, params, @@ -2243,6 +2254,8 @@ async function executeToolImplementation( // copies (`normalizeStringRecord`); this boundary is the longest-lived one. environmentVariables: { ...executionContext?.environmentVariables }, piiBlockOutputRedaction: executionContext?.piiBlockOutputRedaction, + // The child runs under this run's side-effect policy, so its own writes are decided. + sideEffects: executionContext?.sideEffects, } ) const endTime = new Date() @@ -2286,6 +2299,7 @@ async function executeToolImplementation( abortSignal: effectiveSignal, resolvedSecretTraceRegistry, principal: executionContext?.principal, + sideEffects: executionContext?.sideEffects, } ) const endTime = new Date() @@ -2302,6 +2316,20 @@ async function executeToolImplementation( } } + // After the workflow-running tools above, whose children decide their own writes. + if (tool.effect !== 'read') { + const unsentTool = tool + const unsent = answerUnsentWrite({ + toolId: normalizedToolId, + params: contextParams, + executionContext, + registry: resolvedSecretTraceRegistry, + describeRequest: () => + describeToolRequest(unsentTool, contextParams, resolvedSecretTraceRegistry), + }) + if (unsent) return unsent + } + if (tool.operation) { const result = await executeDeclaredInternalOperation({ toolId: normalizedToolId, diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts new file mode 100644 index 00000000000..bdca98c9d0f --- /dev/null +++ b/apps/sim/tools/side-effects.test.ts @@ -0,0 +1,39 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { DryRunSideEffects } from '@/lib/workflows/dry-run' +import type { ExecutionContext } from '@/executor/types' +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' +import { answerUnsentWrite } from '@/tools/side-effects' + +describe('a write a dry run does not send', () => { + it('records its request without the credentials the call resolved, wherever they appear', () => { + const dryRun = new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'stub' }) + const params = { + accessToken: 'oauth-token-123', + apiKey: 'hosted-key-456', + channel: 'ops', + _context: { blockId: 'notify' }, + } + + const response = answerUnsentWrite({ + toolId: 'slack_message', + params, + executionContext: { workflowId: 'wf-1', sideEffects: dryRun } as ExecutionContext, + registry: new ResolvedSecretTraceRegistry(), + describeRequest: () => ({ + method: 'POST', + url: 'https://slack.example/api?token=oauth-token-123', + body: { channel: 'ops', text: 'sent with hosted-key-456', apiKey: 'hosted-key-456' }, + }), + }) + + expect(response?.success).toBe(true) + const [stubbed] = dryRun.summary().stubbed + expect(stubbed.request).toMatchObject({ method: 'POST', body: { channel: 'ops' } }) + const recorded = JSON.stringify(stubbed.request) + expect(recorded).not.toContain('oauth-token-123') + expect(recorded).not.toContain('hosted-key-456') + }) +}) diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts new file mode 100644 index 00000000000..231a9668c6c --- /dev/null +++ b/apps/sim/tools/side-effects.ts @@ -0,0 +1,117 @@ +/** + * Where a run's side-effect policy (a dry run, or a workflow test's unmocked writes) meets a tool + * call: `executeTool` asks {@link answerUnsentWrite} about every call not declared `read`, after + * credentials resolve and before anything is sent. + */ +import { isPlainRecord, toRecord } from '@sim/utils/object' +import { + isSensitiveKey, + REDACTED_MARKER, + redactExactSensitiveValues, +} from '@/lib/core/security/redaction' +import type { SideEffectSite } from '@/executor/execution/types' +import type { ExecutionContext } from '@/executor/types' +import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' +import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' +import { stripCloneSuffixes } from '@/executor/utils/subflow-node-id-codec' +import { prepareToolRequest, projectToolModelInputParams } from '@/tools/request-transport' +import { type ExecutableToolConfig, isInternalToolConfig, type ToolResponse } from '@/tools/types' + +/** The block of the executing workflow that made a tool call, from its server-set `_context`. */ +function sideEffectSite( + executionContext: ExecutionContext, + params: Record +): SideEffectSite { + const calledFrom = toRecord(params._context).blockId + const blockId = typeof calledFrom === 'string' ? stripCloneSuffixes(calledFrom) : '' + const block = blockId + ? executionContext.workflow?.blocks.find((candidate) => candidate.id === blockId) + : undefined + return { + workflowId: executionContext.workflowId, + blockId, + blockName: block?.metadata?.name ?? blockId, + blockType: block?.metadata?.id ?? '', + } +} + +/** A string body as the JSON it carries, when it carries JSON. */ +function readBody(body: string | undefined): unknown { + if (body === undefined) return undefined + try { + return JSON.parse(body) + } catch { + return body + } +} + +/** + * What a call to `tool` would send: an in-process operation's input, or an HTTP request's method, + * URL and body. Headers are never kept, since they carry the credentials. + */ +export function describeToolRequest( + tool: ExecutableToolConfig, + params: Record, + registry: ResolvedSecretTraceRegistry | undefined +): unknown { + if (isInternalToolConfig(tool)) { + return tool.operation.input(projectToolModelInputParams(tool, params, registry)) + } + const prepared = prepareToolRequest(tool, params, registry) + return { method: prepared.method, url: prepared.url, body: readBody(prepared.body) } +} + +/** Every credential-named field masked, and each credential value masked wherever it reappears. */ +function redactCredentials(value: unknown, credentials: string[]): unknown { + if (typeof value === 'string') return redactExactSensitiveValues(value, credentials) + if (Array.isArray(value)) return value.map((item) => redactCredentials(item, credentials)) + if (!isPlainRecord(value)) return value + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + isSensitiveKey(key) ? REDACTED_MARKER : redactCredentials(item, credentials), + ]) + ) +} + +/** + * The request as a run may report it: credentials the call resolved (an access token, a hosted + * key, a secret access key) masked by field and by value, then every secret the run resolved + * masked by the run's registry. Null when the registry cannot vouch that none remain. + */ +function redactRequest( + request: unknown, + params: Record, + registry: ResolvedSecretTraceRegistry | undefined +): Record | null { + const credentials = Object.entries(params).flatMap(([key, value]) => + isSensitiveKey(key) && typeof value === 'string' && value !== '' ? [value] : [] + ) + const redacted = redactCredentials( + isPlainRecord(request) ? request : { input: request }, + credentials + ) + const projection = projectResolvedSecretModelContent(redacted, registry) + return projection.safe && isPlainRecord(projection.value) ? projection.value : null +} + +/** + * The response answering a write tool call the run's side-effect policy does not send, after the + * policy recorded the request it would have sent; null when the call is sent. `describeRequest` + * runs only for an unsent call, and a request it cannot build fails the call as sending it would. + */ +export function answerUnsentWrite(input: { + toolId: string + params: Record + executionContext: ExecutionContext | undefined + registry: ResolvedSecretTraceRegistry | undefined + describeRequest: () => unknown +}): ToolResponse | null { + const { executionContext, params } = input + const policy = executionContext?.sideEffects + if (!policy) return null + const call = { ...sideEffectSite(executionContext, params), toolId: input.toolId } + if (policy.sendsWrite(call)) return null + const request = redactRequest(input.describeRequest(), params, input.registry) + return { success: true, output: policy.stubWrite({ ...call, request }) } +} diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index a7904e1014d..314e260c8c9 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -18,8 +18,11 @@ ID in a variable: one holding "--workspace " is one argument, an unknown opt whole ID after -w).` /** Where an author reads a run's result after running the workflow the source defines. */ -const RUN_LOGS_LINE = `Debug a run: \`sim workflows run --manual\`, then \`sim logs list --workflow \` -and \`sim logs get --trace --no-include-workflow-state\` (each block's resolved inputs and errors).` +const RUN_LOGS_LINE = `Test a run: \`sim workflows run --dry\` runs the saved draft without sending its writes +and lists each one, with the request it would have sent, under sideEffects (--allow sends +one block's for real; --manual runs everything for real). Debug it with \`sim logs list --workflow +\` and \`sim logs get --trace --no-include-workflow-state\` (each block's +resolved inputs and errors).` /** The status line both groups end with, for a directory at `dir`. */ function statusLine(group: string, dir: string): string { @@ -36,7 +39,7 @@ ${loopRows([ ['edit ./wf/workflow.ts', 'every file first, then the one command below'], ['sim workflows source check --dir ./wf', 'compile + types: each error as file:line:column'], [' && sim workflows source apply --dir ./wf --yes', 'save the draft (it re-checks)'], - [" && sim workflows run --manual --input '{…}'", 'test the saved draft'], + [" && sim workflows run --dry --input '{…}'", 'test the draft, sending no writes'], ])} Run those three as one chained command: a non-zero exit stops it at the first failure, and the next step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 7ab245689ec..9cbef24917a 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -40,21 +40,21 @@ const PARAMS_COMMAND = 'sim workflows source params' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules(group: string, extraRenames = ''): string { - return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or display name. Rename display names (first argument) or consts, any number per apply, with other edits: apply rewrites every reference, \`$ref.\` too. Renaming both a block's const and display name (one such block per apply) keeps it if settings, neighbours or references match, else it is a delete (\`E_APPLY_BLOCK_DELETE\`). + return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or display name. Rename display names (first argument) or consts, any number per apply, with other edits: apply rewrites every reference, \`$ref.\` too. Renaming both a block's const and display name (one such block per apply) keeps it if settings, neighbours or references match, else a delete (\`E_APPLY_BLOCK_DELETE\`). - **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child call \`runWorkflow('Name', { workflowId: childWorkflow('') })\`'s response field as \`c.result.data.\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, key: the display name lowercased, no whitespace or dots ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files: \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). - **Renames**: one workflow variable per apply (two at once: delete + add).${extraRenames} - **Builders**: \`${PARAMS_COMMAND} \` (or a namespace). - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). -- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only the request (timeout, reset, 429, 5xx) per try. A reference to a block that did not run is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. -- **Run and debug**: \`--manual\` runs the saved draft, else the deployed version. Runs write real data: use test resources. With \`--dir \` a failed run names its file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list \`. Rerun from a block on a run's outputs: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after one. -- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` +- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (3rd argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only its request (timeout, reset, 429, 5xx) per try. A reference to a block that never ran is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. +- **Run and debug**: \`--dry\` runs the draft, sending no writes: check each in \`sideEffects.stubbed\`. \`--allow \` sends its writes (test data); \`--manual\` runs live, else the deployment. \`--dir \` names a failed run's file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. +- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo the edit in a fresh \`${group} get --dir \`), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer \`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Run commands here: they read the workflow id from \`${SOURCE_BASE_FILE}\` (a starter has none: \`${SOURCE_STARTER_FILE}\` names its workspace, and its loop ends in \`sim workflows source create --dir . --yes\`, not \`apply\`, which makes the workflow), and each (table commands too) acts on its workspace; source commands refuse a \`-w\` naming another; others follow it. -**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`. A non-zero exit stops the chain. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. - **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`). - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. @@ -67,13 +67,13 @@ const WORKSPACE_RENAMES = const WORKSPACE_PRIMER = `# Sim workspace source: primer -A Sim workspace as files (\`tables/\`, \`workflows//\`); nothing here runs. Commands run here (table commands too) act on the workspace \`${SOURCE_BASE_FILE}\` names; source commands refuse a \`-w\` naming another; others follow it. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. +A Sim workspace as files (\`tables/\`, \`workflows//\`); nothing here runs. Commands here (table commands too) act on the workspace \`${SOURCE_BASE_FILE}\` names; source commands refuse a \`-w\` naming another; others follow it. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run --manual --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply rewrites files: reread before editing. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run --dry --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks: \`apply --dry-run\` only reviews. Apply rewrites files: reread before editing. - **Deletes**: removing a file, folder, column, block or variable needs \`apply --allow-delete\` and is permanent. -- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys it on apply; without one, no deploy. -- **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written; changes needing an unset secret or unbound credential are held: set it, reapply. +- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys on apply; no file, no deploy. +- **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written; changes needing an unset secret or unbound credential wait: set it, reapply. ${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 2f5ac88a3dd..58c8081e86f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -216,7 +216,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 and the dry run in step 4 are for a person, CI, or a change you want reviewed first. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 and the dry run in step 4 are for a person, CI, or a change you want reviewed first. The test run's \`--dry\` is another thing: the run executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. \`--allow \` sends one block's writes for real against a test resource; \`--mock ='{…}'\` answers a block with fixed output to steer a branch. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and the dry run do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. The dry run is the authority: a type error on a printed line you did not edit that the dry run accepts can be skipped with \`--no-types\`. diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 2c28ccac9ae..90119c195ba 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -628,3 +628,146 @@ describe('sim workflows run --follow', () => { expect(cancel).toHaveBeenCalled() }) }) + +describe('sim workflows run --dry', () => { + const sideEffects = { + stubbed: [ + { + workflowId: WORKFLOW_ID, + blockId: 'save', + block: 'Save lead', + tool: 'table_upsert_row', + request: { tableId: 'tbl_1', data: { email: 'a@b.co' } }, + returned: { row: { id: 'item_1' } }, + }, + ], + allowed: [], + unchecked: [ + { + workflowId: WORKFLOW_ID, + blockId: 'enrich', + block: 'Enrich', + reason: 'Its code ran for real; network calls it makes are not stubbed', + }, + ], + omitted: 0, + } + let stderr: string[] + + beforeEach(() => { + stderr = [] + vi.spyOn(process.stderr, 'write').mockImplementation((chunk: unknown) => { + stderr.push(String(chunk)) + return true + }) + }) + + it('runs the draft dry with allowed and mocked blocks, reading a mock from a file', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + const dir = mkdtempSync(join(tmpdir(), 'sim-dry-')) + try { + writeFileSync(join(dir, 'route.json'), '{"route":"vip"}') + + await run( + WORKFLOW_ID, + '--dry', + '--allow', + 'Save lead', + '--allow', + 'log', + '--mock', + 'Score={"content":"spam","note":"a=b"}', + '--mock', + `Router=@${join(dir, 'route.json')}`, + '--input', + '{"email":"a@b.co"}' + ) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + + expect(requestRaw.mock.calls[0][1].body).toEqual({ + input: { email: 'a@b.co' }, + run: { + source: 'manual', + dry: true, + allowBlocks: ['Save lead', 'log'], + mocks: { Score: { content: 'spam', note: 'a=b' }, Router: { route: 'vip' } }, + }, + }) + }) + + it('keeps a rerun from a block dry, and a mock alone runs the draft without --dry', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await run(WORKFLOW_ID, '--from-block', 'agent-1', '--source-run', 'run-1', '--dry') + await run(WORKFLOW_ID, '--mock', 'Score={"content":"spam"}') + + expect(requestRaw.mock.calls[0][1].body.run).toEqual({ + source: 'manual', + entry: { type: 'block', blockId: 'agent-1', sourceRunId: 'run-1' }, + dry: true, + }) + expect(requestRaw.mock.calls[1][1].body.run).toEqual({ + source: 'manual', + mocks: { Score: { content: 'spam' } }, + }) + }) + + it('refuses combinations a dry run cannot honour before sending anything', async () => { + await expect(run(WORKFLOW_ID, '--allow', 'Save lead')).rejects.toThrow('add --dry') + await expect(run(WORKFLOW_ID, '--dry', '--follow')).rejects.toThrow('drop --follow') + await expect(run(WORKFLOW_ID, '--dry', '--wait-timeout', '30')).rejects.toThrow( + 'drop --wait-timeout' + ) + await expect(run(WORKFLOW_ID, '--dry', '--async')).rejects.toThrow( + 'Manual execution does not support --async' + ) + await expect(run(WORKFLOW_ID, '--mock', '{"content":"spam"}')).rejects.toThrow( + 'must be =' + ) + await expect(run(WORKFLOW_ID, '--mock', 'Score=spam')).rejects.toThrow('is not valid JSON') + await expect(run(WORKFLOW_ID, '--mock', 'Score=[1]')).rejects.toThrow('must be a JSON object') + expect(requestRaw).not.toHaveBeenCalled() + }) + + it('passes sideEffects through in JSON and summarizes them on stderr in table output', async () => { + const stdout = vi.spyOn(console, 'log').mockImplementation(() => {}) + requestRaw.mockImplementation(async () => + jsonResponse({ + data: { runId: 'run-1', workflowId: WORKFLOW_ID, status: 'completed', sideEffects }, + }) + ) + + await run(WORKFLOW_ID, '--dry') + expect(JSON.parse(String(stdout.mock.calls[0][0])).sideEffects).toEqual(sideEffects) + expect(stderr.join('')).not.toContain('Dry run') + + output.format = 'table' + await run(WORKFLOW_ID, '--dry') + const summary = stderr.join('') + expect(summary).toContain('Dry run: 1 not sent, 0 sent (allowed), 1 unchecked') + expect(summary).toContain('not sent Save lead → table_upsert_row') + expect(summary).toContain('unchecked Enrich: Its code ran for real') + }) + + it('prints a rerun of a failed dry run that stays dry', async () => { + const stdout = vi.spyOn(console, 'log').mockImplementation(() => {}) + requestRaw.mockImplementation(async () => + jsonResponse({ + data: { + runId: 'run-1', + workflowId: WORKFLOW_ID, + status: 'failed', + error: { message: 'Agent failed', blockId: 'agent-1', rerunFromBlockId: 'agent-1' }, + sideEffects, + }, + }) + ) + + await expect(run(WORKFLOW_ID, '--dry')).rejects.toThrow('Agent failed') + expect(JSON.parse(String(stdout.mock.calls[0][0])).next).toBe( + `sim workflows run ${WORKFLOW_ID} --from-block agent-1 --source-run run-1 --dry` + ) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index dc57655d2f1..c9de1b46af5 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -13,7 +13,7 @@ import { safeOneLine, sanitize } from '../../output/render' import { callsOperations, connect } from '../../runtime/called-operations' import { executeOperation, runFailureMessage } from '../../runtime/execute' import { retypeApiError } from '../../runtime/naming' -import { buildRequest } from '../../runtime/request' +import { buildRequest, readArgumentSource } from '../../runtime/request' import { renderResult } from '../../runtime/result' import type { OperationSpec } from '../../runtime/types' import { printRunFailureSite } from './run-source-location' @@ -60,21 +60,84 @@ type WorkflowRunSelection = { | { type: 'trigger'; blockId?: string; useMockPayload?: boolean } | { type: 'block'; blockId: string; sourceRunId: string } stopAfterBlockId?: string + dry?: true + allowBlocks?: string[] + mocks?: Record +} + +/** Collects every use of a repeatable option, in order. */ +function collect(value: string, previous: string[] = []): string[] { + return [...previous, value] +} + +/** `--mock =` values as the block selector each names and its output object. */ +async function readBlockMocks(values: string[]): Promise> { + const mocks: Record = {} + for (const value of values) { + const separator = value.indexOf('=') + const block = separator > 0 ? value.slice(0, separator).trim() : '' + if (!block) { + throw new SimApiError(`--mock "${value}" must be =`, 0) + } + const source = await readArgumentSource(value.slice(separator + 1), 'mock') + let output: unknown + try { + output = JSON.parse(source.text) + } catch { + throw new SimApiError(`--mock ${block}: the output${source.from} is not valid JSON`, 0) + } + if (!isRecordLike(output) || Array.isArray(output)) { + throw new SimApiError( + `--mock ${block}: the output must be a JSON object, like {"ok":true}`, + 0 + ) + } + if (Object.hasOwn(mocks, block)) throw new SimApiError(`--mock names ${block} twice`, 0) + mocks[block] = output + } + return mocks } /** Projects friendly CLI flags into the API's strict nested run selector. */ -function resolveWorkflowRunSelection( +async function resolveWorkflowRunSelection( flags: Record -): WorkflowRunSelection | undefined { +): Promise { const trigger = typeof flags.trigger === 'string' ? flags.trigger : undefined const useMockPayload = flags.mockPayload === true const stopAfter = typeof flags.stopAfter === 'string' ? flags.stopAfter : undefined - /** A trigger entry and a stop block only exist on the draft, so these flags imply `--manual`. */ + const dry = flags.dry === true + const allowBlocks = Array.isArray(flags.allow) ? (flags.allow as string[]) : [] + const mockValues = Array.isArray(flags.mock) ? (flags.mock as string[]) : [] + /** These flags only apply to the draft, so each implies `--manual`. */ const manual = - flags.manual === true || trigger !== undefined || useMockPayload || stopAfter !== undefined + flags.manual === true || + trigger !== undefined || + useMockPayload || + stopAfter !== undefined || + dry || + mockValues.length > 0 const fromBlock = typeof flags.fromBlock === 'string' ? flags.fromBlock : undefined const sourceRun = typeof flags.sourceRun === 'string' ? flags.sourceRun : undefined + if (allowBlocks.length > 0 && !dry) { + throw new SimApiError("--allow sends one block's writes during a dry run; add --dry", 0) + } + if (allowBlocks.some((block) => block.trim() === '')) { + throw new SimApiError('--allow requires a block id, name or key', 0) + } + if (dry && flags.follow === true) { + throw new SimApiError( + '--dry reports its side effects with the run result, which --follow does not return; drop --follow', + 0 + ) + } + if (dry && flags.waitTimeout !== undefined) { + throw new SimApiError( + '--dry reports its side effects with the run result, so the command waits for it; drop --wait-timeout', + 0 + ) + } + if (fromBlock && (trigger || useMockPayload)) { throw new SimApiError('--from-block cannot be combined with --trigger or --mock-payload', 0) } @@ -97,16 +160,22 @@ function resolveWorkflowRunSelection( throw new SimApiError('--stop-after requires a block id, name or key', 0) } - const stop = stopAfter !== undefined ? { stopAfterBlockId: stopAfter } : {} + const mocks = await readBlockMocks(mockValues) + const options = { + ...(stopAfter !== undefined ? { stopAfterBlockId: stopAfter } : {}), + ...(dry ? { dry: true as const } : {}), + ...(allowBlocks.length > 0 ? { allowBlocks } : {}), + ...(mockValues.length > 0 ? { mocks } : {}), + } if (fromBlock && sourceRun) { return { source: 'manual', entry: { type: 'block', blockId: fromBlock, sourceRunId: sourceRun }, - ...stop, + ...options, } } if (!manual) return undefined - if (!trigger && !useMockPayload) return { source: 'manual', ...stop } + if (!trigger && !useMockPayload) return { source: 'manual', ...options } return { source: 'manual', entry: { @@ -114,10 +183,39 @@ function resolveWorkflowRunSelection( ...(trigger ? { blockId: trigger } : {}), ...(useMockPayload ? { useMockPayload: true } : {}), }, - ...stop, + ...options, } } +/** + * A dry run's side effects in a few lines on stderr, for the human formats: each write that was + * not sent, sent because its block was allowed, or made by code the run cannot see. The request + * payloads are in the result itself (`--output json`). + */ +function printSideEffects(sideEffects: unknown): void { + if (!isRecordLike(sideEffects)) return + const list = (key: string) => + Array.isArray(sideEffects[key]) ? sideEffects[key].filter(isRecordLike) : [] + const stubbed = list('stubbed') + const allowed = list('allowed') + const unchecked = list('unchecked') + const label = (entry: Record) => + safeOneLine(`${String(entry.block)}${typeof entry.tool === 'string' ? ` → ${entry.tool}` : ''}`) + const lines = [ + `Dry run: ${stubbed.length} not sent, ${allowed.length} sent (allowed), ${unchecked.length} unchecked`, + ...stubbed.map((entry) => ` not sent ${label(entry)}`), + ...allowed.map((entry) => ` sent ${label(entry)}`), + ...unchecked.map( + (entry) => ` unchecked ${label(entry)}: ${safeOneLine(String(entry.reason))}` + ), + ] + if (typeof sideEffects.omitted === 'number' && sideEffects.omitted > 0) { + lines.push(` … ${sideEffects.omitted} more`) + } + lines.push('Request payloads: sideEffects in --output json') + writeStderr(styles().dim(`${lines.join('\n')}\n`)) +} + function stringField(frame: Record, key: string): string | null { const value = frame[key] return typeof value === 'string' ? value : null @@ -264,6 +362,9 @@ async function runWithResultStream( renderResult('executeWorkflow', profile.output, payload, commandSpec, { expandedTrace: flags.trace === true, }) + if (profile.output === 'table' || profile.output === 'text') { + printSideEffects(payload.sideEffects) + } const failure = runFailureMessage('executeWorkflow', payload) if (failure) { @@ -555,7 +656,7 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { 0 ) } - const selection = resolveWorkflowRunSelection(initialFlags) + const selection = await resolveWorkflowRunSelection(initialFlags) const stopBlock = stopBlockSelection(selection, initialFlags) if (stopBlock) command.setOptionValue('selectOutput', stopBlock) const flags = command.optsWithGlobals() as Record @@ -607,6 +708,13 @@ const RUN_HELP = ` Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, +table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in +sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run +and are listed in sideEffects.unchecked. Child workflows run dry too. --allow sends that +block's writes for real (use a test resource); --mock = answers a block with fixed +output, to steer a branch. + The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame @@ -646,6 +754,20 @@ export function attachWorkflowRunFollow(workflows: Command): void { run .option('--manual', 'Run the current saved workflow state instead of the active deployment') + .option( + '--dry', + 'Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout' + ) + .option( + '--allow ', + "Send this block's writes for real during a --dry run (its id, display name or key); repeatable", + collect + ) + .option( + '--mock =', + 'Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual', + collect + ) .option( '--trigger ', 'Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual)' diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index dd78a46c503..5ad0bdb8b78 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -2396,8 +2396,9 @@ always prints as null. For a copy to share outside this workspace, pass "Maximum duration of the run in seconds, capped by the plan's execution timeout. Requires --async or --wait-timeout", }, input: { json: true, describe: 'Trigger input as JSON' }, - // Built from --manual, --trigger, --mock-payload, --from-block, --source-run and - // --stop-after by `workflow-run-follow.ts`, so a run is selected one way only. + // Built from --manual, --trigger, --mock-payload, --from-block, --source-run, + // --stop-after, --dry, --allow and --mock by `workflow-run-follow.ts`, so a run is + // selected one way only. run: { omit: true }, // `workflows runs get` takes the same names (`workflow-run-get.ts` resolves // them against the draft graph), which is why both describes name theirs. diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 9922aefd93b..105f48c23f8 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -7122,6 +7122,9 @@ export type ExecuteWorkflowBody = { sourceRunId: string } stopAfterBlockId?: string + dry?: boolean + allowBlocks?: Array + mocks?: Record } async?: boolean executionTimeoutSeconds?: number @@ -7156,6 +7159,30 @@ type ExecuteWorkflowResponseRef0 = { } type ExecuteWorkflowResponseRef1 = { + stubbed: Array<{ + workflowId: string + blockId: string + block: string + tool: string | null + request: Record | null + returned: Record + }> + allowed: Array<{ + workflowId: string + blockId: string + block: string + tool: string | null + }> + unchecked: Array<{ + workflowId: string + blockId: string + block: string + reason: string + }> + omitted: number +} + +type ExecuteWorkflowResponseRef2 = { runId: string workflowId: string status: 'completed' | 'failed' | 'paused' | 'cancelled' @@ -7174,9 +7201,10 @@ type ExecuteWorkflowResponseRef1 = { status: 'paused' | 'queued' | 'resuming' | 'resumed' | 'failed' }> } | null + sideEffects?: ExecuteWorkflowResponseRef1 } -type ExecuteWorkflowResponseRef2 = { +type ExecuteWorkflowResponseRef3 = { runId: string statusUrl: string executionTimeoutSeconds: number | null @@ -7184,10 +7212,10 @@ type ExecuteWorkflowResponseRef2 = { export type ExecuteWorkflowResponse = | { - data: ExecuteWorkflowResponseRef1 + data: ExecuteWorkflowResponseRef2 } | { - data: ExecuteWorkflowResponseRef2 + data: ExecuteWorkflowResponseRef3 } /** `GET /api/v2/knowledge/[knowledgeBaseId]/export` */ diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index a54197f3091..c36b4cde14c 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -48,14 +48,17 @@ export function resumeCommandFor( * The exact command that reruns a failed run from where the server says a rerun of its failure * starts (`error.rerunFromBlockId`: the failed block, or the outermost loop or parallel holding * it, which a rerun cannot start inside), with the run as the source of every upstream output, so - * a fix applied to that block's source is tested without repeating the blocks before it. Null + * a fix applied to that block's source is tested without repeating the blocks before it; a dry + * run's rerun adds `--dry`. Null * when the server names no start block or an id is not in the format the server issues. */ function rerunCommandFor(record: Record, workflowId: string): string | null { const startBlockId = toRecordOrNull(record.error)?.rerunFromBlockId const { runId } = record if (!issuedId(startBlockId) || !issuedId(runId) || !issuedId(workflowId)) return null - return `sim workflows run ${shellArgument(workflowId)} --from-block ${shellArgument(startBlockId)} --source-run ${shellArgument(runId)}` + // A dry run's rerun stays dry, so following `next` never sends what the run held back. + const dry = isRecordLike(record.sideEffects) ? ' --dry' : '' + return `sim workflows run ${shellArgument(workflowId)} --from-block ${shellArgument(startBlockId)} --source-run ${shellArgument(runId)}${dry}` } /** From c250f3f078d4e9dfe6a71f3ef81008e845de9c5e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 01:00:41 -0800 Subject: [PATCH 02/10] fix(workflows): close dry-run escapes and secret exposure found in review A dry run now sends no externally visible write and keeps nothing beyond its own `test`-trigger log: - Test runs raise no workspace event (emitExecutionCompletedEvent) and are left out of alert-rule statistics (excludeEventlessExecutionsCondition), so a dry run never starts a Sim-trigger subscriber. - Test runs do not bump workflow.runCount or lastRunAt. - Agents read memory but write none under a side-effect policy (no turn session, no appended messages). - The policy decides a write before a hosted key is drawn, so a stubbed write spends no rate-limit slot; credential resolution still runs. - Files a dry run uploads to a provider Files API are deleted once the model call settles. - Custom blocks, on a canvas or called by an Agent (deployed_block_executor), are answered whole and never run, so nothing lands in the publisher's workspace and none of its internals reach the consumer. - Code (function_execute) runs for real for a Function block or an Agent and is listed unchecked with a reason naming the caller; Condition evaluation is not listed. - run.mocks requires run.dry. Allowed and mocked blocks are keyed by the run's own workflow and block; --allow on a Workflow or custom block is refused. - A tool's nested executeTool calls (postProcess) run in the caller's _context, so an allowed block's follow-up writes are allowed too; Pi's Sim tools carry the Pi block id. - A test run is refused as the source of a non-dry from-block run. - A failed dry run keeps its sideEffects, compacted inside the result's own error mapping; the run result and `runs get` report the dry run's allowed and mocked blocks (`dryRun`), so every `next` rerun keeps --dry, --allow and --mock (a workflow test's run keeps --dry). - sideEffects requests: MCP and custom tool calls are recorded by their arguments only (never envVars or other run context), password-field values are masked whatever the field is called, and the workspace's PII redaction is applied; a request that cannot be vouched for is null. Contract and CLI: mocks are typed as objects, `omitted` is counted per list, `allowed` is deduped per block and tool, blockId/block are null instead of empty, the policy is WriteStubPolicy with decideWrite/answerBlock and mocks live on it (block-mocks.ts and the service's testHooks param are gone), `--dry --async` says to drop --async, and the CLI's repeated-option collector and plain-object check are shared. The workflow-dir guide names `apply --dry-run` and `run --dry` apart, and the primer's run line is reworded; its other rewordings from the previous commit stay because the 4096-byte primer budget forces them. --- .../api-reference/build-and-run-workflows.mdx | 4 +- apps/docs/content/docs/cli/reference.mdx | 8 +- apps/docs/content/docs/cli/workflows.mdx | 8 +- apps/docs/openapi-v2-workflows.json | 176 +++- .../workflows/[workflowId]/execute/route.ts | 1 + .../[workflowId]/runs/[runId]/route.test.ts | 1 + .../[workflowId]/runs/[runId]/route.ts | 1 + apps/sim/executor/execution/block-executor.ts | 17 +- apps/sim/executor/execution/types.ts | 53 +- apps/sim/executor/handlers/agent/handler.ts | 17 +- apps/sim/executor/handlers/pi/handler.test.ts | 14 +- apps/sim/executor/handlers/pi/handler.ts | 2 +- .../handlers/pi/local/sim-tools.test.ts | 13 +- .../executor/handlers/pi/local/sim-tools.ts | 6 +- .../workflow/custom-block-tool-runner.ts | 2 - .../sim/executor/handlers/workflow/handler.ts | 3 +- .../contracts/mothership-management-tools.ts | 2 +- .../lib/api/contracts/v2/openapi/workflows.ts | 1 + apps/sim/lib/api/contracts/v2/workflows.ts | 66 +- apps/sim/lib/internal/mcp/execute-tool.ts | 39 +- apps/sim/lib/mcp/tool-arguments.ts | 45 + .../tasks/application/tasks.test.ts | 1 + .../application/dry-run.integration.ts | 768 +++++++++++++++--- .../execute-manual-workflow.test.ts | 2 + .../application/execute-manual-workflow.ts | 80 +- .../application/read-workflow-run.ts | 13 + .../application/run-workflow-for-test.ts | 4 +- apps/sim/lib/workflows/dry-run/block-mocks.ts | 27 - apps/sim/lib/workflows/dry-run/index.ts | 4 +- .../sim/lib/workflows/dry-run/side-effects.ts | 196 +++-- .../lib/workflows/executor/execute-service.ts | 96 ++- .../lib/workflows/executor/execution-core.ts | 48 +- .../lib/workflows/executor/execution-state.ts | 59 +- apps/sim/lib/workspace-events/constants.ts | 7 + apps/sim/lib/workspace-events/emitter.ts | 6 +- .../lib/workspace-events/no-activity.test.ts | 2 +- apps/sim/lib/workspace-events/no-activity.ts | 4 +- apps/sim/lib/workspace-events/rules.ts | 24 +- apps/sim/providers/file-attachments.server.ts | 65 +- apps/sim/providers/index.ts | 59 +- apps/sim/tools/index.test.ts | 42 +- apps/sim/tools/index.ts | 111 ++- apps/sim/tools/side-effects.test.ts | 73 +- apps/sim/tools/side-effects.ts | 176 +++- .../src/commands/protocol/logs-follow.ts | 22 +- .../src/commands/protocol/source-primer.ts | 2 +- .../src/commands/protocol/workflow-dir.ts | 4 +- .../protocol/workflow-run-follow.test.ts | 57 +- .../commands/protocol/workflow-run-follow.ts | 57 +- packages/sim-cli/src/generated/v2-api.ts | 40 +- packages/sim-cli/src/runtime/options.ts | 5 + packages/sim-cli/src/runtime/run-next.test.ts | 17 + packages/sim-cli/src/runtime/run-next.ts | 31 +- 53 files changed, 1912 insertions(+), 669 deletions(-) create mode 100644 apps/sim/lib/mcp/tool-arguments.ts delete mode 100644 apps/sim/lib/workflows/dry-run/block-mocks.ts diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index 898b961adb2..966432ce766 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and Function blocks run for real and are listed under `sideEffects.unchecked`. Dry runs are logged under the `test` trigger. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. A failed dry run still returns its `sideEffects`, and only another dry run can use it as `run.entry.sourceRunId`. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. @@ -194,7 +194,7 @@ Narrow a test run with these options: | Rerun from a block, reusing an earlier run's upstream outputs | `run.entry: {type: "block", blockId, sourceRunId}` | `--from-block --source-run ` | | Rerun one block only | Block entry plus `stopAfterBlockId` naming the same block | `--from-block` and `--stop-after` with the same block | | Send one block's writes for real during a dry run | `run.allowBlocks: [""]` | `--allow ` | -| Answer a block with a fixed output, to steer a branch | `run.mocks: {"": {...}}` | `--mock ='{...}'` | +| Answer a block with a fixed output during a dry run, to steer a branch | `run.mocks: {"": {...}}` | `--mock ='{...}'` | | Run everything for real | omit `run.dry` | `--manual` | `stopAfterBlockId` cannot name a block inside a loop or parallel. A run that routes away from the stop block fails as soon as that is decided. diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index a6c8ba7f449..1e613a92693 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,9 +8516,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8534,11 +8534,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run and are listed in sideEffects.unchecked. Child workflows run dry too. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. A dry run is the --source-run only of another dry run. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 9b3397b30e0..1ba4401cfbb 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,9 +833,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -851,11 +851,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run and are listed in sideEffects.unchecked. Child workflows run dry too. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. A dry run is the --source-run only of another dry run. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index c6578ce0971..5a60f4c50fd 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -4976,7 +4976,8 @@ "downloadPath": "/api/v2/workflows/3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36/runs/run_8f14e45f-ceea-467f-a/files/file_1a2b3c", "base64": null } - ] + ], + "dryRun": null } } } @@ -17217,12 +17218,26 @@ "description": "Workflow whose block it was: the run workflow, or a child workflow it called." }, "blockId": { - "type": "string", - "description": "Block id in that workflow; empty when the call named no block." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." }, "block": { - "type": "string", - "description": "Block display name." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." }, "tool": { "anyOf": [ @@ -17250,7 +17265,7 @@ "type": "null" } ], - "description": "What the call would have sent: an in-process operation's input, or an HTTP call's `method`, `url` and `body` (never headers). For a block answered whole, its logged inputs. Credentials and resolved secrets are redacted; null when the run could not prove none remain." + "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain." }, "returned": { "type": "object", @@ -17278,12 +17293,26 @@ "description": "Workflow whose block it was: the run workflow, or a child workflow it called." }, "blockId": { - "type": "string", - "description": "Block id in that workflow; empty when the call named no block." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." }, "block": { - "type": "string", - "description": "Block display name." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." }, "tool": { "anyOf": [ @@ -17300,7 +17329,7 @@ "required": ["workflowId", "blockId", "block", "tool"], "additionalProperties": false }, - "description": "Writes sent for real because `run.allowBlocks` named their block." + "description": "Writes sent for real because `run.allowBlocks` named their block, once per block and tool." }, "unchecked": { "type": "array", @@ -17312,28 +17341,62 @@ "description": "Workflow whose block it was: the run workflow, or a child workflow it called." }, "blockId": { - "type": "string", - "description": "Block id in that workflow; empty when the call named no block." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." }, "block": { - "type": "string", - "description": "Block display name." + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." }, "reason": { "type": "string", - "description": "Why the run cannot see what this block changed." + "description": "Why the run cannot see what this code changed." } }, "required": ["workflowId", "blockId", "block", "reason"], "additionalProperties": false }, - "description": "Blocks that ran for real whose own effects the run cannot see: Function blocks, whose code may make network calls." + "description": "Blocks whose code ran for real, once per block: a Function block's code, or code an Agent's model wrote, which may make network calls the run cannot see." }, "omitted": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Entries left out once a list held 50." + "type": "object", + "properties": { + "stubbed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Writes left out of `stubbed`." + }, + "allowed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Writes left out of `allowed`." + }, + "unchecked": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Blocks left out of `unchecked`." + } + }, + "required": ["stubbed", "allowed", "unchecked"], + "additionalProperties": false, + "description": "Entries each list left out once it held 50." } }, "required": ["stubbed", "allowed", "unchecked", "omitted"], @@ -17341,6 +17404,39 @@ "title": "Workflow run side effects", "description": "What a dry run did with each write it reached." }, + "WorkflowDryRun": { + "type": "object", + "properties": { + "allowBlocks": { + "type": "array", + "items": { + "type": "string", + "description": "Block id." + }, + "description": "Blocks whose writes the run sent (`run.allowBlocks`), by id." + }, + "mocks": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Output field." + } + }, + "description": "Blocks the run answered with fixed outputs (`run.mocks`), keyed by id." + } + }, + "required": ["allowBlocks", "mocks"], + "additionalProperties": false, + "title": "Workflow dry run", + "description": "The blocks a dry run sent and mocked, which a rerun of it passes again." + }, "WorkflowRunResult": { "type": "object", "properties": { @@ -17464,8 +17560,12 @@ "description": "Where the run waits when `status` is `paused`; null otherwise." }, "sideEffects": { - "description": "What a dry run (`run.dry`) did with each write it reached; absent otherwise.", + "description": "What a dry run (`run.dry`) did with each write it reached, whatever its status; absent otherwise.", "$ref": "#/components/schemas/WorkflowRunSideEffects" + }, + "dryRun": { + "description": "A dry run's allowed and mocked blocks (`run.dry`); absent for any other run.", + "$ref": "#/components/schemas/WorkflowDryRun" } }, "required": [ @@ -17652,7 +17752,7 @@ "sourceRunId": { "type": "string", "minLength": 1, - "description": "Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404." + "description": "Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404. A test run (a dry run, or a workflow test) holds placeholders for the writes it did not send, so it is the source only of a `dry` run." } }, "required": ["type", "blockId", "sourceRunId"], @@ -17666,11 +17766,11 @@ "minLength": 1 }, "dry": { - "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Reads, model calls, conditions and credential resolution run for real, and so do Function blocks, listed in `sideEffects.unchecked`. Child workflows inherit it. Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls, conditions and credential resolution run for real, and so does code (a Function block's, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", "type": "boolean" }, "allowBlocks": { - "description": "Blocks (id, display name or reference key) whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block cannot be allowed.", + "description": "Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed.", "maxItems": 50, "type": "array", "items": { @@ -17679,12 +17779,19 @@ } }, "mocks": { - "description": "Blocks (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. With or without `dry`.", + "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`.", "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Output field." + }, "description": "Output object that answers the block instead of its handler." } } @@ -18567,6 +18674,17 @@ } ], "description": "Run-produced files when `includeOutput=true`, or null when not requested or execution data is hidden by organization permission groups." + }, + "dryRun": { + "anyOf": [ + { + "$ref": "#/components/schemas/WorkflowDryRun" + }, + { + "type": "null" + } + ], + "description": "A failed dry run's allowed and mocked blocks, which a rerun of it passes again; null for any other run, or when execution data is hidden by organization permission groups." } }, "required": [ @@ -18583,7 +18701,8 @@ "error", "output", "blockOutputs", - "files" + "files", + "dryRun" ], "additionalProperties": false, "title": "Workflow run status", @@ -18630,7 +18749,8 @@ "downloadPath": "/api/v2/workflows/3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36/runs/run_8f14e45f-ceea-467f-a/files/file_1a2b3c", "base64": null } - ] + ], + "dryRun": null } } ] diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index 9cd459aedf5..92f6e987d9a 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -139,6 +139,7 @@ function presentRun(result: ExecuteWorkflowServiceRun) { durationMs: result.durationMs, executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), ...(result.sideEffects ? { sideEffects: result.sideEffects } : {}), + ...(result.dryRun ? { dryRun: result.dryRun } : {}), output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, paused: presentV2RunPause(result.paused), diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts index 7e2e5b9aa16..ea14a294680 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts @@ -66,6 +66,7 @@ const baseStatus = { finalOutput: null, blockOutputs: null, files: null, + dryRun: null, } describe('v2 run detail and cancel adapters', () => { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts index fcaf4a3e6cd..c38294bb99c 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts @@ -61,6 +61,7 @@ export const GET = defineV2JsonRoute({ output: status.finalOutput, blockOutputs: status.blockOutputs, files: status.files, + dryRun: status.dryRun, }, }), }) diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index 9b06ddc165e..eb24d1ff41c 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -93,6 +93,7 @@ import { import { createAgentStreamPump } from '@/providers/stream-pump' import { isRunAbortError } from '@/providers/streaming-tool-loop-shared' import type { SerializedBlock } from '@/serializer/types' +import { redactSideEffectPayload } from '@/tools/side-effects' const logger = createLogger('BlockExecutor') @@ -292,7 +293,7 @@ export class BlockExecutor { blockName: block.metadata?.name ?? mockedBlockId, blockType: block.metadata?.id ?? '', } - const isStubbed = !isSentinel && !isMocked && sideEffects?.stubsBlock(site) === true + const isAnswered = !isSentinel && !isMocked && sideEffects?.answersBlock(site) === true try { /** * Only the handler call is retried. A streaming handler returns before any @@ -311,8 +312,18 @@ export class BlockExecutor { inputDisplayRegistry ) } - if (isStubbed && sideEffects) { - return Promise.resolve(sideEffects.stubBlock({ ...site, input: blockLog?.input ?? {} })) + if (isAnswered && sideEffects) { + return sideEffects.answerBlock({ + ...site, + input: () => + redactSideEffectPayload({ + payload: blockLog?.input ?? {}, + params: inputsForLog, + blockTypes: [site.blockType], + executionContext: blockCtx, + registry: inputDisplayRegistry, + }), + }) } const invocationMetadata = retry ? { ...nodeMetadata, retry } : nodeMetadata return handler.executeWithNode diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 8e8a2cecd81..b891ff34827 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -87,6 +87,8 @@ export interface ExecutionMetadata { allowLargeValueWorkflowScope?: boolean callChain?: string[] correlation?: AsyncExecutionCorrelation + /** A dry run's allowed and mocked blocks, recorded on its log so a rerun can pass them again. */ + dryRun?: DryRunOptions executionMode?: 'sync' | 'stream' | 'async' /** * Deployed-chat thinking policy half of the SSE dual gate. Persisted so HITL @@ -318,10 +320,23 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } +/** The blocks of the workflow a dry run started that it sent and mocked, by id. */ +export interface DryRunOptions { + allowBlocks: string[] + mocks: Record +} + /** Where a call that may change state outside the run was made: a block of one executing workflow. */ export interface SideEffectSite { workflowId: string - /** The workflow block id, never a parallel-branch clone id; empty when the caller named none. */ + /** The workflow block id, never a parallel-branch clone id; null when the caller named none. */ + blockId: string | null + blockName: string | null + blockType: string | null +} + +/** A block of one executing workflow, which the block executor always knows. */ +export interface SideEffectBlockSite extends SideEffectSite { blockId: string blockName: string blockType: string @@ -330,32 +345,40 @@ export interface SideEffectSite { /** A write tool call the run answers instead of sending, with the request it would have sent. */ export interface StubbedToolCall extends SideEffectSite { toolId: string - /** The request with credentials and resolved secrets redacted; null when it could not be. */ + /** The request with credentials, secrets and PII redacted; null when that cannot be vouched for. */ request: Record | null } -/** A block the run answers instead of running its handler, with the inputs its log shows. */ -export interface StubbedBlockCall extends SideEffectSite { - input: Record +/** A block the run answers instead of running its handler. */ +export interface AnsweredBlockCall extends SideEffectBlockSite { + /** + * The inputs its log shows, redacted like a stubbed write's request (null when that cannot be + * vouched for); built only when the block is recorded as stubbed rather than mocked. + */ + input: () => Promise | null> } /** * How a run treats work that may change state outside it: a dry run, or a workflow test's * unmocked writes. Unlike {@link ExecutionTestHooks}, every child execution inherits it, including - * a custom block's source workflow and a workflow or custom block an Agent calls as a tool, so a - * child's writes follow the run that started it. `tools/index.ts` consults it for every tool call - * not declared `read` (an MCP tool declares nothing, so every one), after credentials resolve and - * before anything is sent; the block executor consults it before each block's handler. + * a workflow an Agent calls as a tool, so a child's writes follow the run that started it. + * `tools/index.ts` consults it for every tool call not declared `read` (an MCP tool declares + * nothing, so every one) before a hosted key is drawn, and answers a stubbed call after + * credentials resolve and before anything is sent; the block executor consults it before each + * block's handler. */ export interface SideEffectPolicy { - /** Whether this write tool call is sent for real; a sent call is recorded with why it was. */ - sendsWrite(call: SideEffectSite & { toolId: string }): boolean + /** + * Whether this write tool call is sent or answered with {@link stubWrite}. Records a sent call + * the run should report: an allowed block's write, or code that runs unchecked. + */ + decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' /** Records a write that was not sent and returns the placeholder output answering it. */ stubWrite(call: StubbedToolCall): Record - /** Whether this block is answered with a placeholder instead of running its handler. */ - stubsBlock(block: SideEffectSite): boolean - /** Records a block that did not run and returns the placeholder output answering it. */ - stubBlock(call: StubbedBlockCall): NormalizedBlockOutput + /** Whether this block is answered with {@link answerBlock} instead of running its handler. */ + answersBlock(block: SideEffectBlockSite): boolean + /** The output answering a block that does not run: its mock, or a recorded placeholder. */ + answerBlock(call: AnsweredBlockCall): Promise } export interface ContextExtensions { diff --git a/apps/sim/executor/handlers/agent/handler.ts b/apps/sim/executor/handlers/agent/handler.ts index 90c44d3e588..47e6c914017 100644 --- a/apps/sim/executor/handlers/agent/handler.ts +++ b/apps/sim/executor/handlers/agent/handler.ts @@ -182,6 +182,15 @@ interface IndexedToolInput { toolIndex: number } +/** + * Whether this Agent writes its turn to memory. It reads memory either way; under a run's + * side-effect policy (a dry run, or a workflow test) it writes nothing, so a conversation is left + * as the run found it. + */ +function persistsMemory(ctx: ExecutionContext, inputs: AgentInputs): boolean { + return Boolean(inputs.memoryType && inputs.memoryType !== 'none' && !ctx.sideEffects) +} + /** * Removes the sim-auto identity preamble from the system messages built for a * routed primary. A fallback the builder named is not a pool model, so it must @@ -519,8 +528,7 @@ export class AgentBlockHandler implements BlockHandler { const streamingConfig = this.getStreamingConfig(ctx, block) const agentConversation = - filteredInputs.memoryType && - filteredInputs.memoryType !== 'none' && + persistsMemory(ctx, filteredInputs) && filteredInputs.conversationId && nodeMetadata && nodeMetadata.executionOrder !== undefined @@ -641,7 +649,7 @@ export class AgentBlockHandler implements BlockHandler { if (this.isStreamingExecution(result)) { const streamingResult = result as StreamingExecution streamingResult.diagnosticResolvedSecretTraceRegistry = providerErrorRegistry - if (filteredInputs.memoryType && filteredInputs.memoryType !== 'none') { + if (persistsMemory(ctx, filteredInputs)) { return this.wrapStreamForMemoryPersistence( ctx, filteredInputs, @@ -653,7 +661,7 @@ export class AgentBlockHandler implements BlockHandler { return streamingResult } - if (filteredInputs.memoryType && filteredInputs.memoryType !== 'none') { + if (persistsMemory(ctx, filteredInputs)) { await this.persistResponseToMemory( ctx, filteredInputs, @@ -1608,6 +1616,7 @@ export class AgentBlockHandler implements BlockHandler { const attachedUserMessage = messagesWithFiles ?.filter((message) => message.role === 'user' && !isConversationHistoryNotice(message)) .at(-1) + if (!persistsMemory(ctx, inputs)) return messagesWithFiles const messagesToStore = pendingMemoryMessages.map(({ raw, model }) => model === lastUserMessage && attachedUserMessage?.files ? { ...raw, files: attachedUserMessage.files } diff --git a/apps/sim/executor/handlers/pi/handler.test.ts b/apps/sim/executor/handlers/pi/handler.test.ts index b5493f04d72..0a70ed35cfb 100644 --- a/apps/sim/executor/handlers/pi/handler.test.ts +++ b/apps/sim/executor/handlers/pi/handler.test.ts @@ -229,7 +229,12 @@ describe('PiBlockHandler', () => { it('adds successful Function tool cost once to a non-streaming Local Dev result', async () => { mockBuildSimToolSpecs.mockImplementation( - async (_ctx: unknown, _tools: unknown, functionToolCost: { total: number }) => { + async ( + _ctx: unknown, + _blockId: string, + _tools: unknown, + functionToolCost: { total: number } + ) => { functionToolCost.total += 0.125 return [] } @@ -553,7 +558,12 @@ describe('PiBlockHandler', () => { it('streams text when the block is selected for streaming output', async () => { mockBuildSimToolSpecs.mockImplementation( - async (_ctx: unknown, _tools: unknown, functionToolCost: { total: number }) => { + async ( + _ctx: unknown, + _blockId: string, + _tools: unknown, + functionToolCost: { total: number } + ) => { functionToolCost.total += 0.25 return [] } diff --git a/apps/sim/executor/handlers/pi/handler.ts b/apps/sim/executor/handlers/pi/handler.ts index 13eff86979b..a66c9c97ad3 100644 --- a/apps/sim/executor/handlers/pi/handler.ts +++ b/apps/sim/executor/handlers/pi/handler.ts @@ -301,7 +301,7 @@ export class PiBlockHandler implements BlockHandler { const usePrivateKey = inputs.authMethod === 'privateKey' const port = parseOptionalNumberInput(inputs.port, 'port', { integer: true, min: 1 }) ?? 22 const sandboxCost: SandboxCostSink = { total: 0 } - const tools = await buildSimToolSpecs(ctx, inputs.tools, sandboxCost) + const tools = await buildSimToolSpecs(ctx, block.id, inputs.tools, sandboxCost) const params: PiLocalRunParams = { ...contextualBase, mode: 'local', diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.test.ts b/apps/sim/executor/handlers/pi/local/sim-tools.test.ts index 62de6856b0e..a175940bb00 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.test.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.test.ts @@ -60,7 +60,7 @@ describe('buildSimToolSpecs', () => { }) mockExecuteTool.mockResolvedValue({ success: true, output: 'sent' }) - const specs = await buildSimToolSpecs(executionContext(undefined), [ + const specs = await buildSimToolSpecs(executionContext(undefined), 'pi-1', [ { type: 'gmail', operation: 'send', usageControl: 'auto' }, { type: 'gmail', operation: 'send', usageControl: 'auto' }, ]) @@ -95,7 +95,7 @@ describe('buildSimToolSpecs', () => { resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), } as ExecutionContext - const [spec] = await buildSimToolSpecs(trustedCtx, [ + const [spec] = await buildSimToolSpecs(trustedCtx, 'pi-1', [ { type: 'exa', operation: 'exa_search', usageControl: 'auto' }, ]) // An attacker-influenced tool arg tries to spoof the execution context. @@ -127,6 +127,7 @@ describe('buildSimToolSpecs', () => { const functionToolCost = { total: 0 } const [functionSpec, searchSpec] = await buildSimToolSpecs( executionContext(undefined), + 'pi-1', [ { type: 'function', operation: 'execute', usageControl: 'auto' }, { type: 'exa', operation: 'exa_search', usageControl: 'auto' }, @@ -179,7 +180,7 @@ describe('buildSimToolSpecs', () => { ]) registry.recordResolved('API_KEY', 'secret-value') - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) await expect(spec.execute({})).resolves.toEqual({ text: JSON.stringify({ authorization: 'Bearer {{API_KEY}}' }), @@ -216,7 +217,7 @@ describe('buildSimToolSpecs', () => { registry.recordResolvedAtInputPath('UNRELATED', 'Test', ['task']) registry.recordResolvedInputProjection(['task'], 'Test', '{{UNRELATED}}') - const [spec] = await buildSimToolSpecs(executionContext(registry), tools) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', tools) await expect(spec.execute({ query: 'pi' })).resolves.toEqual({ text: JSON.stringify({ selected: '{{API_KEY}}', unrelated: 'Test' }), @@ -236,7 +237,7 @@ describe('buildSimToolSpecs', () => { const registry = new ResolvedSecretTraceRegistry([ { name: 'API_KEY', plaintext: 'secret-value', encryptedValue: 'ciphertext' }, ]) - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) mockExecuteTool.mockImplementationOnce(async (_toolId, _params, options) => { await options.resolvedSecretTraceRegistry.importProvenance( @@ -283,7 +284,7 @@ describe('buildSimToolSpecs', () => { }) const registry = new ResolvedSecretTraceRegistry() registry.markIncomplete('unspecified') - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) const result = await spec.execute({}) diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.ts b/apps/sim/executor/handlers/pi/local/sim-tools.ts index bcfab3229a8..6f3d44eb587 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.ts @@ -107,6 +107,7 @@ function projectToolResult( function buildSimToolSpec( ctx: ExecutionContext, + blockId: string, inputTools: ToolInput[], provider: ProviderToolConfig, toolIndex: number, @@ -211,6 +212,7 @@ function buildSimToolSpec( // Trusted execution context is written last so model arguments cannot override it. _context: { workflowId: ctx.workflowId, + blockId, workspaceId: ctx.workspaceId, executionId: ctx.executionId, userId: ctx.userId, @@ -267,6 +269,8 @@ function buildSimToolSpec( */ export async function buildSimToolSpecs( ctx: ExecutionContext, + /** The Pi block, the block its tool calls act for. */ + blockId: string, inputTools: unknown, sandboxCost?: SandboxCostSink ): Promise { @@ -312,6 +316,6 @@ export async function buildSimToolSpecs( await annotateDuplicateToolBindings(ctx, providers) assignProviderToolIdentities(providers) return configuredTools.map(({ provider, toolIndex }) => - buildSimToolSpec(ctx, inputTools, provider, toolIndex, sandboxCost) + buildSimToolSpec(ctx, blockId, inputTools, provider, toolIndex, sandboxCost) ) } diff --git a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts index 2f525085dfb..ea8a9e7e8a2 100644 --- a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts +++ b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts @@ -148,7 +148,6 @@ export async function runCustomBlockTool( abortSignal?: AbortSignal resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry principal?: WorkflowExecutionPrincipal - sideEffects?: SideEffectPolicy } = {} ): Promise { if (!params.blockType) { @@ -160,7 +159,6 @@ export async function runCustomBlockTool( abortSignal: options.abortSignal, resolvedSecretTraceRegistry: options.resolvedSecretTraceRegistry, principal: options.principal, - sideEffects: options.sideEffects, }) const block: SerializedBlock = { id: generateId(), diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index a3715fa11e6..8e5b58b95af 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -931,7 +931,8 @@ export class WorkflowBlockHandler implements BlockHandler { // A workflow test's mocks and spies reach every child it runs, except a custom // block's: that workflow is the publisher's, so the test mocks the block whole. testHooks: isCustomBlock ? undefined : ctx.testHooks, - // A dry run's writes stay stubbed in every child, a custom block's included. + // A dry run's writes stay stubbed in every child; a custom block never runs under one, + // since the policy answers it whole. sideEffects: ctx.sideEffects, callChain: childCallChain, // A custom block's own session markers and the parent's live stream, fanned diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index 60ef983d2d0..d69beebcb63 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run, while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts index 32077cd08dc..d2390d7a0e6 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts @@ -1559,6 +1559,7 @@ const declaredRoutes = [ base64: null, }, ], + dryRun: null, }, }, ] diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 79f762fff5b..10c11342d63 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1686,7 +1686,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .string() .min(1, 'run.entry.sourceRunId cannot be empty') .describe( - 'Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404.' + 'Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404. A test run (a dry run, or a workflow test) holds placeholders for the writes it did not send, so it is the source only of a `dry` run.' ), }) .strict(), @@ -1706,26 +1706,28 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .boolean() .optional() .describe( - "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials and secrets redacted. Reads, model calls, conditions and credential resolution run for real, and so do Function blocks, listed in `sideEffects.unchecked`. Child workflows inherit it. Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls, conditions and credential resolution run for real, and so does code (a Function block's, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." ), allowBlocks: z .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) .max(50) .optional() .describe( - 'Blocks (id, display name or reference key) whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block cannot be allowed.' + 'Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed.' ), mocks: z .record( z.string(), - z.unknown().describe('Output object that answers the block instead of its handler.') + z + .record(z.string(), z.unknown().describe('Output field.')) + .describe('Output object that answers the block instead of its handler.') ) .optional() .refine((mocks) => mocks === undefined || Object.keys(mocks).length <= 50, { message: 'run.mocks names at most 50 blocks', }) .describe( - 'Blocks (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. With or without `dry`.' + 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`.' ), }) .strict(), @@ -1980,8 +1982,11 @@ const sideEffectBlockFields = { workflowId: z .string() .describe('Workflow whose block it was: the run workflow, or a child workflow it called.'), - blockId: z.string().describe('Block id in that workflow; empty when the call named no block.'), - block: z.string().describe('Block display name.'), + blockId: z + .string() + .nullable() + .describe('Block id in that workflow; null when the call named no block.'), + block: z.string().nullable().describe('Block display name; null when the call named no block.'), } const v2RunSideEffectsSchema = z @@ -2000,7 +2005,7 @@ const v2RunSideEffectsSchema = z .record(z.string(), z.unknown().describe('Request field.')) .nullable() .describe( - "What the call would have sent: an in-process operation's input, or an HTTP call's `method`, `url` and `body` (never headers). For a block answered whole, its logged inputs. Credentials and resolved secrets are redacted; null when the run could not prove none remain." + "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain." ), returned: z .record(z.string(), z.unknown().describe('Placeholder field.')) @@ -2015,18 +2020,26 @@ const v2RunSideEffectsSchema = z tool: z.string().nullable().describe('Tool sent; null when the whole block ran.'), }) ) - .describe('Writes sent for real because `run.allowBlocks` named their block.'), + .describe( + 'Writes sent for real because `run.allowBlocks` named their block, once per block and tool.' + ), unchecked: z .array( z.object({ ...sideEffectBlockFields, - reason: z.string().describe('Why the run cannot see what this block changed.'), + reason: z.string().describe('Why the run cannot see what this code changed.'), }) ) .describe( - 'Blocks that ran for real whose own effects the run cannot see: Function blocks, whose code may make network calls.' + "Blocks whose code ran for real, once per block: a Function block's code, or code an Agent's model wrote, which may make network calls the run cannot see." ), - omitted: z.number().int().nonnegative().describe('Entries left out once a list held 50.'), + omitted: z + .object({ + stubbed: z.number().int().nonnegative().describe('Writes left out of `stubbed`.'), + allowed: z.number().int().nonnegative().describe('Writes left out of `allowed`.'), + unchecked: z.number().int().nonnegative().describe('Blocks left out of `unchecked`.'), + }) + .describe('Entries each list left out once it held 50.'), }) .meta({ id: 'WorkflowRunSideEffects', @@ -2034,6 +2047,21 @@ const v2RunSideEffectsSchema = z description: 'What a dry run did with each write it reached.', }) +const v2RunDryRunSchema = z + .object({ + allowBlocks: z + .array(z.string().describe('Block id.')) + .describe('Blocks whose writes the run sent (`run.allowBlocks`), by id.'), + mocks: z + .record(z.string(), z.record(z.string(), z.unknown().describe('Output field.'))) + .describe('Blocks the run answered with fixed outputs (`run.mocks`), keyed by id.'), + }) + .meta({ + id: 'WorkflowDryRun', + title: 'Workflow dry run', + description: 'The blocks a dry run sent and mocked, which a rerun of it passes again.', + }) + /** * The run result resource. In-band run failures are `status: 'failed'` * with a structured `error` — never an HTTP error: **a `runId` means 200/202 + @@ -2082,7 +2110,12 @@ export const v2ExecuteWorkflowDataSchema = z .describe('Where the run waits when `status` is `paused`; null otherwise.'), sideEffects: v2RunSideEffectsSchema .optional() - .describe('What a dry run (`run.dry`) did with each write it reached; absent otherwise.'), + .describe( + 'What a dry run (`run.dry`) did with each write it reached, whatever its status; absent otherwise.' + ), + dryRun: v2RunDryRunSchema + .optional() + .describe("A dry run's allowed and mocked blocks (`run.dry`); absent for any other run."), }) .meta({ id: 'WorkflowRunResult', @@ -2176,7 +2209,7 @@ export const v2ResumeWorkflowQueuedSchema = v2ExecuteWorkflowQueuedSchema export type V2ResumeWorkflowQueued = z.output export const v2ResumeWorkflowDataSchema = v2ExecuteWorkflowDataSchema - .omit({ executionTimeoutSeconds: true, sideEffects: true }) + .omit({ executionTimeoutSeconds: true, sideEffects: true, dryRun: true }) .extend({ error: v2ExecutionErrorSchema .omit({ rerunFromBlockId: true }) @@ -2474,6 +2507,11 @@ export const v2WorkflowRunStatusSchema = z .describe( 'Run-produced files when `includeOutput=true`, or null when not requested or execution data is hidden by organization permission groups.' ), + dryRun: v2RunDryRunSchema + .nullable() + .describe( + "A failed dry run's allowed and mocked blocks, which a rerun of it passes again; null for any other run, or when execution data is hidden by organization permission groups." + ), }) .meta({ id: 'WorkflowRunStatus', diff --git a/apps/sim/lib/internal/mcp/execute-tool.ts b/apps/sim/lib/internal/mcp/execute-tool.ts index 22c733328bb..ea348cc924a 100644 --- a/apps/sim/lib/internal/mcp/execute-tool.ts +++ b/apps/sim/lib/internal/mcp/execute-tool.ts @@ -27,6 +27,7 @@ import { McpToolsNotAllowedError, } from '@/lib/mcp/application/execute-tool' import { McpOauthRedirectRequired } from '@/lib/mcp/oauth' +import { parseMcpToolArguments } from '@/lib/mcp/tool-arguments' import { McpOauthAuthorizationRequiredError } from '@/lib/mcp/types' import { categorizeError, @@ -46,42 +47,6 @@ import { const logger = createLogger('McpInternalOperation') -const MCP_SYSTEM_PARAMETERS = new Set([ - 'operationPolicy', - 'serverId', - 'serverUrl', - 'toolName', - 'serverName', - '_context', - 'envVars', - 'workflowVariables', - 'blockData', - 'blockNameMapping', - '_toolSchema', -]) - -function parseArguments(input: unknown): Record | null { - if (!isPlainRecord(input)) return null - if (!Object.hasOwn(input, 'arguments')) { - return Object.fromEntries( - Object.entries(input).filter(([name]) => !MCP_SYSTEM_PARAMETERS.has(name)) - ) - } - - const value = input.arguments - if (typeof value !== 'string') return isPlainRecord(value) ? value : null - try { - const parsed: unknown = JSON.parse(value) - return isPlainRecord(parsed) ? parsed : null - } catch (error) { - logger.warn('Failed to parse MCP arguments JSON', { - errorName: error instanceof Error ? error.name : 'UnknownError', - argumentsLength: value.length, - }) - return null - } -} - async function createResponse( body: Record, status: number, @@ -157,7 +122,7 @@ export const executeMcpTool: InternalToolOperationHandler = async (request) => { { status: 400 } ) } - const args = parseArguments(request.input) + const args = parseMcpToolArguments(request.input) if (!args) return Response.json({ success: false, error: 'Invalid request format' }, { status: 400 }) diff --git a/apps/sim/lib/mcp/tool-arguments.ts b/apps/sim/lib/mcp/tool-arguments.ts new file mode 100644 index 00000000000..e4460cb7b1f --- /dev/null +++ b/apps/sim/lib/mcp/tool-arguments.ts @@ -0,0 +1,45 @@ +import { createLogger } from '@sim/logger' +import { isPlainRecord } from '@sim/utils/object' + +const logger = createLogger('McpToolArguments') + +/** Params an MCP tool call carries for the run, never sent to the server as arguments. */ +const MCP_SYSTEM_PARAMETERS = new Set([ + 'operationPolicy', + 'serverId', + 'serverUrl', + 'toolName', + 'serverName', + '_context', + 'envVars', + 'workflowVariables', + 'blockData', + 'blockNameMapping', + '_toolSchema', +]) + +/** + * The arguments an MCP tool call sends its server: an explicit `arguments` object (or JSON + * string), else every param that is not the run's own. Null when they cannot be read. + */ +export function parseMcpToolArguments(input: unknown): Record | null { + if (!isPlainRecord(input)) return null + if (!Object.hasOwn(input, 'arguments')) { + return Object.fromEntries( + Object.entries(input).filter(([name]) => !MCP_SYSTEM_PARAMETERS.has(name)) + ) + } + + const value = input.arguments + if (typeof value !== 'string') return isPlainRecord(value) ? value : null + try { + const parsed: unknown = JSON.parse(value) + return isPlainRecord(parsed) ? parsed : null + } catch (error) { + logger.warn('Failed to parse MCP arguments JSON', { + errorName: error instanceof Error ? error.name : 'UnknownError', + argumentsLength: value.length, + }) + return null + } +} diff --git a/apps/sim/lib/mothership/tasks/application/tasks.test.ts b/apps/sim/lib/mothership/tasks/application/tasks.test.ts index 8920442838b..e31610ca702 100644 --- a/apps/sim/lib/mothership/tasks/application/tasks.test.ts +++ b/apps/sim/lib/mothership/tasks/application/tasks.test.ts @@ -260,6 +260,7 @@ describe('worker HTTP contracts', () => { output: { report: 'completed result' }, blockOutputs: null, files: [], + dryRun: null, }, }) const transport = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 56c3315732d..9c2e46a19e5 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -1,16 +1,27 @@ /** - * Dry runs against real PostgreSQL, through the manual run use case: a dry run writes no table row - * and sends no HTTP request, and reports both writes with the payloads they would have sent (the - * run's secrets redacted) under the `test` trigger; an allowed block writes for real while reads - * run for real; a child workflow's write stays stubbed; and a mocked block steers a branch. + * Dry runs against real PostgreSQL and Redis, through the manual run use cases and the v2 execute + * route: a dry run writes no table row and sends no request, reports each write with the payload + * it would have sent (credentials, run secrets and password fields redacted) under the `test` + * trigger, and keeps nothing else: no Agent memory, no workspace event, no run count. An allowed + * block writes for real while reads run for real; a child workflow's writes, an Agent's included, + * stay stubbed; custom and Wait blocks are answered whole; code runs and is listed unchecked; a + * mocked block steers a branch; a failed dry run keeps its side effects and is the source only of + * another dry run. Model calls are answered by a simulated Anthropic API. */ import { db } from '@sim/db' import { + apiKey, + customBlock, + customTools, + memory, + organization, + pausedExecutions, permissions, user, userStats, userTableDefinitions, userTableRows, + webhook, workflow, workflowExecutionLogs, workflowExecutionSnapshots, @@ -24,35 +35,54 @@ import { generateId } from '@sim/utils/id' import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' import type { BlockState, SubBlockState, WorkflowState } from '@sim/workflow-types/workflow' import { eq, inArray } from 'drizzle-orm' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { NextRequest } from 'next/server' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' + +const subscriberRuns = vi.hoisted(() => { + /** Custom blocks are a self-hosted opt-in, read when the config module loads. */ + process.env.CUSTOM_BLOCKS_ENABLED = 'true' + return { runIds: [] as string[] } +}) + +/** A Sim-trigger subscriber's run starts here; the suite records the run that raised it. */ +vi.mock('@/lib/webhooks/processor', () => ({ + processPolledWebhookEvent: async (_webhook: unknown, _workflow: unknown, payload: unknown) => { + const { runId } = payload as { runId?: unknown } + subscriberRuns.runIds.push(typeof runId === 'string' ? runId : 'unknown') + return { success: true } + }, +})) + +import { hashApiKey } from '@/lib/api-key/crypto' import { closeRedisConnection } from '@/lib/core/config/redis' +import type { OrchestrationError } from '@/lib/core/orchestration/types' import { encryptSecret } from '@/lib/core/security/encryption' +import { WorkflowTestSession } from '@/lib/workflow-tests/session' import { type ExecuteManualWorkflowInput, + executeManualWorkflowFromBlockOperation, executeManualWorkflowOperation, } from '@/lib/workflows/application/execute-manual-workflow' import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' +import { POST as v2Execute } from '@/app/api/v2/workflows/[workflowId]/execute/route' const ownerId = generateId() +const organizationId = generateId() const workspaceId = generateId() -const parentId = generateId() -const childId = generateId() -const branchingId = generateId() -const tableId = generateId() const SECRET = `dry-secret-${generateId()}` +const UNREFERENCED_SECRET = `unreferenced-${generateId()}` +const API_KEY = `sk-sim-fixture-${generateId()}` const principal = createDelegatedPrincipal({ subjectUserId: ownerId, workspaceId, audience: 'sim:workflows', }) +const workflowIds: string[] = [] +const validationError = { code: 'validation' } satisfies Partial /** Block ids are global keys, so each block gets a fresh one; tests address blocks by name. */ -function block( - name: string, - type: string, - values: Record = {} -): BlockState { +function block(name: string, type: string, values: Record = {}): BlockState { return { id: generateId(), type, @@ -61,7 +91,10 @@ function block( enabled: true, outputs: {}, subBlocks: Object.fromEntries( - Object.entries(values).map(([key, value]) => [key, { id: key, type: 'short-input', value }]) + Object.entries(values).map(([key, value]) => [ + key, + { id: key, type: 'short-input', value: value as SubBlockState['value'] }, + ]) ), } } @@ -90,80 +123,124 @@ function graph( return { state, idOf } } -const upsertLead = (id: string, email: string) => - block(id, 'table', { +/** A Condition block routing to `-if` when `expression` holds, else to `-else`. */ +function condition(name: string, expression: string): BlockState { + const gate = block(name, 'condition') + gate.subBlocks.conditions = { + id: 'conditions', + type: 'condition-input', + value: JSON.stringify([ + { id: `${gate.id}-if`, title: 'if', value: expression }, + { id: `${gate.id}-else`, title: 'else', value: '' }, + ]), + } + return gate +} + +/** Saves `state` as the draft of a new workflow in the fixture workspace. */ +async function saveWorkflow(state: WorkflowState, name = `Dry run ${generateId()}`) { + const id = generateId() + const now = new Date() + await db.insert(workflow).values({ + id, + userId: ownerId, + workspaceId, + name, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + workflowIds.push(id) + const saved = await saveWorkflowToNormalizedTables(id, state) + expect(saved.success, saved.error).toBe(true) + return id +} + +/** A fresh `leads` table, so no test reads another's rows. */ +async function createTable(): Promise { + const tableId = generateId() + await db.insert(userTableDefinitions).values({ + id: tableId, + workspaceId, + name: `leads_${tableId.replaceAll('-', '_')}`, + createdBy: ownerId, + schema: { + columns: [ + { id: 'col_email', name: 'email', type: 'string', required: true, unique: true }, + { id: 'col_score', name: 'score', type: 'number' }, + ], + }, + }) + return tableId +} + +const upsertLead = (name: string, tableId: string, email: string) => + block(name, 'table', { operation: 'upsert_row', tableSelector: tableId, data: JSON.stringify({ email, score: 82 }), }) -/** A POST to a host that never resolves: sent, it fails the run. Its body carries a secret. */ -const notify = (id: string) => - block(id, 'api', { - url: 'http://dry-run.invalid/hook', +const queryLeads = (name: string, tableId: string) => + block(name, 'table', { operation: 'query_rows', tableSelector: tableId }) + +/** A POST to a host that never resolves: sent, it fails the run. Its URL and body hold a secret. */ +const notify = (name: string) => + block(name, 'api', { + url: 'http://dry-run.invalid/hook?key={{DRY_SECRET}}', method: 'POST', body: JSON.stringify({ email: 'a@b.co', note: 'key={{DRY_SECRET}}' }), }) /** Start → lookup (read) → save (table upsert) → notify (HTTP POST) → child (Workflow block). */ -const parent = graph( - [ - block('start', 'start_trigger'), - block('lookup', 'table', { operation: 'query_rows', tableSelector: tableId }), - upsertLead('save', 'a@b.co'), - notify('notify'), - block('child', 'workflow', { workflowId: childId }), - ], - [ - ['start', 'lookup'], - ['lookup', 'save'], - ['save', 'notify'], - ['notify', 'child'], - ] -) - -const child = graph( - [block('start', 'start_trigger'), upsertLead('childsave', 'child@b.co')], - [['start', 'childsave']] -) - -/** Start → lookup → gate: over 50 rows goes to `big`, else to `small`; both are POSTs. */ -const gate = block('gate', 'condition') -gate.subBlocks.conditions = { - id: 'conditions', - type: 'condition-input', - value: JSON.stringify([ - { id: `${gate.id}-if`, title: 'if', value: ' > 50' }, - { id: `${gate.id}-else`, title: 'else', value: '' }, - ]), +async function parentFixture() { + const tableId = await createTable() + const childId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), upsertLead('childsave', tableId, 'child@b.co')], + [['start', 'childsave']] + ).state + ) + const parent = graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + upsertLead('save', tableId, 'a@b.co'), + notify('notify'), + block('child', 'workflow', { workflowId: childId }), + ], + [ + ['start', 'lookup'], + ['lookup', 'save'], + ['save', 'notify'], + ['notify', 'child'], + ] + ) + return { tableId, childId, parent, parentId: await saveWorkflow(parent.state) } +} + +/** A sync run's result once its terminal log is durable. */ +async function settled(result: unknown, workflowId: string): Promise { + const run = result as ExecuteWorkflowServiceRun + if (!run.ok || !('status' in run)) throw new Error(`Run did not settle: ${JSON.stringify(run)}`) + const deadline = Date.now() + 10_000 + while ((await getWorkflowExecutionLogStatus(run.executionId, workflowId)) !== run.status) { + if (Date.now() >= deadline) throw new Error('Run did not persist its terminal log') + await sleep(25) + } + return run } -const branching = graph( - [ - block('start', 'start_trigger'), - block('lookup', 'table', { operation: 'query_rows', tableSelector: tableId }), - gate, - notify('big'), - notify('small'), - ], - [ - ['start', 'lookup'], - ['lookup', 'gate'], - ['gate', 'big', `condition-${gate.id}-if`], - ['gate', 'small', `condition-${gate.id}-else`], - ] -) async function run( workflowId: string, options: Partial = {} ): Promise { - const executionId = generateId() const result = await executeManualWorkflowOperation.execute({ principal, input: { workflowId, requestId: generateId(), - executionId, + executionId: generateId(), input: {}, mode: 'sync', requestHeaders: new Headers(), @@ -171,18 +248,11 @@ async function run( ...options, }, }) - if (!result.ok || !('status' in result)) { - throw new Error(`Run did not settle: ${JSON.stringify(result)}`) - } - const deadline = Date.now() + 10_000 - while ((await getWorkflowExecutionLogStatus(executionId, workflowId)) !== result.status) { - if (Date.now() >= deadline) throw new Error('Run did not persist its terminal log') - await sleep(25) - } - return result + return settled(result, workflowId) } -async function rowEmails(): Promise { +/** Each row of the table, as JSON. */ +async function tableRows(tableId: string): Promise { const rows = await db .select({ data: userTableRows.data }) .from(userTableRows) @@ -190,12 +260,94 @@ async function rowEmails(): Promise { return rows.map((row) => JSON.stringify(row.data)) } -async function triggerOf(executionId: string): Promise { - const [log] = await db +async function logTriggers(workflowId: string): Promise { + const rows = await db .select({ trigger: workflowExecutionLogs.trigger }) .from(workflowExecutionLogs) - .where(eq(workflowExecutionLogs.executionId, executionId)) - return log?.trigger + .where(eq(workflowExecutionLogs.workflowId, workflowId)) + return rows.map((row) => row.trigger) +} + +async function runCountOf(workflowId: string): Promise { + const [row] = await db + .select({ runCount: workflow.runCount }) + .from(workflow) + .where(eq(workflow.id, workflowId)) + return row.runCount +} + +/** The simulated Anthropic API: the first `toolTurns` turns call the first tool offered. */ +const model = { toolTurns: 0 } + +async function answerModel(input: RequestInfo | URL, init?: RequestInit): Promise { + const request = new Request(input, init) + const url = new URL(request.url) + if (url.hostname !== 'api.anthropic.com') { + throw new Error(`Unexpected network destination in a dry run: ${url.hostname}`) + } + const body = (await request.json()) as Record + const tools = Array.isArray(body.tools) ? (body.tools as Array<{ name: string }>) : [] + const callsTool = model.toolTurns > 0 && tools.length > 0 + if (callsTool) model.toolTurns-- + const toolUse = { + type: 'tool_use', + id: `toolu_${generateId().replaceAll('-', '')}`, + name: tools[0]?.name, + input: { message: 'tell the team' }, + } + const stopReason = callsTool ? 'tool_use' : 'end_turn' + const message = { + id: `msg_${generateId()}`, + type: 'message', + role: 'assistant', + model: body.model, + content: callsTool ? [toolUse] : [{ type: 'text', text: 'Done' }], + stop_reason: stopReason, + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 5 }, + } + if (!body.stream) return Response.json(message) + const events = [ + { type: 'message_start', message: { ...message, content: [], stop_reason: null } }, + callsTool + ? { type: 'content_block_start', index: 0, content_block: { ...toolUse, input: {} } } + : { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + callsTool + ? { + type: 'content_block_delta', + index: 0, + delta: { type: 'input_json_delta', partial_json: JSON.stringify(toolUse.input) }, + } + : { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Done' } }, + { type: 'content_block_stop', index: 0 }, + { + type: 'message_delta', + delta: { stop_reason: stopReason, stop_sequence: null }, + usage: { output_tokens: 5 }, + }, + { type: 'message_stop' }, + ] + return new Response( + events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''), + { headers: { 'Content-Type': 'text/event-stream' } } + ) +} + +/** An Agent on the simulated Anthropic model. */ +function agent(name: string, values: Record): BlockState { + return block(name, 'agent', { + model: 'claude-haiku-4-5', + apiKey: 'synthetic-anthropic-key', + messages: [{ role: 'user', content: 'Notify the team' }], + ...values, + }) +} + +/** A dry run whose model calls its first tool on each of its first `toolTurns` turns. */ +async function runWithModel(workflowId: string, toolTurns: number) { + model.toolTurns = toolTurns + vi.stubGlobal('fetch', answerModel) + return run(workflowId, { dry: true }) } beforeAll(async () => { @@ -209,11 +361,15 @@ beforeAll(async () => { updatedAt: now, }) await db.insert(userStats).values({ id: generateId(), userId: ownerId }) + await db + .insert(organization) + .values({ id: organizationId, name: 'Dry run', slug: organizationId }) await insertWorkspaceFixture(db, { id: workspaceId, name: 'Dry run fixture', ownerId, billedAccountUserId: ownerId, + organizationId, }) await db.insert(permissions).values({ id: generateId(), @@ -225,41 +381,27 @@ beforeAll(async () => { await db.insert(workspaceEnvironment).values({ id: generateId(), workspaceId, - variables: { DRY_SECRET: (await encryptSecret(SECRET)).encrypted }, - }) - await db.insert(userTableDefinitions).values({ - id: tableId, - workspaceId, - name: 'leads', - createdBy: ownerId, - schema: { - columns: [ - { id: 'col_email', name: 'email', type: 'string', required: true, unique: true }, - { id: 'col_score', name: 'score', type: 'number' }, - ], + variables: { + DRY_SECRET: (await encryptSecret(SECRET)).encrypted, + UNREFERENCED_SECRET: (await encryptSecret(UNREFERENCED_SECRET)).encrypted, }, }) - for (const [id, state] of [ - [parentId, parent], - [childId, child], - [branchingId, branching], - ] as const) { - await db.insert(workflow).values({ - id, - userId: ownerId, - workspaceId, - name: `Dry run ${id}`, - lastSynced: now, - createdAt: now, - updatedAt: now, - }) - const saved = await saveWorkflowToNormalizedTables(id, state.state) - expect(saved.success, saved.error).toBe(true) - } + await db.insert(apiKey).values({ + id: generateId(), + userId: ownerId, + name: 'Dry run fixture', + key: API_KEY, + keyHash: hashApiKey(API_KEY), + type: 'personal', + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() }) afterAll(async () => { - const workflowIds = [parentId, childId, branchingId] + await db.delete(webhook).where(inArray(webhook.workflowId, workflowIds)) await db .delete(workflowExecutionLogs) .where(inArray(workflowExecutionLogs.workflowId, workflowIds)) @@ -267,6 +409,7 @@ afterAll(async () => { .delete(workflowExecutionSnapshots) .where(inArray(workflowExecutionSnapshots.workflowId, workflowIds)) await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(organization).where(eq(organization.id, organizationId)) await db.delete(user).where(eq(user.id, ownerId)) await closeRedisConnection() await db.$client.end() @@ -274,37 +417,60 @@ afterAll(async () => { describe('a dry run', () => { it('writes no row and sends no request, and reports each write it held back', async () => { + const { tableId, childId, parentId } = await parentFixture() + const result = await run(parentId, { dry: true }) expect(result.status, JSON.stringify(result.error)).toBe('completed') - expect(await rowEmails()).toEqual([]) - expect(await triggerOf(result.executionId)).toBe('test') - + expect(await tableRows(tableId)).toEqual([]) + expect(await logTriggers(parentId)).toEqual(['test']) const stubbed = result.sideEffects?.stubbed ?? [] expect(stubbed.map((entry) => [entry.workflowId, entry.block, entry.tool])).toEqual([ [parentId, 'save', 'table_upsert_row'], [parentId, 'notify', 'http_request'], [childId, 'childsave', 'table_upsert_row'], ]) - expect(stubbed[0].request).toMatchObject({ - tableId, - data: { email: 'a@b.co', score: 82 }, - }) + expect(stubbed[0].request).toMatchObject({ tableId, data: { email: 'a@b.co', score: 82 } }) expect(stubbed[1].request).toMatchObject({ method: 'POST', - url: 'http://dry-run.invalid/hook', + url: expect.stringContaining('http://dry-run.invalid/hook?key='), body: { email: 'a@b.co' }, }) expect(JSON.stringify(stubbed[1].request)).not.toContain(SECRET) expect(stubbed[2].request).toMatchObject({ data: { email: 'child@b.co' } }) - expect(result.sideEffects?.allowed).toEqual([]) }) - it('sends an allowed block’s write and still runs reads for real', async () => { + it('keeps nothing beyond its own log: no run count and no workspace event', async () => { + const { parentId } = await parentFixture() + const subscriber = await saveWorkflow(graph([block('start', 'start_trigger')], []).state) + await db.update(workflow).set({ isDeployed: true }).where(eq(workflow.id, subscriber)) + await db.insert(webhook).values({ + id: generateId(), + workflowId: subscriber, + provider: 'sim', + path: generateId(), + providerConfig: { eventType: 'execution_success', workflowIds: [parentId] }, + }) + + const dry = await run(parentId, { dry: true }) + const live = await run(parentId, { stopAfterBlockId: 'lookup' }) + + const deadline = Date.now() + 10_000 + while (!subscriberRuns.runIds.includes(live.executionId)) { + if (Date.now() >= deadline) throw new Error('The live run raised no event') + await sleep(25) + } + expect(subscriberRuns.runIds).not.toContain(dry.executionId) + expect(await runCountOf(parentId)).toBe(1) + }) + + it('sends an allowed block’s writes, keyed to the run’s own blocks, while reads run for real', async () => { + const { tableId, parent, parentId } = await parentFixture() + const allowed = await run(parentId, { dry: true, allowBlocks: ['save'] }) expect(allowed.status, JSON.stringify(allowed.error)).toBe('completed') - expect(await rowEmails()).toEqual([expect.stringContaining('a@b.co')]) + expect(await tableRows(tableId)).toEqual([expect.stringContaining('a@b.co')]) expect(allowed.sideEffects?.allowed).toEqual([ { workflowId: parentId, @@ -317,30 +483,362 @@ describe('a dry run', () => { 'notify', 'childsave', ]) + expect(allowed.dryRun).toEqual({ allowBlocks: [parent.idOf('save')], mocks: {} }) const reread = await run(parentId, { dry: true, selectedOutputs: ['lookup.rows'] }) expect(JSON.stringify(reread.blockOutputs?.['lookup.rows'])).toContain('a@b.co') - expect(await rowEmails()).toHaveLength(1) + await expect(run(parentId, { dry: true, allowBlocks: ['child'] })).rejects.toMatchObject( + validationError + ) }) - it('takes the branch a mocked block steers it to', async () => { - const unmocked = await run(branchingId, { dry: true }) - expect(unmocked.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['small']) + it('records an Agent’s custom tool call by its arguments, never the run’s environment', async () => { + const schema = { + type: 'function', + function: { + name: 'notify_team', + description: 'Tell the team', + parameters: { + type: 'object', + properties: { message: { type: 'string' } }, + required: ['message'], + }, + }, + } + const customToolId = generateId() + await db.insert(customTools).values({ + id: customToolId, + workspaceId, + userId: ownerId, + title: `Notify ${customToolId}`, + schema, + code: 'return { sent: true }', + }) + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + agent('assistant', { + tools: [{ type: 'custom-tool', customToolId, usageControl: 'auto' }], + }), + ], + [['start', 'assistant']] + ).state + ) - const mocked = await run(branchingId, { - dry: true, - mocks: { lookup: { rows: [], rowCount: 0, totalCount: 99 } }, + const result = await runWithModel(workflowId, 1) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ + block: 'assistant', + request: { arguments: { message: 'tell the team' } }, + }), + ]) + expect(JSON.stringify(result.sideEffects)).not.toContain(UNREFERENCED_SECRET) + }) + + it('keeps a write in a workflow an Agent calls stubbed, and writes no Agent memory', async () => { + const tableId = await createTable() + const childId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), upsertLead('childsave', tableId, 'child@b.co')], + [['start', 'childsave']] + ).state + ) + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + agent('assistant', { + memoryType: 'conversation', + conversationId: `conversation-${generateId()}`, + tools: [{ type: 'workflow', params: { workflowId: childId }, usageControl: 'auto' }], + }), + ], + [['start', 'assistant']] + ).state + ) + + const result = await runWithModel(workflowId, 1) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([]) + expect(result.sideEffects?.stubbed.map((entry) => [entry.workflowId, entry.block])).toEqual([ + [childId, 'childsave'], + ]) + const memories = await db + .select({ id: memory.id }) + .from(memory) + .where(eq(memory.workspaceId, workspaceId)) + expect(memories).toEqual([]) + }) + + it('masks a secret typed into a password field, whatever the field is called', async () => { + const routingKey = `routing-${generateId()}` + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('page', 'pagerduty', { + operation: 'send_event', + routingKey, + eventAction: 'trigger', + eventSummary: 'Disk full', + eventSource: 'db-1', + eventSeverity: 'critical', + }), + ], + [['start', 'page']] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ + tool: 'pagerduty_send_event', + request: expect.objectContaining({ + body: expect.objectContaining({ event_action: 'trigger' }), + }), + }), + ]) + expect(JSON.stringify(result.sideEffects)).not.toContain(routingKey) + }) + + it('answers custom and Wait blocks whole, without running the publisher’s workflow or pausing', async () => { + const tableId = await createTable() + const sourceId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), upsertLead('publisher save', tableId, 's@b.co')], + [['start', 'publisher save']] + ).state + ) + const customType = `custom_block_${generateId().replaceAll('-', '_')}` + await db.insert(customBlock).values({ + id: generateId(), + organizationId, + workflowId: sourceId, + type: customType, + name: 'Publisher block', }) + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('hold', 'wait', { timeValue: '1', timeUnit: 'seconds' }), + block('published', customType), + upsertLead('save', tableId, 'a@b.co'), + ], + [ + ['start', 'hold'], + ['hold', 'published'], + ['published', 'save'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool])).toEqual([ + ['hold', null], + ['published', null], + ['save', 'table_upsert_row'], + ]) + expect(await logTriggers(sourceId)).toEqual([]) + const paused = await db + .select({ id: pausedExecutions.id }) + .from(pausedExecutions) + .where(eq(pausedExecutions.executionId, result.executionId)) + expect(paused).toEqual([]) + for (const allowed of ['hold', 'published']) { + await expect(run(workflowId, { dry: true, allowBlocks: [allowed] })).rejects.toMatchObject( + validationError + ) + } + }) + + it('runs code for real, listing a Function block unchecked and a Condition not at all', async () => { + const tableId = await createTable() + const gate = condition('gate', ' > 50') + const branching = graph( + [ + block('start', 'start_trigger'), + block('score', 'function', { language: 'javascript', code: 'return 41 + 41' }), + gate, + upsertLead('high', tableId, 'high@b.co'), + upsertLead('low', tableId, 'low@b.co'), + ], + [ + ['start', 'score'], + ['score', 'gate'], + ['gate', 'high', `condition-${gate.id}-if`], + ['gate', 'low', `condition-${gate.id}-else`], + ] + ) + const workflowId = await saveWorkflow(branching.state) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['high']) + expect(result.sideEffects?.unchecked).toEqual([ + expect.objectContaining({ blockId: branching.idOf('score'), block: 'score' }), + ]) + }) + + it('takes the branch a mocked block steers it to, and refuses mocks outside a dry run', async () => { + const tableId = await createTable() + const gate = condition('gate', ' > 50') + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + gate, + notify('big'), + notify('small'), + ], + [ + ['start', 'lookup'], + ['lookup', 'gate'], + ['gate', 'big', `condition-${gate.id}-if`], + ['gate', 'small', `condition-${gate.id}-else`], + ] + ).state + ) + const mocks = { lookup: { rows: [], rowCount: 0, totalCount: 99 } } + + const unmocked = await run(workflowId, { dry: true }) + const mocked = await run(workflowId, { dry: true, mocks }) + + expect(unmocked.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['small']) expect(mocked.status, JSON.stringify(mocked.error)).toBe('completed') expect(mocked.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['big']) + await expect(run(workflowId, { mocks })).rejects.toMatchObject(validationError) + }) + + it('refuses what it cannot honour: allow outside a dry run, an unknown block, stream or detach', async () => { + const { tableId, parentId } = await parentFixture() + + for (const options of [ + { allowBlocks: ['save'] }, + { dry: true, allowBlocks: ['nope'] }, + { dry: true, mode: 'stream' as const }, + { dry: true, mode: 'sync-result-stream' as const, detachable: true }, + ]) { + await expect(run(parentId, options)).rejects.toMatchObject(validationError) + } + expect(await tableRows(tableId)).toEqual([]) }) - it('refuses to allow a block outside a dry run, or one the draft does not have', async () => { - await expect(run(parentId, { allowBlocks: ['save'] })).rejects.toThrow( - 'run.allowBlocks requires run.dry' + it('keeps a failed run’s side effects, and is the source only of another dry run', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + upsertLead('save', tableId, 'a@b.co'), + queryLeads('broken', generateId()), + upsertLead('after', tableId, 'after@b.co'), + ], + [ + ['start', 'save'], + ['save', 'broken'], + ['broken', 'after'], + ] + ).state ) - await expect(run(parentId, { dry: true, allowBlocks: ['nope'] })).rejects.toThrow( - /run\.allowBlocks "nope" is not a block/ + + const failed = await run(workflowId, { dry: true }) + + expect(failed.status).toBe('failed') + expect(failed.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['save']) + const fromBlock = async (options: { dry?: boolean }) => + settled( + await executeManualWorkflowFromBlockOperation.execute({ + principal, + input: { + workflowId, + requestId: generateId(), + executionId: generateId(), + mode: 'sync', + requestHeaders: new Headers(), + blockId: 'after', + sourceRunId: failed.executionId, + ...options, + }, + }), + workflowId + ) + await expect(fromBlock({})).rejects.toMatchObject(validationError) + const rerun = await fromBlock({ dry: true }) + expect(rerun.status, JSON.stringify(rerun.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([]) + }) + + it('stubs a workflow test’s unmocked writes', async () => { + const tableId = await createTable() + const name = `Dry test ${generateId()}` + await saveWorkflow( + graph( + [block('start', 'start_trigger'), upsertLead('save', tableId, 'a@b.co')], + [['start', 'save']] + ).state, + name ) + const session = new WorkflowTestSession({ + workspaceId, + principal, + version: 'draft', + only: null, + onProgress: async () => {}, + }) + + let event = await session.start({ workflow: name, trigger: null, input: {}, targets: [] }) + while (event.kind === 'waiting') event = await session.next(event.runId) + + expect(event).toMatchObject({ kind: 'done' }) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('is forwarded by the v2 execute route, a block entry’s included', async () => { + const { tableId, parentId } = await parentFixture() + const execute = async (runSelection: Record) => { + const request = new NextRequest( + `http://localhost:3000/api/v2/workflows/${parentId}/execute`, + { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-api-key': API_KEY, + 'x-forwarded-for': '127.0.0.1', + }, + body: JSON.stringify({ input: {}, run: runSelection }), + } + ) + const response = await v2Execute(request, { + params: Promise.resolve({ workflowId: parentId }), + }) + const body = (await response.json()) as { + data: { runId: string; status: string; sideEffects?: { stubbed: unknown[] } } + } + expect(response.status, JSON.stringify(body)).toBe(200) + return body.data + } + + const first = await execute({ source: 'manual', dry: true }) + expect(first.status).toBe('completed') + expect(first.sideEffects?.stubbed).toHaveLength(3) + const rerun = await execute({ + source: 'manual', + dry: true, + entry: { type: 'block', blockId: 'save', sourceRunId: first.runId }, + }) + expect(rerun.status).toBe('completed') + expect(rerun.sideEffects?.stubbed).toHaveLength(3) + expect(await tableRows(tableId)).toEqual([]) }) }) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts index 3efe284975e..673e8667025 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts @@ -16,6 +16,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ executeService: vi.fn(), loadSourceState: vi.fn(), + loadSourceTrigger: vi.fn(async () => 'manual'), resolveOptions: vi.fn(), validateInput: vi.fn(), })) @@ -34,6 +35,7 @@ vi.mock('@/lib/workflows/executor/execute-service', () => ({ vi.mock('@/lib/workflows/executor/execution-state', () => ({ getExecutionStateForWorkflow: mocks.loadSourceState, + getWorkflowExecutionLogTrigger: mocks.loadSourceTrigger, })) vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index 8c0e1afc404..f942064fb2f 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,5 +1,4 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' -import { isPlainRecord } from '@sim/utils/object' import { formatQuotedNameList } from '@sim/utils/string' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' @@ -12,16 +11,15 @@ import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/aut import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import type { ExecuteWorkflowInput } from '@/lib/workflows/application/execute-workflow' import { workflowOperations } from '@/lib/workflows/application/operations' -import { - createBlockMockHooks, - DryRunSideEffects, - PAUSING_BLOCK_TYPES, -} from '@/lib/workflows/dry-run' +import { PAUSING_BLOCK_TYPES, runsAnotherWorkflow, WriteStubPolicy } from '@/lib/workflows/dry-run' import { type ExecuteWorkflowServiceResult, executeWorkflowService, } from '@/lib/workflows/executor/execute-service' -import { getExecutionStateForWorkflow } from '@/lib/workflows/executor/execution-state' +import { + getExecutionStateForWorkflow, + getWorkflowExecutionLogTrigger, +} from '@/lib/workflows/executor/execution-state' import { loadWorkflowFromNormalizedTables, type NormalizedWorkflowData, @@ -39,8 +37,8 @@ interface ManualExecutionInput extends Omit + /** Block selector to the output that answers the block in a dry run (`run.mocks`). */ + mocks?: Record> } export interface ExecuteManualWorkflowInput extends ManualExecutionInput { @@ -167,15 +165,29 @@ function resolveStopAfterBlock( } /** - * The dry run and block mocks a manual run asked for, their blocks resolved like + * The dry run a manual run asked for, its allowed and mocked blocks resolved like * {@link resolveBlockSelector}. A dry run is logged under the `test` trigger, never as a manual * run, and returns its side effects with the result it waits for, so it cannot stream or detach. + * Mocks need a dry run: a fixed output must never drive a run's real writes. */ -function resolveRunOverrides(state: ManualWorkflowState, input: ManualExecutionInput) { - if (input.allowBlocks?.length && !input.dry) { - throw new OrchestrationError('validation', 'run.allowBlocks requires run.dry') +function resolveRunOverrides( + state: ManualWorkflowState, + input: ManualExecutionInput, + workflowId: string +) { + if (!input.dry) { + if (input.allowBlocks?.length) { + throw new OrchestrationError('validation', 'run.allowBlocks requires run.dry') + } + if (input.mocks && Object.keys(input.mocks).length > 0) { + throw new OrchestrationError( + 'validation', + 'run.mocks requires run.dry: a mocked block must never steer a run that sends its writes' + ) + } + return { triggerType: 'manual' as const } } - if (input.dry && (input.mode === 'stream' || input.detachable)) { + if (input.mode === 'stream' || input.detachable) { throw new OrchestrationError( 'validation', 'run.dry returns its side effects with the run result, so it cannot be combined with stream or waitTimeoutSeconds' @@ -184,32 +196,37 @@ function resolveRunOverrides(state: ManualWorkflowState, input: ManualExecutionI const allowBlockIds = new Set() for (const selector of input.allowBlocks ?? []) { const blockId = resolveBlockSelector(state, selector, 'run.allowBlocks') - if (PAUSING_BLOCK_TYPES.has(state.blocks[blockId].type)) { + const blockType = state.blocks[blockId].type + if (PAUSING_BLOCK_TYPES.has(blockType)) { throw new OrchestrationError( 'validation', `run.allowBlocks "${selector}" pauses the run, which would resume without the dry run; mock its output with run.mocks instead.` ) } - allowBlockIds.add(blockId) - } - const mocks = new Map>() - for (const [selector, output] of Object.entries(input.mocks ?? {})) { - if (!isPlainRecord(output)) { + if (runsAnotherWorkflow(blockType)) { throw new OrchestrationError( 'validation', - `run.mocks "${selector}" must be an object, the output the block returns` + `run.allowBlocks "${selector}" runs another workflow (a Workflow or custom block), whose writes a dry run never sends; mock its output with run.mocks instead.` ) } + allowBlockIds.add(blockId) + } + const blockMocks = new Map>() + for (const [selector, output] of Object.entries(input.mocks ?? {})) { const blockId = resolveBlockSelector(state, selector, 'run.mocks') - if (mocks.has(blockId)) { + if (blockMocks.has(blockId)) { throw new OrchestrationError('validation', `run.mocks names block "${blockId}" twice`) } - mocks.set(blockId, output) + blockMocks.set(blockId, output) } return { - triggerType: input.dry ? ('test' as const) : ('manual' as const), - dryRun: input.dry ? new DryRunSideEffects({ allowBlockIds, pausingBlocks: 'stub' }) : undefined, - testHooks: mocks.size > 0 ? createBlockMockHooks(mocks) : undefined, + triggerType: 'test' as const, + sideEffectPolicy: new WriteStubPolicy({ + workflowId, + allowBlockIds, + blockMocks, + pausingBlocks: 'stub', + }), } } @@ -226,7 +243,7 @@ function executionServiceInput(params: { stopAfterBlockId: string | undefined }) { return { - ...resolveRunOverrides(params.draftState, params.input), + ...resolveRunOverrides(params.draftState, params.input, params.context.workflowId), workflowId: params.context.workflowId, principal: params.principal, userId: requirePrincipalSubjectUserId(params.principal), @@ -328,6 +345,15 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU `No execution state found for source run "${input.sourceRunId}" in this workflow.` ) } + if ( + !input.dry && + (await getWorkflowExecutionLogTrigger(input.sourceRunId, context.workflowId)) === 'test' + ) { + throw new OrchestrationError( + 'validation', + `run.entry.sourceRunId "${input.sourceRunId}" is a test run (a dry run or a workflow test): its upstream outputs include placeholders for writes it did not send. Add run.dry to rerun it dry, or rerun from a run that was not a test.` + ) + } const result = await executeWorkflowService({ ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), diff --git a/apps/sim/lib/workflows/application/read-workflow-run.ts b/apps/sim/lib/workflows/application/read-workflow-run.ts index 2bf37cb2e19..b7b68ca46e0 100644 --- a/apps/sim/lib/workflows/application/read-workflow-run.ts +++ b/apps/sim/lib/workflows/application/read-workflow-run.ts @@ -15,6 +15,7 @@ import { getWorkflowRunFiles, type WorkflowRunFileDescriptor, } from '@/lib/workflows/executor/execution-run-files' +import { getWorkflowExecutionDryRun } from '@/lib/workflows/executor/execution-state' import { getProjectedWorkflowExecutionStatus, projectPausedRunPoints, @@ -188,6 +189,17 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ ) : undefined + /** + * A failed dry run's allowed and mocked blocks, which its rerun passes again. The mocks are + * outputs, so a group that withholds execution data withholds them too. + * + * permission-group-enforced: logs.trace_spans + */ + const dryRun = + status.status === 'failed' && !projection.hideTraceSpans + ? await getWorkflowExecutionDryRun(stateExecutionId, context.workflowId) + : null + return { ...status, files, @@ -195,6 +207,7 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ pausedRunId: stateExecutionId, failedBlock, rerunFromBlockId, + dryRun, } } catch (error) { if (error instanceof FunctionalOutputsUnavailableError) { diff --git a/apps/sim/lib/workflows/application/run-workflow-for-test.ts b/apps/sim/lib/workflows/application/run-workflow-for-test.ts index 067c893e2c8..6c3a0431a38 100644 --- a/apps/sim/lib/workflows/application/run-workflow-for-test.ts +++ b/apps/sim/lib/workflows/application/run-workflow-for-test.ts @@ -16,7 +16,7 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { generateRequestId } from '@/lib/core/utils/request' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { resolveTriggerExecution } from '@/lib/workflows/application/run-workflow-from-copilot' -import { DryRunSideEffects } from '@/lib/workflows/dry-run' +import { WriteStubPolicy } from '@/lib/workflows/dry-run' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import type { ExecutionTestHooks } from '@/executor/execution/types' import type { ExecutionResult } from '@/executor/types' @@ -138,7 +138,7 @@ export async function runWorkflowForTest( abortSignal: input.abortSignal, billingAttribution, testHooks: input.testHooks, - sideEffects: new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'run' }), + sideEffects: new WriteStubPolicy({ workflowId: context.workflowId, pausingBlocks: 'run' }), }, executionId ) diff --git a/apps/sim/lib/workflows/dry-run/block-mocks.ts b/apps/sim/lib/workflows/dry-run/block-mocks.ts deleted file mode 100644 index fa85e2221b4..00000000000 --- a/apps/sim/lib/workflows/dry-run/block-mocks.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { ExecutionTestHooks } from '@/executor/execution/types' -import type { NormalizedBlockOutput } from '@/executor/types' - -/** - * Test hooks that answer each block in `outputs` (keyed by workflow block id) with its output - * instead of running its handler (`run.mocks`). Normalization, logging and edges run as for any - * mocked block. Child workflows inherit the hooks, where these ids name no block. - */ -export function createBlockMockHooks( - outputs: ReadonlyMap -): ExecutionTestHooks { - return { - enterWorkflow: async () => {}, - mocksBlock: (blockId) => outputs.has(blockId), - resolveMock: async (call) => { - const output = outputs.get(call.blockId) - if (!output) throw new Error(`Block ${call.blockName} has no mock`) - return output - }, - mocksTool: () => false, - resolveToolMock: async (call) => { - throw new Error(`Tool ${call.toolId} has no mock`) - }, - spiesBlock: () => false, - recordSpy: () => {}, - } -} diff --git a/apps/sim/lib/workflows/dry-run/index.ts b/apps/sim/lib/workflows/dry-run/index.ts index 2d4cb5bfeb7..4d13be40722 100644 --- a/apps/sim/lib/workflows/dry-run/index.ts +++ b/apps/sim/lib/workflows/dry-run/index.ts @@ -1,7 +1,7 @@ -export { createBlockMockHooks } from './block-mocks' export { sampleBlockOutput, sampleToolOutput } from './samples' export { - DryRunSideEffects, PAUSING_BLOCK_TYPES, + runsAnotherWorkflow, type SideEffectsSummary, + WriteStubPolicy, } from './side-effects' diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 9031bcea9d5..86c5486b610 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -1,24 +1,34 @@ import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run/samples' +import { isCustomBlockType } from '@/blocks/custom/build-config' import { BlockType, HUMAN_IN_THE_LOOP_BLOCK_TYPES } from '@/executor/constants' import type { + AnsweredBlockCall, + DryRunOptions, + SideEffectBlockSite, SideEffectPolicy, SideEffectSite, - StubbedBlockCall, StubbedToolCall, } from '@/executor/execution/types' import type { NormalizedBlockOutput } from '@/executor/types' -/** Each list keeps at most this many entries; `omitted` counts the rest. */ +/** Each list keeps at most this many entries; `omitted` counts the rest per list. */ const MAX_RECORDED = 50 /** - * The one tool a dry run sends although it is a `write`: `function_execute` runs a Function - * block's code, which is the workflow's own logic rather than a side effect, so it runs and the - * block is listed as unchecked (its code can make network calls the run cannot see). + * The one write tool a policy always sends: `function_execute` runs code (a Function block's, a + * Condition's expressions, or code an Agent's model wrote), which is the workflow's own logic + * rather than a side effect. Code other than a Condition's is listed as unchecked, since it can + * make network calls the run cannot see. */ -const WORKFLOW_CODE_TOOL_ID = 'function_execute' +const CODE_TOOL_ID = 'function_execute' -/** Blocks whose handlers change state outside the tool seam, so a dry run answers them whole. */ +/** + * The tool an Agent calls a custom block with. A custom block runs its publisher's workflow, so a + * policy answers it whole, like the block on a canvas, and never runs it. + */ +const CUSTOM_BLOCK_TOOL_ID = 'deployed_block_executor' + +/** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) /** @@ -30,10 +40,24 @@ export const PAUSING_BLOCK_TYPES: ReadonlySet = new Set([ BlockType.WAIT, ]) +/** + * Blocks that run another workflow, whose writes a dry run always stubs, so allowing one would + * send nothing: a Workflow block's child keeps its own block ids, and a custom block is answered + * whole. + */ +export function runsAnotherWorkflow(blockType: string): boolean { + return ( + blockType === BlockType.WORKFLOW || + blockType === BlockType.WORKFLOW_INPUT || + isCustomBlockType(blockType) + ) +} + interface RecordedSite { workflowId: string - blockId: string - block: string + /** Null when the call named no block. */ + blockId: string | null + block: string | null } /** A write the run did not send: the request it would have sent and the placeholder it got. */ @@ -49,7 +73,7 @@ interface AllowedSideEffect extends RecordedSite { tool: string | null } -/** A block that ran for real whose effects the run cannot see. */ +/** Code that ran for real whose effects the run cannot see. */ interface UncheckedSideEffect extends RecordedSite { reason: string } @@ -59,89 +83,151 @@ export interface SideEffectsSummary { stubbed: StubbedSideEffect[] allowed: AllowedSideEffect[] unchecked: UncheckedSideEffect[] - /** Entries left out of the lists above once they were full. */ - omitted: number + /** Entries each list left out once it was full. */ + omitted: { stubbed: number; allowed: number; unchecked: number } } function recordedSite(site: SideEffectSite): RecordedSite { return { workflowId: site.workflowId, blockId: site.blockId, block: site.blockName } } +/** Why code the run cannot see ran for real, named for the block that ran it. */ +function uncheckedCodeReason(blockType: string | null): string { + if (blockType === BlockType.FUNCTION) { + return 'Function block code ran for real; network calls it makes are not stubbed' + } + if (blockType === BlockType.AGENT) { + return 'Code the Agent’s model wrote ran for real; network calls it makes are not stubbed' + } + return 'Code ran for real; network calls it makes are not stubbed' +} + +/** + * A bounded record of one kind of side effect: an entry keyed by `key` is kept once, and once + * the list holds {@link MAX_RECORDED} the rest are counted. + */ +class RecordedList { + readonly entries: T[] = [] + omitted = 0 + private readonly keys = new Set() + + add(entry: T, key?: string): void { + if (key !== undefined) { + if (this.keys.has(key)) return + this.keys.add(key) + } + if (this.entries.length < MAX_RECORDED) this.entries.push(entry) + else this.omitted++ + } +} + /** * The side-effect policy of a dry run (`run.dry`) and of a workflow test's unmocked writes: every * write tool call is answered with a placeholder shaped like the tool's output and recorded with - * the request it would have sent, except an allowed block's, which are sent and recorded. Reads - * always run. `pausingBlocks: 'stub'` also answers {@link PAUSING_BLOCK_TYPES} whole. + * the request it would have sent, except an allowed block's, which are sent and recorded once per + * block and tool. Reads always run. Custom blocks and blocks that act outside the tool seam are + * answered whole; `pausingBlocks: 'stub'` also answers {@link PAUSING_BLOCK_TYPES} whole, and + * `blockMocks` answers its blocks with fixed outputs. Allowed and mocked blocks are blocks of the + * workflow the run started, never of a child it calls. */ -export class DryRunSideEffects implements SideEffectPolicy { - private readonly stubbed: StubbedSideEffect[] = [] - private readonly allowed: AllowedSideEffect[] = [] - private readonly unchecked = new Map() - private omitted = 0 +export class WriteStubPolicy implements SideEffectPolicy { + private readonly stubbed = new RecordedList() + private readonly allowed = new RecordedList() + private readonly unchecked = new RecordedList() + private readonly allowBlockIds: ReadonlySet + private readonly blockMocks: ReadonlyMap constructor( private readonly options: { - /** Top-level workflow blocks whose writes are sent. */ - allowBlockIds: ReadonlySet + /** The workflow the run started. */ + workflowId: string + /** Its blocks whose writes are sent. */ + allowBlockIds?: ReadonlySet + /** Its blocks answered with these outputs instead of running. */ + blockMocks?: ReadonlyMap pausingBlocks: 'run' | 'stub' } - ) {} + ) { + this.allowBlockIds = options.allowBlockIds ?? new Set() + this.blockMocks = options.blockMocks ?? new Map() + } - private record(list: T[], entry: T): void { - if (list.length < MAX_RECORDED) list.push(entry) - else this.omitted++ + /** The block's id when it is a block of the workflow the run started. */ + private runBlockId(site: SideEffectSite): string | null { + return site.workflowId === this.options.workflowId ? site.blockId : null } - sendsWrite(call: SideEffectSite & { toolId: string }): boolean { - if (call.toolId === WORKFLOW_CODE_TOOL_ID) { - const key = `${call.workflowId}:${call.blockId}` - if (this.unchecked.has(key)) return true - if (this.unchecked.size < MAX_RECORDED) { - this.unchecked.set(key, { - ...recordedSite(call), - reason: 'Its code ran for real; network calls it makes are not stubbed', - }) - } else this.omitted++ - return true + private allows(site: SideEffectSite): boolean { + const blockId = this.runBlockId(site) + return blockId !== null && this.allowBlockIds.has(blockId) + } + + private mockOf(site: SideEffectSite): NormalizedBlockOutput | undefined { + const blockId = this.runBlockId(site) + return blockId === null ? undefined : this.blockMocks.get(blockId) + } + + decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' { + if (call.toolId === CUSTOM_BLOCK_TOOL_ID) return 'stub' + if (call.toolId === CODE_TOOL_ID) { + if (call.blockType !== BlockType.CONDITION) { + this.unchecked.add( + { ...recordedSite(call), reason: uncheckedCodeReason(call.blockType) }, + `${call.workflowId}:${call.blockId}` + ) + } + return 'send' } - if (!this.options.allowBlockIds.has(call.blockId)) return false - this.record(this.allowed, { ...recordedSite(call), tool: call.toolId }) - return true + if (!this.allows(call)) return 'stub' + this.allowed.add( + { ...recordedSite(call), tool: call.toolId }, + `${call.workflowId}:${call.blockId}:${call.toolId}` + ) + return 'send' } stubWrite(call: StubbedToolCall): Record { const returned = sampleToolOutput(call.toolId) - this.record(this.stubbed, { - ...recordedSite(call), - tool: call.toolId, - request: call.request, - returned, - }) + this.stubbed.add({ ...recordedSite(call), tool: call.toolId, request: call.request, returned }) return returned } - stubsBlock(block: SideEffectSite): boolean { + answersBlock(block: SideEffectBlockSite): boolean { + if (this.mockOf(block)) return true if (this.options.pausingBlocks === 'stub' && PAUSING_BLOCK_TYPES.has(block.blockType)) { return true } + if (isCustomBlockType(block.blockType)) return true if (!SELF_DIRECTED_BLOCK_TYPES.has(block.blockType)) return false - if (!this.options.allowBlockIds.has(block.blockId)) return true - this.record(this.allowed, { ...recordedSite(block), tool: null }) + if (!this.allows(block)) return true + this.allowed.add({ ...recordedSite(block), tool: null }, `${block.workflowId}:${block.blockId}`) return false } - stubBlock(call: StubbedBlockCall): NormalizedBlockOutput { - const returned = sampleBlockOutput({ type: call.blockType, params: call.input }) - this.record(this.stubbed, { ...recordedSite(call), tool: null, request: call.input, returned }) + async answerBlock(call: AnsweredBlockCall): Promise { + const mock = this.mockOf(call) + if (mock) return structuredClone(mock) + const input = await call.input() + const returned = sampleBlockOutput({ type: call.blockType, params: input ?? {} }) + this.stubbed.add({ ...recordedSite(call), tool: null, request: input, returned }) return returned } + /** The allowed and mocked blocks, which a rerun of this run passes again. */ + runOptions(): DryRunOptions { + return { allowBlocks: [...this.allowBlockIds], mocks: Object.fromEntries(this.blockMocks) } + } + summary(): SideEffectsSummary { return { - stubbed: [...this.stubbed], - allowed: [...this.allowed], - unchecked: [...this.unchecked.values()], - omitted: this.omitted, + stubbed: [...this.stubbed.entries], + allowed: [...this.allowed.entries], + unchecked: [...this.unchecked.entries], + omitted: { + stubbed: this.stubbed.omitted, + allowed: this.allowed.omitted, + unchecked: this.unchecked.omitted, + }, } } } diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index 2377438d370..d200d98181d 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -22,7 +22,7 @@ import { LoggingSession } from '@/lib/logs/execution/logging-session' import type { TraceSpan } from '@/lib/logs/types' import { MAX_MCP_WORKFLOW_RESPONSE_BYTES } from '@/lib/mcp/constants' import { hydrateUserFilesWithBase64 } from '@/lib/uploads/utils/user-file-base64.server' -import type { DryRunSideEffects, SideEffectsSummary } from '@/lib/workflows/dry-run' +import type { SideEffectsSummary, WriteStubPolicy } from '@/lib/workflows/dry-run' import { enqueueWorkflowExecution } from '@/lib/workflows/executor/enqueue-execution' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core' @@ -54,8 +54,8 @@ import { workflowHasResponseBlock } from '@/lib/workflows/utils' import { normalizeName } from '@/executor/constants' import { ExecutionSnapshot } from '@/executor/execution/snapshot' import type { + DryRunOptions, ExecutionMetadata, - ExecutionTestHooks, SerializableExecutionState, } from '@/executor/execution/types' import type { BlockLog, NormalizedBlockOutput } from '@/executor/types' @@ -160,13 +160,12 @@ export interface ExecuteWorkflowServiceParams { /** Saved block after which execution stops, validated by the application use case. */ stopAfterBlockId?: string /** - * A dry run: writes are answered with placeholders, and what each would have sent is returned - * as the run's `sideEffects`. Requires `useDraftState` and a `sync` or non-detachable - * `sync-result-stream` run, the modes that return the run's result. + * A dry run's side-effect policy, built by the application use case: writes are answered with + * placeholders, and what each would have sent is returned as the run's `sideEffects`, failed + * runs included. Requires `useDraftState` and a `sync` or non-detachable `sync-result-stream` + * run, the modes that return the run's result. */ - dryRun?: DryRunSideEffects - /** Blocks answered with fixed outputs instead of running, built by the application use case. */ - testHooks?: ExecutionTestHooks + sideEffectPolicy?: WriteStubPolicy } export interface ExecuteWorkflowServiceFailure { @@ -204,6 +203,8 @@ export interface ExecuteWorkflowServiceRun { paused?: RunPause | null /** What a dry run did with each write it reached; absent for any other run. */ sideEffects?: SideEffectsSummary + /** The blocks a dry run sent and mocked, which a rerun of it passes again; absent otherwise. */ + dryRun?: DryRunOptions } /** A run's result before the applied timeout is stamped onto it. */ @@ -349,8 +350,7 @@ export async function executeWorkflowService( runFromBlock, stopAfterBlockId, detachable = false, - dryRun, - testHooks, + sideEffectPolicy, } = params let reqLogger = logger.withMetadata({ requestId, workflowId, userId }) @@ -374,10 +374,10 @@ export async function executeWorkflowService( if (draftState && !useDraftState) { throw new Error('A preloaded draft state requires manual execution state') } - if ((dryRun || testHooks) && !useDraftState) { - throw new Error('Dry runs and block mocks require manual execution state') + if (sideEffectPolicy && !useDraftState) { + throw new Error('A dry run requires manual execution state') } - if (dryRun && (mode === 'stream' || detachable)) { + if (sideEffectPolicy && (mode === 'stream' || detachable)) { throw new Error('A dry run returns its side effects with the result it waits for') } if (detachable && (mode !== 'sync-result-stream' || abortSignal)) { @@ -696,7 +696,6 @@ export async function executeWorkflowService( pinnedDeploymentVersionId: deploymentVersionId, runFromBlock, stopAfterBlockId, - testHooks, onStream, onBlockComplete: (blockId, data) => onBlockComplete(blockId, data.output, data.outputBlockId), @@ -757,6 +756,7 @@ export async function executeWorkflowService( allowLargeValueWorkflowScope: false, callChain, executionMode: 'sync', + ...(sideEffectPolicy ? { dryRun: sideEffectPolicy.runOptions() } : {}), } const executionTimeoutMs = preprocessResult.executionTimeout?.[executionType] ?? 0 @@ -802,8 +802,7 @@ export async function executeWorkflowService( runFromBlock, stopAfterBlockId, draftState, - testHooks, - sideEffects: dryRun, + sideEffects: sideEffectPolicy, }) await handlePostExecutionPauseState({ result, workflowId, executionId, loggingSession }) @@ -1007,20 +1006,57 @@ export async function executeWorkflowService( } } - const pending = runSynchronousWorkflow().then( - async (result): Promise => - result.ok - ? { - ...result, - executionTimeoutMs, - ...(dryRun - ? { - sideEffects: await compactServiceOutput(dryRun.summary(), compactionContext), - } - : {}), - } - : result - ) + /** + * A dry run's side effects on its result, whatever its status: a failed run's allowed writes + * were sent all the same. Compacted like the run's output, and mapped the same way when too + * large; a summary that cannot be compacted otherwise keeps every entry without its request. + */ + const withSideEffects = async ( + result: UnstampedTerminalResult + ): Promise => { + if (!sideEffectPolicy || !result.ok) return result + const summary = sideEffectPolicy.summary() + const dryRun = sideEffectPolicy.runOptions() + try { + return { + ...result, + sideEffects: await compactServiceOutput(summary, compactionContext), + dryRun, + } + } catch (error) { + if ( + error instanceof PayloadSizeLimitError && + rejectLargeInlineOutput && + error.label === 'Workflow execution response' + ) { + return failure({ + kind: 'output_too_large', + message: 'Workflow execution response exceeds maximum size', + statusCode: 413, + code: 'workflow_response_too_large', + executionId, + }) + } + reqLogger.warn('Failed to compact dry-run side effects; returning them without requests', { + error: getErrorMessage(error), + }) + return { + ...result, + sideEffects: { + ...summary, + stubbed: summary.stubbed.map((entry) => ({ ...entry, request: null })), + }, + dryRun, + } + } + } + + const pending = runSynchronousWorkflow() + .then(withSideEffects) + .then( + (result): ExecuteWorkflowServiceTerminalResult => + result.ok ? { ...result, executionTimeoutMs } : result + ) if (mode === 'sync-result-stream') { /** Keep the claim until the pending run can prove whether durable ownership exists. */ executionIdClaimTransferred = true diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index b47074ca6b0..82f027df8c6 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -59,6 +59,7 @@ import type { ChildWorkflowContext, ContextExtensions, ExecutionCallbacks, + ExecutionMetadata, ExecutionTestHooks, IterationContext, SerializableExecutionState, @@ -313,6 +314,18 @@ export function wasExecutionFinalizedByCore(error: unknown, executionId?: string ) } +/** + * What a run records on its log's trigger: its correlation, and a dry run's allowed and mocked + * blocks, which a rerun of it reads back. + */ +function logTriggerData(metadata: ExecutionMetadata): Record | undefined { + if (!metadata.correlation && !metadata.dryRun) return undefined + return { + ...(metadata.correlation ? { correlation: metadata.correlation } : {}), + ...(metadata.dryRun ? { dryRun: metadata.dryRun } : {}), + } +} + /** * Counts a settled run — completed, failed, or cancelled alike — on the * workflow and stamps `lastRunAt`. Paused runs are not settled and are counted @@ -356,6 +369,14 @@ function buildTraceSpansForLog( } } +/** + * Whether a settled run counts on its workflow. A test run (a dry run or a workflow test) changes + * nothing beyond its own log, so it does not. + */ +function countsAsRun(triggerType: string): boolean { + return triggerType !== 'test' +} + async function finalizeExecutionOutcome(params: { result: ExecutionResult loggingSession: LoggingSession @@ -364,9 +385,18 @@ async function finalizeExecutionOutcome(params: { requestId: string workflowInput: unknown abortSignal?: AbortSignal + triggerType: string }): Promise { - const { result, loggingSession, workflowId, executionId, requestId, workflowInput, abortSignal } = - params + const { + result, + loggingSession, + workflowId, + executionId, + requestId, + workflowInput, + abortSignal, + triggerType, + } = params const { traceSpans, totalDuration } = buildTraceSpansForLog( result, loggingSession, @@ -434,7 +464,7 @@ async function finalizeExecutionOutcome(params: { } // Every non-paused outcome above is a settled run; the paused branch returned. - await recordSettledRun(workflowId, requestId, loggingSession) + if (countsAsRun(triggerType)) await recordSettledRun(workflowId, requestId, loggingSession) } async function finalizeExecutionError(params: { @@ -445,8 +475,10 @@ async function finalizeExecutionError(params: { requestId: string /** The input the executor ran with; absent when the run failed before its input stage finished. */ workflowInput: unknown + triggerType: string }): Promise { - const { error, loggingSession, workflowId, executionId, requestId, workflowInput } = params + const { error, loggingSession, workflowId, executionId, requestId, workflowInput, triggerType } = + params const executionResult = hasExecutionResult(error) ? error.executionResult : undefined const { traceSpans } = executionResult ? buildTraceSpansForLog(executionResult, loggingSession, requestId, executionId) @@ -479,7 +511,7 @@ async function finalizeExecutionError(params: { } // A run that threw after starting is a failed run, and failed runs count. - await recordSettledRun(workflowId, requestId, loggingSession) + if (countsAsRun(triggerType)) await recordSettledRun(workflowId, requestId, loggingSession) return finalized } @@ -892,7 +924,7 @@ async function executeWorkflowCoreImpl( billingAttribution: metadata.billingAttribution, workspaceId: providedWorkspaceId, variables, - triggerData: metadata.correlation ? { correlation: metadata.correlation } : undefined, + triggerData: logTriggerData(metadata), skipLogCreation, deploymentVersionId, workflowState: loadedWorkflow && { @@ -1408,6 +1440,7 @@ async function executeWorkflowCoreImpl( requestId, workflowInput: processedInput, abortSignal, + triggerType, }) } catch (postExecError) { logger.error( @@ -1450,7 +1483,7 @@ async function executeWorkflowCoreImpl( billingAttribution: metadata.billingAttribution, workspaceId: providedWorkspaceId, variables: {}, - triggerData: metadata.correlation ? { correlation: metadata.correlation } : undefined, + triggerData: logTriggerData(metadata), skipLogCreation, deploymentVersionId, }) @@ -1467,6 +1500,7 @@ async function executeWorkflowCoreImpl( executionId, requestId, workflowInput: executorInput, + triggerType, }) : false diff --git a/apps/sim/lib/workflows/executor/execution-state.ts b/apps/sim/lib/workflows/executor/execution-state.ts index 1b66b7cbf4d..64916b9f60a 100644 --- a/apps/sim/lib/workflows/executor/execution-state.ts +++ b/apps/sim/lib/workflows/executor/execution-state.ts @@ -1,12 +1,12 @@ import { db } from '@sim/db' import { pausedExecutions, workflowExecutionLogs } from '@sim/db/schema' -import { filterUndefined, isRecordLike } from '@sim/utils/object' +import { filterUndefined, isPlainRecord, isRecordLike } from '@sim/utils/object' import { and, desc, eq, or, sql } from 'drizzle-orm' import { getBaseUrl } from '@/lib/core/utils/urls' import { materializeExecutionData, TRACE_STORE_REF_KEY } from '@/lib/logs/execution/trace-store' import { forceFailedMessage } from '@/lib/workflows/executor/failure-message' import { buildResumeUiUrl } from '@/executor/constants' -import type { SerializableExecutionState } from '@/executor/execution/types' +import type { DryRunOptions, SerializableExecutionState } from '@/executor/execution/types' import type { PausePoint } from '@/executor/types' import { isResolvedSecretTraceProvenanceV1, @@ -158,6 +158,61 @@ export async function getWorkflowExecutionLogStatus( return row?.status } +/** The trigger an execution's workflow log recorded, or `undefined` when it never started one. */ +export async function getWorkflowExecutionLogTrigger( + executionId: string, + workflowId: string +): Promise { + const [row] = await db + .select({ trigger: workflowExecutionLogs.trigger }) + .from(workflowExecutionLogs) + .where( + and( + eq(workflowExecutionLogs.executionId, executionId), + eq(workflowExecutionLogs.workflowId, workflowId) + ) + ) + .limit(1) + return row?.trigger +} + +/** + * A dry run's allowed and mocked blocks, as its log's trigger recorded them; null for any other + * run, or a record not in the shape a dry run writes. + */ +export async function getWorkflowExecutionDryRun( + executionId: string, + workflowId: string +): Promise { + const [row] = await db + .select({ + dryRun: sql`${workflowExecutionLogs.executionData} #> '{trigger,data,dryRun}'`, + }) + .from(workflowExecutionLogs) + .where( + and( + eq(workflowExecutionLogs.executionId, executionId), + eq(workflowExecutionLogs.workflowId, workflowId) + ) + ) + .limit(1) + const dryRun = row?.dryRun + if (!isPlainRecord(dryRun) || !isPlainRecord(dryRun.mocks)) return null + const { allowBlocks } = dryRun + if (!Array.isArray(allowBlocks)) return null + const allowed: string[] = [] + for (const blockId of allowBlocks) { + if (typeof blockId !== 'string') return null + allowed.push(blockId) + } + const mocks: DryRunOptions['mocks'] = {} + for (const [blockId, output] of Object.entries(dryRun.mocks)) { + if (!isPlainRecord(output)) return null + mocks[blockId] = output + } + return { allowBlocks: allowed, mocks } +} + /** The log's own correlation wins; older logs carried it only on the trigger data. */ function selectCorrelation( topLevel: unknown, diff --git a/apps/sim/lib/workspace-events/constants.ts b/apps/sim/lib/workspace-events/constants.ts index 12f855dc7f0..4f160b1c9f6 100644 --- a/apps/sim/lib/workspace-events/constants.ts +++ b/apps/sim/lib/workspace-events/constants.ts @@ -9,6 +9,13 @@ /** Provider string recorded on webhook rows and execution logs for Sim trigger runs. */ export const SIM_TRIGGER_PROVIDER = 'sim' +/** + * Triggers whose runs raise no workspace event and count toward no rule: a Sim trigger's own runs + * (loop prevention), and test runs (a dry run or a workflow test), which change nothing beyond + * their own log. + */ +export const EVENTLESS_EXECUTION_TRIGGERS: readonly string[] = [SIM_TRIGGER_PROVIDER, 'test'] + /** Trigger ID in the trigger registry. Must equal the block type for pure trigger blocks. */ export const SIM_WORKSPACE_EVENT_TRIGGER_ID = 'sim_workspace_event' diff --git a/apps/sim/lib/workspace-events/emitter.ts b/apps/sim/lib/workspace-events/emitter.ts index 19c56f7fa85..0f3dff7989e 100644 --- a/apps/sim/lib/workspace-events/emitter.ts +++ b/apps/sim/lib/workspace-events/emitter.ts @@ -3,9 +3,9 @@ import { getActiveWorkflowContext } from '@sim/platform-authz/workflow' import { generateShortId } from '@sim/utils/id' import type { WorkflowExecutionLog } from '@/lib/logs/types' import { + EVENTLESS_EXECUTION_TRIGGERS, isSimRuleEventType, SIM_RULE_COOLDOWN_HOURS, - SIM_TRIGGER_PROVIDER, } from '@/lib/workspace-events/constants' import { buildDeployEventPayload, @@ -82,12 +82,12 @@ function matchesWorkflowScope(config: SimSubscriptionConfig, sourceWorkflowId: s * * Fire-and-forget: errors are logged and never thrown, so event emission can * never break the source execution. Executions started by the Sim trigger - * itself never emit (loop prevention). + * itself never emit (loop prevention), and neither do test runs. */ export async function emitExecutionCompletedEvent(log: WorkflowExecutionLog): Promise { try { if (!log.workflowId) return - if (log.trigger === SIM_TRIGGER_PROVIDER) return + if (EVENTLESS_EXECUTION_TRIGGERS.includes(log.trigger)) return const workflowContext = await getActiveWorkflowContext(log.workflowId) if (!workflowContext?.workspaceId) return diff --git a/apps/sim/lib/workspace-events/no-activity.test.ts b/apps/sim/lib/workspace-events/no-activity.test.ts index af4572f7bca..93a7889d700 100644 --- a/apps/sim/lib/workspace-events/no-activity.test.ts +++ b/apps/sim/lib/workspace-events/no-activity.test.ts @@ -25,7 +25,7 @@ vi.mock('@/lib/workspace-events/subscriptions', () => ({ })) vi.mock('@/lib/workspace-events/rules', () => ({ - excludeSimExecutionsCondition: vi.fn(() => ({ type: 'ne', right: 'sim' })), + excludeEventlessExecutionsCondition: vi.fn(() => ({ type: 'ne', right: 'sim' })), })) import { diff --git a/apps/sim/lib/workspace-events/no-activity.ts b/apps/sim/lib/workspace-events/no-activity.ts index 8f633f94726..bf5d59ecd67 100644 --- a/apps/sim/lib/workspace-events/no-activity.ts +++ b/apps/sim/lib/workspace-events/no-activity.ts @@ -6,7 +6,7 @@ import { deliverableWebhookPredicate } from '@/lib/webhooks/delivery-predicate' import { SIM_RULE_COOLDOWN_HOURS, SIM_TRIGGER_PROVIDER } from '@/lib/workspace-events/constants' import { dispatchSimEvent } from '@/lib/workspace-events/emitter' import { buildNoActivityEventPayload } from '@/lib/workspace-events/payload' -import { excludeSimExecutionsCondition } from '@/lib/workspace-events/rules' +import { excludeEventlessExecutionsCondition } from '@/lib/workspace-events/rules' import { claimCooldown, isWithinCooldown, readLastFiredAt } from '@/lib/workspace-events/state' import { parseSubscriptionConfig } from '@/lib/workspace-events/subscriptions' import type { SimSubscription, SimSubscriptionConfig } from '@/lib/workspace-events/types' @@ -127,7 +127,7 @@ async function hasRecentActivity( and( eq(workflowExecutionLogs.workflowId, workflowId), gte(workflowExecutionLogs.startedAt, windowStart), - excludeSimExecutionsCondition() + excludeEventlessExecutionsCondition() ) ) .limit(1) diff --git a/apps/sim/lib/workspace-events/rules.ts b/apps/sim/lib/workspace-events/rules.ts index 674d446076b..de4b41924df 100644 --- a/apps/sim/lib/workspace-events/rules.ts +++ b/apps/sim/lib/workspace-events/rules.ts @@ -1,11 +1,11 @@ import { db } from '@sim/db' import { workflowExecutionLogs } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { and, avg, count, desc, eq, gte, ne, type SQL, sql } from 'drizzle-orm' +import { and, avg, count, desc, eq, gte, notInArray, type SQL, sql } from 'drizzle-orm' import { creditsToDollars } from '@/lib/billing/credits/conversion' import { + EVENTLESS_EXECUTION_TRIGGERS, SIM_MIN_EXECUTIONS_FOR_RATE_RULES, - SIM_TRIGGER_PROVIDER, type SimRuleEventType, } from '@/lib/workspace-events/constants' import type { ExecutionEventContext, SimSubscriptionConfig } from '@/lib/workspace-events/types' @@ -13,19 +13,21 @@ import type { ExecutionEventContext, SimSubscriptionConfig } from '@/lib/workspa const logger = createLogger('WorkspaceEventRules') /** - * Excludes executions started by the Sim trigger from rule statistics, so - * side-effect runs never pollute failure/latency counts for workflows that - * are both source and subscriber. + * Excludes runs that count toward no rule from rule statistics: Sim-trigger side-effect runs, so + * they never pollute failure/latency counts for workflows that are both source and subscriber, + * and test runs, which are not the workflow's real traffic. */ -export function excludeSimExecutionsCondition(): SQL { - return ne(workflowExecutionLogs.trigger, SIM_TRIGGER_PROVIDER) +export function excludeEventlessExecutionsCondition(): SQL { + return notInArray(workflowExecutionLogs.trigger, [...EVENTLESS_EXECUTION_TRIGGERS]) } async function checkConsecutiveFailures(workflowId: string, threshold: number): Promise { const recentLogs = await db .select({ level: workflowExecutionLogs.level }) .from(workflowExecutionLogs) - .where(and(eq(workflowExecutionLogs.workflowId, workflowId), excludeSimExecutionsCondition())) + .where( + and(eq(workflowExecutionLogs.workflowId, workflowId), excludeEventlessExecutionsCondition()) + ) .orderBy(desc(workflowExecutionLogs.startedAt)) .limit(threshold) @@ -61,7 +63,7 @@ async function checkFailureRate( and( eq(workflowExecutionLogs.workflowId, workflowId), gte(workflowExecutionLogs.startedAt, windowStart), - excludeSimExecutionsCondition() + excludeEventlessExecutionsCondition() ) ) @@ -92,7 +94,7 @@ async function checkLatencySpike( and( eq(workflowExecutionLogs.workflowId, workflowId), gte(workflowExecutionLogs.startedAt, windowStart), - excludeSimExecutionsCondition() + excludeEventlessExecutionsCondition() ) ) @@ -122,7 +124,7 @@ async function checkErrorCount( eq(workflowExecutionLogs.workflowId, workflowId), eq(workflowExecutionLogs.level, 'error'), gte(workflowExecutionLogs.startedAt, windowStart), - excludeSimExecutionsCondition() + excludeEventlessExecutionsCondition() ) ) diff --git a/apps/sim/providers/file-attachments.server.ts b/apps/sim/providers/file-attachments.server.ts index a08209d2770..ba5c1d2e7a2 100644 --- a/apps/sim/providers/file-attachments.server.ts +++ b/apps/sim/providers/file-attachments.server.ts @@ -132,6 +132,15 @@ export async function attachLargeFileRemoteUrls( } } +/** The files one request uploaded to a provider's Files API. */ +export interface ProviderFileUploads { + /** + * Deletes them from the provider account. Best effort: a failure is logged, and the files + * expire on their own (OpenAI's after {@link OPENAI_FILE_EXPIRY_SECONDS}, Gemini's in 48 hours). + */ + remove(): Promise +} + /** * For `files-api` providers, uploads each large attachment (already carrying a signed * `remoteUrl` from {@link attachLargeFileRemoteUrls}) to the provider Files API and records @@ -142,11 +151,17 @@ export async function uploadLargeFilesToProvider( request: ProviderRequest, providerId: ProviderId | string, executionContext?: ExecutionContext -): Promise { - if (getProviderFileStrategy(providerId) !== 'files-api') return +): Promise { + const removals: Array<() => Promise> = [] + const uploads: ProviderFileUploads = { + remove: async () => { + for (const removal of removals.splice(0)) await removal() + }, + } + if (getProviderFileStrategy(providerId) !== 'files-api') return uploads const groups = groupUploadableFiles(request.messages) - if (groups.length === 0) return + if (groups.length === 0) return uploads const maxBytes = getProviderAttachmentMaxBytes(providerId) const ai = @@ -158,15 +173,23 @@ export async function uploadLargeFilesToProvider( const [representative] = group await assertFileAccessForUpload(representative, request.userId, executionContext) if (providerId === 'openai') { - await uploadOpenAIFile(representative, request.apiKey, maxBytes, request.abortSignal) + const fileId = await uploadOpenAIFile( + representative, + request.apiKey, + maxBytes, + request.abortSignal + ) + removals.push(() => deleteOpenAIFile(fileId, request.apiKey)) } else if (ai) { - await uploadGeminiFile(representative, ai, maxBytes, request.abortSignal) + const name = await uploadGeminiFile(representative, ai, maxBytes, request.abortSignal) + removals.push(() => deleteGeminiFile(name, ai)) } for (const file of group) { file.providerFileId = representative.providerFileId file.providerFileUri = representative.providerFileUri } } + return uploads } /** @@ -244,7 +267,7 @@ async function uploadOpenAIFile( apiKey: string | undefined, maxBytes: number, signal?: AbortSignal -): Promise { +): Promise { const mimeType = inferAttachmentMimeType(file) const blob = await downloadFileForUpload(file, maxBytes) @@ -271,6 +294,22 @@ async function uploadOpenAIFile( } file.providerFileId = uploaded.id logger.info(`Uploaded "${file.name}" to OpenAI Files API`, { fileId: uploaded.id }) + return uploaded.id +} + +async function deleteOpenAIFile(fileId: string, apiKey: string | undefined): Promise { + try { + const response = await outboundFetch(`${OPENAI_FILES_ENDPOINT}/${encodeURIComponent(fileId)}`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${apiKey}` }, + }) + if (!response.ok) throw new Error(`OpenAI answered ${response.status}`) + } catch (error) { + logger.warn('Failed to delete an uploaded file from OpenAI', { + fileId, + error: getErrorMessage(error), + }) + } } async function uploadGeminiFile( @@ -278,7 +317,7 @@ async function uploadGeminiFile( ai: GoogleGenAI, maxBytes: number, signal?: AbortSignal -): Promise { +): Promise { const mimeType = inferAttachmentMimeType(file) const blob = await downloadFileForUpload(file, maxBytes) @@ -304,4 +343,16 @@ async function uploadGeminiFile( } file.providerFileUri = uploaded.uri logger.info(`Uploaded "${file.name}" to Gemini File API`, { fileUri: uploaded.uri }) + return uploadedName +} + +async function deleteGeminiFile(name: string, ai: GoogleGenAI): Promise { + try { + await ai.files.delete({ name }) + } catch (error) { + logger.warn('Failed to delete an uploaded file from Gemini', { + name, + error: getErrorMessage(error), + }) + } } diff --git a/apps/sim/providers/index.ts b/apps/sim/providers/index.ts index fc5fb806040..a493204830d 100644 --- a/apps/sim/providers/index.ts +++ b/apps/sim/providers/index.ts @@ -394,32 +394,45 @@ export async function executeProviderRequest( ) } await attachLargeFileRemoteUrls(modelSafeRequest, providerId, runtimeContext?.executionContext) - await uploadLargeFilesToProvider(modelSafeRequest, providerId, runtimeContext?.executionContext) - if (final && session) { - modelSafeRequest.abortSignal?.throwIfAborted() - const usage = session.getUsage() - cachedFinalResponse = { - ...final, - tokens: { - ...usage.tokens, - total: - usage.tokens.input + - usage.tokens.output + - (usage.tokens.cacheRead ?? 0) + - (usage.tokens.cacheWrite ?? 0), - }, - cost: { - ...usage.cost, - pricing: getModelPricing(final.model) ?? { - input: 0, - output: 0, - updatedAt: new Date(0).toISOString(), + const uploads = await uploadLargeFilesToProvider( + modelSafeRequest, + providerId, + runtimeContext?.executionContext + ) + /** + * A run under a side-effect policy (a dry run, or a workflow test) leaves nothing on the + * provider account: its uploads are deleted once the call settles. Such a run waits for its + * result and never streams, so the call has settled when it returns here. + */ + try { + if (final && session) { + modelSafeRequest.abortSignal?.throwIfAborted() + const usage = session.getUsage() + cachedFinalResponse = { + ...final, + tokens: { + ...usage.tokens, + total: + usage.tokens.input + + usage.tokens.output + + (usage.tokens.cacheRead ?? 0) + + (usage.tokens.cacheWrite ?? 0), }, - }, + cost: { + ...usage.cost, + pricing: getModelPricing(final.model) ?? { + input: 0, + output: 0, + updatedAt: new Date(0).toISOString(), + }, + }, + } + return cachedFinalResponse } - return cachedFinalResponse + return await provider.executeRequest(modelSafeRequest) + } finally { + if (runtimeContext?.executionContext?.sideEffects) await uploads.remove() } - return provider.executeRequest(modelSafeRequest) }) if (cachedFinalResponse) return cachedFinalResponse diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index 032cc4601c0..bde362842c7 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -77,7 +77,7 @@ import { executeVantaTool } from '@/lib/internal/vanta/execute-tool' import { buildDirectVideoRequest } from '@/lib/internal/video/direct-request' import { buildFalVideoRequest } from '@/lib/internal/video/fal-request' import { projectToolResultForCopilot } from '@/lib/mothership/request/tools/resolved-secret-result' -import { DryRunSideEffects } from '@/lib/workflows/dry-run' +import { WriteStubPolicy } from '@/lib/workflows/dry-run' import { VideoGeneratorV2Block, VideoGeneratorV3Block } from '@/blocks/blocks/video_generator' import { ANONYMOUS_SECRET_TRACE_REPLACEMENT, @@ -7491,20 +7491,40 @@ describe('MCP Tool Execution', () => { }) }) - it('stubs an MCP tool in a dry run, since it declares no effect', async () => { - const dryRun = new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'stub' }) + it('stubs an MCP tool in a dry run, recording only its arguments, and sends an allowed one', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch') + const dryRun = new WriteStubPolicy({ workflowId: 'test-workflow', pausingBlocks: 'stub' }) + const params = { + path: '/test', + envVars: { UNREFERENCED_SECRET: 'workspace-secret-value' }, + _context: { blockId: 'agent-1' }, + } - const result = await executeTool( - 'mcp-123-delete_file', - { path: '/test', _context: { blockId: 'agent-1' } }, - { executionContext: createToolExecutionContext({ sideEffects: dryRun }) } - ) + const result = await executeTool('mcp-123-delete_file', params, { + executionContext: createToolExecutionContext({ sideEffects: dryRun }), + resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), + }) expect(mockExecuteInternalToolOperation).not.toHaveBeenCalled() + expect(fetchSpy).not.toHaveBeenCalled() expect(result.success).toBe(true) - expect(dryRun.summary().stubbed).toEqual([ - expect.objectContaining({ blockId: 'agent-1', tool: 'mcp-123-delete_file' }), - ]) + const [stubbed] = dryRun.summary().stubbed + expect(stubbed).toMatchObject({ blockId: 'agent-1', tool: 'mcp-123-delete_file' }) + expect(stubbed.request).toEqual({ arguments: { path: '/test' } }) + + mockExecuteInternalToolOperation.mockResolvedValueOnce( + Response.json({ success: true, data: { output: { deleted: true } } }) + ) + const allowed = new WriteStubPolicy({ + workflowId: 'test-workflow', + allowBlockIds: new Set(['agent-1']), + pausingBlocks: 'stub', + }) + await executeTool('mcp-123-delete_file', params, { + executionContext: createToolExecutionContext({ sideEffects: allowed }), + }) + expect(mockExecuteInternalToolOperation).toHaveBeenCalledTimes(1) + expect(allowed.summary().stubbed).toEqual([]) }) it('preserves MCP operation error envelopes', async () => { diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index b996485f7fc..a38bfbfdd61 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -41,6 +41,7 @@ import { validateAndPinProxyUrl, validateUrlWithDNS, } from '@/lib/core/security/input-validation.server' +import { REDACTED_MARKER } from '@/lib/core/security/redaction' import { PlatformEvents } from '@/lib/core/telemetry' import { waitWithAbort } from '@/lib/core/utils/concurrency' import { HttpError } from '@/lib/core/utils/http-error' @@ -133,7 +134,12 @@ import { readRequestedDeadline, } from '@/tools/request-transport' import { AWS_CREDENTIAL_OAUTH, AWS_SESSION_SIGNED_TOOL_IDS } from '@/tools/shared/saved-credentials' -import { answerUnsentWrite, describeToolRequest } from '@/tools/side-effects' +import { + answerUnsentWrite, + describeMcpToolRequest, + describeToolRequest, + unsentWriteFor, +} from '@/tools/side-effects' import type { BYOKProviderId, CredentialParamSource, @@ -648,13 +654,18 @@ function applyCredentialParams( * Checks BYOK workspace keys first, refuses Sim's key to a payer without paid access, then uses the * HostedKeyRateLimiter for round-robin key selection. * Returns whether a hosted (billable) key was injected and which env var it came from. + * + * `drawKey: false` is a call that will not be sent (a run's side-effect policy answers it): it + * passes every check a sent call does but draws no key, so it spends no rate-limit slot, and its + * key param holds the redaction marker instead. */ async function injectHostedKeyIfNeeded( tool: ToolDefinition, params: Record, executionContext: ExecutionContext | undefined, requestId: string, - signal: AbortSignal | undefined + signal: AbortSignal | undefined, + { drawKey }: { drawKey: boolean } ): Promise { if (!tool.hosting || !hostedKeyMayFill(tool, params)) return { isUsingHostedKey: false } @@ -689,6 +700,11 @@ async function injectHostedKeyIfNeeded( throw new HostedKeyRequiresPaidPlanError(tool.name) } + if (!drawKey) { + params[apiKeyParam] = REDACTED_MARKER + return { isUsingHostedKey: false } + } + const rateLimiter = getHostedKeyRateLimiter() const provider = byokProviderId || tool.id const billingActorId = workspaceId @@ -1796,18 +1812,30 @@ async function executeToolImplementation( : suppliedOperationContext ? { ...suppliedOperationContext, resolvedSecretTraceRegistry } : undefined + /** + * A tool's own follow-up calls (a `postProcess` that writes again) run in its caller's + * `_context`, so they act for the same block: a run's side-effect policy decides them as it + * decided the call that made them. + */ + const callerContext = isPlainRecord(params._context) ? params._context : undefined const executeNestedTool: typeof executeTool = (nestedToolId, nestedParams, nestedOptions = {}) => - executeTool(nestedToolId, nestedParams, { - ...nestedOptions, - ...(operationContext?.requestMode === 'assistant' ? { operationContext } : {}), - executionContext: - operationContext?.requestMode === 'assistant' - ? undefined - : (nestedOptions.executionContext ?? executionContext), - signal: nestedOptions.signal ?? effectiveSignal, - resolvedSecretTraceRegistry: - nestedOptions.resolvedSecretTraceRegistry ?? resolvedSecretTraceRegistry, - }) + executeTool( + nestedToolId, + callerContext + ? { ...nestedParams, _context: { ...callerContext, ...toRecord(nestedParams._context) } } + : nestedParams, + { + ...nestedOptions, + ...(operationContext?.requestMode === 'assistant' ? { operationContext } : {}), + executionContext: + operationContext?.requestMode === 'assistant' + ? undefined + : (nestedOptions.executionContext ?? executionContext), + signal: nestedOptions.signal ?? effectiveSignal, + resolvedSecretTraceRegistry: + nestedOptions.resolvedSecretTraceRegistry ?? resolvedSecretTraceRegistry, + } + ) const startTime = new Date() const startTimeISO = startTime.toISOString() const requestId = generateRequestId() @@ -1917,16 +1945,15 @@ async function executeToolImplementation( logger.error(`Custom tool not found: ${normalizedToolId}`, { requestId }) } } else if (isMcpTool(normalizedToolId)) { - // An MCP tool declares no effect, so a dry run never sends one. - const unsent = answerUnsentWrite({ - toolId: normalizedToolId, - params, - executionContext, - registry: resolvedSecretTraceRegistry, - describeRequest: () => - Object.fromEntries(Object.entries(params).filter(([key]) => !key.startsWith('_'))), - }) - if (unsent) return unsent + // An MCP tool declares no effect, so a run's side-effect policy decides every one. + const unsentMcpWrite = unsentWriteFor({ toolId: normalizedToolId, params, executionContext }) + if (unsentMcpWrite) { + return await answerUnsentWrite(unsentMcpWrite, { + params, + registry: resolvedSecretTraceRegistry, + describeRequest: () => describeMcpToolRequest(params), + }) + } return await executeMcpTool( normalizedToolId, params, @@ -1972,12 +1999,22 @@ async function executeToolImplementation( enforceCopilotCredentialSelection(toolId, tool, contextParams, scope) await resolveToolEnvReferences(tool, contextParams, scope, resolvedSecretTraceRegistry) + /** + * Decided before a hosted key is drawn, so a write the run's side-effect policy will not send + * spends no rate-limit slot. A workflow a tool runs decides its own writes. + */ + const unsentWrite = + tool.effect !== 'read' && normalizedToolId !== 'workflow_executor' + ? unsentWriteFor({ toolId: normalizedToolId, params: contextParams, executionContext }) + : null + const hostedKeyInfo = await injectHostedKeyIfNeeded( tool, contextParams, executionContext, requestId, - effectiveSignal + effectiveSignal, + { drawKey: !unsentWrite } ) if (hostedKeyInfo.isUsingHostedKey) { @@ -2211,6 +2248,17 @@ async function executeToolImplementation( contextParams.sessionToken = session.sessionToken } + // After credentials resolve, so an unsent write still proves them. + if (unsentWrite) { + const unsentTool = tool + return await answerUnsentWrite(unsentWrite, { + params: contextParams, + registry: resolvedSecretTraceRegistry, + describeRequest: () => + describeToolRequest(unsentTool, contextParams, resolvedSecretTraceRegistry), + }) + } + // Custom blocks (deploy-as-block) run in-process through WorkflowBlockHandler. // The runner is dynamic-imported from a server-only module so the client-bundled // tool registry never pulls in the executor/db dependency graph (a static or @@ -2299,7 +2347,6 @@ async function executeToolImplementation( abortSignal: effectiveSignal, resolvedSecretTraceRegistry, principal: executionContext?.principal, - sideEffects: executionContext?.sideEffects, } ) const endTime = new Date() @@ -2316,20 +2363,6 @@ async function executeToolImplementation( } } - // After the workflow-running tools above, whose children decide their own writes. - if (tool.effect !== 'read') { - const unsentTool = tool - const unsent = answerUnsentWrite({ - toolId: normalizedToolId, - params: contextParams, - executionContext, - registry: resolvedSecretTraceRegistry, - describeRequest: () => - describeToolRequest(unsentTool, contextParams, resolvedSecretTraceRegistry), - }) - if (unsent) return unsent - } - if (tool.operation) { const result = await executeDeclaredInternalOperation({ toolId: normalizedToolId, diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index bdca98c9d0f..71cb53cef1e 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -2,38 +2,59 @@ * @vitest-environment node */ import { describe, expect, it } from 'vitest' -import { DryRunSideEffects } from '@/lib/workflows/dry-run' +import { WriteStubPolicy } from '@/lib/workflows/dry-run' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' -import { answerUnsentWrite } from '@/tools/side-effects' +import { answerUnsentWrite, unsentWriteFor } from '@/tools/side-effects' -describe('a write a dry run does not send', () => { - it('records its request without the credentials the call resolved, wherever they appear', () => { - const dryRun = new DryRunSideEffects({ allowBlockIds: new Set(), pausingBlocks: 'stub' }) - const params = { - accessToken: 'oauth-token-123', - apiKey: 'hosted-key-456', - channel: 'ops', - _context: { blockId: 'notify' }, - } +/** Stubs one `slack_message` call from block `notify` and returns what the policy recorded. */ +async function stubSlackMessage( + registry: ResolvedSecretTraceRegistry, + describeRequest: () => unknown +) { + const policy = new WriteStubPolicy({ workflowId: 'wf-1', pausingBlocks: 'stub' }) + const params = { + accessToken: 'oauth-token-123', + apiKey: 'hosted-key-456', + channel: 'ops', + _context: { blockId: 'notify' }, + } + const write = unsentWriteFor({ + toolId: 'slack_message', + params, + executionContext: { workflowId: 'wf-1', sideEffects: policy } as ExecutionContext, + }) + if (!write) throw new Error('The policy sent the write') + const response = await answerUnsentWrite(write, { params, registry, describeRequest }) + return { response, stubbed: policy.summary().stubbed } +} - const response = answerUnsentWrite({ - toolId: 'slack_message', - params, - executionContext: { workflowId: 'wf-1', sideEffects: dryRun } as ExecutionContext, - registry: new ResolvedSecretTraceRegistry(), - describeRequest: () => ({ - method: 'POST', - url: 'https://slack.example/api?token=oauth-token-123', - body: { channel: 'ops', text: 'sent with hosted-key-456', apiKey: 'hosted-key-456' }, - }), - }) +describe('a write a dry run does not send', () => { + it('records its request without the credentials the call resolved, wherever they appear', async () => { + const { response, stubbed } = await stubSlackMessage(new ResolvedSecretTraceRegistry(), () => ({ + method: 'POST', + url: 'https://slack.example/api?token=oauth-token-123', + body: { channel: 'ops', text: 'sent with hosted-key-456', apiKey: 'hosted-key-456' }, + })) - expect(response?.success).toBe(true) - const [stubbed] = dryRun.summary().stubbed - expect(stubbed.request).toMatchObject({ method: 'POST', body: { channel: 'ops' } }) - const recorded = JSON.stringify(stubbed.request) + expect(response.success).toBe(true) + expect(stubbed[0].request).toMatchObject({ method: 'POST', body: { channel: 'ops' } }) + const recorded = JSON.stringify(stubbed[0].request) expect(recorded).not.toContain('oauth-token-123') expect(recorded).not.toContain('hosted-key-456') }) + + it('records no request when the run cannot vouch that no secret remains in it', async () => { + const registry = new ResolvedSecretTraceRegistry() + registry.markIncomplete('secret-transformed-by-tool') + + const { response, stubbed } = await stubSlackMessage(registry, () => ({ + method: 'POST', + url: 'https://slack.example/api', + body: { channel: 'ops' }, + })) + + expect(response.success).toBe(true) + expect(stubbed[0].request).toBeNull() + }) }) diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index 231a9668c6c..ba6a26cb337 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -1,15 +1,21 @@ /** * Where a run's side-effect policy (a dry run, or a workflow test's unmocked writes) meets a tool - * call: `executeTool` asks {@link answerUnsentWrite} about every call not declared `read`, after + * call: `executeTool` asks {@link unsentWriteFor} about every call not declared `read` before a + * hosted key is drawn for it, and answers an unsent one with {@link answerUnsentWrite} after * credentials resolve and before anything is sent. */ +import { createLogger } from '@sim/logger' import { isPlainRecord, toRecord } from '@sim/utils/object' import { isSensitiveKey, REDACTED_MARKER, redactExactSensitiveValues, } from '@/lib/core/security/redaction' -import type { SideEffectSite } from '@/executor/execution/types' +import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' +import { parseMcpToolArguments } from '@/lib/mcp/tool-arguments' +import { getBlock, getBlockByToolName } from '@/blocks/registry' +import { isCustomTool } from '@/executor/constants' +import type { SideEffectPolicy, SideEffectSite } from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' @@ -17,13 +23,26 @@ import { stripCloneSuffixes } from '@/executor/utils/subflow-node-id-codec' import { prepareToolRequest, projectToolModelInputParams } from '@/tools/request-transport' import { type ExecutableToolConfig, isInternalToolConfig, type ToolResponse } from '@/tools/types' +const logger = createLogger('ToolSideEffects') + +/** + * Params an Agent's tool call carries for the run itself (every env var, workflow variable and + * block output), which no stubbed tool sends and a recorded request must never show. + */ +const RUN_CONTEXT_PARAMS: ReadonlySet = new Set([ + 'envVars', + 'workflowVariables', + 'blockData', + 'blockNameMapping', +]) + /** The block of the executing workflow that made a tool call, from its server-set `_context`. */ function sideEffectSite( executionContext: ExecutionContext, params: Record ): SideEffectSite { const calledFrom = toRecord(params._context).blockId - const blockId = typeof calledFrom === 'string' ? stripCloneSuffixes(calledFrom) : '' + const blockId = typeof calledFrom === 'string' ? stripCloneSuffixes(calledFrom) : null const block = blockId ? executionContext.workflow?.blocks.find((candidate) => candidate.id === blockId) : undefined @@ -31,10 +50,33 @@ function sideEffectSite( workflowId: executionContext.workflowId, blockId, blockName: block?.metadata?.name ?? blockId, - blockType: block?.metadata?.id ?? '', + blockType: block?.metadata?.id ?? null, } } +/** A write tool call the run's policy answers instead of sending. */ +export interface UnsentWrite { + policy: SideEffectPolicy + executionContext: ExecutionContext + call: SideEffectSite & { toolId: string } +} + +/** + * The write the run's side-effect policy will not send, decided before anything is drawn for it + * (a hosted key's rate-limit slot); null when the run has no policy or the policy sends the call. + */ +export function unsentWriteFor(input: { + toolId: string + params: Record + executionContext: ExecutionContext | undefined +}): UnsentWrite | null { + const { executionContext } = input + const policy = executionContext?.sideEffects + if (!executionContext || !policy) return null + const call = { ...sideEffectSite(executionContext, input.params), toolId: input.toolId } + return policy.decideWrite(call) === 'stub' ? { policy, executionContext, call } : null +} + /** A string body as the JSON it carries, when it carries JSON. */ function readBody(body: string | undefined): unknown { if (body === undefined) return undefined @@ -45,19 +87,36 @@ function readBody(body: string | undefined): unknown { } } +/** What an MCP tool call would send its server: only the arguments it was given. */ +export function describeMcpToolRequest(params: Record): unknown { + return { arguments: parseMcpToolArguments(params) } +} + /** - * What a call to `tool` would send: an in-process operation's input, or an HTTP request's method, - * URL and body. Headers are never kept, since they carry the credentials. + * What a call to `tool` would send. A custom tool runs the workspace's own code with the run's + * environment, so it is described by the arguments it was given; any other tool by an in-process + * operation's input, or an HTTP request's method, URL and body. Headers are never kept, since + * they carry the credentials, and neither are the run-context params an Agent's call carries. */ export function describeToolRequest( tool: ExecutableToolConfig, params: Record, registry: ResolvedSecretTraceRegistry | undefined ): unknown { + if (isCustomTool(tool.id)) { + return { + arguments: Object.fromEntries( + Object.entries(params).filter(([key]) => Object.hasOwn(tool.params, key)) + ), + } + } + const toolParams = Object.fromEntries( + Object.entries(params).filter(([key]) => !RUN_CONTEXT_PARAMS.has(key)) + ) if (isInternalToolConfig(tool)) { - return tool.operation.input(projectToolModelInputParams(tool, params, registry)) + return tool.operation.input(projectToolModelInputParams(tool, toolParams, registry)) } - const prepared = prepareToolRequest(tool, params, registry) + const prepared = prepareToolRequest(tool, toolParams, registry) return { method: prepared.method, url: prepared.url, body: readBody(prepared.body) } } @@ -75,43 +134,84 @@ function redactCredentials(value: unknown, credentials: string[]): unknown { } /** - * The request as a run may report it: credentials the call resolved (an access token, a hosted - * key, a secret access key) masked by field and by value, then every secret the run resolved - * masked by the run's registry. Null when the registry cannot vouch that none remain. + * The values in `params` that are secrets: credential-named params (an access token, a hosted + * key, a secret access key), and whatever was typed into a password field of the blocks + * `blockTypes` names, whatever the field is called. */ -function redactRequest( - request: unknown, - params: Record, - registry: ResolvedSecretTraceRegistry | undefined -): Record | null { - const credentials = Object.entries(params).flatMap(([key, value]) => - isSensitiveKey(key) && typeof value === 'string' && value !== '' ? [value] : [] +function secretValues(params: Record, blockTypes: string[]): string[] { + const passwordParams = new Set() + for (const blockType of blockTypes) { + for (const subBlock of getBlock(blockType)?.subBlocks ?? []) { + if (!subBlock.password) continue + passwordParams.add(subBlock.id) + if (subBlock.canonicalParamId) passwordParams.add(subBlock.canonicalParamId) + } + } + return Object.entries(params).flatMap(([key, value]) => + (isSensitiveKey(key) || passwordParams.has(key)) && typeof value === 'string' && value !== '' + ? [value] + : [] ) +} + +/** + * A side effect's payload (a stubbed write's request, or an answered block's inputs) as a run may + * report it: the secrets in `params` masked by field and by value, every secret the run resolved + * masked by its registry, then the run's PII redaction applied as it is to a block's output. Null + * when the registry cannot vouch that no secret remains, or the PII redaction fails. + */ +export async function redactSideEffectPayload(input: { + payload: unknown + params: Record + /** Blocks whose password fields `params` may carry. */ + blockTypes: string[] + executionContext: ExecutionContext + registry: ResolvedSecretTraceRegistry | undefined +}): Promise | null> { const redacted = redactCredentials( - isPlainRecord(request) ? request : { input: request }, - credentials + isPlainRecord(input.payload) ? input.payload : { input: input.payload }, + secretValues(input.params, input.blockTypes) ) - const projection = projectResolvedSecretModelContent(redacted, registry) - return projection.safe && isPlainRecord(projection.value) ? projection.value : null + const projection = projectResolvedSecretModelContent(redacted, input.registry) + if (!projection.safe || !isPlainRecord(projection.value)) return null + const pii = input.executionContext.piiBlockOutputRedaction + if (!pii?.enabled) return projection.value + try { + return await redactObjectStrings(projection.value, { + entityTypes: pii.entityTypes, + language: pii.language, + customPatterns: pii.customPatterns, + onFailure: 'throw', + }) + } catch (error) { + logger.warn('PII redaction of a side effect failed; recording no payload', { + errorName: error instanceof Error ? error.name : 'UnknownError', + }) + return null + } } /** * The response answering a write tool call the run's side-effect policy does not send, after the - * policy recorded the request it would have sent; null when the call is sent. `describeRequest` - * runs only for an unsent call, and a request it cannot build fails the call as sending it would. + * policy recorded the request it would have sent. `describeRequest` runs only for an unsent call, + * and a request it cannot build fails the call as sending it would. */ -export function answerUnsentWrite(input: { - toolId: string - params: Record - executionContext: ExecutionContext | undefined - registry: ResolvedSecretTraceRegistry | undefined - describeRequest: () => unknown -}): ToolResponse | null { - const { executionContext, params } = input - const policy = executionContext?.sideEffects - if (!policy) return null - const call = { ...sideEffectSite(executionContext, params), toolId: input.toolId } - if (policy.sendsWrite(call)) return null - const request = redactRequest(input.describeRequest(), params, input.registry) - return { success: true, output: policy.stubWrite({ ...call, request }) } +export async function answerUnsentWrite( + write: UnsentWrite, + input: { + params: Record + registry: ResolvedSecretTraceRegistry | undefined + describeRequest: () => unknown + } +): Promise { + const { call } = write + const toolBlockType = getBlockByToolName(call.toolId)?.type + const request = await redactSideEffectPayload({ + payload: input.describeRequest(), + params: input.params, + blockTypes: [call.blockType, toolBlockType].filter((type): type is string => Boolean(type)), + executionContext: write.executionContext, + registry: input.registry, + }) + return { success: true, output: write.policy.stubWrite({ ...call, request }) } } diff --git a/packages/sim-cli/src/commands/protocol/logs-follow.ts b/packages/sim-cli/src/commands/protocol/logs-follow.ts index 0a812451347..265633cfadf 100644 --- a/packages/sim-cli/src/commands/protocol/logs-follow.ts +++ b/packages/sim-cli/src/commands/protocol/logs-follow.ts @@ -19,6 +19,7 @@ import { visibleWidth, } from '../../output/render' import { apiCommand, type OperationClient } from '../../runtime/called-operations' +import { collectRepeated } from '../../runtime/options' import { encodeFolderPath } from '../../runtime/request' /** One run, as `GET /api/v2/logs` returns it. */ @@ -96,11 +97,6 @@ interface FollowOptions { interval: string } -/** Collects a repeatable flag, as the generated `list` flags do. */ -function collect(value: string, previous: string[]): string[] { - return [...previous, value] -} - function at(row: unknown, path: string): unknown { return path .split('.') @@ -499,14 +495,24 @@ export function attachLogsFollow(logs: Command): void { const [follow, connectFollow] = apiCommand(logs, 'follow', ['listLogs']) follow .description('Watch runs live as they arrive, printing each new run once') - .option('--workflow ', 'Only follow runs of this workflow (repeatable)', collect, []) + .option( + '--workflow ', + 'Only follow runs of this workflow (repeatable)', + collectRepeated, + [] + ) .option( '--folder ', 'Only follow runs of workflows in this folder (repeatable)', - collect, + collectRepeated, + [] + ) + .option( + '--trigger ', + 'Only follow runs with this trigger type (repeatable)', + collectRepeated, [] ) - .option('--trigger ', 'Only follow runs with this trigger type (repeatable)', collect, []) .addOption( new Option('--level ', 'Only follow runs at this severity').choices([ ...V2_OPERATIONS.listLogs.query.level.values, diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 9cbef24917a..d8550837e4c 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -46,7 +46,7 @@ function sharedRules(group: string, extraRenames = ''): string { - **Builders**: \`${PARAMS_COMMAND} \` (or a namespace). - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). - **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (3rd argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only its request (timeout, reset, 429, 5xx) per try. A reference to a block that never ran is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. -- **Run and debug**: \`--dry\` runs the draft, sending no writes: check each in \`sideEffects.stubbed\`. \`--allow \` sends its writes (test data); \`--manual\` runs live, else the deployment. \`--dir \` names a failed run's file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. +- **Run and debug**: \`--dry\` runs the draft sending no writes (check \`sideEffects.stubbed\`), \`--allow \` sends a block's (test data), \`--manual\` sends all; else the deployment runs. \`--dir \` names a failed run's file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo the edit in a fresh \`${group} get --dir \`), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 58c8081e86f..5a05b45f4dd 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -216,10 +216,10 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 and the dry run in step 4 are for a person, CI, or a change you want reviewed first. The test run's \`--dry\` is another thing: the run executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. \`--allow \` sends one block's writes for real against a test resource; \`--mock ='{…}'\` answers a block with fixed output to steer a branch. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. \`--allow \` sends one block's writes for real against a test resource; \`--mock ='{…}'\` answers a block with fixed output to steer a branch. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. -2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and the dry run do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. The dry run is the authority: a type error on a printed line you did not edit that the dry run accepts can be skipped with \`--no-types\`. +2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry-run\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry-run\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. 3. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. 4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). 5. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 90119c195ba..eda99d065a2 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -647,10 +647,10 @@ describe('sim workflows run --dry', () => { workflowId: WORKFLOW_ID, blockId: 'enrich', block: 'Enrich', - reason: 'Its code ran for real; network calls it makes are not stubbed', + reason: 'Function block code ran for real; network calls it makes are not stubbed', }, ], - omitted: 0, + omitted: { stubbed: 0, allowed: 0, unchecked: 0 }, } let stderr: string[] @@ -697,41 +697,41 @@ describe('sim workflows run --dry', () => { }) }) - it('keeps a rerun from a block dry, and a mock alone runs the draft without --dry', async () => { + it('keeps a rerun from a block dry', async () => { vi.spyOn(console, 'log').mockImplementation(() => {}) await run(WORKFLOW_ID, '--from-block', 'agent-1', '--source-run', 'run-1', '--dry') - await run(WORKFLOW_ID, '--mock', 'Score={"content":"spam"}') expect(requestRaw.mock.calls[0][1].body.run).toEqual({ source: 'manual', entry: { type: 'block', blockId: 'agent-1', sourceRunId: 'run-1' }, dry: true, }) - expect(requestRaw.mock.calls[1][1].body.run).toEqual({ - source: 'manual', - mocks: { Score: { content: 'spam' } }, - }) }) it('refuses combinations a dry run cannot honour before sending anything', async () => { await expect(run(WORKFLOW_ID, '--allow', 'Save lead')).rejects.toThrow('add --dry') + await expect(run(WORKFLOW_ID, '--mock', 'Score={"content":"spam"}')).rejects.toThrow( + 'add --dry' + ) await expect(run(WORKFLOW_ID, '--dry', '--follow')).rejects.toThrow('drop --follow') await expect(run(WORKFLOW_ID, '--dry', '--wait-timeout', '30')).rejects.toThrow( 'drop --wait-timeout' ) - await expect(run(WORKFLOW_ID, '--dry', '--async')).rejects.toThrow( - 'Manual execution does not support --async' - ) - await expect(run(WORKFLOW_ID, '--mock', '{"content":"spam"}')).rejects.toThrow( + await expect(run(WORKFLOW_ID, '--dry', '--async')).rejects.toThrow('drop --async') + await expect(run(WORKFLOW_ID, '--dry', '--mock', '{"content":"spam"}')).rejects.toThrow( 'must be =' ) - await expect(run(WORKFLOW_ID, '--mock', 'Score=spam')).rejects.toThrow('is not valid JSON') - await expect(run(WORKFLOW_ID, '--mock', 'Score=[1]')).rejects.toThrow('must be a JSON object') + await expect(run(WORKFLOW_ID, '--dry', '--mock', 'Score=spam')).rejects.toThrow( + 'is not valid JSON' + ) + await expect(run(WORKFLOW_ID, '--dry', '--mock', 'Score=[1]')).rejects.toThrow( + 'must be a JSON object' + ) expect(requestRaw).not.toHaveBeenCalled() }) - it('passes sideEffects through in JSON and summarizes them on stderr in table output', async () => { + it('passes sideEffects through in JSON, keeping the stderr summary to the human formats', async () => { const stdout = vi.spyOn(console, 'log').mockImplementation(() => {}) requestRaw.mockImplementation(async () => jsonResponse({ @@ -742,32 +742,5 @@ describe('sim workflows run --dry', () => { await run(WORKFLOW_ID, '--dry') expect(JSON.parse(String(stdout.mock.calls[0][0])).sideEffects).toEqual(sideEffects) expect(stderr.join('')).not.toContain('Dry run') - - output.format = 'table' - await run(WORKFLOW_ID, '--dry') - const summary = stderr.join('') - expect(summary).toContain('Dry run: 1 not sent, 0 sent (allowed), 1 unchecked') - expect(summary).toContain('not sent Save lead → table_upsert_row') - expect(summary).toContain('unchecked Enrich: Its code ran for real') - }) - - it('prints a rerun of a failed dry run that stays dry', async () => { - const stdout = vi.spyOn(console, 'log').mockImplementation(() => {}) - requestRaw.mockImplementation(async () => - jsonResponse({ - data: { - runId: 'run-1', - workflowId: WORKFLOW_ID, - status: 'failed', - error: { message: 'Agent failed', blockId: 'agent-1', rerunFromBlockId: 'agent-1' }, - sideEffects, - }, - }) - ) - - await expect(run(WORKFLOW_ID, '--dry')).rejects.toThrow('Agent failed') - expect(JSON.parse(String(stdout.mock.calls[0][0])).next).toBe( - `sim workflows run ${WORKFLOW_ID} --from-block agent-1 --source-run run-1 --dry` - ) }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index c9de1b46af5..75f4d809891 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -1,4 +1,4 @@ -import { isRecordLike, toRecord } from '@sim/utils/object' +import { isPlainRecord, isRecordLike, toRecord } from '@sim/utils/object' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import type { Command } from 'commander' import { writeStderr } from '#sim-cli/output/io' @@ -13,6 +13,7 @@ import { safeOneLine, sanitize } from '../../output/render' import { callsOperations, connect } from '../../runtime/called-operations' import { executeOperation, runFailureMessage } from '../../runtime/execute' import { retypeApiError } from '../../runtime/naming' +import { collectRepeated } from '../../runtime/options' import { buildRequest, readArgumentSource } from '../../runtime/request' import { renderResult } from '../../runtime/result' import type { OperationSpec } from '../../runtime/types' @@ -62,17 +63,12 @@ type WorkflowRunSelection = { stopAfterBlockId?: string dry?: true allowBlocks?: string[] - mocks?: Record -} - -/** Collects every use of a repeatable option, in order. */ -function collect(value: string, previous: string[] = []): string[] { - return [...previous, value] + mocks?: Record> } /** `--mock =` values as the block selector each names and its output object. */ -async function readBlockMocks(values: string[]): Promise> { - const mocks: Record = {} +async function readBlockMocks(values: string[]): Promise>> { + const mocks: Record> = {} for (const value of values) { const separator = value.indexOf('=') const block = separator > 0 ? value.slice(0, separator).trim() : '' @@ -86,7 +82,7 @@ async function readBlockMocks(values: string[]): Promise } catch { throw new SimApiError(`--mock ${block}: the output${source.from} is not valid JSON`, 0) } - if (!isRecordLike(output) || Array.isArray(output)) { + if (!isPlainRecord(output)) { throw new SimApiError( `--mock ${block}: the output must be a JSON object, like {"ok":true}`, 0 @@ -114,14 +110,19 @@ async function resolveWorkflowRunSelection( trigger !== undefined || useMockPayload || stopAfter !== undefined || - dry || - mockValues.length > 0 + dry const fromBlock = typeof flags.fromBlock === 'string' ? flags.fromBlock : undefined const sourceRun = typeof flags.sourceRun === 'string' ? flags.sourceRun : undefined if (allowBlocks.length > 0 && !dry) { throw new SimApiError("--allow sends one block's writes during a dry run; add --dry", 0) } + if (mockValues.length > 0 && !dry) { + throw new SimApiError( + '--mock answers a block during a dry run, so its output never drives real writes; add --dry', + 0 + ) + } if (allowBlocks.some((block) => block.trim() === '')) { throw new SimApiError('--allow requires a block id, name or key', 0) } @@ -131,9 +132,9 @@ async function resolveWorkflowRunSelection( 0 ) } - if (dry && flags.waitTimeout !== undefined) { + if (dry && (flags.waitTimeout !== undefined || flags.async === true)) { throw new SimApiError( - '--dry reports its side effects with the run result, so the command waits for it; drop --wait-timeout', + `--dry reports its side effects with the run result, so the command waits for it; drop ${flags.async === true ? '--async' : '--wait-timeout'}`, 0 ) } @@ -209,9 +210,11 @@ function printSideEffects(sideEffects: unknown): void { (entry) => ` unchecked ${label(entry)}: ${safeOneLine(String(entry.reason))}` ), ] - if (typeof sideEffects.omitted === 'number' && sideEffects.omitted > 0) { - lines.push(` … ${sideEffects.omitted} more`) - } + const omitted = Object.values(toRecord(sideEffects.omitted)).reduce( + (total, count) => total + (typeof count === 'number' ? count : 0), + 0 + ) + if (omitted > 0) lines.push(` … ${omitted} more`) lines.push('Request payloads: sideEffects in --output json') writeStderr(styles().dim(`${lines.join('\n')}\n`)) } @@ -710,10 +713,12 @@ deployed has none. --manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in -sideEffects.stubbed with the request it would have sent; check those payloads. Function blocks run -and are listed in sideEffects.unchecked. Child workflows run dry too. --allow sends that -block's writes for real (use a test resource); --mock = answers a block with fixed -output, to steer a branch. +sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function +block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child +workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the +run raises no workspace event. --allow sends that block's writes for real (use a test +resource); --mock = answers a block with fixed output, to steer a branch. A dry run is +the --source-run only of another dry run. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: @@ -722,7 +727,7 @@ instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix -only that block and those after it run again. Add --stop-after to stop after a block; +only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed @@ -756,17 +761,17 @@ export function attachWorkflowRunFollow(workflows: Command): void { .option('--manual', 'Run the current saved workflow state instead of the active deployment') .option( '--dry', - 'Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and Function code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout' + 'Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout' ) .option( '--allow ', "Send this block's writes for real during a --dry run (its id, display name or key); repeatable", - collect + collectRepeated ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable, implies --manual', - collect + 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable', + collectRepeated ) .option( '--trigger ', diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 105f48c23f8..2721b326160 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -7124,7 +7124,7 @@ export type ExecuteWorkflowBody = { stopAfterBlockId?: string dry?: boolean allowBlocks?: Array - mocks?: Record + mocks?: Record> } async?: boolean executionTimeoutSeconds?: number @@ -7161,28 +7161,37 @@ type ExecuteWorkflowResponseRef0 = { type ExecuteWorkflowResponseRef1 = { stubbed: Array<{ workflowId: string - blockId: string - block: string + blockId: string | null + block: string | null tool: string | null request: Record | null returned: Record }> allowed: Array<{ workflowId: string - blockId: string - block: string + blockId: string | null + block: string | null tool: string | null }> unchecked: Array<{ workflowId: string - blockId: string - block: string + blockId: string | null + block: string | null reason: string }> - omitted: number + omitted: { + stubbed: number + allowed: number + unchecked: number + } } type ExecuteWorkflowResponseRef2 = { + allowBlocks: Array + mocks: Record> +} + +type ExecuteWorkflowResponseRef3 = { runId: string workflowId: string status: 'completed' | 'failed' | 'paused' | 'cancelled' @@ -7202,9 +7211,10 @@ type ExecuteWorkflowResponseRef2 = { }> } | null sideEffects?: ExecuteWorkflowResponseRef1 + dryRun?: ExecuteWorkflowResponseRef2 } -type ExecuteWorkflowResponseRef3 = { +type ExecuteWorkflowResponseRef4 = { runId: string statusUrl: string executionTimeoutSeconds: number | null @@ -7212,10 +7222,10 @@ type ExecuteWorkflowResponseRef3 = { export type ExecuteWorkflowResponse = | { - data: ExecuteWorkflowResponseRef2 + data: ExecuteWorkflowResponseRef3 } | { - data: ExecuteWorkflowResponseRef3 + data: ExecuteWorkflowResponseRef4 } /** `GET /api/v2/knowledge/[knowledgeBaseId]/export` */ @@ -10377,6 +10387,11 @@ type GetWorkflowRunResponseRef3 = { } type GetWorkflowRunResponseRef4 = { + allowBlocks: Array + mocks: Record> +} + +type GetWorkflowRunResponseRef5 = { runId: string workflowId: string status: @@ -10412,10 +10427,11 @@ type GetWorkflowRunResponseRef4 = { output: unknown | null blockOutputs: Record | null files: Array | null + dryRun: GetWorkflowRunResponseRef4 | null } export type GetWorkflowRunResponse = { - data: GetWorkflowRunResponseRef4 + data: GetWorkflowRunResponseRef5 } /** `GET /api/v2/workflows/[workflowId]/source` */ diff --git a/packages/sim-cli/src/runtime/options.ts b/packages/sim-cli/src/runtime/options.ts index 1fa37cf80e6..7e618d01861 100644 --- a/packages/sim-cli/src/runtime/options.ts +++ b/packages/sim-cli/src/runtime/options.ts @@ -13,6 +13,11 @@ import { } from './request' import type { OperationSpec } from './types' +/** Collects every use of a repeatable option, in order. */ +export function collectRepeated(value: string, previous: string[] = []): string[] { + return [...previous, value] +} + export const DEFAULT_PAGE_SIZE = 100 /** Resource inventories fetch all pages; data and history commands retain a bounded default. */ diff --git a/packages/sim-cli/src/runtime/run-next.test.ts b/packages/sim-cli/src/runtime/run-next.test.ts index 8f0e2617f22..d0e0a5bf690 100644 --- a/packages/sim-cli/src/runtime/run-next.test.ts +++ b/packages/sim-cli/src/runtime/run-next.test.ts @@ -104,6 +104,23 @@ describe('withRunNext on a failed run', () => { }) }) + it('keeps a test run a test: a dry run with its allowed and mocked blocks, a workflow test dry', () => { + const dryRun = { allowBlocks: ['blk_1'], mocks: { blk_2: { route: "vip's" } } } + const next = `sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow blk_1 --mock 'blk_2={"route":"vip'\\''s"}'` + expect(withRunNext('executeWorkflow', { ...failed, dryRun })).toMatchObject({ next }) + expect(withRunNext('getWorkflowRun', { ...failed, trigger: 'test', dryRun })).toMatchObject({ + next, + }) + expect( + withRunNext('getWorkflowRun', { ...failed, trigger: 'test', dryRun: null }) + ).toMatchObject({ next: 'sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry' }) + expect( + withRunNext('getWorkflowRun', { ...failed, trigger: 'manual', dryRun: null }) + ).toMatchObject({ next: 'sim workflows run wf_1 --from-block blk_3 --source-run run_9' }) + const hostile = { ...failed, dryRun: { allowBlocks: ['$(id)'], mocks: {} } } + expect(withRunNext('executeWorkflow', hostile)).toBe(hostile) + }) + it('names no rerun when the server names no start block, or an id it never issues', () => { const unstartable = { message: 'boom', code: 'BLOCK_EXECUTION_FAILED', blockId: 'blk_3' } for (const unnamed of [ diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index c36b4cde14c..d9f0e60cb19 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -44,20 +44,41 @@ export function resumeCommandFor( return commands.length > 0 ? commands.join('\n') : null } +/** + * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` and + * `--mock` blocks (`dryRun`), so following `next` never sends what the run held back or drops the + * outputs it was steered by. A workflow test's run (`trigger: test`) has no `dryRun` but held its + * writes back all the same. Null when a block id is not in the format the server issues. + */ +function dryRerunFlags(record: Record): string | null { + const dryRun = toRecordOrNull(record.dryRun) + if (!dryRun) return record.trigger === 'test' ? ' --dry' : '' + const flags = [' --dry'] + for (const blockId of Array.isArray(dryRun.allowBlocks) ? dryRun.allowBlocks : []) { + if (!issuedId(blockId)) return null + flags.push(` --allow ${shellArgument(blockId)}`) + } + for (const [blockId, output] of Object.entries(toRecordOrNull(dryRun.mocks) ?? {})) { + if (!issuedId(blockId)) return null + flags.push(` --mock ${shellArgument(`${blockId}=${JSON.stringify(output)}`)}`) + } + return flags.join('') +} + /** * The exact command that reruns a failed run from where the server says a rerun of its failure * starts (`error.rerunFromBlockId`: the failed block, or the outermost loop or parallel holding * it, which a rerun cannot start inside), with the run as the source of every upstream output, so - * a fix applied to that block's source is tested without repeating the blocks before it; a dry - * run's rerun adds `--dry`. Null - * when the server names no start block or an id is not in the format the server issues. + * a fix applied to that block's source is tested without repeating the blocks before it; a test + * run's rerun stays one ({@link dryRerunFlags}). Null when the server names no start block or an + * id is not in the format the server issues. */ function rerunCommandFor(record: Record, workflowId: string): string | null { const startBlockId = toRecordOrNull(record.error)?.rerunFromBlockId const { runId } = record if (!issuedId(startBlockId) || !issuedId(runId) || !issuedId(workflowId)) return null - // A dry run's rerun stays dry, so following `next` never sends what the run held back. - const dry = isRecordLike(record.sideEffects) ? ' --dry' : '' + const dry = dryRerunFlags(record) + if (dry === null) return null return `sim workflows run ${shellArgument(workflowId)} --from-block ${shellArgument(startBlockId)} --source-run ${shellArgument(runId)}${dry}` } From bf56d1318bc9a17fdf36aa2f0d19be8d38e2583b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 02:21:58 -0800 Subject: [PATCH 03/10] fix(workflows): enforce dry-run guarantees at the state layer and stop persisting mocks - A test run (trigger test: dry runs and workflow tests) is never the source of a run that sends its writes: getExecutionStateForWorkflow refuses one unless the caller passes allowTestRun (only a dry run from a block does), and getLatestExecutionStateWithExecutionId skips them. This covers the v2 use case, the editor execute route (named and latest) and Copilot run_from_block/run_block, and replaces the per-surface check. - A test run is never resumed: resume admission refuses an execution logged under test, the CLI names no resume command for one, and workflow tests answer Human in the loop and Wait blocks whole like dry runs, so the pausingBlocks option is gone. - run.mocks are data: a field starting with _ (_pauseMetadata and other executor control fields) is refused, and so is a mock of a locked block or one inside a locked container. - Mock outputs are no longer persisted: the log records only allowed and mocked block ids. readWorkflowRun reads them from the execution data the status read already materialized (so they survive externalization), validated with the contract schema and gated like other execution data. The CLI rerun keeps --dry and --allow; --mock values are passed again. - Provider Files API uploads register their removal as soon as the provider names the file, the caller owns the list, and the try/finally starts before the first upload, so a dry or test run deletes every file that landed, including on a partial or Gemini processing failure. - A dry run never rejects a large inline response, so its result always carries sideEffects. - Nested tool calls inherit the caller's _context only under a side-effect policy. - Cleanups: one response-too-large mapping, request passed directly to answerUnsentWrite, one run-context param set, one log lookup for the source run, recordSettledRun reads the trigger from the LoggingSession, a TEST_TRIGGER constant, tool special cases in one declarative map, password fields indexed once from the registry, agent memory decided once, and toArray in the CLI. Allowing an Agent covers only its own tool calls (documented; the CLI notes when an allowed block sent nothing). --- .../api-reference/build-and-run-workflows.mdx | 2 +- apps/docs/content/docs/cli/reference.mdx | 8 +- apps/docs/content/docs/cli/workflows.mdx | 8 +- apps/docs/openapi-v2-workflows.json | 30 +- .../workflows/[workflowId]/execute/route.ts | 4 +- .../app/api/workflows/[id]/execute/route.ts | 31 +- apps/sim/executor/execution/block-executor.ts | 23 +- apps/sim/executor/execution/types.ts | 10 +- apps/sim/executor/handlers/agent/handler.ts | 12 +- apps/sim/lib/api/contracts/v2/workflows.ts | 19 +- .../sim/lib/logs/execution/logging-session.ts | 5 + apps/sim/lib/mcp/tool-arguments.ts | 19 +- .../dry-run-hosted-key.integration.ts | 159 ++++++++++ .../application/dry-run.integration.ts | 291 +++++++++++++++++- .../execute-manual-workflow.test.ts | 10 +- .../application/execute-manual-workflow.ts | 49 +-- .../application/read-workflow-run.ts | 13 +- .../application/run-workflow-for-test.ts | 10 +- .../sim/lib/workflows/dry-run/side-effects.ts | 56 ++-- .../lib/workflows/executor/execute-service.ts | 75 ++--- .../workflows/executor/execution-core.test.ts | 1 + .../lib/workflows/executor/execution-core.ts | 37 +-- .../lib/workflows/executor/execution-state.ts | 84 ++--- .../workflows/executor/execution-status.ts | 37 ++- .../executor/human-in-the-loop-manager.ts | 23 ++ apps/sim/lib/workspace-events/constants.ts | 4 +- .../providers/file-attachments.server.test.ts | 44 ++- apps/sim/providers/file-attachments.server.ts | 56 ++-- apps/sim/providers/index.test.ts | 24 +- apps/sim/providers/index.ts | 22 +- apps/sim/stores/logs/filters/types.ts | 7 + apps/sim/tools/index.test.ts | 3 +- apps/sim/tools/index.ts | 19 +- apps/sim/tools/side-effects.test.ts | 60 +++- apps/sim/tools/side-effects.ts | 81 +++-- .../commands/protocol/workflow-run-follow.ts | 43 ++- packages/sim-cli/src/generated/v2-api.ts | 4 +- packages/sim-cli/src/runtime/run-next.test.ts | 13 +- packages/sim-cli/src/runtime/run-next.ts | 35 ++- .../testing/src/mocks/logging-session.mock.ts | 5 +- 40 files changed, 1032 insertions(+), 404 deletions(-) create mode 100644 apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index 966432ce766..8db4a50eadd 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. A failed dry run still returns its `sideEffects`, and only another dry run can use it as `run.entry.sourceRunId`. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock cannot replace a locked block or set a field starting with `_`, and its output is never stored: the run records only which blocks were mocked, so a rerun passes `run.mocks` again. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 1e613a92693..c624afd56c8 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8517,8 +8517,8 @@ sim workflows run [options] | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8534,11 +8534,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. A dry run is the --source-run only of another dry run. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. Mock outputs are never stored, so pass each --mock again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 1ba4401cfbb..e9784f77039 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -834,8 +834,8 @@ sim workflows run [options] | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -851,11 +851,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); --mock <block>=<json> answers a block with fixed output, to steer a branch. A dry run is the --source-run only of another dry run. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. Mock outputs are never stored, so pass each --mock again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 5a60f4c50fd..00640982e65 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17415,27 +17415,19 @@ }, "description": "Blocks whose writes the run sent (`run.allowBlocks`), by id." }, - "mocks": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "description": "Output field." - } + "mockedBlocks": { + "type": "array", + "items": { + "type": "string", + "description": "Block id." }, - "description": "Blocks the run answered with fixed outputs (`run.mocks`), keyed by id." + "description": "Blocks the run answered with fixed outputs (`run.mocks`), by id. Their outputs are never stored, so a rerun passes them again." } }, - "required": ["allowBlocks", "mocks"], + "required": ["allowBlocks", "mockedBlocks"], "additionalProperties": false, "title": "Workflow dry run", - "description": "The blocks a dry run sent and mocked, which a rerun of it passes again." + "description": "The blocks a dry run sent and mocked, by id, which a rerun of it names again; never a mock output." }, "WorkflowRunResult": { "type": "object", @@ -17770,7 +17762,7 @@ "type": "boolean" }, "allowBlocks": { - "description": "Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed.", + "description": "Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.", "maxItems": 50, "type": "array", "items": { @@ -17779,7 +17771,7 @@ } }, "mocks": { - "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`.", + "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked, and an output field cannot start with `_` (those control the run). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.", "type": "object", "propertyNames": { "type": "string" @@ -18684,7 +18676,7 @@ "type": "null" } ], - "description": "A failed dry run's allowed and mocked blocks, which a rerun of it passes again; null for any other run, or when execution data is hidden by organization permission groups." + "description": "A failed dry run's allowed and mocked blocks, by id, which a rerun of it names again; null for any other run, or when execution data is hidden by organization permission groups." } }, "required": [ diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index 92f6e987d9a..027e08ddc3e 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -138,8 +138,8 @@ function presentRun(result: ExecuteWorkflowServiceRun) { endedAt: result.endedAt, durationMs: result.durationMs, executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), - ...(result.sideEffects ? { sideEffects: result.sideEffects } : {}), - ...(result.dryRun ? { dryRun: result.dryRun } : {}), + sideEffects: result.sideEffects, + dryRun: result.dryRun, output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, paused: presentV2RunPause(result.paused), diff --git a/apps/sim/app/api/workflows/[id]/execute/route.ts b/apps/sim/app/api/workflows/[id]/execute/route.ts index 31ca931b575..07fd7c2ae7b 100644 --- a/apps/sim/app/api/workflows/[id]/execute/route.ts +++ b/apps/sim/app/api/workflows/[id]/execute/route.ts @@ -37,6 +37,7 @@ import { isTimeoutAbortReason, isTimeoutError, } from '@/lib/core/execution-limits' +import { OrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types' import { isCrossSiteSessionRequest } from '@/lib/core/security/same-origin' import { generateRequestId } from '@/lib/core/utils/request' import { SSE_HEADERS } from '@/lib/core/utils/sse' @@ -859,15 +860,25 @@ async function handleExecutePost( if (rawRunFromBlock.executionId) { const { getExecutionStateForWorkflow, getLatestExecutionStateWithExecutionId } = await import('@/lib/workflows/executor/execution-state') - const sourceExecution = - rawRunFromBlock.executionId === 'latest' - ? await getLatestExecutionStateWithExecutionId(workflowId) - : { - executionId: rawRunFromBlock.executionId, - state: await getExecutionStateForWorkflow(rawRunFromBlock.executionId, workflowId), - } - const snapshot = sourceExecution?.state - if (!snapshot) { + let sourceExecution: { executionId: string; state: SerializableExecutionState } | null + try { + if (rawRunFromBlock.executionId === 'latest') { + sourceExecution = await getLatestExecutionStateWithExecutionId(workflowId) + } else { + const state = await getExecutionStateForWorkflow( + rawRunFromBlock.executionId, + workflowId + ) + sourceExecution = state ? { executionId: rawRunFromBlock.executionId, state } : null + } + } catch (error) { + if (!(error instanceof OrchestrationError)) throw error + return NextResponse.json( + { error: error.message }, + { status: statusForOrchestrationError(error.code) } + ) + } + if (!sourceExecution) { if (rawRunFromBlock.sourceSnapshot && !isPublicApiAccess) { resolvedRunFromBlock = { startBlockId: rawRunFromBlock.startBlockId, @@ -891,7 +902,7 @@ async function handleExecutePost( } else { resolvedRunFromBlock = { startBlockId: rawRunFromBlock.startBlockId, - sourceSnapshot: snapshot, + sourceSnapshot: sourceExecution.state, sourceExecutionId: sourceExecution.executionId, } } diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index eb24d1ff41c..a3d51db22f9 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -44,6 +44,8 @@ import type { BlockStateWriter, ContextExtensions, ExecutionTestHooks, + SideEffectBlockSite, + SideEffectPolicy, WorkflowNodeMetadata, } from '@/executor/execution/types' import { @@ -286,14 +288,18 @@ export class BlockExecutor { const testHooks = this.contextExtensions.testHooks const mockedBlockId = node.metadata.originalBlockId ?? block.id const isMocked = !isSentinel && testHooks?.mocksBlock(mockedBlockId) === true + /** The run's side-effect policy and the block's site, when the policy answers the block. */ + let answered: { policy: SideEffectPolicy; site: SideEffectBlockSite } | undefined const sideEffects = this.contextExtensions.sideEffects - const site = { - workflowId: blockCtx.workflowId, - blockId: mockedBlockId, - blockName: block.metadata?.name ?? mockedBlockId, - blockType: block.metadata?.id ?? '', + if (sideEffects && !isSentinel && !isMocked) { + const site = { + workflowId: blockCtx.workflowId, + blockId: mockedBlockId, + blockName: block.metadata?.name ?? mockedBlockId, + blockType: block.metadata?.id ?? '', + } + if (sideEffects.answersBlock(site)) answered = { policy: sideEffects, site } } - const isAnswered = !isSentinel && !isMocked && sideEffects?.answersBlock(site) === true try { /** * Only the handler call is retried. A streaming handler returns before any @@ -312,8 +318,9 @@ export class BlockExecutor { inputDisplayRegistry ) } - if (isAnswered && sideEffects) { - return sideEffects.answerBlock({ + if (answered) { + const { policy, site } = answered + return policy.answerBlock({ ...site, input: () => redactSideEffectPayload({ diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index b891ff34827..b8f88720956 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -87,7 +87,7 @@ export interface ExecutionMetadata { allowLargeValueWorkflowScope?: boolean callChain?: string[] correlation?: AsyncExecutionCorrelation - /** A dry run's allowed and mocked blocks, recorded on its log so a rerun can pass them again. */ + /** A dry run's allowed and mocked blocks, recorded on its log so a rerun can name them again. */ dryRun?: DryRunOptions executionMode?: 'sync' | 'stream' | 'async' /** @@ -320,10 +320,10 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } -/** The blocks of the workflow a dry run started that it sent and mocked, by id. */ +/** The blocks of the workflow a dry run started that it sent and mocked, by id; never a mock's output. */ export interface DryRunOptions { allowBlocks: string[] - mocks: Record + mockedBlocks: string[] } /** Where a call that may change state outside the run was made: a block of one executing workflow. */ @@ -365,7 +365,9 @@ export interface AnsweredBlockCall extends SideEffectBlockSite { * `tools/index.ts` consults it for every tool call not declared `read` (an MCP tool declares * nothing, so every one) before a hosted key is drawn, and answers a stubbed call after * credentials resolve and before anything is sent; the block executor consults it before each - * block's handler. + * block's handler. Its presence alone also means the run keeps nothing beyond its log: an Agent + * writes no memory, and files uploaded to a provider's Files API are deleted once the call + * settles. Where only the log is at hand, the `test` trigger says the same. */ export interface SideEffectPolicy { /** diff --git a/apps/sim/executor/handlers/agent/handler.ts b/apps/sim/executor/handlers/agent/handler.ts index 47e6c914017..53c653c2a18 100644 --- a/apps/sim/executor/handlers/agent/handler.ts +++ b/apps/sim/executor/handlers/agent/handler.ts @@ -527,8 +527,9 @@ export class AgentBlockHandler implements BlockHandler { } const streamingConfig = this.getStreamingConfig(ctx, block) + const writesMemory = persistsMemory(ctx, filteredInputs) const agentConversation = - persistsMemory(ctx, filteredInputs) && + writesMemory && filteredInputs.conversationId && nodeMetadata && nodeMetadata.executionOrder !== undefined @@ -546,6 +547,7 @@ export class AgentBlockHandler implements BlockHandler { modelInputs, skillMetadata, fileProjection, + writesMemory, agentConversation ) /** @@ -649,7 +651,7 @@ export class AgentBlockHandler implements BlockHandler { if (this.isStreamingExecution(result)) { const streamingResult = result as StreamingExecution streamingResult.diagnosticResolvedSecretTraceRegistry = providerErrorRegistry - if (persistsMemory(ctx, filteredInputs)) { + if (writesMemory) { return this.wrapStreamForMemoryPersistence( ctx, filteredInputs, @@ -661,7 +663,7 @@ export class AgentBlockHandler implements BlockHandler { return streamingResult } - if (persistsMemory(ctx, filteredInputs)) { + if (writesMemory) { await this.persistResponseToMemory( ctx, filteredInputs, @@ -1450,6 +1452,8 @@ export class AgentBlockHandler implements BlockHandler { modelInputs: AgentInputs, skillMetadata: Array<{ name: string; description: string }>, fileProjection: ReturnType, + /** Whether this turn is written to memory ({@link persistsMemory}). */ + writesMemory: boolean, agentConversation?: AgentTurnSession ): Promise { const messages: Message[] = [] @@ -1608,6 +1612,7 @@ export class AgentBlockHandler implements BlockHandler { fileProjection.projectedNameByFile, fileProjection.directNameInputPaths ) + if (!writesMemory) return messagesWithFiles /** Persist the complete turn before provider hydration adds bytes or transient handles. */ const lastUserMessage = messages @@ -1616,7 +1621,6 @@ export class AgentBlockHandler implements BlockHandler { const attachedUserMessage = messagesWithFiles ?.filter((message) => message.role === 'user' && !isConversationHistoryNotice(message)) .at(-1) - if (!persistsMemory(ctx, inputs)) return messagesWithFiles const messagesToStore = pendingMemoryMessages.map(({ raw, model }) => model === lastUserMessage && attachedUserMessage?.files ? { ...raw, files: attachedUserMessage.files } diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 10c11342d63..ce681c55cb7 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1713,7 +1713,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .max(50) .optional() .describe( - 'Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed.' + 'Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.' ), mocks: z .record( @@ -1727,7 +1727,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ message: 'run.mocks names at most 50 blocks', }) .describe( - 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`.' + 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked, and an output field cannot start with `_` (those control the run). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.' ), }) .strict(), @@ -2047,19 +2047,22 @@ const v2RunSideEffectsSchema = z description: 'What a dry run did with each write it reached.', }) -const v2RunDryRunSchema = z +export const v2RunDryRunSchema = z .object({ allowBlocks: z .array(z.string().describe('Block id.')) .describe('Blocks whose writes the run sent (`run.allowBlocks`), by id.'), - mocks: z - .record(z.string(), z.record(z.string(), z.unknown().describe('Output field.'))) - .describe('Blocks the run answered with fixed outputs (`run.mocks`), keyed by id.'), + mockedBlocks: z + .array(z.string().describe('Block id.')) + .describe( + 'Blocks the run answered with fixed outputs (`run.mocks`), by id. Their outputs are never stored, so a rerun passes them again.' + ), }) .meta({ id: 'WorkflowDryRun', title: 'Workflow dry run', - description: 'The blocks a dry run sent and mocked, which a rerun of it passes again.', + description: + 'The blocks a dry run sent and mocked, by id, which a rerun of it names again; never a mock output.', }) /** @@ -2510,7 +2513,7 @@ export const v2WorkflowRunStatusSchema = z dryRun: v2RunDryRunSchema .nullable() .describe( - "A failed dry run's allowed and mocked blocks, which a rerun of it passes again; null for any other run, or when execution data is hidden by organization permission groups." + "A failed dry run's allowed and mocked blocks, by id, which a rerun of it names again; null for any other run, or when execution data is hidden by organization permission groups." ), }) .meta({ diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index e6721a971a4..5139e90dffd 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -937,6 +937,11 @@ export class LoggingSession { return this.deletedScope } + /** The trigger the run is logged under. */ + getTriggerType(): ExecutionTrigger['type'] { + return this.triggerType + } + private async releaseAdmissionSlot(): Promise { try { await releaseExecutionSlot(this.reservationId) diff --git a/apps/sim/lib/mcp/tool-arguments.ts b/apps/sim/lib/mcp/tool-arguments.ts index e4460cb7b1f..31146271b5e 100644 --- a/apps/sim/lib/mcp/tool-arguments.ts +++ b/apps/sim/lib/mcp/tool-arguments.ts @@ -3,18 +3,27 @@ import { isPlainRecord } from '@sim/utils/object' const logger = createLogger('McpToolArguments') +/** + * Params an Agent's tool call carries for the run itself (every env var, workflow variable and + * block output), which no tool sends: neither an MCP server's arguments nor a stubbed write's + * recorded request may show them. + */ +export const RUN_CONTEXT_PARAMS: ReadonlySet = new Set([ + 'envVars', + 'workflowVariables', + 'blockData', + 'blockNameMapping', +]) + /** Params an MCP tool call carries for the run, never sent to the server as arguments. */ -const MCP_SYSTEM_PARAMETERS = new Set([ +const MCP_SYSTEM_PARAMETERS: ReadonlySet = new Set([ + ...RUN_CONTEXT_PARAMS, 'operationPolicy', 'serverId', 'serverUrl', 'toolName', 'serverName', '_context', - 'envVars', - 'workflowVariables', - 'blockData', - 'blockNameMapping', '_toolSchema', ]) diff --git a/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts b/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts new file mode 100644 index 00000000000..cbcb52230c1 --- /dev/null +++ b/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts @@ -0,0 +1,159 @@ +/** + * A dry run on a hosted deployment, against real PostgreSQL and Redis: a write that would use + * Sim's hosted key is answered with a placeholder before a key is drawn, so the workspace's + * hosted-key rate-limit counter in Redis is never touched and the recorded request carries no key. + */ +import { db } from '@sim/db' +import { + permissions, + user, + userStats, + workflow, + workflowExecutionLogs, + workflowExecutionSnapshots, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, SubBlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' + +const HOSTED_KEY = vi.hoisted(() => { + const key = 'hunter-hosted-fixture-key' + process.env.HUNTER_API_KEY_COUNT = '1' + process.env.HUNTER_API_KEY_1 = key + return key +}) + +vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isHosted: true, +})) + +import { closeRedisConnection, getRedisClient } from '@/lib/core/config/redis' +import { executeManualWorkflowOperation } from '@/lib/workflows/application/execute-manual-workflow' +import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' + +const ownerId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const principal = createDelegatedPrincipal({ + subjectUserId: ownerId, + workspaceId, + audience: 'sim:workflows', +}) + +function block(name: string, type: string, values: Record = {}): BlockState { + return { + id: generateId(), + type, + name, + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: Object.fromEntries( + Object.entries(values).map(([key, value]) => [ + key, + { id: key, type: 'short-input', value: value as SubBlockState['value'] }, + ]) + ), + } +} + +/** Every Redis key that names the fixture workspace: a hosted-key counter is keyed by it. */ +async function workspaceRedisKeys(): Promise { + const redis = getRedisClient() + if (!redis) throw new Error('The suite needs Redis') + return redis.keys(`*${workspaceId}*`) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Hosted key fixture', + email: `${ownerId}@dry-run-hosted.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ id: generateId(), userId: ownerId }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Hosted key fixture', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId: ownerId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + const start = block('start', 'start_trigger') + const finder = block('find', 'hunter', { + operation: 'hunter_email_finder', + domain: 'example.com', + first_name: 'Ada', + last_name: 'Lovelace', + }) + const state: WorkflowState = { + blocks: { [start.id]: start, [finder.id]: finder }, + edges: [{ id: generateId(), source: start.id, target: finder.id }], + loops: {}, + parallels: {}, + } + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: 'Hosted key dry run', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const saved = await saveWorkflowToNormalizedTables(workflowId, state) + expect(saved.success, saved.error).toBe(true) +}) + +afterAll(async () => { + await db.delete(workflowExecutionLogs).where(eq(workflowExecutionLogs.workflowId, workflowId)) + await db + .delete(workflowExecutionSnapshots) + .where(eq(workflowExecutionSnapshots.workflowId, workflowId)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) + await closeRedisConnection() + await db.$client.end() +}) + +describe('a dry run on a hosted deployment', () => { + it('stubs a hosted-key write without drawing a key or counting it against the workspace', async () => { + expect(await workspaceRedisKeys()).toEqual([]) + + const result = (await executeManualWorkflowOperation.execute({ + principal, + input: { + workflowId, + requestId: generateId(), + executionId: generateId(), + input: {}, + mode: 'sync', + requestHeaders: new Headers(), + useMockPayload: false, + dry: true, + }, + })) as ExecuteWorkflowServiceRun + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ block: 'find', tool: 'hunter_email_finder' }), + ]) + expect(JSON.stringify(result.sideEffects)).not.toContain(HOSTED_KEY) + expect(await workspaceRedisKeys()).toEqual([]) + }) +}) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 9c2e46a19e5..4464cc2a806 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -6,7 +6,10 @@ * block writes for real while reads run for real; a child workflow's writes, an Agent's included, * stay stubbed; custom and Wait blocks are answered whole; code runs and is listed unchecked; a * mocked block steers a branch; a failed dry run keeps its side effects and is the source only of - * another dry run. Model calls are answered by a simulated Anthropic API. + * another dry run. A test run is never the source of a run that sends its writes (the v2 use case, + * Copilot and the editor route alike) and is never resumed; a mock never controls the run or + * replaces a locked block, and only the ids of mocked blocks are kept. Model calls are answered by + * a simulated Anthropic API. */ import { db } from '@sim/db' import { @@ -29,7 +32,10 @@ import { workspaceEnvironment, } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' -import { createDelegatedPrincipal } from '@sim/testing/factories/principal.factory' +import { + createDelegatedPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' @@ -38,12 +44,26 @@ import { eq, inArray } from 'drizzle-orm' import { NextRequest } from 'next/server' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -const subscriberRuns = vi.hoisted(() => { +const { subscriberRuns, session } = vi.hoisted(() => { /** Custom blocks are a self-hosted opt-in, read when the config module loads. */ process.env.CUSTOM_BLOCKS_ENABLED = 'true' - return { runIds: [] as string[] } + return { + subscriberRuns: { runIds: [] as string[] }, + /** The browser session the editor route sees; none unless a test signs in. */ + session: { + current: null as null | { + user: { id: string; name: string; email: string } + session: { id: string } + }, + }, + } }) +vi.mock('@/lib/auth', async (importOriginal) => ({ + ...(await importOriginal()), + getSession: async () => session.current, +})) + /** A Sim-trigger subscriber's run starts here; the suite records the run that raised it. */ vi.mock('@/lib/webhooks/processor', () => ({ processPolledWebhookEvent: async (_webhook: unknown, _workflow: unknown, payload: unknown) => { @@ -54,18 +74,25 @@ vi.mock('@/lib/webhooks/processor', () => ({ })) import { hashApiKey } from '@/lib/api-key/crypto' +import { resolveBillingAttribution } from '@/lib/billing/core/attribution' import { closeRedisConnection } from '@/lib/core/config/redis' import type { OrchestrationError } from '@/lib/core/orchestration/types' import { encryptSecret } from '@/lib/core/security/encryption' +import { materializeExecutionData } from '@/lib/logs/execution/trace-store' import { WorkflowTestSession } from '@/lib/workflow-tests/session' import { type ExecuteManualWorkflowInput, executeManualWorkflowFromBlockOperation, executeManualWorkflowOperation, } from '@/lib/workflows/application/execute-manual-workflow' +import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' +import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' +import { runFromBlockFromCopilot } from '@/lib/workflows/application/run-workflow-from-copilot' import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' import { POST as v2Execute } from '@/app/api/v2/workflows/[workflowId]/execute/route' +import { POST as editorExecute } from '@/app/api/workflows/[id]/execute/route' +import type { PausePoint } from '@/executor/types' const ownerId = generateId() const organizationId = generateId() @@ -398,6 +425,7 @@ beforeAll(async () => { afterEach(() => { vi.unstubAllGlobals() + session.current = null }) afterAll(async () => { @@ -483,7 +511,7 @@ describe('a dry run', () => { 'notify', 'childsave', ]) - expect(allowed.dryRun).toEqual({ allowBlocks: [parent.idOf('save')], mocks: {} }) + expect(allowed.dryRun).toEqual({ allowBlocks: [parent.idOf('save')], mockedBlocks: [] }) const reread = await run(parentId, { dry: true, selectedOutputs: ['lookup.rows'] }) expect(JSON.stringify(reread.blockOutputs?.['lookup.rows'])).toContain('a@b.co') @@ -842,3 +870,256 @@ describe('a dry run', () => { expect(await tableRows(tableId)).toEqual([]) }) }) + +/** Start → save → after, two table writes, and a dry run of it, which wrote neither. */ +async function dryRunSource() { + const tableId = await createTable() + const fixture = graph( + [ + block('start', 'start_trigger'), + upsertLead('save', tableId, 'a@b.co'), + upsertLead('after', tableId, 'after@b.co'), + ], + [ + ['start', 'save'], + ['save', 'after'], + ] + ) + const workflowId = await saveWorkflow(fixture.state) + const dry = await run(workflowId, { dry: true }) + expect(dry.status, JSON.stringify(dry.error)).toBe('completed') + return { tableId, workflowId, afterId: fixture.idOf('after'), dryRunId: dry.executionId } +} + +/** Start → a Human in the loop block → a table write. */ +async function approvalFixture() { + const tableId = await createTable() + const approval = block('approval', 'human_in_the_loop', { + inputFormat: [{ id: 'approved', name: 'approved', type: 'boolean', required: true }], + }) + approval.subBlocks.inputFormat.type = 'input-format' + const name = `Approval ${generateId()}` + const workflowId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), approval, upsertLead('save', tableId, 'a@b.co')], + [ + ['start', 'approval'], + ['approval', 'save'], + ] + ).state, + name + ) + return { tableId, workflowId, name } +} + +async function pausedExecutionsOf(workflowId: string) { + return db + .select({ + executionId: pausedExecutions.executionId, + pausePoints: pausedExecutions.pausePoints, + }) + .from(pausedExecutions) + .where(eq(pausedExecutions.workflowId, workflowId)) +} + +describe('a test run', () => { + it('is not the source of a Copilot run from a block, named or as the latest run', async () => { + const { tableId, workflowId, afterId, dryRunId } = await dryRunSource() + const billingAttribution = await resolveBillingAttribution({ + actorUserId: ownerId, + workspaceId, + }) + const fromBlock = (sourceExecutionId?: string) => + runFromBlockFromCopilot.execute({ + principal, + input: { + workflowId, + useDraftState: true, + lifecycle: { billingAttribution }, + blockId: afterId, + ...(sourceExecutionId ? { sourceExecutionId } : {}), + }, + }) + + await expect(fromBlock(dryRunId)).rejects.toMatchObject(validationError) + await expect(fromBlock()).rejects.toMatchObject({ code: 'not_found' }) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('is not the source of an editor run from a block, named or as the latest run', async () => { + const { tableId, workflowId, afterId, dryRunId } = await dryRunSource() + session.current = { + user: { id: ownerId, name: 'Dry run fixture', email: `${ownerId}@dry-run.test` }, + session: { id: generateId() }, + } + const fromBlock = async (executionId: string) => { + const response = await editorExecute( + new NextRequest(`http://localhost:3000/api/workflows/${workflowId}/execute`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: 'session=fixture' }, + body: JSON.stringify({ + input: {}, + useDraftState: true, + runFromBlock: { startBlockId: afterId, executionId }, + }), + }), + { params: Promise.resolve({ id: workflowId }) } + ) + return { status: response.status, body: await response.json() } + } + + expect(await fromBlock(dryRunId)).toMatchObject({ + status: 400, + body: { error: expect.stringContaining('is a test run') }, + }) + expect(await fromBlock('latest')).toMatchObject({ status: 400 }) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('is never resumed, so a pause in one sends nothing after it', async () => { + const { tableId, workflowId } = await approvalFixture() + const paused = (await executeManualWorkflowOperation.execute({ + principal, + input: { + workflowId, + requestId: generateId(), + executionId: generateId(), + input: {}, + mode: 'sync', + requestHeaders: new Headers(), + useMockPayload: false, + }, + })) as ExecuteWorkflowServiceRun + expect(paused.status, JSON.stringify(paused.error)).toBe('paused') + const contextId = paused.paused?.points[0]?.contextId + if (!contextId) throw new Error('The run named no pause point') + await vi.waitFor( + async () => { + const [row] = await pausedExecutionsOf(workflowId) + const point = (row?.pausePoints as Record | null)?.[contextId] + if (!point?.snapshotReady) throw new Error('Pause not yet resumable') + }, + { timeout: 20_000, interval: 100 } + ) + /** A pausing block can no longer pause a test run; this stands in for one that did. */ + await db + .update(workflowExecutionLogs) + .set({ trigger: 'test' }) + .where(eq(workflowExecutionLogs.executionId, paused.executionId)) + + await expect( + resumeWorkflowRun.execute({ + principal: createSessionPrincipal({ userId: ownerId, sessionId: generateId() }), + input: { + workflowId, + runId: paused.executionId, + contextId, + resumeInput: { approved: true }, + surface: 'v2', + }, + }) + ).rejects.toThrow('is never resumed') + await sleep(500) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('answers a Human in the loop block in a workflow test, which never pauses', async () => { + const { tableId, workflowId, name } = await approvalFixture() + const testSession = new WorkflowTestSession({ + workspaceId, + principal, + version: 'draft', + only: null, + onProgress: async () => {}, + }) + + let event = await testSession.start({ workflow: name, trigger: null, input: {}, targets: [] }) + while (event.kind === 'waiting') event = await testSession.next(event.runId) + + expect(event).toMatchObject({ kind: 'done' }) + expect(await pausedExecutionsOf(workflowId)).toEqual([]) + expect(await tableRows(tableId)).toEqual([]) + }) +}) + +describe('a dry run’s mocks', () => { + it('cannot set a field that controls the run, such as a pause', async () => { + const { parentId } = await parentFixture() + const pause = { + contextId: 'mocked', + pauseKind: 'time', + resumeAt: new Date().toISOString(), + blockId: 'lookup', + } + + await expect( + run(parentId, { dry: true, mocks: { lookup: { rows: [], _pauseMetadata: pause } } }) + ).rejects.toMatchObject(validationError) + expect(await pausedExecutionsOf(parentId)).toEqual([]) + }) + + it('cannot replace a locked block', async () => { + const tableId = await createTable() + const lookup = queryLeads('lookup', tableId) + lookup.locked = true + const workflowId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), lookup, notify('notify')], + [ + ['start', 'lookup'], + ['lookup', 'notify'], + ] + ).state + ) + + await expect( + run(workflowId, { dry: true, mocks: { lookup: { rows: [], totalCount: 99 } } }) + ).rejects.toMatchObject(validationError) + expect(await logTriggers(workflowId)).toEqual([]) + }) + + it('are kept only as block ids, which a failed run reads back for its rerun', async () => { + const tableId = await createTable() + const secret = `mock-secret-${generateId()}` + const fixture = graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + upsertLead('save', tableId, 'a@b.co'), + queryLeads('broken', generateId()), + ], + [ + ['start', 'lookup'], + ['lookup', 'save'], + ['save', 'broken'], + ] + ) + const workflowId = await saveWorkflow(fixture.state) + const recorded = { allowBlocks: [fixture.idOf('save')], mockedBlocks: [fixture.idOf('lookup')] } + + const failed = await run(workflowId, { + dry: true, + allowBlocks: ['save'], + mocks: { lookup: { rows: [], rowCount: 0, totalCount: 0, note: secret } }, + }) + + expect(failed.status).toBe('failed') + expect(failed.dryRun).toEqual(recorded) + const [row] = await db + .select({ executionData: workflowExecutionLogs.executionData }) + .from(workflowExecutionLogs) + .where(eq(workflowExecutionLogs.executionId, failed.executionId)) + const executionData = await materializeExecutionData( + row.executionData as Record, + { workspaceId, workflowId, executionId: failed.executionId } + ) + const trigger = executionData.trigger as { data?: { dryRun?: unknown } } + expect(trigger.data?.dryRun).toEqual(recorded) + const read = await readWorkflowRun.execute({ + principal, + input: { workflowId, runId: failed.executionId, includeOutput: false, selectedOutputs: [] }, + }) + expect(read.dryRun).toEqual(recorded) + expect(JSON.stringify(read)).not.toContain(secret) + }) +}) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts index 673e8667025..9538ff6e192 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts @@ -16,7 +16,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ executeService: vi.fn(), loadSourceState: vi.fn(), - loadSourceTrigger: vi.fn(async () => 'manual'), resolveOptions: vi.fn(), validateInput: vi.fn(), })) @@ -35,7 +34,6 @@ vi.mock('@/lib/workflows/executor/execute-service', () => ({ vi.mock('@/lib/workflows/executor/execution-state', () => ({ getExecutionStateForWorkflow: mocks.loadSourceState, - getWorkflowExecutionLogTrigger: mocks.loadSourceTrigger, })) vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) @@ -145,7 +143,9 @@ describe('manual workflow execution application operations', () => { principal: delegated, input: { ...baseInput, blockId: 'agent-1', sourceRunId: 'source-run' }, }) - expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run', context.workflowId) + expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run', context.workflowId, { + allowTestRun: false, + }) expect(mocks.executeService).toHaveBeenLastCalledWith( expect.objectContaining({ principal: delegated, @@ -278,7 +278,9 @@ describe('manual workflow execution application operations', () => { input: { ...baseInput, blockId: 'agent-1', sourceRunId: 'source-run-1' }, }) - expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run-1', 'workflow-1') + expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run-1', 'workflow-1', { + allowTestRun: false, + }) expect(mocks.executeService).toHaveBeenCalledWith( expect.objectContaining({ triggerType: 'manual', diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index f942064fb2f..7f2197717fc 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,7 +1,7 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' import { formatQuotedNameList } from '@sim/utils/string' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' -import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' +import { isWorkflowBlockProtected, normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { OrchestrationError } from '@/lib/core/orchestration/types' import { inlinesRunFiles, @@ -16,10 +16,7 @@ import { type ExecuteWorkflowServiceResult, executeWorkflowService, } from '@/lib/workflows/executor/execute-service' -import { - getExecutionStateForWorkflow, - getWorkflowExecutionLogTrigger, -} from '@/lib/workflows/executor/execution-state' +import { getExecutionStateForWorkflow } from '@/lib/workflows/executor/execution-state' import { loadWorkflowFromNormalizedTables, type NormalizedWorkflowData, @@ -28,6 +25,7 @@ import { resolveTriggerRunOptions, validateTriggerInput, } from '@/lib/workflows/triggers/run-options' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' interface ManualExecutionInput extends Omit { input?: unknown @@ -168,7 +166,9 @@ function resolveStopAfterBlock( * The dry run a manual run asked for, its allowed and mocked blocks resolved like * {@link resolveBlockSelector}. A dry run is logged under the `test` trigger, never as a manual * run, and returns its side effects with the result it waits for, so it cannot stream or detach. - * Mocks need a dry run: a fixed output must never drive a run's real writes. + * Mocks need a dry run: a fixed output must never drive a run's real writes. A mock is data: it + * never carries an executor control field (`_pauseMetadata`, any `_` field), and never replaces a + * locked block, whose configured behaviour only an admin may change. */ function resolveRunOverrides( state: ManualWorkflowState, @@ -217,16 +217,24 @@ function resolveRunOverrides( if (blockMocks.has(blockId)) { throw new OrchestrationError('validation', `run.mocks names block "${blockId}" twice`) } + if (isWorkflowBlockProtected(blockId, state.blocks)) { + throw new OrchestrationError( + 'validation', + `run.mocks "${selector}" is a locked block (or inside a locked loop or parallel); its configured behaviour cannot be replaced.` + ) + } + const controlFields = Object.keys(output).filter((field) => field.startsWith('_')) + if (controlFields.length > 0) { + throw new OrchestrationError( + 'validation', + `run.mocks "${selector}" sets ${controlFields.join(', ')}: fields starting with "_" control the run's execution, so a mock cannot set them.` + ) + } blockMocks.set(blockId, output) } return { - triggerType: 'test' as const, - sideEffectPolicy: new WriteStubPolicy({ - workflowId, - allowBlockIds, - blockMocks, - pausingBlocks: 'stub', - }), + triggerType: TEST_TRIGGER, + sideEffectPolicy: new WriteStubPolicy({ workflowId, allowBlockIds, blockMocks }), } } @@ -338,22 +346,17 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU const blockId = resolveBlockSelector(state, input.blockId, 'run.entry.blockId') const stopAfterBlockId = resolveStopAfterBlock(state, input.stopAfterBlockId, blockId) - const sourceSnapshot = await getExecutionStateForWorkflow(input.sourceRunId, context.workflowId) + const sourceSnapshot = await getExecutionStateForWorkflow( + input.sourceRunId, + context.workflowId, + { allowTestRun: input.dry === true } + ) if (!sourceSnapshot) { throw new OrchestrationError( 'not_found', `No execution state found for source run "${input.sourceRunId}" in this workflow.` ) } - if ( - !input.dry && - (await getWorkflowExecutionLogTrigger(input.sourceRunId, context.workflowId)) === 'test' - ) { - throw new OrchestrationError( - 'validation', - `run.entry.sourceRunId "${input.sourceRunId}" is a test run (a dry run or a workflow test): its upstream outputs include placeholders for writes it did not send. Add run.dry to rerun it dry, or rerun from a run that was not a test.` - ) - } const result = await executeWorkflowService({ ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), diff --git a/apps/sim/lib/workflows/application/read-workflow-run.ts b/apps/sim/lib/workflows/application/read-workflow-run.ts index b7b68ca46e0..a1916ef5799 100644 --- a/apps/sim/lib/workflows/application/read-workflow-run.ts +++ b/apps/sim/lib/workflows/application/read-workflow-run.ts @@ -15,7 +15,6 @@ import { getWorkflowRunFiles, type WorkflowRunFileDescriptor, } from '@/lib/workflows/executor/execution-run-files' -import { getWorkflowExecutionDryRun } from '@/lib/workflows/executor/execution-state' import { getProjectedWorkflowExecutionStatus, projectPausedRunPoints, @@ -95,6 +94,7 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ stateExecutionId, pausePoints: loadedPausePoints, failedBlock, + dryRun, } = projected /** @@ -189,17 +189,6 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ ) : undefined - /** - * A failed dry run's allowed and mocked blocks, which its rerun passes again. The mocks are - * outputs, so a group that withholds execution data withholds them too. - * - * permission-group-enforced: logs.trace_spans - */ - const dryRun = - status.status === 'failed' && !projection.hideTraceSpans - ? await getWorkflowExecutionDryRun(stateExecutionId, context.workflowId) - : null - return { ...status, files, diff --git a/apps/sim/lib/workflows/application/run-workflow-for-test.ts b/apps/sim/lib/workflows/application/run-workflow-for-test.ts index 6c3a0431a38..16d26b389ab 100644 --- a/apps/sim/lib/workflows/application/run-workflow-for-test.ts +++ b/apps/sim/lib/workflows/application/run-workflow-for-test.ts @@ -21,6 +21,7 @@ import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import type { ExecutionTestHooks } from '@/executor/execution/types' import type { ExecutionResult } from '@/executor/types' import { attachAttemptedExecutionId } from '@/executor/utils/errors' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' export type WorkflowTestVersion = 'draft' | 'deployed' @@ -45,8 +46,9 @@ export interface RunWorkflowForTestInput { /** * One workflow run inside a workflow test: the workflow's single runnable trigger, the * test's input, and its mocks installed as executor test hooks. A write the test does not mock - * is not sent: as in a dry run, it is answered with a placeholder shaped like the tool's output. - * Billed and logged like any run, under the `test` trigger. + * is not sent: as in a dry run, it is answered with a placeholder shaped like the tool's output, + * and so is a Human in the loop or Wait block, so the run never pauses. Billed and logged like any + * run, under the `test` trigger. * * A step of the `workflow_tests.run` operation, which authorized the caller's write access to * the workspace before any test ran; nothing else may call it. Each nested run is not @@ -132,13 +134,13 @@ export async function runWorkflowForTest( enabled: true, principal, useDraftState, - workflowTriggerType: 'test', + workflowTriggerType: TEST_TRIGGER, enforceCredentialAccess: true, triggerBlockId: prepared.triggerBlockId, abortSignal: input.abortSignal, billingAttribution, testHooks: input.testHooks, - sideEffects: new WriteStubPolicy({ workflowId: context.workflowId, pausingBlocks: 'run' }), + sideEffects: new WriteStubPolicy({ workflowId: context.workflowId }), }, executionId ) diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 86c5486b610..b7c822bd499 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -14,26 +14,31 @@ import type { NormalizedBlockOutput } from '@/executor/types' /** Each list keeps at most this many entries; `omitted` counts the rest per list. */ const MAX_RECORDED = 50 -/** - * The one write tool a policy always sends: `function_execute` runs code (a Function block's, a - * Condition's expressions, or code an Agent's model wrote), which is the workflow's own logic - * rather than a side effect. Code other than a Condition's is listed as unchecked, since it can - * make network calls the run cannot see. - */ -const CODE_TOOL_ID = 'function_execute' +type ToolRuns = 'runs-code' | 'runs-workflow' | 'runs-custom-block' /** - * The tool an Agent calls a custom block with. A custom block runs its publisher's workflow, so a - * policy answers it whole, like the block on a canvas, and never runs it. + * Write tools a policy decides by what they run rather than by their block: + * - `runs-code`: `function_execute` runs code (a Function block's, a Condition's expressions, or + * code an Agent's model wrote), which is the workflow's own logic rather than a side effect, so + * it is sent; code other than a Condition's is listed as unchecked, since it can make network + * calls the run cannot see. + * - `runs-workflow`: `workflow_executor` runs a child workflow, which inherits the policy and + * decides its own writes, so it is sent. + * - `runs-custom-block`: `deployed_block_executor` runs a custom block's publisher workflow, so it + * is answered whole, like the block on a canvas, and never runs. */ -const CUSTOM_BLOCK_TOOL_ID = 'deployed_block_executor' +const TOOLS_DECIDED_BY_WHAT_THEY_RUN: ReadonlyMap = new Map([ + ['function_execute', 'runs-code'], + ['workflow_executor', 'runs-workflow'], + ['deployed_block_executor', 'runs-custom-block'], +]) /** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) /** - * Blocks that pause the run. A paused run resumes later without its dry run, so a dry run - * answers them whole and never pauses; they cannot be allowed. + * Blocks that pause the run. A test run is never resumed, so a policy answers them whole and the + * run never pauses; they cannot be allowed. */ export const PAUSING_BLOCK_TYPES: ReadonlySet = new Set([ ...HUMAN_IN_THE_LOOP_BLOCK_TYPES, @@ -125,10 +130,11 @@ class RecordedList { * The side-effect policy of a dry run (`run.dry`) and of a workflow test's unmocked writes: every * write tool call is answered with a placeholder shaped like the tool's output and recorded with * the request it would have sent, except an allowed block's, which are sent and recorded once per - * block and tool. Reads always run. Custom blocks and blocks that act outside the tool seam are - * answered whole; `pausingBlocks: 'stub'` also answers {@link PAUSING_BLOCK_TYPES} whole, and - * `blockMocks` answers its blocks with fixed outputs. Allowed and mocked blocks are blocks of the - * workflow the run started, never of a child it calls. + * block and tool. Reads always run. Custom blocks, blocks that act outside the tool seam and + * {@link PAUSING_BLOCK_TYPES} are answered whole, and `blockMocks` answers its blocks with fixed + * outputs. Allowed and mocked blocks are blocks of the workflow the run started, never of a child + * it calls, and an allowed Agent's own tool calls are sent, not a workflow or custom block it + * calls. */ export class WriteStubPolicy implements SideEffectPolicy { private readonly stubbed = new RecordedList() @@ -145,7 +151,6 @@ export class WriteStubPolicy implements SideEffectPolicy { allowBlockIds?: ReadonlySet /** Its blocks answered with these outputs instead of running. */ blockMocks?: ReadonlyMap - pausingBlocks: 'run' | 'stub' } ) { this.allowBlockIds = options.allowBlockIds ?? new Set() @@ -168,8 +173,10 @@ export class WriteStubPolicy implements SideEffectPolicy { } decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' { - if (call.toolId === CUSTOM_BLOCK_TOOL_ID) return 'stub' - if (call.toolId === CODE_TOOL_ID) { + const runs = TOOLS_DECIDED_BY_WHAT_THEY_RUN.get(call.toolId) + if (runs === 'runs-custom-block') return 'stub' + if (runs === 'runs-workflow') return 'send' + if (runs === 'runs-code') { if (call.blockType !== BlockType.CONDITION) { this.unchecked.add( { ...recordedSite(call), reason: uncheckedCodeReason(call.blockType) }, @@ -194,9 +201,7 @@ export class WriteStubPolicy implements SideEffectPolicy { answersBlock(block: SideEffectBlockSite): boolean { if (this.mockOf(block)) return true - if (this.options.pausingBlocks === 'stub' && PAUSING_BLOCK_TYPES.has(block.blockType)) { - return true - } + if (PAUSING_BLOCK_TYPES.has(block.blockType)) return true if (isCustomBlockType(block.blockType)) return true if (!SELF_DIRECTED_BLOCK_TYPES.has(block.blockType)) return false if (!this.allows(block)) return true @@ -213,9 +218,12 @@ export class WriteStubPolicy implements SideEffectPolicy { return returned } - /** The allowed and mocked blocks, which a rerun of this run passes again. */ + /** + * The allowed and mocked blocks, by id, which a rerun of this run passes again. Never the mock + * outputs: they may carry secrets or personal data, and the run's log keeps this record. + */ runOptions(): DryRunOptions { - return { allowBlocks: [...this.allowBlockIds], mocks: Object.fromEntries(this.blockMocks) } + return { allowBlocks: [...this.allowBlockIds], mockedBlocks: [...this.blockMocks.keys()] } } summary(): SideEffectsSummary { diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index d200d98181d..3d0cf83c0eb 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -163,7 +163,7 @@ export interface ExecuteWorkflowServiceParams { * A dry run's side-effect policy, built by the application use case: writes are answered with * placeholders, and what each would have sent is returned as the run's `sideEffects`, failed * runs included. Requires `useDraftState` and a `sync` or non-detachable `sync-result-stream` - * run, the modes that return the run's result. + * run that returns its whole result, never rejecting a large inline response. */ sideEffectPolicy?: WriteStubPolicy } @@ -270,6 +270,9 @@ function rerunStartOf( return error?.blockId ? findRerunStartBlockId(error.blockId, blocks) : undefined } +/** The label a response too large to return inline is rejected under. */ +const WORKFLOW_RESPONSE_LABEL = 'Workflow execution response' + function failure(f: ExecuteWorkflowServiceFailure): ExecuteWorkflowServiceFailureResult { return { ok: false, failure: f } } @@ -292,14 +295,14 @@ async function compactServiceOutput( preserveUserFileBase64: true, preserveRoot: !context.rejectLargeInlineOutput, rejectLargeValues: context.rejectLargeInlineOutput, - rejectLargeValueLabel: 'Workflow execution response', + rejectLargeValueLabel: WORKFLOW_RESPONSE_LABEL, thresholdBytes: context.rejectLargeInlineOutput ? MAX_MCP_WORKFLOW_RESPONSE_BYTES : undefined, requireDurable: true, }) if (context.rejectLargeInlineOutput && containsLargeValueRef(compacted)) { throw new PayloadSizeLimitError({ - label: 'Workflow execution response', + label: WORKFLOW_RESPONSE_LABEL, maxBytes: MAX_MCP_WORKFLOW_RESPONSE_BYTES, observedBytes: MAX_MCP_WORKFLOW_RESPONSE_BYTES + 1, }) @@ -377,8 +380,8 @@ export async function executeWorkflowService( if (sideEffectPolicy && !useDraftState) { throw new Error('A dry run requires manual execution state') } - if (sideEffectPolicy && (mode === 'stream' || detachable)) { - throw new Error('A dry run returns its side effects with the result it waits for') + if (sideEffectPolicy && (mode === 'stream' || detachable || rejectLargeInlineOutput)) { + throw new Error('A dry run returns its side effects with the whole result it waits for') } if (detachable && (mode !== 'sync-result-stream' || abortSignal)) { throw new Error('A detachable run returns its pending result and outlives its request') @@ -781,6 +784,20 @@ export async function executeWorkflowService( rejectLargeInlineOutput, } + /** The failure a response too large to return inline maps to; null for any other error. */ + const responseTooLarge = (error: unknown): ExecuteWorkflowServiceFailureResult | null => + error instanceof PayloadSizeLimitError && + rejectLargeInlineOutput && + error.label === WORKFLOW_RESPONSE_LABEL + ? failure({ + kind: 'output_too_large', + message: `${WORKFLOW_RESPONSE_LABEL} exceeds maximum size`, + statusCode: 413, + code: 'workflow_response_too_large', + executionId, + }) + : null + const runSynchronousWorkflow = async (): Promise => { if (detachable) registerManualExecutionAborter(executionId, timeoutController.abort) try { @@ -929,19 +946,8 @@ export async function executeWorkflowService( } } - if ( - error instanceof PayloadSizeLimitError && - rejectLargeInlineOutput && - error.label === 'Workflow execution response' - ) { - return failure({ - kind: 'output_too_large', - message: 'Workflow execution response exceeds maximum size', - statusCode: 413, - code: 'workflow_response_too_large', - executionId, - }) - } + const tooLarge = responseTooLarge(error) + if (tooLarge) return tooLarge logFailureOnce(reqLogger, `Execution failed: ${errorMessage}`, error, { executionId }) @@ -958,19 +964,8 @@ export async function executeWorkflowService( compactionContext ) } catch (compactError) { - if ( - compactError instanceof PayloadSizeLimitError && - rejectLargeInlineOutput && - compactError.label === 'Workflow execution response' - ) { - return failure({ - kind: 'output_too_large', - message: 'Workflow execution response exceeds maximum size', - statusCode: 413, - code: 'workflow_response_too_large', - executionId, - }) - } + const tooLarge = responseTooLarge(compactError) + if (tooLarge) return tooLarge throw compactError } } @@ -1008,8 +1003,9 @@ export async function executeWorkflowService( /** * A dry run's side effects on its result, whatever its status: a failed run's allowed writes - * were sent all the same. Compacted like the run's output, and mapped the same way when too - * large; a summary that cannot be compacted otherwise keeps every entry without its request. + * were sent all the same. A dry run never rejects a large inline response (refused above), so + * its result is always a run that carries them. Compacted like the run's output; a summary + * that cannot be compacted keeps every entry without its request. */ const withSideEffects = async ( result: UnstampedTerminalResult @@ -1024,19 +1020,6 @@ export async function executeWorkflowService( dryRun, } } catch (error) { - if ( - error instanceof PayloadSizeLimitError && - rejectLargeInlineOutput && - error.label === 'Workflow execution response' - ) { - return failure({ - kind: 'output_too_large', - message: 'Workflow execution response exceeds maximum size', - statusCode: 413, - code: 'workflow_response_too_large', - executionId, - }) - } reqLogger.warn('Failed to compact dry-run side effects; returning them without requests', { error: getErrorMessage(error), }) diff --git a/apps/sim/lib/workflows/executor/execution-core.test.ts b/apps/sim/lib/workflows/executor/execution-core.test.ts index 810090f6912..964a6d8cbda 100644 --- a/apps/sim/lib/workflows/executor/execution-core.test.ts +++ b/apps/sim/lib/workflows/executor/execution-core.test.ts @@ -190,6 +190,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { hasCompleted: hasCompletedMock, getPersistedCompletionStatus: getPersistedCompletionStatusMock, getDeletedScope: getDeletedScopeMock, + getTriggerType: () => 'manual', onBlockStart: onBlockStartPersistenceMock, onBlockComplete: vi.fn(), projectDisplayContent: projectDisplayContentMock, diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index 82f027df8c6..2e26957de35 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -81,6 +81,7 @@ import { } from '@/executor/utils/subflow-node-id-codec' import { Serializer } from '@/serializer' import type { SerializedWorkflow } from '@/serializer/types' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' const logger = createLogger('ExecutionCore') @@ -331,14 +332,15 @@ function logTriggerData(metadata: ExecutionMetadata): Record | * workflow and stamps `lastRunAt`. Paused runs are not settled and are counted * when they finish. Awaited from the finalization path rather than fired and * forgotten, so a process reload after the log write cannot drop it. A run - * whose workspace or workflow was deleted has no row left to count on. + * whose workspace or workflow was deleted has no row left to count on, and a + * test run (a dry run or a workflow test) changes nothing beyond its own log. */ async function recordSettledRun( workflowId: string, requestId: string, loggingSession: LoggingSession ): Promise { - if (loggingSession.getDeletedScope()) return + if (loggingSession.getDeletedScope() || loggingSession.getTriggerType() === TEST_TRIGGER) return try { await updateWorkflowRunCounts(workflowId) } catch (error) { @@ -369,14 +371,6 @@ function buildTraceSpansForLog( } } -/** - * Whether a settled run counts on its workflow. A test run (a dry run or a workflow test) changes - * nothing beyond its own log, so it does not. - */ -function countsAsRun(triggerType: string): boolean { - return triggerType !== 'test' -} - async function finalizeExecutionOutcome(params: { result: ExecutionResult loggingSession: LoggingSession @@ -385,18 +379,9 @@ async function finalizeExecutionOutcome(params: { requestId: string workflowInput: unknown abortSignal?: AbortSignal - triggerType: string }): Promise { - const { - result, - loggingSession, - workflowId, - executionId, - requestId, - workflowInput, - abortSignal, - triggerType, - } = params + const { result, loggingSession, workflowId, executionId, requestId, workflowInput, abortSignal } = + params const { traceSpans, totalDuration } = buildTraceSpansForLog( result, loggingSession, @@ -464,7 +449,7 @@ async function finalizeExecutionOutcome(params: { } // Every non-paused outcome above is a settled run; the paused branch returned. - if (countsAsRun(triggerType)) await recordSettledRun(workflowId, requestId, loggingSession) + await recordSettledRun(workflowId, requestId, loggingSession) } async function finalizeExecutionError(params: { @@ -475,10 +460,8 @@ async function finalizeExecutionError(params: { requestId: string /** The input the executor ran with; absent when the run failed before its input stage finished. */ workflowInput: unknown - triggerType: string }): Promise { - const { error, loggingSession, workflowId, executionId, requestId, workflowInput, triggerType } = - params + const { error, loggingSession, workflowId, executionId, requestId, workflowInput } = params const executionResult = hasExecutionResult(error) ? error.executionResult : undefined const { traceSpans } = executionResult ? buildTraceSpansForLog(executionResult, loggingSession, requestId, executionId) @@ -511,7 +494,7 @@ async function finalizeExecutionError(params: { } // A run that threw after starting is a failed run, and failed runs count. - if (countsAsRun(triggerType)) await recordSettledRun(workflowId, requestId, loggingSession) + await recordSettledRun(workflowId, requestId, loggingSession) return finalized } @@ -1440,7 +1423,6 @@ async function executeWorkflowCoreImpl( requestId, workflowInput: processedInput, abortSignal, - triggerType, }) } catch (postExecError) { logger.error( @@ -1500,7 +1482,6 @@ async function executeWorkflowCoreImpl( executionId, requestId, workflowInput: executorInput, - triggerType, }) : false diff --git a/apps/sim/lib/workflows/executor/execution-state.ts b/apps/sim/lib/workflows/executor/execution-state.ts index 64916b9f60a..25ef34086f1 100644 --- a/apps/sim/lib/workflows/executor/execution-state.ts +++ b/apps/sim/lib/workflows/executor/execution-state.ts @@ -1,17 +1,19 @@ import { db } from '@sim/db' import { pausedExecutions, workflowExecutionLogs } from '@sim/db/schema' -import { filterUndefined, isPlainRecord, isRecordLike } from '@sim/utils/object' -import { and, desc, eq, or, sql } from 'drizzle-orm' +import { filterUndefined, isRecordLike } from '@sim/utils/object' +import { and, desc, eq, ne, or, sql } from 'drizzle-orm' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { getBaseUrl } from '@/lib/core/utils/urls' import { materializeExecutionData, TRACE_STORE_REF_KEY } from '@/lib/logs/execution/trace-store' import { forceFailedMessage } from '@/lib/workflows/executor/failure-message' import { buildResumeUiUrl } from '@/executor/constants' -import type { DryRunOptions, SerializableExecutionState } from '@/executor/execution/types' +import type { SerializableExecutionState } from '@/executor/execution/types' import type { PausePoint } from '@/executor/types' import { isResolvedSecretTraceProvenanceV1, type ResolvedSecretTraceProvenanceV1, } from '@/executor/utils/resolved-secret-trace-registry' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' const LATEST_EXECUTION_STATE_CANDIDATE_LIMIT = 10 @@ -63,6 +65,7 @@ interface ExecutionStateRow { workflowId: string | null workspaceId: string status?: string + trigger?: string executionData: unknown } @@ -99,6 +102,7 @@ async function getExecutionStateRow( workflowId: workflowExecutionLogs.workflowId, workspaceId: workflowExecutionLogs.workspaceId, status: workflowExecutionLogs.status, + trigger: workflowExecutionLogs.trigger, executionData: workflowExecutionLogs.executionData, }) .from(workflowExecutionLogs) @@ -132,11 +136,23 @@ async function extractExecutionStateFromRow( return extractExecutionState(executionData) } +/** + * The execution state a run that starts from a block reuses as its source. A test run (a dry run + * or a workflow test) answered its writes with placeholders, so its state is the source only of + * another dry run, which says so with `allowTestRun`; any other run is refused it. + */ export async function getExecutionStateForWorkflow( executionId: string, - workflowId: string + workflowId: string, + { allowTestRun = false }: { allowTestRun?: boolean } = {} ): Promise { const row = await getExecutionStateRow(executionId, workflowId) + if (row?.trigger === TEST_TRIGGER && !allowTestRun) { + throw new OrchestrationError( + 'validation', + `Execution "${executionId}" is a test run (a dry run or a workflow test): its outputs hold placeholders for the writes it did not send, so only a dry run can start from it. Start from a run that was not a test, or run dry.` + ) + } return extractExecutionStateFromRow(row) } @@ -158,61 +174,6 @@ export async function getWorkflowExecutionLogStatus( return row?.status } -/** The trigger an execution's workflow log recorded, or `undefined` when it never started one. */ -export async function getWorkflowExecutionLogTrigger( - executionId: string, - workflowId: string -): Promise { - const [row] = await db - .select({ trigger: workflowExecutionLogs.trigger }) - .from(workflowExecutionLogs) - .where( - and( - eq(workflowExecutionLogs.executionId, executionId), - eq(workflowExecutionLogs.workflowId, workflowId) - ) - ) - .limit(1) - return row?.trigger -} - -/** - * A dry run's allowed and mocked blocks, as its log's trigger recorded them; null for any other - * run, or a record not in the shape a dry run writes. - */ -export async function getWorkflowExecutionDryRun( - executionId: string, - workflowId: string -): Promise { - const [row] = await db - .select({ - dryRun: sql`${workflowExecutionLogs.executionData} #> '{trigger,data,dryRun}'`, - }) - .from(workflowExecutionLogs) - .where( - and( - eq(workflowExecutionLogs.executionId, executionId), - eq(workflowExecutionLogs.workflowId, workflowId) - ) - ) - .limit(1) - const dryRun = row?.dryRun - if (!isPlainRecord(dryRun) || !isPlainRecord(dryRun.mocks)) return null - const { allowBlocks } = dryRun - if (!Array.isArray(allowBlocks)) return null - const allowed: string[] = [] - for (const blockId of allowBlocks) { - if (typeof blockId !== 'string') return null - allowed.push(blockId) - } - const mocks: DryRunOptions['mocks'] = {} - for (const [blockId, output] of Object.entries(dryRun.mocks)) { - if (!isPlainRecord(output)) return null - mocks[blockId] = output - } - return { allowBlocks: allowed, mocks } -} - /** The log's own correlation wins; older logs carried it only on the trigger data. */ function selectCorrelation( topLevel: unknown, @@ -373,6 +334,10 @@ export async function getExecutionInputForWorkflow( return { found: true, input: extractLegacyWorkflowInput(data) } } +/** + * The newest run of the workflow with execution state, the source a run from a block reuses when + * it names none. Never a test run: see {@link getExecutionStateForWorkflow}. + */ export async function getLatestExecutionStateWithExecutionId( workflowId: string ): Promise { @@ -388,6 +353,7 @@ export async function getLatestExecutionStateWithExecutionId( .where( and( eq(workflowExecutionLogs.workflowId, workflowId), + ne(workflowExecutionLogs.trigger, TEST_TRIGGER), or( sql`${workflowExecutionLogs.executionData} -> 'executionState' IS NOT NULL`, sql`${workflowExecutionLogs.executionData} -> ${TRACE_STORE_REF_KEY} IS NOT NULL` diff --git a/apps/sim/lib/workflows/executor/execution-status.ts b/apps/sim/lib/workflows/executor/execution-status.ts index 51bcbf9ca8a..1bfc67468be 100644 --- a/apps/sim/lib/workflows/executor/execution-status.ts +++ b/apps/sim/lib/workflows/executor/execution-status.ts @@ -7,6 +7,7 @@ import { } from '@sim/db/schema' import { compareStrings } from '@sim/utils/string' import { and, eq, inArray, sql } from 'drizzle-orm' +import { v2RunDryRunSchema } from '@/lib/api/contracts/v2/workflows' import type { WorkflowExecutionStatusResponse } from '@/lib/api/contracts/workflows' import { getJobQueue } from '@/lib/core/async-jobs' import type { Job } from '@/lib/core/async-jobs/types' @@ -29,7 +30,9 @@ import { runFailureMessage } from '@/lib/workflows/executor/failure-message' import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' import { namePausePoints, pauseBaseBlockId } from '@/lib/workflows/executor/pause-block-names' import { getAutomaticResumeWaitingMetadata } from '@/lib/workflows/executor/paused-execution-metadata' +import type { DryRunOptions } from '@/executor/execution/types' import type { PauseInputField, PausePoint, ResumeStatus } from '@/executor/types' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' /** * Reads a single execution's status resource — the log row, the paused-state @@ -45,6 +48,7 @@ type LogStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' interface ExecutionDataShape { finalOutput?: unknown traceSpans?: unknown + trigger?: { data?: { dryRun?: unknown } } } function resolvePath(value: unknown, path: string[]): unknown { @@ -265,6 +269,13 @@ export interface ProjectedWorkflowExecutionStatus { * permission-group-enforced: logs.trace_spans */ failedBlock: FailedTraceBlock | null + /** + * A failed dry run's allowed and mocked blocks, which a rerun of it names again; null for any + * other run, or when the viewer's group withholds execution data. + * + * permission-group-enforced: logs.trace_spans + */ + dryRun: DryRunOptions | null } /** @@ -297,6 +308,7 @@ export async function getProjectedWorkflowExecutionStatus( stateExecutionId: resolved.stateExecutionId, pausePoints: resolved.pausePoints, failedBlock: projection.hideTraceSpans ? null : resolved.failedBlock, + dryRun: projection.hideTraceSpans ? null : resolved.dryRun, } } @@ -361,6 +373,8 @@ interface ResolvedExecutionStatus { pausePoints: unknown /** The failing block the recorded trace names, when the answered `error` is the run's own. */ failedBlock: FailedTraceBlock | null + /** A failed dry run's allowed and mocked blocks, as its log's trigger recorded them. */ + dryRun: DryRunOptions | null } async function readWorkflowExecutionStatus( @@ -450,6 +464,7 @@ async function readWorkflowExecutionStatus( stateExecutionId: executionId, pausePoints: null, failedBlock: null, + dryRun: null, } } } @@ -472,7 +487,13 @@ async function readWorkflowExecutionStatus( finalOutput: null, blockOutputs: null, } - return { status, stateExecutionId: executionId, pausePoints: null, failedBlock: null } + return { + status, + stateExecutionId: executionId, + pausePoints: null, + failedBlock: null, + dryRun: null, + } } if (!logRow) { @@ -489,6 +510,7 @@ async function readWorkflowExecutionStatus( pausePoints: run.pausePoints, failedBlock: status.status === 'failed' && run.status.status === 'failed' ? run.failedBlock : null, + dryRun: null, } } @@ -573,6 +595,7 @@ async function readWorkflowExecutionStatus( stateExecutionId: executionId, pausePoints: paused ? pausedRow?.pausePoints : null, failedBlock: null, + dryRun: null, } } @@ -607,9 +630,21 @@ async function readWorkflowExecutionStatus( stateExecutionId: executionId, pausePoints: paused ? pausedRow?.pausePoints : null, failedBlock: error ? findFailedTraceBlock(executionData?.traceSpans, error) : null, + dryRun: + status === 'failed' && logRow.trigger === TEST_TRIGGER ? readDryRun(executionData) : null, } } +/** + * A dry run's allowed and mocked blocks from its log's trigger, recovered with the rest of the + * execution data however it was stored; null for a test run that recorded none (a workflow test) + * or a record not in that shape. + */ +function readDryRun(executionData: ExecutionDataShape | null): DryRunOptions | null { + const parsed = v2RunDryRunSchema.safeParse(executionData?.trigger?.data?.dryRun) + return parsed.success ? parsed.data : null +} + /** * Most pause points a run detail lists. A run that pauses again after resuming keeps its * resumed points, so a run over the cap keeps every point not yet resumed before any resumed diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts index d0e124aaa75..222b586fbd6 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts @@ -85,6 +85,7 @@ import { filterOutputForLog } from '@/executor/utils/output-filter' import { projectResolvedSecretDiagnosticError } from '@/executor/utils/resolved-secret-content-projection' import { stripLoopDigest } from '@/executor/utils/subflow-node-id-codec' import type { SerializedConnection } from '@/serializer/types' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' /** * All paused-execution / resume-queue / execution-log persistence in this @@ -822,6 +823,28 @@ export class PauseResumeManager { throw new ResumeAdmissionError('Paused execution is not resumable', 409, false) } + /** + * A test run (a dry run or a workflow test) answered its writes with placeholders, and a + * resumed run carries no side-effect policy, so resuming it would send writes built on them. + */ + const [pausedLog] = await tx + .select({ trigger: workflowExecutionLogs.trigger }) + .from(workflowExecutionLogs) + .where( + and( + eq(workflowExecutionLogs.executionId, executionId), + eq(workflowExecutionLogs.workflowId, workflowId) + ) + ) + .limit(1) + if (pausedLog?.trigger === TEST_TRIGGER) { + throw new ResumeAdmissionError( + 'A test run (a dry run or a workflow test) is never resumed: its outputs hold placeholders for the writes it did not send', + 409, + false + ) + } + const pausePoints = pausedExecution.pausePoints as Record const pausePoint = pausePoints?.[contextId] if (!pausePoint) { diff --git a/apps/sim/lib/workspace-events/constants.ts b/apps/sim/lib/workspace-events/constants.ts index 4f160b1c9f6..6e7028407ed 100644 --- a/apps/sim/lib/workspace-events/constants.ts +++ b/apps/sim/lib/workspace-events/constants.ts @@ -6,6 +6,8 @@ * dependencies such as the database client. */ +import { TEST_TRIGGER } from '@/stores/logs/filters/types' + /** Provider string recorded on webhook rows and execution logs for Sim trigger runs. */ export const SIM_TRIGGER_PROVIDER = 'sim' @@ -14,7 +16,7 @@ export const SIM_TRIGGER_PROVIDER = 'sim' * (loop prevention), and test runs (a dry run or a workflow test), which change nothing beyond * their own log. */ -export const EVENTLESS_EXECUTION_TRIGGERS: readonly string[] = [SIM_TRIGGER_PROVIDER, 'test'] +export const EVENTLESS_EXECUTION_TRIGGERS: readonly string[] = [SIM_TRIGGER_PROVIDER, TEST_TRIGGER] /** Trigger ID in the trigger registry. Must equal the block type for pure trigger blocks. */ export const SIM_WORKSPACE_EVENT_TRIGGER_ID = 'sim_workspace_event' diff --git a/apps/sim/providers/file-attachments.server.test.ts b/apps/sim/providers/file-attachments.server.test.ts index 9834ff06acc..0f54584362c 100644 --- a/apps/sim/providers/file-attachments.server.test.ts +++ b/apps/sim/providers/file-attachments.server.test.ts @@ -39,9 +39,10 @@ const mockDownloadServableFileFromStorage = const mockHasCloudStorage = storageServiceMockFns.mockHasCloudStorage const mockGeneratePresignedDownloadUrl = storageServiceMockFns.mockGeneratePresignedDownloadUrl -const { mockAssertUserFileContentAccess, mockGoogleUpload } = vi.hoisted(() => ({ +const { mockAssertUserFileContentAccess, mockGoogleUpload, mockGoogleDelete } = vi.hoisted(() => ({ mockAssertUserFileContentAccess: vi.fn(), mockGoogleUpload: vi.fn(), + mockGoogleDelete: vi.fn(), })) vi.mock('@/lib/internal/principals/executor', () => executorPrincipalMock) @@ -53,7 +54,7 @@ vi.mock('@/lib/execution/payloads/materialization.server', () => ({ vi.mock('@google/genai', () => ({ FileState: { PROCESSING: 'PROCESSING', FAILED: 'FAILED' }, GoogleGenAI: class { - files = { upload: mockGoogleUpload } + files = { upload: mockGoogleUpload, delete: mockGoogleDelete } }, })) @@ -283,6 +284,45 @@ describe('OpenAI large-file attachment lifecycle', () => { } ) + it('can delete every OpenAI file that landed when a later upload fails', async () => { + const request = makeRequest(CSV_BYTES) + const [first] = request.messages?.[0].files ?? [] + request.messages?.[0].files?.push({ ...first, id: 'file-2', key: `${first.key}-2` }) + const sent = vi.fn(async (_url: string, init: RequestInit) => + init.method === 'DELETE' + ? new Response(null, { status: 200 }) + : sent.mock.calls.filter(([, call]) => call.method === 'POST').length === 1 + ? Response.json({ id: 'file-landed' }) + : new Response('overloaded', { status: 503 }) + ) + vi.stubGlobal('fetch', sent) + const removals: Array<() => Promise> = [] + + await attachLargeFileRemoteUrls(request, 'openai') + await expect( + uploadLargeFilesToProvider(request, 'openai', undefined, removals) + ).rejects.toThrow('503') + await Promise.all(removals.map((remove) => remove())) + + expect(sent.mock.calls.filter(([, init]) => init.method === 'DELETE')).toEqual([ + ['https://api.openai.com/v1/files/file-landed', expect.anything()], + ]) + }) + + it('can delete a Gemini file whose processing failed after it landed', async () => { + mockGoogleUpload.mockResolvedValueOnce({ name: 'files/failed', state: 'FAILED' }) + const request = makeRequest(CSV_BYTES) + const removals: Array<() => Promise> = [] + + await attachLargeFileRemoteUrls(request, 'google') + await expect( + uploadLargeFilesToProvider(request, 'google', undefined, removals) + ).rejects.toThrow('processing failed') + await Promise.all(removals.map((remove) => remove())) + + expect(mockGoogleDelete).toHaveBeenCalledWith({ name: 'files/failed' }) + }) + it('does not mint a remote URL after execution authorization fails', async () => { mockCreateExecutorPrincipal.mockRejectedValueOnce(new Error('Run no longer active')) await expect( diff --git a/apps/sim/providers/file-attachments.server.ts b/apps/sim/providers/file-attachments.server.ts index ba5c1d2e7a2..c2b5843bf40 100644 --- a/apps/sim/providers/file-attachments.server.ts +++ b/apps/sim/providers/file-attachments.server.ts @@ -132,36 +132,31 @@ export async function attachLargeFileRemoteUrls( } } -/** The files one request uploaded to a provider's Files API. */ -export interface ProviderFileUploads { - /** - * Deletes them from the provider account. Best effort: a failure is logged, and the files - * expire on their own (OpenAI's after {@link OPENAI_FILE_EXPIRY_SECONDS}, Gemini's in 48 hours). - */ - remove(): Promise -} +/** + * Deletes one uploaded file from the provider account. Best effort: a failure is logged, and the + * file expires on its own (OpenAI's after {@link OPENAI_FILE_EXPIRY_SECONDS}, Gemini's in 48 + * hours). + */ +export type ProviderFileRemoval = () => Promise /** * For `files-api` providers, uploads each large attachment (already carrying a signed * `remoteUrl` from {@link attachLargeFileRemoteUrls}) to the provider Files API and records * the returned handle on the file. Runs after the request's API key is resolved so hosted - * and BYOK keys both work. + * and BYOK keys both work. Each file's removal is pushed onto `removals` the moment the provider + * names it, so a caller that deletes its uploads deletes every one that landed, even when a later + * upload, or the provider's processing of this one, fails. */ export async function uploadLargeFilesToProvider( request: ProviderRequest, providerId: ProviderId | string, - executionContext?: ExecutionContext -): Promise { - const removals: Array<() => Promise> = [] - const uploads: ProviderFileUploads = { - remove: async () => { - for (const removal of removals.splice(0)) await removal() - }, - } - if (getProviderFileStrategy(providerId) !== 'files-api') return uploads + executionContext?: ExecutionContext, + removals: ProviderFileRemoval[] = [] +): Promise { + if (getProviderFileStrategy(providerId) !== 'files-api') return const groups = groupUploadableFiles(request.messages) - if (groups.length === 0) return uploads + if (groups.length === 0) return const maxBytes = getProviderAttachmentMaxBytes(providerId) const ai = @@ -173,23 +168,21 @@ export async function uploadLargeFilesToProvider( const [representative] = group await assertFileAccessForUpload(representative, request.userId, executionContext) if (providerId === 'openai') { - const fileId = await uploadOpenAIFile( + await uploadOpenAIFile( representative, request.apiKey, maxBytes, + removals, request.abortSignal ) - removals.push(() => deleteOpenAIFile(fileId, request.apiKey)) } else if (ai) { - const name = await uploadGeminiFile(representative, ai, maxBytes, request.abortSignal) - removals.push(() => deleteGeminiFile(name, ai)) + await uploadGeminiFile(representative, ai, maxBytes, removals, request.abortSignal) } for (const file of group) { file.providerFileId = representative.providerFileId file.providerFileUri = representative.providerFileUri } } - return uploads } /** @@ -266,8 +259,9 @@ async function uploadOpenAIFile( file: UserFile, apiKey: string | undefined, maxBytes: number, + removals: ProviderFileRemoval[], signal?: AbortSignal -): Promise { +): Promise { const mimeType = inferAttachmentMimeType(file) const blob = await downloadFileForUpload(file, maxBytes) @@ -292,9 +286,10 @@ async function uploadOpenAIFile( if (!uploaded.id) { throw new Error(`OpenAI file upload for "${file.name}" returned no id`) } - file.providerFileId = uploaded.id - logger.info(`Uploaded "${file.name}" to OpenAI Files API`, { fileId: uploaded.id }) - return uploaded.id + const fileId = uploaded.id + removals.push(() => deleteOpenAIFile(fileId, apiKey)) + file.providerFileId = fileId + logger.info(`Uploaded "${file.name}" to OpenAI Files API`, { fileId }) } async function deleteOpenAIFile(fileId: string, apiKey: string | undefined): Promise { @@ -316,8 +311,9 @@ async function uploadGeminiFile( file: UserFile, ai: GoogleGenAI, maxBytes: number, + removals: ProviderFileRemoval[], signal?: AbortSignal -): Promise { +): Promise { const mimeType = inferAttachmentMimeType(file) const blob = await downloadFileForUpload(file, maxBytes) @@ -326,6 +322,7 @@ async function uploadGeminiFile( throw new Error(`Gemini upload for "${file.name}" returned no file name`) } const uploadedName = uploaded.name + removals.push(() => deleteGeminiFile(uploadedName, ai)) const deadline = Date.now() + GEMINI_PROCESSING_TIMEOUT_MS while (uploaded.state === FileState.PROCESSING) { @@ -343,7 +340,6 @@ async function uploadGeminiFile( } file.providerFileUri = uploaded.uri logger.info(`Uploaded "${file.name}" to Gemini File API`, { fileUri: uploaded.uri }) - return uploadedName } async function deleteGeminiFile(name: string, ai: GoogleGenAI): Promise { diff --git a/apps/sim/providers/index.test.ts b/apps/sim/providers/index.test.ts index b3cdab9ef83..ce8b32472ae 100644 --- a/apps/sim/providers/index.test.ts +++ b/apps/sim/providers/index.test.ts @@ -480,6 +480,27 @@ describe('executeProviderRequest — durable Agent continuation', () => { }) describe('executeProviderRequest — tool identities', () => { + it.each([ + ['a run under a side-effect policy deletes', { sideEffects: {} }, 1], + ['any other run leaves', {}, 0], + ])('%s the files it uploaded when a later upload fails', async (_, policy, deletions) => { + const removeLanded = vi.fn(async () => {}) + mockUploadLargeFilesToProvider.mockImplementationOnce( + async (_request, _provider, _context, removals: Array<() => Promise>) => { + removals.push(removeLanded) + throw new Error('The second upload failed') + } + ) + const executionContext = { workflowId: 'workflow-1', ...policy } as ExecutionContext + + await expect( + executeProviderRequest('openai', { model: 'test-model' }, { executionContext }) + ).rejects.toThrow('The second upload failed') + + expect(removeLanded).toHaveBeenCalledTimes(deletions) + expect(mockExecuteRequest).not.toHaveBeenCalled() + }) + it('passes trusted execution context to both attachment authorization stages without serializing it', async () => { const executionContext = { workflowId: 'workflow-1', @@ -496,7 +517,8 @@ describe('executeProviderRequest — tool identities', () => { expect(mockUploadLargeFilesToProvider).toHaveBeenCalledWith( expect.objectContaining({ model: 'test-model' }), 'anthropic', - executionContext + executionContext, + [] ) expect(mockExecuteRequest.mock.calls[0][0]).not.toHaveProperty('executionContext') expect(mockExecuteRequest.mock.calls[0][0]).not.toHaveProperty('principal') diff --git a/apps/sim/providers/index.ts b/apps/sim/providers/index.ts index a493204830d..00843c41d21 100644 --- a/apps/sim/providers/index.ts +++ b/apps/sim/providers/index.ts @@ -33,6 +33,7 @@ import { } from '@/providers/cost-policy' import { attachLargeFileRemoteUrls, + type ProviderFileRemoval, uploadLargeFilesToProvider, } from '@/providers/file-attachments.server' import { isEvaluationModel, isKnownModelId, supportsTemperature } from '@/providers/models' @@ -394,17 +395,20 @@ export async function executeProviderRequest( ) } await attachLargeFileRemoteUrls(modelSafeRequest, providerId, runtimeContext?.executionContext) - const uploads = await uploadLargeFilesToProvider( - modelSafeRequest, - providerId, - runtimeContext?.executionContext - ) /** * A run under a side-effect policy (a dry run, or a workflow test) leaves nothing on the - * provider account: its uploads are deleted once the call settles. Such a run waits for its - * result and never streams, so the call has settled when it returns here. + * provider account: every file it uploaded is deleted once the call settles, or once an + * upload fails. Such a run waits for its result and never streams, so the call has settled + * when it returns here. */ + const uploadRemovals: ProviderFileRemoval[] = [] try { + await uploadLargeFilesToProvider( + modelSafeRequest, + providerId, + runtimeContext?.executionContext, + uploadRemovals + ) if (final && session) { modelSafeRequest.abortSignal?.throwIfAborted() const usage = session.getUsage() @@ -431,7 +435,9 @@ export async function executeProviderRequest( } return await provider.executeRequest(modelSafeRequest) } finally { - if (runtimeContext?.executionContext?.sideEffects) await uploads.remove() + if (runtimeContext?.executionContext?.sideEffects) { + await Promise.all(uploadRemovals.map((remove) => remove())) + } } }) diff --git a/apps/sim/stores/logs/filters/types.ts b/apps/sim/stores/logs/filters/types.ts index a5414fe6036..c467c298ff7 100644 --- a/apps/sim/stores/logs/filters/types.ts +++ b/apps/sim/stores/logs/filters/types.ts @@ -37,6 +37,13 @@ export const CORE_TRIGGER_TYPES = [ export type CoreTriggerType = (typeof CORE_TRIGGER_TYPES)[number] +/** + * The trigger of a test run: a dry run or a workflow test. Its writes were held back, so its + * outputs hold placeholders; it keeps nothing beyond its own log and is never resumed or the + * source of a run that sends its writes. + */ +export const TEST_TRIGGER = 'test' as const satisfies CoreTriggerType + export type TriggerType = CoreTriggerType | 'all' | (string & {}) export type LogViewMode = 'logs' | 'dashboard' diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index bde362842c7..3684a87ee72 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -7493,7 +7493,7 @@ describe('MCP Tool Execution', () => { it('stubs an MCP tool in a dry run, recording only its arguments, and sends an allowed one', async () => { const fetchSpy = vi.spyOn(globalThis, 'fetch') - const dryRun = new WriteStubPolicy({ workflowId: 'test-workflow', pausingBlocks: 'stub' }) + const dryRun = new WriteStubPolicy({ workflowId: 'test-workflow' }) const params = { path: '/test', envVars: { UNREFERENCED_SECRET: 'workspace-secret-value' }, @@ -7518,7 +7518,6 @@ describe('MCP Tool Execution', () => { const allowed = new WriteStubPolicy({ workflowId: 'test-workflow', allowBlockIds: new Set(['agent-1']), - pausingBlocks: 'stub', }) await executeTool('mcp-123-delete_file', params, { executionContext: createToolExecutionContext({ sideEffects: allowed }), diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index a38bfbfdd61..b8ccf8dc01e 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -1813,11 +1813,12 @@ async function executeToolImplementation( ? { ...suppliedOperationContext, resolvedSecretTraceRegistry } : undefined /** - * A tool's own follow-up calls (a `postProcess` that writes again) run in its caller's - * `_context`, so they act for the same block: a run's side-effect policy decides them as it - * decided the call that made them. + * Under a run's side-effect policy, a tool's own follow-up calls (a `postProcess` that writes + * again) run in its caller's `_context`, so the policy decides them for the same block as the + * call that made them. Any other run passes them on as they are. */ - const callerContext = isPlainRecord(params._context) ? params._context : undefined + const callerContext = + executionContext?.sideEffects && isPlainRecord(params._context) ? params._context : undefined const executeNestedTool: typeof executeTool = (nestedToolId, nestedParams, nestedOptions = {}) => executeTool( nestedToolId, @@ -1951,7 +1952,7 @@ async function executeToolImplementation( return await answerUnsentWrite(unsentMcpWrite, { params, registry: resolvedSecretTraceRegistry, - describeRequest: () => describeMcpToolRequest(params), + request: describeMcpToolRequest(params), }) } return await executeMcpTool( @@ -2001,10 +2002,10 @@ async function executeToolImplementation( /** * Decided before a hosted key is drawn, so a write the run's side-effect policy will not send - * spends no rate-limit slot. A workflow a tool runs decides its own writes. + * spends no rate-limit slot. */ const unsentWrite = - tool.effect !== 'read' && normalizedToolId !== 'workflow_executor' + tool.effect !== 'read' ? unsentWriteFor({ toolId: normalizedToolId, params: contextParams, executionContext }) : null @@ -2250,12 +2251,10 @@ async function executeToolImplementation( // After credentials resolve, so an unsent write still proves them. if (unsentWrite) { - const unsentTool = tool return await answerUnsentWrite(unsentWrite, { params: contextParams, registry: resolvedSecretTraceRegistry, - describeRequest: () => - describeToolRequest(unsentTool, contextParams, resolvedSecretTraceRegistry), + request: describeToolRequest(tool, contextParams, resolvedSecretTraceRegistry), }) } diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index 71cb53cef1e..84cd2d3525a 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -1,18 +1,29 @@ /** * @vitest-environment node */ -import { describe, expect, it } from 'vitest' +import { maskClientMock, maskClientMockFns } from '@sim/testing/mocks/mask-client.mock' +import { describe, expect, it, vi } from 'vitest' import { WriteStubPolicy } from '@/lib/workflows/dry-run' +import type { PiiBlockOutputRedaction } from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { answerUnsentWrite, unsentWriteFor } from '@/tools/side-effects' +vi.mock('@/lib/guardrails/mask-client', () => maskClientMock) + +const PII_REDACTION: PiiBlockOutputRedaction = { + enabled: true, + entityTypes: ['EMAIL_ADDRESS'], + language: 'en', +} + /** Stubs one `slack_message` call from block `notify` and returns what the policy recorded. */ async function stubSlackMessage( registry: ResolvedSecretTraceRegistry, - describeRequest: () => unknown + request: unknown, + piiBlockOutputRedaction?: PiiBlockOutputRedaction ) { - const policy = new WriteStubPolicy({ workflowId: 'wf-1', pausingBlocks: 'stub' }) + const policy = new WriteStubPolicy({ workflowId: 'wf-1' }) const params = { accessToken: 'oauth-token-123', apiKey: 'hosted-key-456', @@ -22,20 +33,24 @@ async function stubSlackMessage( const write = unsentWriteFor({ toolId: 'slack_message', params, - executionContext: { workflowId: 'wf-1', sideEffects: policy } as ExecutionContext, + executionContext: { + workflowId: 'wf-1', + sideEffects: policy, + piiBlockOutputRedaction, + } as ExecutionContext, }) if (!write) throw new Error('The policy sent the write') - const response = await answerUnsentWrite(write, { params, registry, describeRequest }) + const response = await answerUnsentWrite(write, { params, registry, request }) return { response, stubbed: policy.summary().stubbed } } describe('a write a dry run does not send', () => { it('records its request without the credentials the call resolved, wherever they appear', async () => { - const { response, stubbed } = await stubSlackMessage(new ResolvedSecretTraceRegistry(), () => ({ + const { response, stubbed } = await stubSlackMessage(new ResolvedSecretTraceRegistry(), { method: 'POST', url: 'https://slack.example/api?token=oauth-token-123', body: { channel: 'ops', text: 'sent with hosted-key-456', apiKey: 'hosted-key-456' }, - })) + }) expect(response.success).toBe(true) expect(stubbed[0].request).toMatchObject({ method: 'POST', body: { channel: 'ops' } }) @@ -48,12 +63,41 @@ describe('a write a dry run does not send', () => { const registry = new ResolvedSecretTraceRegistry() registry.markIncomplete('secret-transformed-by-tool') - const { response, stubbed } = await stubSlackMessage(registry, () => ({ + const { response, stubbed } = await stubSlackMessage(registry, { method: 'POST', url: 'https://slack.example/api', body: { channel: 'ops' }, + }) + + expect(response.success).toBe(true) + expect(stubbed[0].request).toBeNull() + }) + + it('records its request with the workspace’s PII redaction applied, as a block output gets it', async () => { + maskClientMockFns.mockMaskPIIBatchViaHttp.mockImplementationOnce(async (texts: string[]) => ({ + masked: texts.map((text) => text.replaceAll('ada@example.com', '')), + scrubbedCount: 0, })) + const { stubbed } = await stubSlackMessage( + new ResolvedSecretTraceRegistry(), + { method: 'POST', body: { channel: 'ops', text: 'Reply to ada@example.com' } }, + PII_REDACTION + ) + + expect(stubbed[0].request).toMatchObject({ body: { text: 'Reply to ' } }) + expect(JSON.stringify(stubbed[0].request)).not.toContain('ada@example.com') + }) + + it('records no request when the PII redaction fails', async () => { + maskClientMockFns.mockMaskPIIBatchViaHttp.mockRejectedValueOnce(new Error('Presidio down')) + + const { response, stubbed } = await stubSlackMessage( + new ResolvedSecretTraceRegistry(), + { method: 'POST', body: { channel: 'ops', text: 'Reply to ada@example.com' } }, + PII_REDACTION + ) + expect(response.success).toBe(true) expect(stubbed[0].request).toBeNull() }) diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index ba6a26cb337..b436a43ff7a 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -12,8 +12,9 @@ import { redactExactSensitiveValues, } from '@/lib/core/security/redaction' import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' -import { parseMcpToolArguments } from '@/lib/mcp/tool-arguments' -import { getBlock, getBlockByToolName } from '@/blocks/registry' +import { parseMcpToolArguments, RUN_CONTEXT_PARAMS } from '@/lib/mcp/tool-arguments' +import { getBlock, getBlockRegistry } from '@/blocks/registry' +import type { BlockConfig } from '@/blocks/types' import { isCustomTool } from '@/executor/constants' import type { SideEffectPolicy, SideEffectSite } from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' @@ -25,17 +26,6 @@ import { type ExecutableToolConfig, isInternalToolConfig, type ToolResponse } fr const logger = createLogger('ToolSideEffects') -/** - * Params an Agent's tool call carries for the run itself (every env var, workflow variable and - * block output), which no stubbed tool sends and a recorded request must never show. - */ -const RUN_CONTEXT_PARAMS: ReadonlySet = new Set([ - 'envVars', - 'workflowVariables', - 'blockData', - 'blockNameMapping', -]) - /** The block of the executing workflow that made a tool call, from its server-set `_context`. */ function sideEffectSite( executionContext: ExecutionContext, @@ -55,7 +45,7 @@ function sideEffectSite( } /** A write tool call the run's policy answers instead of sending. */ -export interface UnsentWrite { +interface UnsentWrite { policy: SideEffectPolicy executionContext: ExecutionContext call: SideEffectSite & { toolId: string } @@ -133,22 +123,58 @@ function redactCredentials(value: unknown, credentials: string[]): unknown { ) } +/** The params a block's password fields fill: each field's id and canonical param. */ +function passwordParamsOf(block: BlockConfig | undefined): ReadonlySet { + const params = new Set() + for (const subBlock of block?.subBlocks ?? []) { + if (!subBlock.password) continue + params.add(subBlock.id) + if (subBlock.canonicalParamId) params.add(subBlock.canonicalParamId) + } + return params +} + +/** + * The static block registry's password params per block type, and the block each tool belongs + * to, read once on the first unsent write rather than on every one. + */ +let registryPasswordIndex: + | { paramsByBlockType: Map>; blockTypeByTool: Map } + | undefined + +function readRegistryPasswordIndex() { + if (registryPasswordIndex) return registryPasswordIndex + const paramsByBlockType = new Map>() + const blockTypeByTool = new Map() + for (const block of Object.values(getBlockRegistry())) { + paramsByBlockType.set(block.type, passwordParamsOf(block)) + for (const toolId of block.tools?.access ?? []) { + if (!blockTypeByTool.has(toolId)) blockTypeByTool.set(toolId, block.type) + } + } + registryPasswordIndex = { paramsByBlockType, blockTypeByTool } + return registryPasswordIndex +} + +/** A block type's password params; a custom block's config is per workspace, so it is read live. */ +function passwordParamsFor(blockType: string): ReadonlySet { + return ( + readRegistryPasswordIndex().paramsByBlockType.get(blockType) ?? + passwordParamsOf(getBlock(blockType)) + ) +} + /** * The values in `params` that are secrets: credential-named params (an access token, a hosted * key, a secret access key), and whatever was typed into a password field of the blocks * `blockTypes` names, whatever the field is called. */ function secretValues(params: Record, blockTypes: string[]): string[] { - const passwordParams = new Set() - for (const blockType of blockTypes) { - for (const subBlock of getBlock(blockType)?.subBlocks ?? []) { - if (!subBlock.password) continue - passwordParams.add(subBlock.id) - if (subBlock.canonicalParamId) passwordParams.add(subBlock.canonicalParamId) - } - } + const passwordParams = blockTypes.map(passwordParamsFor) return Object.entries(params).flatMap(([key, value]) => - (isSensitiveKey(key) || passwordParams.has(key)) && typeof value === 'string' && value !== '' + (isSensitiveKey(key) || passwordParams.some((fields) => fields.has(key))) && + typeof value === 'string' && + value !== '' ? [value] : [] ) @@ -193,21 +219,20 @@ export async function redactSideEffectPayload(input: { /** * The response answering a write tool call the run's side-effect policy does not send, after the - * policy recorded the request it would have sent. `describeRequest` runs only for an unsent call, - * and a request it cannot build fails the call as sending it would. + * policy recorded `request`, the request it would have sent. */ export async function answerUnsentWrite( write: UnsentWrite, input: { params: Record registry: ResolvedSecretTraceRegistry | undefined - describeRequest: () => unknown + request: unknown } ): Promise { const { call } = write - const toolBlockType = getBlockByToolName(call.toolId)?.type + const toolBlockType = readRegistryPasswordIndex().blockTypeByTool.get(call.toolId) const request = await redactSideEffectPayload({ - payload: input.describeRequest(), + payload: input.request, params: input.params, blockTypes: [call.blockType, toolBlockType].filter((type): type is string => Boolean(type)), executionContext: write.executionContext, diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 75f4d809891..522985d7eec 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -1,4 +1,4 @@ -import { isPlainRecord, isRecordLike, toRecord } from '@sim/utils/object' +import { isPlainRecord, isRecordLike, toArray, toRecord } from '@sim/utils/object' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import type { Command } from 'commander' import { writeStderr } from '#sim-cli/output/io' @@ -102,8 +102,8 @@ async function resolveWorkflowRunSelection( const useMockPayload = flags.mockPayload === true const stopAfter = typeof flags.stopAfter === 'string' ? flags.stopAfter : undefined const dry = flags.dry === true - const allowBlocks = Array.isArray(flags.allow) ? (flags.allow as string[]) : [] - const mockValues = Array.isArray(flags.mock) ? (flags.mock as string[]) : [] + const allowBlocks = toArray(flags.allow) + const mockValues = toArray(flags.mock) /** These flags only apply to the draft, so each implies `--manual`. */ const manual = flags.manual === true || @@ -190,13 +190,13 @@ async function resolveWorkflowRunSelection( /** * A dry run's side effects in a few lines on stderr, for the human formats: each write that was - * not sent, sent because its block was allowed, or made by code the run cannot see. The request - * payloads are in the result itself (`--output json`). + * not sent, sent because its block was allowed, or made by code the run cannot see, and a note + * for an allowed block whose writes all stayed stubbed (an Agent's call to a custom block). The + * request payloads are in the result itself (`--output json`). */ -function printSideEffects(sideEffects: unknown): void { +function printSideEffects(sideEffects: unknown, dryRun: unknown): void { if (!isRecordLike(sideEffects)) return - const list = (key: string) => - Array.isArray(sideEffects[key]) ? sideEffects[key].filter(isRecordLike) : [] + const list = (key: string) => toArray(sideEffects[key]).filter(isRecordLike) const stubbed = list('stubbed') const allowed = list('allowed') const unchecked = list('unchecked') @@ -215,6 +215,14 @@ function printSideEffects(sideEffects: unknown): void { 0 ) if (omitted > 0) lines.push(` … ${omitted} more`) + for (const blockId of toArray(toRecord(dryRun).allowBlocks)) { + if (allowed.some((entry) => entry.blockId === blockId)) continue + const held = stubbed.find((entry) => entry.blockId === blockId) + if (!held) continue + lines.push( + ` note ${safeOneLine(String(held.block))} was allowed but sent nothing: allowing an Agent sends only its own tool calls, not a workflow or custom block it calls` + ) + } lines.push('Request payloads: sideEffects in --output json') writeStderr(styles().dim(`${lines.join('\n')}\n`)) } @@ -366,7 +374,7 @@ async function runWithResultStream( expandedTrace: flags.trace === true, }) if (profile.output === 'table' || profile.output === 'text') { - printSideEffects(payload.sideEffects) + printSideEffects(payload.sideEffects, payload.dryRun) } const failure = runFailureMessage('executeWorkflow', payload) @@ -715,10 +723,12 @@ deployed has none. --manual runs the saved draft, as the source loop leaves it. table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child -workflows run dry too; custom blocks are answered whole. Agents read memory but write none, and the -run raises no workspace event. --allow sends that block's writes for real (use a test -resource); --mock = answers a block with fixed output, to steer a branch. A dry run is -the --source-run only of another dry run. +workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run +never pauses. Agents read memory but write none, and the run raises no workspace event. +--allow sends that block's writes for real (use a test resource); allowing an Agent sends +only its own tool calls, not a workflow or custom block it calls. --mock = answers a +block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field +cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: @@ -727,7 +737,8 @@ instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix -only that block and those after it run again; a dry run's keeps --dry, --allow and --mock. Add --stop-after to stop after a block; +only that block and those after it run again; a dry run's keeps --dry and --allow. Mock outputs +are never stored, so pass each --mock again. Add --stop-after to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed @@ -765,12 +776,12 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--allow ', - "Send this block's writes for real during a --dry run (its id, display name or key); repeatable", + "Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable", collectRepeated ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result; repeatable', + 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable', collectRepeated ) .option( diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 2721b326160..93765342ecd 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -7188,7 +7188,7 @@ type ExecuteWorkflowResponseRef1 = { type ExecuteWorkflowResponseRef2 = { allowBlocks: Array - mocks: Record> + mockedBlocks: Array } type ExecuteWorkflowResponseRef3 = { @@ -10388,7 +10388,7 @@ type GetWorkflowRunResponseRef3 = { type GetWorkflowRunResponseRef4 = { allowBlocks: Array - mocks: Record> + mockedBlocks: Array } type GetWorkflowRunResponseRef5 = { diff --git a/packages/sim-cli/src/runtime/run-next.test.ts b/packages/sim-cli/src/runtime/run-next.test.ts index d0e0a5bf690..a18413fca3b 100644 --- a/packages/sim-cli/src/runtime/run-next.test.ts +++ b/packages/sim-cli/src/runtime/run-next.test.ts @@ -104,9 +104,9 @@ describe('withRunNext on a failed run', () => { }) }) - it('keeps a test run a test: a dry run with its allowed and mocked blocks, a workflow test dry', () => { - const dryRun = { allowBlocks: ['blk_1'], mocks: { blk_2: { route: "vip's" } } } - const next = `sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow blk_1 --mock 'blk_2={"route":"vip'\\''s"}'` + it('keeps a test run a test: a dry run with its allowed blocks, a workflow test dry', () => { + const dryRun = { allowBlocks: ['blk_1'], mockedBlocks: ['blk_2'] } + const next = 'sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow blk_1' expect(withRunNext('executeWorkflow', { ...failed, dryRun })).toMatchObject({ next }) expect(withRunNext('getWorkflowRun', { ...failed, trigger: 'test', dryRun })).toMatchObject({ next, @@ -117,10 +117,15 @@ describe('withRunNext on a failed run', () => { expect( withRunNext('getWorkflowRun', { ...failed, trigger: 'manual', dryRun: null }) ).toMatchObject({ next: 'sim workflows run wf_1 --from-block blk_3 --source-run run_9' }) - const hostile = { ...failed, dryRun: { allowBlocks: ['$(id)'], mocks: {} } } + const hostile = { ...failed, dryRun: { allowBlocks: ['$(id)'], mockedBlocks: [] } } expect(withRunNext('executeWorkflow', hostile)).toBe(hostile) }) + it('names no resume for a paused test run, which is never resumed', () => { + const pausedTest = { ...paused, trigger: 'test' } + expect(withRunNext('getWorkflowRun', pausedTest)).toBe(pausedTest) + }) + it('names no rerun when the server names no start block, or an id it never issues', () => { const unstartable = { message: 'boom', code: 'BLOCK_EXECUTION_FAILED', blockId: 'blk_3' } for (const unnamed of [ diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index d9f0e60cb19..9be4129618a 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -1,4 +1,4 @@ -import { isRecordLike, toRecordOrNull } from '@sim/utils/object' +import { isRecordLike, toArray, toRecordOrNull } from '@sim/utils/object' import type { V2OperationName } from '../generated/v2-api' /** Operations whose payload is a run record that may be paused or failed. */ @@ -44,24 +44,25 @@ export function resumeCommandFor( return commands.length > 0 ? commands.join('\n') : null } +/** Whether a run record is a test run: a dry run, or a workflow test's run. */ +function isTestRun(record: Record): boolean { + return record.trigger === 'test' || toRecordOrNull(record.dryRun) !== null +} + /** - * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` and - * `--mock` blocks (`dryRun`), so following `next` never sends what the run held back or drops the - * outputs it was steered by. A workflow test's run (`trigger: test`) has no `dryRun` but held its - * writes back all the same. Null when a block id is not in the format the server issues. + * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` + * blocks (`dryRun.allowBlocks`), so following `next` never sends what the run held back. A + * workflow test's run has no `dryRun` but held its writes back all the same. A dry run's mock + * outputs are never stored, so `next` cannot repeat its `--mock` flags; the caller passes them + * again. Null when a block id is not in the format the server issues. */ function dryRerunFlags(record: Record): string | null { - const dryRun = toRecordOrNull(record.dryRun) - if (!dryRun) return record.trigger === 'test' ? ' --dry' : '' + if (!isTestRun(record)) return '' const flags = [' --dry'] - for (const blockId of Array.isArray(dryRun.allowBlocks) ? dryRun.allowBlocks : []) { + for (const blockId of toArray(toRecordOrNull(record.dryRun)?.allowBlocks)) { if (!issuedId(blockId)) return null flags.push(` --allow ${shellArgument(blockId)}`) } - for (const [blockId, output] of Object.entries(toRecordOrNull(dryRun.mocks) ?? {})) { - if (!issuedId(blockId)) return null - flags.push(` --mock ${shellArgument(`${blockId}=${JSON.stringify(output)}`)}`) - } return flags.join('') } @@ -83,16 +84,18 @@ function rerunCommandFor(record: Record, workflowId: string): s } /** - * A run record with `next` added: the `runs resume` command when it is paused for input, the - * rerun from the failed block when it failed in one. Any other payload comes back as it was, and - * so does one that already has a `next`. + * A run record with `next` added: the `runs resume` command when it is paused for input (never + * for a test run, which is never resumed), the rerun from the failed block when it failed in one. + * Any other payload comes back as it was, and so does one that already has a `next`. */ export function withRunNext(operation: V2OperationName, payload: unknown): unknown { if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload if ('next' in payload || typeof payload.workflowId !== 'string') return payload const next = payload.status === 'paused' - ? resumeCommandFor(payload, payload.workflowId) + ? isTestRun(payload) + ? null + : resumeCommandFor(payload, payload.workflowId) : payload.status === 'failed' ? rerunCommandFor(payload, payload.workflowId) : null diff --git a/packages/testing/src/mocks/logging-session.mock.ts b/packages/testing/src/mocks/logging-session.mock.ts index 92fc139bad0..0178f335f27 100644 --- a/packages/testing/src/mocks/logging-session.mock.ts +++ b/packages/testing/src/mocks/logging-session.mock.ts @@ -7,7 +7,8 @@ import { vi } from 'vitest' * mock state. `mockSafeStart` defaults to `true` because callers branch on the * boolean result, and `mockWhenLogStarted` resolves at once, as for a log already written. Display projection methods (incl. `projectTraceSpansForLiveDisplay`) return * their input, diagnostic projection fails closed to structural metadata, `hasCompleted` is - * `false`, `getPersistedCompletionStatus` and `getDeletedScope` are `null`, and other methods + * `false`, `getPersistedCompletionStatus` and `getDeletedScope` are `null`, `getTriggerType` is + * `manual`, and other methods * resolve to `undefined`. * Defaults are `vi.fn(impl)`, so `mockReset()` restores them. * @@ -44,6 +45,7 @@ export const loggingSessionMockFns = { mockHasCompleted: vi.fn((): boolean => false), mockGetPersistedCompletionStatus: vi.fn((): string | null => null), mockGetDeletedScope: vi.fn((): 'workspace' | 'workflow' | null => null), + mockGetTriggerType: vi.fn((): string => 'manual'), mockProjectTraceSpansForLiveDisplay: vi.fn(async (traceSpans: unknown) => traceSpans), mockMarkExecutionAsFailed: vi.fn(async (..._args: unknown[]): Promise => {}), mockProjectBlockLogsForDisplay: vi.fn(async (logs: unknown) => logs), @@ -87,6 +89,7 @@ function buildLoggingSessionInstance() { hasCompleted: loggingSessionMockFns.mockHasCompleted, getPersistedCompletionStatus: loggingSessionMockFns.mockGetPersistedCompletionStatus, getDeletedScope: loggingSessionMockFns.mockGetDeletedScope, + getTriggerType: loggingSessionMockFns.mockGetTriggerType, projectTraceSpansForLiveDisplay: loggingSessionMockFns.mockProjectTraceSpansForLiveDisplay, exportResolvedSecretTraceProvenanceForValue: loggingSessionMockFns.mockExportResolvedSecretTraceProvenanceForValue, From 92cb73debaf0d6796f20292faaddf61e5e8dc74d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 03:12:02 -0800 Subject: [PATCH 04/10] fix(workflows): treat mocks as data only and list every code execution in a dry run - One rule for mocks (run.mocks and workflow-test mockBlock): refuse any _ field and the output fields the trace span and bill are built from (cost, tokens, model, providerTiming, toolCalls, executionData, childTraceSpans, child workflow ids); block samples omit them too - List Condition expressions and While/Do While loop conditions under sideEffects.unchecked, once per block, via a new SideEffectPolicy.ranCode - Upload provider Files API attachments only after the cached-final early return - Keep a failed dry run's sideEffects when compacting its error output fails - Read the paused run's trigger in the same locked query; memoize getBlockByToolName and password params lazily; drop the test-only removals default; simplify answered-block and tool decisions; narrow the editor route try - Tests: durable-state check instead of sleep, specific refusals, positive controls, transport guard on the hosted-key test, success-path upload cleanup --- .../api-reference/build-and-run-workflows.mdx | 2 +- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 4 +- apps/docs/openapi-v2-workflows.json | 6 +- .../app/api/workflows/[id]/execute/route.ts | 26 ++- apps/sim/blocks/registry.ts | 14 +- apps/sim/executor/execution/block-executor.ts | 38 ++-- apps/sim/executor/execution/types.ts | 19 +- .../agent/memory-harness.integration.ts | 2 +- .../sim/executor/handlers/workflow/handler.ts | 4 +- apps/sim/executor/orchestrators/loop.ts | 18 +- apps/sim/executor/utils/mock-output.ts | 20 ++ .../contracts/mothership-management-tools.ts | 2 +- apps/sim/lib/api/contracts/v2/workflows.ts | 6 +- .../lib/logs/execution/trace-spans/factory.ts | 18 ++ .../dry-run-hosted-key.integration.ts | 67 +++++-- .../application/dry-run.integration.ts | 172 ++++++++++++++++-- .../execute-manual-workflow.test.ts | 6 - .../application/execute-manual-workflow.ts | 18 +- apps/sim/lib/workflows/dry-run/samples.ts | 13 +- .../sim/lib/workflows/dry-run/side-effects.ts | 80 ++++---- .../lib/workflows/executor/execute-service.ts | 10 +- .../human-in-the-loop-manager.test.ts | 18 +- .../executor/human-in-the-loop-manager.ts | 26 ++- .../file-attachments-authorization.test.ts | 2 +- .../providers/file-attachments.server.test.ts | 31 ++-- apps/sim/providers/file-attachments.server.ts | 4 +- apps/sim/providers/index.test.ts | 30 +-- apps/sim/providers/index.ts | 48 ++--- apps/sim/tools/side-effects.test.ts | 5 +- apps/sim/tools/side-effects.ts | 36 +--- .../protocol/workflow-run-follow.test.ts | 5 + .../commands/protocol/workflow-run-follow.ts | 18 +- .../testing/src/mocks/logging-session.mock.ts | 3 +- 34 files changed, 513 insertions(+), 262 deletions(-) create mode 100644 apps/sim/executor/utils/mock-output.ts diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index 8db4a50eadd..4863f1c266c 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads, model calls and conditions run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock cannot replace a locked block or set a field starting with `_`, and its output is never stored: the run records only which blocks were mocked, so a rerun passes `run.mocks` again. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads and model calls run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock is data: it cannot replace a locked block or set a field the run's execution, trace or billing reads (such as `cost`, `tokens`, `model` or a field starting with `_`), and its output is never stored: the run records only which blocks were mocked, so a rerun passes `run.mocks` again. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index c624afd56c8..1c133f690be 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8518,7 +8518,7 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. Not stored, so a rerun passes it again; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8534,7 +8534,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index e9784f77039..f15fadf0ab6 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -835,7 +835,7 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. Not stored, so a rerun passes it again; repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -851,7 +851,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 00640982e65..3f89707f4b7 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17370,7 +17370,7 @@ "required": ["workflowId", "blockId", "block", "reason"], "additionalProperties": false }, - "description": "Blocks whose code ran for real, once per block: a Function block's code, or code an Agent's model wrote, which may make network calls the run cannot see." + "description": "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." }, "omitted": { "type": "object", @@ -17758,7 +17758,7 @@ "minLength": 1 }, "dry": { - "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls, conditions and credential resolution run for real, and so does code (a Function block's, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", "type": "boolean" }, "allowBlocks": { @@ -17771,7 +17771,7 @@ } }, "mocks": { - "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked, and an output field cannot start with `_` (those control the run). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.", + "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.", "type": "object", "propertyNames": { "type": "string" diff --git a/apps/sim/app/api/workflows/[id]/execute/route.ts b/apps/sim/app/api/workflows/[id]/execute/route.ts index 07fd7c2ae7b..dc735847632 100644 --- a/apps/sim/app/api/workflows/[id]/execute/route.ts +++ b/apps/sim/app/api/workflows/[id]/execute/route.ts @@ -861,22 +861,20 @@ async function handleExecutePost( const { getExecutionStateForWorkflow, getLatestExecutionStateWithExecutionId } = await import('@/lib/workflows/executor/execution-state') let sourceExecution: { executionId: string; state: SerializableExecutionState } | null - try { - if (rawRunFromBlock.executionId === 'latest') { - sourceExecution = await getLatestExecutionStateWithExecutionId(workflowId) - } else { - const state = await getExecutionStateForWorkflow( - rawRunFromBlock.executionId, - workflowId + if (rawRunFromBlock.executionId === 'latest') { + sourceExecution = await getLatestExecutionStateWithExecutionId(workflowId) + } else { + let state: SerializableExecutionState | null + try { + state = await getExecutionStateForWorkflow(rawRunFromBlock.executionId, workflowId) + } catch (error) { + if (!(error instanceof OrchestrationError)) throw error + return NextResponse.json( + { error: error.message }, + { status: statusForOrchestrationError(error.code) } ) - sourceExecution = state ? { executionId: rawRunFromBlock.executionId, state } : null } - } catch (error) { - if (!(error instanceof OrchestrationError)) throw error - return NextResponse.json( - { error: error.message }, - { status: statusForOrchestrationError(error.code) } - ) + sourceExecution = state ? { executionId: rawRunFromBlock.executionId, state } : null } if (!sourceExecution) { if (rawRunFromBlock.sourceSnapshot && !isPublicApiAccess) { diff --git a/apps/sim/blocks/registry.ts b/apps/sim/blocks/registry.ts index 4708c8fdf3e..2ecc739c25c 100644 --- a/apps/sim/blocks/registry.ts +++ b/apps/sim/blocks/registry.ts @@ -165,9 +165,19 @@ function versionCandidates(type: string): BlockConfig[] { return candidates } -/** Find the block whose `tools.access` contains the given tool id. */ +let blockByTool: Map | undefined + +/** Find the first block, in registry order, whose `tools.access` contains the given tool id. */ export function getBlockByToolName(toolName: string): BlockConfig | undefined { - return Object.values(BLOCK_REGISTRY).find((b) => b.tools?.access?.includes(toolName)) + if (!blockByTool) { + blockByTool = new Map() + for (const block of Object.values(BLOCK_REGISTRY)) { + for (const toolId of block.tools?.access ?? []) { + if (!blockByTool.has(toolId)) blockByTool.set(toolId, block) + } + } + } + return blockByTool.get(toolName) } /** diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index a3d51db22f9..1279af29851 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -44,8 +44,6 @@ import type { BlockStateWriter, ContextExtensions, ExecutionTestHooks, - SideEffectBlockSite, - SideEffectPolicy, WorkflowNodeMetadata, } from '@/executor/execution/types' import { @@ -76,6 +74,7 @@ import { getIterationContext, } from '@/executor/utils/iteration-context' import { isJSONString } from '@/executor/utils/json' +import { mockOutputRefusal } from '@/executor/utils/mock-output' import { filterOutputForLog } from '@/executor/utils/output-filter' import { projectResolvedSecretDiagnosticError } from '@/executor/utils/resolved-secret-content-projection' import type { @@ -288,18 +287,14 @@ export class BlockExecutor { const testHooks = this.contextExtensions.testHooks const mockedBlockId = node.metadata.originalBlockId ?? block.id const isMocked = !isSentinel && testHooks?.mocksBlock(mockedBlockId) === true - /** The run's side-effect policy and the block's site, when the policy answers the block. */ - let answered: { policy: SideEffectPolicy; site: SideEffectBlockSite } | undefined - const sideEffects = this.contextExtensions.sideEffects - if (sideEffects && !isSentinel && !isMocked) { - const site = { - workflowId: blockCtx.workflowId, - blockId: mockedBlockId, - blockName: block.metadata?.name ?? mockedBlockId, - blockType: block.metadata?.id ?? '', - } - if (sideEffects.answersBlock(site)) answered = { policy: sideEffects, site } + const sideEffects = isSentinel || isMocked ? undefined : this.contextExtensions.sideEffects + const site = sideEffects && { + workflowId: blockCtx.workflowId, + blockId: mockedBlockId, + blockName: block.metadata?.name ?? mockedBlockId, + blockType: block.metadata?.id ?? '', } + const answeredBy = site && sideEffects?.answersBlock(site) ? sideEffects : undefined try { /** * Only the handler call is retried. A streaming handler returns before any @@ -318,9 +313,8 @@ export class BlockExecutor { inputDisplayRegistry ) } - if (answered) { - const { policy, site } = answered - return policy.answerBlock({ + if (answeredBy && site) { + return answeredBy.answerBlock({ ...site, input: () => redactSideEffectPayload({ @@ -1011,8 +1005,11 @@ export class BlockExecutor { return { result: output } } - /** A test mock sees exactly what the block's execution log shows, never raw resolved secrets. */ - private resolveMockedBlock( + /** + * A test mock sees exactly what the block's execution log shows, never raw resolved secrets, + * and answers with data only ({@link mockOutputRefusal}). + */ + private async resolveMockedBlock( ctx: ExecutionContext, node: DAGNode, block: SerializedBlock, @@ -1026,7 +1023,7 @@ export class BlockExecutor { if (projection && !projection.complete) { throw new Error(`Mocked block "${blockName}" has inputs whose secrets cannot be redacted`) } - return testHooks.resolveMock( + const output = await testHooks.resolveMock( { blockId, blockName, @@ -1038,6 +1035,9 @@ export class BlockExecutor { }, ctx.abortSignal ) + const refusal = mockOutputRefusal(`Mocked block "${blockName}"`, output) + if (refusal) throw new Error(refusal) + return output } /** Builds the log-facing input copy from resolver-recorded projections only. */ diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index b8f88720956..21ef948cd3a 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -320,7 +320,7 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } -/** The blocks of the workflow a dry run started that it sent and mocked, by id; never a mock's output. */ +/** A dry run's allowed and mocked blocks of the workflow it started, by id; never a mock's output. */ export interface DryRunOptions { allowBlocks: string[] mockedBlocks: string[] @@ -361,13 +361,11 @@ export interface AnsweredBlockCall extends SideEffectBlockSite { /** * How a run treats work that may change state outside it: a dry run, or a workflow test's * unmocked writes. Unlike {@link ExecutionTestHooks}, every child execution inherits it, including - * a workflow an Agent calls as a tool, so a child's writes follow the run that started it. - * `tools/index.ts` consults it for every tool call not declared `read` (an MCP tool declares - * nothing, so every one) before a hosted key is drawn, and answers a stubbed call after - * credentials resolve and before anything is sent; the block executor consults it before each - * block's handler. Its presence alone also means the run keeps nothing beyond its log: an Agent - * writes no memory, and files uploaded to a provider's Files API are deleted once the call - * settles. Where only the log is at hand, the `test` trigger says the same. + * a workflow an Agent calls as a tool, so a child's writes follow the run that started it. Tool + * calls meet it in `tools/side-effects.ts`; the block executor consults it before each block's + * handler. Its presence alone also means the run keeps nothing beyond its log: an Agent writes no + * memory, and files uploaded to a provider's Files API are deleted once the call settles. Where + * only the log is at hand, the `test` trigger says the same. */ export interface SideEffectPolicy { /** @@ -375,6 +373,11 @@ export interface SideEffectPolicy { * the run should report: an allowed block's write, or code that runs unchecked. */ decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' + /** + * Records code that ran for real, which can make network calls the run cannot see: code run + * through `function_execute`, or a While or Do While loop's condition. + */ + ranCode(site: SideEffectSite): void /** Records a write that was not sent and returns the placeholder output answering it. */ stubWrite(call: StubbedToolCall): Record /** Whether this block is answered with {@link answerBlock} instead of running its handler. */ diff --git a/apps/sim/executor/handlers/agent/memory-harness.integration.ts b/apps/sim/executor/handlers/agent/memory-harness.integration.ts index 896737de95d..7c18d0b19cc 100644 --- a/apps/sim/executor/handlers/agent/memory-harness.integration.ts +++ b/apps/sim/executor/handlers/agent/memory-harness.integration.ts @@ -532,7 +532,7 @@ describe('Agent memory through PostgreSQL, storage, and provider transports', () return Response.json({ id: 'file-harness' }) }) vi.stubGlobal('fetch', upload) - await uploadLargeFilesToProvider(largeRequest, provider, firstContext) + await uploadLargeFilesToProvider(largeRequest, provider, firstContext, []) expect(upload).toHaveBeenCalledOnce() expect(largeFile.providerFileId).toBe('file-harness') } diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index 8e5b58b95af..baa82628589 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -931,8 +931,8 @@ export class WorkflowBlockHandler implements BlockHandler { // A workflow test's mocks and spies reach every child it runs, except a custom // block's: that workflow is the publisher's, so the test mocks the block whole. testHooks: isCustomBlock ? undefined : ctx.testHooks, - // A dry run's writes stay stubbed in every child; a custom block never runs under one, - // since the policy answers it whole. + // Every child inherits the run's side-effect policy, a custom block's included: the + // policy answers a custom block whole, so its child never runs under it. sideEffects: ctx.sideEffects, callChain: childCallChain, // A custom block's own session markers and the parent's live stream, fanned diff --git a/apps/sim/executor/orchestrators/loop.ts b/apps/sim/executor/orchestrators/loop.ts index d2507fadec0..ee12c24c1af 100644 --- a/apps/sim/executor/orchestrators/loop.ts +++ b/apps/sim/executor/orchestrators/loop.ts @@ -10,7 +10,13 @@ import { generateRequestId } from '@/lib/core/utils/request' import { executeInIsolatedVM } from '@/lib/execution/isolated-vm' import { compactSubflowResults } from '@/lib/execution/payloads/serializer' import { isLikelyReferenceSegment } from '@/lib/workflows/sanitization/references' -import { CONTROL_BACK_EDGE_HANDLES, DEFAULTS, EDGE, PARALLEL } from '@/executor/constants' +import { + BlockType, + CONTROL_BACK_EDGE_HANDLES, + DEFAULTS, + EDGE, + PARALLEL, +} from '@/executor/constants' import type { DAG } from '@/executor/dag/builder' import type { EdgeManager } from '@/executor/execution/edge-manager' import type { LoopScope } from '@/executor/execution/state' @@ -28,6 +34,7 @@ import { extractBaseBlockId, extractLoopIdFromSentinel, extractParallelIdFromSentinel, + stripOuterBranchSuffix, } from '@/executor/utils/subflow-node-id-codec' import { mergeSubflowSecretProvenance } from '@/executor/utils/subflow-secret-provenance' import type { VariableResolver } from '@/executor/variables/resolver' @@ -805,6 +812,15 @@ export class LoopOrchestrator { return match }) + const workflowLoopId = stripOuterBranchSuffix(loopId) + ctx.sideEffects?.ranCode({ + workflowId: ctx.workflowId, + blockId: workflowLoopId, + blockName: + ctx.workflow?.blocks.find((block) => block.id === workflowLoopId)?.metadata?.name ?? + workflowLoopId, + blockType: BlockType.LOOP, + }) vmResult = await executeInIsolatedVM({ code: `return Boolean(${evaluatedCondition})`, params: {}, diff --git a/apps/sim/executor/utils/mock-output.ts b/apps/sim/executor/utils/mock-output.ts new file mode 100644 index 00000000000..6e9e6211e60 --- /dev/null +++ b/apps/sim/executor/utils/mock-output.ts @@ -0,0 +1,20 @@ +import { SPAN_SOURCE_OUTPUT_FIELDS } from '@/lib/logs/execution/trace-spans/factory' + +/** + * Whether a block's own handler alone may set this top-level output field: a `_` field steers + * the executor (a pause, a child-run link), and the run's trace and bill are built from the + * {@link SPAN_SOURCE_OUTPUT_FIELDS}. + */ +export function isRunControlledOutputField(field: string): boolean { + return field.startsWith('_') || SPAN_SOURCE_OUTPUT_FIELDS.has(field) +} + +/** + * Why a mocked output, named by `label`, is refused; null when it sets only data. A mock (a dry + * run's `run.mocks`, or a workflow test's `mockBlock`) is data, never run control or billing. + */ +export function mockOutputRefusal(label: string, output: Record): string | null { + const fields = Object.keys(output).filter(isRunControlledOutputField) + if (fields.length === 0) return null + return `${label} sets ${fields.join(', ')}: a mock is data, so it cannot set a field the run's execution, trace or billing reads (${[...SPAN_SOURCE_OUTPUT_FIELDS].join(', ')}, or any field starting with "_").` +} diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index d69beebcb63..9951634043e 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index ce681c55cb7..97becae269c 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1706,7 +1706,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .boolean() .optional() .describe( - "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls, conditions and credential resolution run for real, and so does code (a Function block's, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." ), allowBlocks: z .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) @@ -1727,7 +1727,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ message: 'run.mocks names at most 50 blocks', }) .describe( - 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked, and an output field cannot start with `_` (those control the run). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.' + 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The outputs are never stored: the run records only which blocks were mocked, so a rerun passes them again.' ), }) .strict(), @@ -2031,7 +2031,7 @@ const v2RunSideEffectsSchema = z }) ) .describe( - "Blocks whose code ran for real, once per block: a Function block's code, or code an Agent's model wrote, which may make network calls the run cannot see." + "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." ), omitted: z .object({ diff --git a/apps/sim/lib/logs/execution/trace-spans/factory.ts b/apps/sim/lib/logs/execution/trace-spans/factory.ts index 63e3f1849a1..66da7ac5f9f 100644 --- a/apps/sim/lib/logs/execution/trace-spans/factory.ts +++ b/apps/sim/lib/logs/execution/trace-spans/factory.ts @@ -62,6 +62,24 @@ function liftChildTraceHandle(output: Record | undefined): { } } +/** + * The top-level block output fields {@link createSpanFromLog} reads beyond the displayed output: + * provider timing, cost, tokens and model become the span's usage, which the run is billed by, + * and the rest build its tool and child-workflow spans. Only a block's own handler sets them. + */ +export const SPAN_SOURCE_OUTPUT_FIELDS: ReadonlySet = new Set([ + 'cost', + 'tokens', + 'model', + 'providerTiming', + 'toolCalls', + 'executionData', + 'childTraceSpans', + 'childWorkflowId', + 'childWorkflowSnapshotId', + 'childDeploymentVersionId', +]) + /** * Creates a TraceSpan from a BlockLog. Returns null for invalid logs. * diff --git a/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts b/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts index cbcb52230c1..81059360a1b 100644 --- a/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run-hosted-key.integration.ts @@ -1,7 +1,8 @@ /** * A dry run on a hosted deployment, against real PostgreSQL and Redis: a write that would use * Sim's hosted key is answered with a placeholder before a key is drawn, so the workspace's - * hosted-key rate-limit counter in Redis is never touched and the recorded request carries no key. + * hosted-key rate-limit counter in Redis is never touched and the recorded request carries no key, + * while the same run sent for real draws one. Hunter is answered at the tool transport. */ import { db } from '@sim/db' import { @@ -34,6 +35,7 @@ vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({ })) import { closeRedisConnection, getRedisClient } from '@/lib/core/config/redis' +import * as toolTransport from '@/lib/core/security/input-validation.server' import { executeManualWorkflowOperation } from '@/lib/workflows/application/execute-manual-workflow' import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' @@ -121,6 +123,9 @@ beforeAll(async () => { }) afterAll(async () => { + vi.restoreAllMocks() + const counters = await workspaceRedisKeys() + if (counters.length > 0) await getRedisClient()?.del(...counters) await db.delete(workflowExecutionLogs).where(eq(workflowExecutionLogs.workflowId, workflowId)) await db .delete(workflowExecutionSnapshots) @@ -134,20 +139,48 @@ afterAll(async () => { describe('a dry run on a hosted deployment', () => { it('stubs a hosted-key write without drawing a key or counting it against the workspace', async () => { expect(await workspaceRedisKeys()).toEqual([]) + const hunterOnly = (url: string) => { + if (new URL(url).hostname !== 'api.hunter.io') { + throw new Error(`Unexpected network destination: ${url}`) + } + } + vi.spyOn(toolTransport, 'validateUrlWithDNS').mockImplementation(async (url) => { + hunterOnly(String(url)) + return { isValid: true, resolvedIP: '203.0.113.1', originalHostname: 'api.hunter.io' } + }) + const sent = vi + .spyOn(toolTransport, 'secureFetchWithPinnedIP') + .mockImplementation(async (url) => { + hunterOnly(url) + const response = Response.json({ data: { email: 'ada@example.com', score: 90 } }) + return { + status: 200, + statusText: 'OK', + ok: true, + url, + headers: new toolTransport.SecureFetchHeaders({ 'content-type': 'application/json' }), + body: response.body, + text: () => response.text(), + json: () => response.json(), + arrayBuffer: () => response.arrayBuffer(), + } + }) + const run = async (dry: boolean) => + (await executeManualWorkflowOperation.execute({ + principal, + input: { + workflowId, + requestId: generateId(), + executionId: generateId(), + input: {}, + mode: 'sync', + requestHeaders: new Headers(), + useMockPayload: false, + dry, + }, + })) as ExecuteWorkflowServiceRun - const result = (await executeManualWorkflowOperation.execute({ - principal, - input: { - workflowId, - requestId: generateId(), - executionId: generateId(), - input: {}, - mode: 'sync', - requestHeaders: new Headers(), - useMockPayload: false, - dry: true, - }, - })) as ExecuteWorkflowServiceRun + const result = await run(true) expect(result.status, JSON.stringify(result.error)).toBe('completed') expect(result.sideEffects?.stubbed).toEqual([ @@ -155,5 +188,11 @@ describe('a dry run on a hosted deployment', () => { ]) expect(JSON.stringify(result.sideEffects)).not.toContain(HOSTED_KEY) expect(await workspaceRedisKeys()).toEqual([]) + expect(sent).not.toHaveBeenCalled() + + const live = await run(false) + expect(live.status, JSON.stringify(live.error)).toBe('completed') + expect(sent).toHaveBeenCalledTimes(1) + expect(await workspaceRedisKeys()).not.toEqual([]) }) }) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 4464cc2a806..3e74efd9cd8 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -4,12 +4,13 @@ * it would have sent (credentials, run secrets and password fields redacted) under the `test` * trigger, and keeps nothing else: no Agent memory, no workspace event, no run count. An allowed * block writes for real while reads run for real; a child workflow's writes, an Agent's included, - * stay stubbed; custom and Wait blocks are answered whole; code runs and is listed unchecked; a - * mocked block steers a branch; a failed dry run keeps its side effects and is the source only of - * another dry run. A test run is never the source of a run that sends its writes (the v2 use case, - * Copilot and the editor route alike) and is never resumed; a mock never controls the run or - * replaces a locked block, and only the ids of mocked blocks are kept. Model calls are answered by - * a simulated Anthropic API. + * stay stubbed; custom and Wait blocks are answered whole; code runs and is listed unchecked, a + * Condition's expressions and a While loop's condition included; a mocked block steers a branch; + * a failed dry run keeps its side effects and is the source only of another dry run. A test run is + * never the source of a run that sends its writes (the v2 use case, Copilot and the editor route + * alike) and is never resumed; a mock, a dry run's or a workflow test's, is data that never + * controls the run, sets what it is billed or replaces a locked block, and only the ids of mocked + * blocks are kept. Model calls are answered by a simulated Anthropic API. */ import { db } from '@sim/db' import { @@ -688,7 +689,7 @@ describe('a dry run', () => { } }) - it('runs code for real, listing a Function block unchecked and a Condition not at all', async () => { + it('runs code for real, listing a Function block and a Condition unchecked once each', async () => { const tableId = await createTable() const gate = condition('gate', ' > 50') const branching = graph( @@ -713,7 +714,43 @@ describe('a dry run', () => { expect(result.status, JSON.stringify(result.error)).toBe('completed') expect(result.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['high']) expect(result.sideEffects?.unchecked).toEqual([ - expect.objectContaining({ blockId: branching.idOf('score'), block: 'score' }), + expect.objectContaining({ + blockId: branching.idOf('score'), + block: 'score', + reason: expect.stringContaining('Function block code ran'), + }), + expect.objectContaining({ + blockId: branching.idOf('gate'), + block: 'gate', + reason: expect.stringContaining('Condition expressions ran'), + }), + ]) + }) + + it('lists a While loop’s condition unchecked once, however often it runs', async () => { + const repeat = block('repeat', 'loop') + repeat.data = { loopType: 'while', whileCondition: ' < 3' } + const tick = block('tick', 'function', { language: 'javascript', code: 'return 1' }) + tick.data = { parentId: repeat.id, extent: 'parent' } + const looping = graph( + [block('start', 'start_trigger'), repeat, tick], + [ + ['start', 'repeat'], + ['repeat', 'tick', 'loop-start-source'], + ] + ) + const workflowId = await saveWorkflow(looping.state) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.unchecked).toEqual([ + expect.objectContaining({ + blockId: looping.idOf('repeat'), + block: 'repeat', + reason: expect.stringContaining('While or Do While loop condition ran'), + }), + expect.objectContaining({ blockId: looping.idOf('tick'), block: 'tick' }), ]) }) @@ -972,7 +1009,10 @@ describe('a test run', () => { status: 400, body: { error: expect.stringContaining('is a test run') }, }) - expect(await fromBlock('latest')).toMatchObject({ status: 400 }) + expect(await fromBlock('latest')).toMatchObject({ + status: 400, + body: { error: expect.stringContaining('No execution state found for workflow') }, + }) expect(await tableRows(tableId)).toEqual([]) }) @@ -1001,11 +1041,20 @@ describe('a test run', () => { }, { timeout: 20_000, interval: 100 } ) - /** A pausing block can no longer pause a test run; this stands in for one that did. */ + // A test run never pauses, so relabel this paused manual run as one to prove resume refuses it. await db .update(workflowExecutionLogs) .set({ trigger: 'test' }) .where(eq(workflowExecutionLogs.executionId, paused.executionId)) + const pausedStatus = async () => { + const [row] = await db + .select({ status: pausedExecutions.status }) + .from(pausedExecutions) + .where(eq(pausedExecutions.executionId, paused.executionId)) + return row?.status + } + const statusBefore = await pausedStatus() + expect(statusBefore).toBe('paused') await expect( resumeWorkflowRun.execute({ @@ -1019,7 +1068,7 @@ describe('a test run', () => { }, }) ).rejects.toThrow('is never resumed') - await sleep(500) + expect(await pausedStatus()).toBe(statusBefore) expect(await tableRows(tableId)).toEqual([]) }) @@ -1054,10 +1103,104 @@ describe('a dry run’s mocks', () => { await expect( run(parentId, { dry: true, mocks: { lookup: { rows: [], _pauseMetadata: pause } } }) - ).rejects.toMatchObject(validationError) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('sets _pauseMetadata'), + }) expect(await pausedExecutionsOf(parentId)).toEqual([]) }) + it('cannot set what the run is billed, beside a real model call', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), queryLeads('lookup', tableId), agent('assistant', {})], + [ + ['start', 'lookup'], + ['lookup', 'assistant'], + ] + ).state + ) + model.toolTurns = 0 + vi.stubGlobal('fetch', answerModel) + const billed = { cost: { input: 0, output: 0, total: -5 }, model: 'claude-haiku-4-5' } + + await expect( + run(workflowId, { dry: true, mocks: { lookup: { rows: [], ...billed } } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('sets cost, model'), + }) + expect(await logTriggers(workflowId)).toEqual([]) + + const dataOnly = await run(workflowId, { dry: true, mocks: { lookup: { rows: [] } } }) + expect(dataOnly.status, JSON.stringify(dataOnly.error)).toBe('completed') + const [log] = await db + .select({ modelsUsed: workflowExecutionLogs.modelsUsed }) + .from(workflowExecutionLogs) + .where(eq(workflowExecutionLogs.executionId, dataOnly.executionId)) + expect(log.modelsUsed).toEqual(['claude-haiku-4-5']) + }) + + it('in a workflow test cannot set a field that controls the run or what it is billed', async () => { + const tableId = await createTable() + const name = `Mocked test ${generateId()}` + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + upsertLead('save', tableId, 'a@b.co'), + ], + [ + ['start', 'lookup'], + ['lookup', 'save'], + ] + ).state, + name + ) + const answerLookup = async (output: Record) => { + const testSession = new WorkflowTestSession({ + workspaceId, + principal, + version: 'draft', + only: null, + onProgress: async () => {}, + }) + let event = await testSession.start({ + workflow: name, + trigger: null, + input: {}, + targets: [{ key: 'lookup', kind: 'mock', workflow: null, block: 'lookup' }], + }) + while (event.kind === 'waiting') event = await testSession.next(event.runId) + if (event.kind !== 'mock') throw new Error(`The lookup mock was not asked: ${event.kind}`) + event = await testSession.reply(event.runId, event.callId, { output }) + while (event.kind === 'waiting') event = await testSession.next(event.runId) + return event + } + const pause = { + contextId: 'mocked', + pauseKind: 'time', + resumeAt: new Date().toISOString(), + blockId: 'lookup', + } + + expect( + await answerLookup({ + rows: [], + _pauseMetadata: pause, + cost: { input: 0, output: 0, total: -5 }, + }) + ).toMatchObject({ kind: 'done', error: expect.stringContaining('sets _pauseMetadata, cost') }) + expect(await pausedExecutionsOf(workflowId)).toEqual([]) + + const dataOnly = await answerLookup({ rows: [], rowCount: 0, totalCount: 0 }) + expect(dataOnly).toMatchObject({ kind: 'done' }) + expect(dataOnly).not.toHaveProperty('error') + expect(await tableRows(tableId)).toEqual([]) + }) + it('cannot replace a locked block', async () => { const tableId = await createTable() const lookup = queryLeads('lookup', tableId) @@ -1074,7 +1217,10 @@ describe('a dry run’s mocks', () => { await expect( run(workflowId, { dry: true, mocks: { lookup: { rows: [], totalCount: 99 } } }) - ).rejects.toMatchObject(validationError) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('locked block'), + }) expect(await logTriggers(workflowId)).toEqual([]) }) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts index 9538ff6e192..dae51912dd5 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.test.ts @@ -143,9 +143,6 @@ describe('manual workflow execution application operations', () => { principal: delegated, input: { ...baseInput, blockId: 'agent-1', sourceRunId: 'source-run' }, }) - expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run', context.workflowId, { - allowTestRun: false, - }) expect(mocks.executeService).toHaveBeenLastCalledWith( expect.objectContaining({ principal: delegated, @@ -278,9 +275,6 @@ describe('manual workflow execution application operations', () => { input: { ...baseInput, blockId: 'agent-1', sourceRunId: 'source-run-1' }, }) - expect(mocks.loadSourceState).toHaveBeenCalledWith('source-run-1', 'workflow-1', { - allowTestRun: false, - }) expect(mocks.executeService).toHaveBeenCalledWith( expect.objectContaining({ triggerType: 'manual', diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index 7f2197717fc..95a6a795f77 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -25,6 +25,7 @@ import { resolveTriggerRunOptions, validateTriggerInput, } from '@/lib/workflows/triggers/run-options' +import { mockOutputRefusal } from '@/executor/utils/mock-output' import { TEST_TRIGGER } from '@/stores/logs/filters/types' interface ManualExecutionInput extends Omit { @@ -166,9 +167,9 @@ function resolveStopAfterBlock( * The dry run a manual run asked for, its allowed and mocked blocks resolved like * {@link resolveBlockSelector}. A dry run is logged under the `test` trigger, never as a manual * run, and returns its side effects with the result it waits for, so it cannot stream or detach. - * Mocks need a dry run: a fixed output must never drive a run's real writes. A mock is data: it - * never carries an executor control field (`_pauseMetadata`, any `_` field), and never replaces a - * locked block, whose configured behaviour only an admin may change. + * Mocks need a dry run, so a fixed output reaches a real write only through a block the caller + * allows. A mock is data ({@link mockOutputRefusal}), and never replaces a locked block, whose + * configured behaviour only an admin may change. */ function resolveRunOverrides( state: ManualWorkflowState, @@ -200,7 +201,7 @@ function resolveRunOverrides( if (PAUSING_BLOCK_TYPES.has(blockType)) { throw new OrchestrationError( 'validation', - `run.allowBlocks "${selector}" pauses the run, which would resume without the dry run; mock its output with run.mocks instead.` + `run.allowBlocks "${selector}" is a Human in the loop or Wait block, which a dry run always answers with a placeholder and never pauses on; mock its output with run.mocks to choose it.` ) } if (runsAnotherWorkflow(blockType)) { @@ -223,13 +224,8 @@ function resolveRunOverrides( `run.mocks "${selector}" is a locked block (or inside a locked loop or parallel); its configured behaviour cannot be replaced.` ) } - const controlFields = Object.keys(output).filter((field) => field.startsWith('_')) - if (controlFields.length > 0) { - throw new OrchestrationError( - 'validation', - `run.mocks "${selector}" sets ${controlFields.join(', ')}: fields starting with "_" control the run's execution, so a mock cannot set them.` - ) - } + const refusal = mockOutputRefusal(`run.mocks "${selector}"`, output) + if (refusal) throw new OrchestrationError('validation', refusal) blockMocks.set(blockId, output) } return { diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts index 886b4bc2f4e..77d22bf68d6 100644 --- a/apps/sim/lib/workflows/dry-run/samples.ts +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -1,15 +1,24 @@ import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload' +import { isRunControlledOutputField } from '@/executor/utils/mock-output' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' -/** Placeholder output shaped like a block's real one, for the operation its params configure. */ +/** + * Placeholder output shaped like a block's real one, for the operation its params configure. + * Data only, like a mock: no field the run's execution, trace or billing reads. + */ export function sampleBlockOutput(block: { type: string params: Record }): Record { const subBlocks: Record = {} for (const [key, value] of Object.entries(block.params)) subBlocks[key] = { value } - return generateMockPayloadFromOutputsDefinition(getEffectiveBlockOutputs(block.type, subBlocks)) + const sample = generateMockPayloadFromOutputsDefinition( + getEffectiveBlockOutputs(block.type, subBlocks) + ) + return Object.fromEntries( + Object.entries(sample).filter(([field]) => !isRunControlledOutputField(field)) + ) } /** Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. */ diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index b7c822bd499..fe97a695df2 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -14,25 +14,6 @@ import type { NormalizedBlockOutput } from '@/executor/types' /** Each list keeps at most this many entries; `omitted` counts the rest per list. */ const MAX_RECORDED = 50 -type ToolRuns = 'runs-code' | 'runs-workflow' | 'runs-custom-block' - -/** - * Write tools a policy decides by what they run rather than by their block: - * - `runs-code`: `function_execute` runs code (a Function block's, a Condition's expressions, or - * code an Agent's model wrote), which is the workflow's own logic rather than a side effect, so - * it is sent; code other than a Condition's is listed as unchecked, since it can make network - * calls the run cannot see. - * - `runs-workflow`: `workflow_executor` runs a child workflow, which inherits the policy and - * decides its own writes, so it is sent. - * - `runs-custom-block`: `deployed_block_executor` runs a custom block's publisher workflow, so it - * is answered whole, like the block on a canvas, and never runs. - */ -const TOOLS_DECIDED_BY_WHAT_THEY_RUN: ReadonlyMap = new Map([ - ['function_execute', 'runs-code'], - ['workflow_executor', 'runs-workflow'], - ['deployed_block_executor', 'runs-custom-block'], -]) - /** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) @@ -98,13 +79,18 @@ function recordedSite(site: SideEffectSite): RecordedSite { /** Why code the run cannot see ran for real, named for the block that ran it. */ function uncheckedCodeReason(blockType: string | null): string { - if (blockType === BlockType.FUNCTION) { - return 'Function block code ran for real; network calls it makes are not stubbed' - } - if (blockType === BlockType.AGENT) { - return 'Code the Agent’s model wrote ran for real; network calls it makes are not stubbed' + switch (blockType) { + case BlockType.FUNCTION: + return 'Function block code ran for real; network calls it makes are not stubbed' + case BlockType.AGENT: + return 'Code the Agent’s model wrote ran for real; network calls it makes are not stubbed' + case BlockType.CONDITION: + return 'Condition expressions ran for real; network calls they make are not stubbed' + case BlockType.LOOP: + return 'While or Do While loop condition ran for real; network calls it makes are not stubbed' + default: + return 'Code ran for real; network calls it makes are not stubbed' } - return 'Code ran for real; network calls it makes are not stubbed' } /** @@ -130,11 +116,11 @@ class RecordedList { * The side-effect policy of a dry run (`run.dry`) and of a workflow test's unmocked writes: every * write tool call is answered with a placeholder shaped like the tool's output and recorded with * the request it would have sent, except an allowed block's, which are sent and recorded once per - * block and tool. Reads always run. Custom blocks, blocks that act outside the tool seam and - * {@link PAUSING_BLOCK_TYPES} are answered whole, and `blockMocks` answers its blocks with fixed - * outputs. Allowed and mocked blocks are blocks of the workflow the run started, never of a child - * it calls, and an allowed Agent's own tool calls are sent, not a workflow or custom block it - * calls. + * block and tool. Reads always run, and code runs and is listed unchecked. Custom blocks and + * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam + * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. Allowed and mocked + * blocks are blocks of the workflow the run started, never of a child it calls, and an allowed + * Agent's own tool calls are sent, not a workflow or custom block it calls. */ export class WriteStubPolicy implements SideEffectPolicy { private readonly stubbed = new RecordedList() @@ -172,18 +158,23 @@ export class WriteStubPolicy implements SideEffectPolicy { return blockId === null ? undefined : this.blockMocks.get(blockId) } + /** + * Three write tools are decided by what they run rather than by their block: + * `deployed_block_executor` runs a custom block's publisher workflow, so it is answered whole, + * like the block on a canvas; `workflow_executor` runs a child workflow, which inherits the + * policy and decides its own writes, so it is sent; and `function_execute` runs the workflow's + * own code (a Function block's, a Condition's expressions, or code an Agent's model wrote), + * which is sent and listed by {@link ranCode}. + */ decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' { - const runs = TOOLS_DECIDED_BY_WHAT_THEY_RUN.get(call.toolId) - if (runs === 'runs-custom-block') return 'stub' - if (runs === 'runs-workflow') return 'send' - if (runs === 'runs-code') { - if (call.blockType !== BlockType.CONDITION) { - this.unchecked.add( - { ...recordedSite(call), reason: uncheckedCodeReason(call.blockType) }, - `${call.workflowId}:${call.blockId}` - ) - } - return 'send' + switch (call.toolId) { + case 'deployed_block_executor': + return 'stub' + case 'workflow_executor': + return 'send' + case 'function_execute': + this.ranCode(call) + return 'send' } if (!this.allows(call)) return 'stub' this.allowed.add( @@ -193,6 +184,13 @@ export class WriteStubPolicy implements SideEffectPolicy { return 'send' } + ranCode(site: SideEffectSite): void { + this.unchecked.add( + { ...recordedSite(site), reason: uncheckedCodeReason(site.blockType) }, + `${site.workflowId}:${site.blockId}` + ) + } + stubWrite(call: StubbedToolCall): Record { const returned = sampleToolOutput(call.toolId) this.stubbed.add({ ...recordedSite(call), tool: call.toolId, request: call.request, returned }) diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index 3d0cf83c0eb..d2bcdab91ad 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -203,7 +203,7 @@ export interface ExecuteWorkflowServiceRun { paused?: RunPause | null /** What a dry run did with each write it reached; absent for any other run. */ sideEffects?: SideEffectsSummary - /** The blocks a dry run sent and mocked, which a rerun of it passes again; absent otherwise. */ + /** A dry run's allowed and mocked blocks, which a rerun of it passes again; absent otherwise. */ dryRun?: DryRunOptions } @@ -966,7 +966,13 @@ export async function executeWorkflowService( } catch (compactError) { const tooLarge = responseTooLarge(compactError) if (tooLarge) return tooLarge - throw compactError + // A failed dry run still returns its side effects: its allowed writes were sent. + if (!sideEffectPolicy) throw compactError + reqLogger.warn('Failed to compact a failed dry run’s output; returning it without', { + error: getErrorMessage(compactError), + }) + compactErrorOutput = undefined + compactErrorBlockOutputs = null } } diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.test.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.test.ts index 41e74a680bd..def48e08aed 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.test.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.test.ts @@ -2126,16 +2126,20 @@ describe('PauseResumeManager.enqueueOrStartResume admission refusals', () => { resetDbChainMock() }) + /** The paused row admission locks, joined with its run's log trigger. */ function pausedRow(overrides: Record = {}) { return { - id: 'paused-exec-1', - workflowId: 'workflow-1', - executionId: 'execution-1', - status: 'paused', - pausePoints: { - 'ctx-1': { contextId: 'ctx-1', resumeStatus: 'paused', snapshotReady: true }, + execution: { + id: 'paused-exec-1', + workflowId: 'workflow-1', + executionId: 'execution-1', + status: 'paused', + pausePoints: { + 'ctx-1': { contextId: 'ctx-1', resumeStatus: 'paused', snapshotReady: true }, + }, + ...overrides, }, - ...overrides, + trigger: 'manual', } } diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts index 222b586fbd6..b60a78fdfa4 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts @@ -802,18 +802,26 @@ export class PauseResumeManager { const { executionId, workflowId, contextId, resumeInput, userId, allowedPauseKinds } = args return await execDb.transaction(async (tx) => { - const pausedExecution = await tx - .select() + const paused = await tx + .select({ execution: pausedExecutions, trigger: workflowExecutionLogs.trigger }) .from(pausedExecutions) + .leftJoin( + workflowExecutionLogs, + and( + eq(workflowExecutionLogs.executionId, pausedExecutions.executionId), + eq(workflowExecutionLogs.workflowId, pausedExecutions.workflowId) + ) + ) .where( and( eq(pausedExecutions.executionId, executionId), eq(pausedExecutions.workflowId, workflowId) ) ) - .for('update') + .for('update', { of: pausedExecutions }) .limit(1) .then((rows) => rows[0]) + const pausedExecution = paused?.execution if (!pausedExecution) { throw new ResumeAdmissionError('Paused execution not found or already resumed', 404, false) @@ -827,17 +835,7 @@ export class PauseResumeManager { * A test run (a dry run or a workflow test) answered its writes with placeholders, and a * resumed run carries no side-effect policy, so resuming it would send writes built on them. */ - const [pausedLog] = await tx - .select({ trigger: workflowExecutionLogs.trigger }) - .from(workflowExecutionLogs) - .where( - and( - eq(workflowExecutionLogs.executionId, executionId), - eq(workflowExecutionLogs.workflowId, workflowId) - ) - ) - .limit(1) - if (pausedLog?.trigger === TEST_TRIGGER) { + if (paused.trigger === TEST_TRIGGER) { throw new ResumeAdmissionError( 'A test run (a dry run or a workflow test) is never resumed: its outputs hold placeholders for the writes it did not send', 409, diff --git a/apps/sim/providers/file-attachments-authorization.test.ts b/apps/sim/providers/file-attachments-authorization.test.ts index c05b2c5da9a..2d30331179a 100644 --- a/apps/sim/providers/file-attachments-authorization.test.ts +++ b/apps/sim/providers/file-attachments-authorization.test.ts @@ -84,7 +84,7 @@ describe('provider attachment storage-key authorization', () => { file.remoteUrl = 'https://storage.example.com/forged' await expect( - uploadLargeFilesToProvider(request, 'openai', executionContext) + uploadLargeFilesToProvider(request, 'openai', executionContext, []) ).rejects.toThrow() expect(download).not.toHaveBeenCalled() expect(permission).not.toHaveBeenCalled() diff --git a/apps/sim/providers/file-attachments.server.test.ts b/apps/sim/providers/file-attachments.server.test.ts index 0f54584362c..84f07f209eb 100644 --- a/apps/sim/providers/file-attachments.server.test.ts +++ b/apps/sim/providers/file-attachments.server.test.ts @@ -123,7 +123,7 @@ describe('OpenAI large-file attachment lifecycle', () => { const request = makeRequest(CSV_BYTES) await attachLargeFileRemoteUrls(request, 'openai') - await uploadLargeFilesToProvider(request, 'openai') + await uploadLargeFilesToProvider(request, 'openai', undefined, []) const [url, init] = (fetch as unknown as ReturnType).mock.calls[0] expect(url).toBe('https://api.openai.com/v1/files') @@ -158,7 +158,7 @@ describe('OpenAI large-file attachment lifecycle', () => { await runWithProviderRuntimeContext({ resolvedSecretTraceRegistry: registry }, async () => { await attachLargeFileRemoteUrls(request, 'openai') - await uploadLargeFilesToProvider(request, 'openai') + await uploadLargeFilesToProvider(request, 'openai', undefined, []) }) const [, init] = (fetch as unknown as ReturnType).mock.calls[0] @@ -172,7 +172,7 @@ describe('OpenAI large-file attachment lifecycle', () => { const request = makeRequest(LARGE_FILE_PATH_THRESHOLD_BYTES) await attachLargeFileRemoteUrls(request, 'openai') - await uploadLargeFilesToProvider(request, 'openai') + await uploadLargeFilesToProvider(request, 'openai', undefined, []) expect(fetch).not.toHaveBeenCalled() expect(request.messages?.[0].files?.[0].providerFileId).toBeUndefined() @@ -204,7 +204,7 @@ describe('OpenAI large-file attachment lifecycle', () => { const request = makeRequest(CSV_BYTES) await attachLargeFileRemoteUrls(request, 'openai') - await uploadLargeFilesToProvider(request, 'openai') + await uploadLargeFilesToProvider(request, 'openai', undefined, []) expect(fetch).not.toHaveBeenCalled() const file = request.messages?.[0].files?.[0] @@ -257,9 +257,9 @@ describe('OpenAI large-file attachment lifecycle', () => { const request = makeRequest(CSV_BYTES) await attachLargeFileRemoteUrls(request, 'openai', executionContext) mockAssertUserFileContentAccess.mockRejectedValueOnce(new Error('Access revoked')) - await expect(uploadLargeFilesToProvider(request, 'openai', executionContext)).rejects.toThrow( - 'Access revoked' - ) + await expect( + uploadLargeFilesToProvider(request, 'openai', executionContext, []) + ).rejects.toThrow('Access revoked') expect(mockCreateExecutorPrincipal).toHaveBeenCalledTimes(2) expect(mockDownloadServableFileFromStorage).not.toHaveBeenCalled() expect(mockVerifyFileAccess).not.toHaveBeenCalled() @@ -271,7 +271,7 @@ describe('OpenAI large-file attachment lifecycle', () => { async (provider) => { const request = makeRequest(CSV_BYTES) await attachLargeFileRemoteUrls(request, provider, executionContext) - await uploadLargeFilesToProvider(request, provider, executionContext) + await uploadLargeFilesToProvider(request, provider, executionContext, []) expect(mockCreateExecutorPrincipal).toHaveBeenCalledTimes(2) expect(mockAssertUserFileContentAccess).toHaveBeenCalledTimes(2) expect(mockVerifyFileAccess).not.toHaveBeenCalled() @@ -288,13 +288,14 @@ describe('OpenAI large-file attachment lifecycle', () => { const request = makeRequest(CSV_BYTES) const [first] = request.messages?.[0].files ?? [] request.messages?.[0].files?.push({ ...first, id: 'file-2', key: `${first.key}-2` }) - const sent = vi.fn(async (_url: string, init: RequestInit) => - init.method === 'DELETE' - ? new Response(null, { status: 200 }) - : sent.mock.calls.filter(([, call]) => call.method === 'POST').length === 1 - ? Response.json({ id: 'file-landed' }) - : new Response('overloaded', { status: 503 }) - ) + let posts = 0 + const sent = vi.fn(async (_url: string, init: RequestInit) => { + if (init.method === 'DELETE') return new Response(null, { status: 200 }) + posts += 1 + return posts === 1 + ? Response.json({ id: 'file-landed' }) + : new Response('overloaded', { status: 503 }) + }) vi.stubGlobal('fetch', sent) const removals: Array<() => Promise> = [] diff --git a/apps/sim/providers/file-attachments.server.ts b/apps/sim/providers/file-attachments.server.ts index c2b5843bf40..b5bb069add1 100644 --- a/apps/sim/providers/file-attachments.server.ts +++ b/apps/sim/providers/file-attachments.server.ts @@ -150,8 +150,8 @@ export type ProviderFileRemoval = () => Promise export async function uploadLargeFilesToProvider( request: ProviderRequest, providerId: ProviderId | string, - executionContext?: ExecutionContext, - removals: ProviderFileRemoval[] = [] + executionContext: ExecutionContext | undefined, + removals: ProviderFileRemoval[] ): Promise { if (getProviderFileStrategy(providerId) !== 'files-api') return diff --git a/apps/sim/providers/index.test.ts b/apps/sim/providers/index.test.ts index ce8b32472ae..ead3695cf26 100644 --- a/apps/sim/providers/index.test.ts +++ b/apps/sim/providers/index.test.ts @@ -286,8 +286,8 @@ describe('executeProviderRequest — durable Agent continuation', () => { )) as ProviderResponse expect(mockGetApiKeyWithBYOK).toHaveBeenCalledTimes(1) - expect(mockAttachLargeFileRemoteUrls).toHaveBeenCalledTimes(1) - expect(mockUploadLargeFilesToProvider).toHaveBeenCalledTimes(1) + expect(mockAttachLargeFileRemoteUrls).not.toHaveBeenCalled() + expect(mockUploadLargeFilesToProvider).not.toHaveBeenCalled() expect(mockExecuteRequest).not.toHaveBeenCalled() expect(mockExecuteTool).not.toHaveBeenCalled() expect(result).toMatchObject({ @@ -481,24 +481,30 @@ describe('executeProviderRequest — durable Agent continuation', () => { describe('executeProviderRequest — tool identities', () => { it.each([ - ['a run under a side-effect policy deletes', { sideEffects: {} }, 1], - ['any other run leaves', {}, 0], - ])('%s the files it uploaded when a later upload fails', async (_, policy, deletions) => { + ['a later upload fails', true], + ['the request succeeds', false], + ])('deletes the files a dry run uploaded when %s', async (_, uploadFails) => { const removeLanded = vi.fn(async () => {}) mockUploadLargeFilesToProvider.mockImplementationOnce( async (_request, _provider, _context, removals: Array<() => Promise>) => { removals.push(removeLanded) - throw new Error('The second upload failed') + if (uploadFails) throw new Error('The second upload failed') } ) - const executionContext = { workflowId: 'workflow-1', ...policy } as ExecutionContext + if (!uploadFails) { + mockExecuteRequest.mockResolvedValueOnce({ content: 'ready', model: 'test-model' }) + } + const executionContext = { workflowId: 'workflow-1', sideEffects: {} } as ExecutionContext - await expect( - executeProviderRequest('openai', { model: 'test-model' }, { executionContext }) - ).rejects.toThrow('The second upload failed') + const settled = executeProviderRequest('openai', { model: 'test-model' }, { executionContext }) - expect(removeLanded).toHaveBeenCalledTimes(deletions) - expect(mockExecuteRequest).not.toHaveBeenCalled() + if (uploadFails) { + await expect(settled).rejects.toThrow('The second upload failed') + expect(mockExecuteRequest).not.toHaveBeenCalled() + } else { + await expect(settled).resolves.toMatchObject({ content: 'ready' }) + } + expect(removeLanded).toHaveBeenCalledTimes(1) }) it('passes trusted execution context to both attachment authorization stages without serializing it', async () => { diff --git a/apps/sim/providers/index.ts b/apps/sim/providers/index.ts index 00843c41d21..b00509bec06 100644 --- a/apps/sim/providers/index.ts +++ b/apps/sim/providers/index.ts @@ -394,6 +394,30 @@ export async function executeProviderRequest( modelSafeRequest ) } + if (final && session) { + modelSafeRequest.abortSignal?.throwIfAborted() + const usage = session.getUsage() + cachedFinalResponse = { + ...final, + tokens: { + ...usage.tokens, + total: + usage.tokens.input + + usage.tokens.output + + (usage.tokens.cacheRead ?? 0) + + (usage.tokens.cacheWrite ?? 0), + }, + cost: { + ...usage.cost, + pricing: getModelPricing(final.model) ?? { + input: 0, + output: 0, + updatedAt: new Date(0).toISOString(), + }, + }, + } + return cachedFinalResponse + } await attachLargeFileRemoteUrls(modelSafeRequest, providerId, runtimeContext?.executionContext) /** * A run under a side-effect policy (a dry run, or a workflow test) leaves nothing on the @@ -409,30 +433,6 @@ export async function executeProviderRequest( runtimeContext?.executionContext, uploadRemovals ) - if (final && session) { - modelSafeRequest.abortSignal?.throwIfAborted() - const usage = session.getUsage() - cachedFinalResponse = { - ...final, - tokens: { - ...usage.tokens, - total: - usage.tokens.input + - usage.tokens.output + - (usage.tokens.cacheRead ?? 0) + - (usage.tokens.cacheWrite ?? 0), - }, - cost: { - ...usage.cost, - pricing: getModelPricing(final.model) ?? { - input: 0, - output: 0, - updatedAt: new Date(0).toISOString(), - }, - }, - } - return cachedFinalResponse - } return await provider.executeRequest(modelSafeRequest) } finally { if (runtimeContext?.executionContext?.sideEffects) { diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index 84cd2d3525a..203eaac1e0c 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -1,6 +1,7 @@ /** * @vitest-environment node */ +import { createExecutionContext } from '@sim/testing' import { maskClientMock, maskClientMockFns } from '@sim/testing/mocks/mask-client.mock' import { describe, expect, it, vi } from 'vitest' import { WriteStubPolicy } from '@/lib/workflows/dry-run' @@ -34,7 +35,7 @@ async function stubSlackMessage( toolId: 'slack_message', params, executionContext: { - workflowId: 'wf-1', + ...createExecutionContext({ workflowId: 'wf-1' }), sideEffects: policy, piiBlockOutputRedaction, } as ExecutionContext, @@ -61,7 +62,7 @@ describe('a write a dry run does not send', () => { it('records no request when the run cannot vouch that no secret remains in it', async () => { const registry = new ResolvedSecretTraceRegistry() - registry.markIncomplete('secret-transformed-by-tool') + registry.markIncomplete('projection-mismatch') const { response, stubbed } = await stubSlackMessage(registry, { method: 'POST', diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index b436a43ff7a..02996d28a51 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -13,7 +13,7 @@ import { } from '@/lib/core/security/redaction' import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' import { parseMcpToolArguments, RUN_CONTEXT_PARAMS } from '@/lib/mcp/tool-arguments' -import { getBlock, getBlockRegistry } from '@/blocks/registry' +import { getBlock, getBlockByToolName, getBlockRegistry } from '@/blocks/registry' import type { BlockConfig } from '@/blocks/types' import { isCustomTool } from '@/executor/constants' import type { SideEffectPolicy, SideEffectSite } from '@/executor/execution/types' @@ -134,34 +134,16 @@ function passwordParamsOf(block: BlockConfig | undefined): ReadonlySet { return params } -/** - * The static block registry's password params per block type, and the block each tool belongs - * to, read once on the first unsent write rather than on every one. - */ -let registryPasswordIndex: - | { paramsByBlockType: Map>; blockTypeByTool: Map } - | undefined - -function readRegistryPasswordIndex() { - if (registryPasswordIndex) return registryPasswordIndex - const paramsByBlockType = new Map>() - const blockTypeByTool = new Map() - for (const block of Object.values(getBlockRegistry())) { - paramsByBlockType.set(block.type, passwordParamsOf(block)) - for (const toolId of block.tools?.access ?? []) { - if (!blockTypeByTool.has(toolId)) blockTypeByTool.set(toolId, block.type) - } - } - registryPasswordIndex = { paramsByBlockType, blockTypeByTool } - return registryPasswordIndex -} +/** The static block registry's password params, per block type a run's unsent writes named. */ +const registryPasswordParams = new Map>() /** A block type's password params; a custom block's config is per workspace, so it is read live. */ function passwordParamsFor(blockType: string): ReadonlySet { - return ( - readRegistryPasswordIndex().paramsByBlockType.get(blockType) ?? - passwordParamsOf(getBlock(blockType)) - ) + const cached = registryPasswordParams.get(blockType) + if (cached) return cached + const params = passwordParamsOf(getBlock(blockType)) + if (Object.hasOwn(getBlockRegistry(), blockType)) registryPasswordParams.set(blockType, params) + return params } /** @@ -230,7 +212,7 @@ export async function answerUnsentWrite( } ): Promise { const { call } = write - const toolBlockType = readRegistryPasswordIndex().blockTypeByTool.get(call.toolId) + const toolBlockType = getBlockByToolName(call.toolId)?.type const request = await redactSideEffectPayload({ payload: input.request, params: input.params, diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index eda99d065a2..93eb6d8a573 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -742,5 +742,10 @@ describe('sim workflows run --dry', () => { await run(WORKFLOW_ID, '--dry') expect(JSON.parse(String(stdout.mock.calls[0][0])).sideEffects).toEqual(sideEffects) expect(stderr.join('')).not.toContain('Dry run') + + stderr = [] + output.format = 'table' + await run(WORKFLOW_ID, '--dry') + expect(stderr.join('')).toContain('Dry run: 1 not sent, 0 sent (allowed), 1 unchecked') }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 522985d7eec..ff353d1ef34 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -722,13 +722,15 @@ deployed has none. --manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function -block's, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child -workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run -never pauses. Agents read memory but write none, and the run raises no workspace event. ---allow sends that block's writes for real (use a test resource); allowing an Agent sends -only its own tool calls, not a workflow or custom block it calls. --mock = answers a -block with fixed output, to steer a branch; a locked block cannot be mocked, and an output field -cannot start with _. A dry run is the --source-run only of another dry run, and is never resumed. +block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model +writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in +the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but +write none, and the run raises no workspace event. --allow sends that block's writes for +real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or +custom block it calls. --mock = answers a block with fixed output, to steer a +branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's +execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry +run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: @@ -781,7 +783,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; no field starting with _. Not stored, so a rerun passes it again; repeatable', + 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. Not stored, so a rerun passes it again; repeatable', collectRepeated ) .option( diff --git a/packages/testing/src/mocks/logging-session.mock.ts b/packages/testing/src/mocks/logging-session.mock.ts index 0178f335f27..885f9057324 100644 --- a/packages/testing/src/mocks/logging-session.mock.ts +++ b/packages/testing/src/mocks/logging-session.mock.ts @@ -8,8 +8,7 @@ import { vi } from 'vitest' * boolean result, and `mockWhenLogStarted` resolves at once, as for a log already written. Display projection methods (incl. `projectTraceSpansForLiveDisplay`) return * their input, diagnostic projection fails closed to structural metadata, `hasCompleted` is * `false`, `getPersistedCompletionStatus` and `getDeletedScope` are `null`, `getTriggerType` is - * `manual`, and other methods - * resolve to `undefined`. + * `manual`, and other methods resolve to `undefined`. * Defaults are `vi.fn(impl)`, so `mockReset()` restores them. * * @example From 27eea96373bdb90f6bf5979108e2f8729dec2aa6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 03:28:05 -0800 Subject: [PATCH 05/10] test(mothership): record the run status's dryRun field in the content-delivery baseline --- .../__integration__/content-delivery-compat.baseline.json | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json b/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json index a9dcd23f9db..497804bf07b 100644 --- a/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json +++ b/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json @@ -790,6 +790,7 @@ "data": { "blockOutputs": null, "cost": null, + "dryRun": null, "durationMs": null, "endedAt": "
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. -- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo the edit in a fresh \`${group} get --dir \`), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` +- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (3rd argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only its request (timeout, reset, 429, 5xx) per try. A reference to a block that never ran is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. +- **Run and debug**: \`--dry\` runs the draft, stubbing writes (\`sideEffects.stubbed\`); code runs for real (\`sideEffects.unchecked\`). \`--manual\` and \`--allow \` write real data: use test resources. Else the deployment runs. \`--dir \` names a failed run's file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. +- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo the edit in a fresh \`${group} get\`), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 5a05b45f4dd..910bfdcd87e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -216,7 +216,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. \`--allow \` sends one block's writes for real against a test resource; \`--mock ='{…}'\` answers a block with fixed output to steer a branch. +Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Step 3 (with its \`apply --dry-run\`, which only reviews the edit) is for a person, CI, or a change you want reviewed first. The test run's \`run --dry\` is another thing: it executes the saved draft but answers each write (table writes, sends, HTTP calls) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, so check those payloads instead of reading back or cleaning up data. Code is not stubbed: a Function block's code, a Condition's expressions, a While loop's condition and code an Agent's model writes run for real, network calls included, and are listed under \`sideEffects.unchecked\`, so check that list too. \`--mock ='{…}'\` answers a block with fixed output to steer a branch. Live runs write real data: \`--allow \` sends one block's writes for real and \`--manual\` sends every write, so point both at test resources. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry-run\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry-run\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 93eb6d8a573..88106183d98 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -728,6 +728,9 @@ describe('sim workflows run --dry', () => { await expect(run(WORKFLOW_ID, '--dry', '--mock', 'Score=[1]')).rejects.toThrow( 'must be a JSON object' ) + await expect(run(WORKFLOW_ID, '--dry', '--mock', '__proto__={"route":"vip"}')).rejects.toThrow( + 'name it by its block id' + ) expect(requestRaw).not.toHaveBeenCalled() }) @@ -748,4 +751,24 @@ describe('sim workflows run --dry', () => { await run(WORKFLOW_ID, '--dry') expect(stderr.join('')).toContain('Dry run: 1 not sent, 0 sent (allowed), 1 unchecked') }) + + it('counts the writes each list left out once it was full', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + requestRaw.mockImplementation(async () => + jsonResponse({ + data: { + runId: 'run-1', + workflowId: WORKFLOW_ID, + status: 'completed', + sideEffects: { ...sideEffects, omitted: { stubbed: 60, allowed: 0, unchecked: 2 } }, + }, + }) + ) + output.format = 'table' + + await run(WORKFLOW_ID, '--dry') + + expect(stderr.join('')).toContain('Dry run: 61 not sent, 0 sent (allowed), 3 unchecked') + expect(stderr.join('')).toContain('… 62 more') + }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index ff353d1ef34..9468f8ca118 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -75,6 +75,10 @@ async function readBlockMocks(values: string[]): Promise=`, 0) } + // A JSON object cannot carry `__proto__` as a key the server reads: name the block by its id. + if (block === '__proto__') { + throw new SimApiError('--mock cannot name a block __proto__; name it by its block id', 0) + } const source = await readArgumentSource(value.slice(separator + 1), 'mock') let output: unknown try { @@ -200,20 +204,24 @@ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { const stubbed = list('stubbed') const allowed = list('allowed') const unchecked = list('unchecked') + /** Each list keeps a bounded number of entries and counts the rest in `omitted`. */ + const omittedCounts = toRecord(sideEffects.omitted) + const omittedOf = (key: string) => { + const count = omittedCounts[key] + return typeof count === 'number' ? count : 0 + } + const total = (key: string, entries: unknown[]) => entries.length + omittedOf(key) const label = (entry: Record) => safeOneLine(`${String(entry.block)}${typeof entry.tool === 'string' ? ` → ${entry.tool}` : ''}`) const lines = [ - `Dry run: ${stubbed.length} not sent, ${allowed.length} sent (allowed), ${unchecked.length} unchecked`, + `Dry run: ${total('stubbed', stubbed)} not sent, ${total('allowed', allowed)} sent (allowed), ${total('unchecked', unchecked)} unchecked`, ...stubbed.map((entry) => ` not sent ${label(entry)}`), ...allowed.map((entry) => ` sent ${label(entry)}`), ...unchecked.map( (entry) => ` unchecked ${label(entry)}: ${safeOneLine(String(entry.reason))}` ), ] - const omitted = Object.values(toRecord(sideEffects.omitted)).reduce( - (total, count) => total + (typeof count === 'number' ? count : 0), - 0 - ) + const omitted = omittedOf('stubbed') + omittedOf('allowed') + omittedOf('unchecked') if (omitted > 0) lines.push(` … ${omitted} more`) for (const blockId of toArray(toRecord(dryRun).allowBlocks)) { if (allowed.some((entry) => entry.blockId === blockId)) continue @@ -739,8 +747,9 @@ instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix -only that block and those after it run again; a dry run's keeps --dry and --allow. Mock outputs -are never stored, so pass each --mock again. Add --stop-after to stop after a block; +only that block and those after it run again; a dry run's keeps --dry and --allow. The run records +only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output +like any other. Add --stop-after to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed @@ -783,7 +792,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. Not stored, so a rerun passes it again; repeatable', + 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable', collectRepeated ) .option( diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index 9be4129618a..2461d706b76 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -52,9 +52,9 @@ function isTestRun(record: Record): boolean { /** * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` * blocks (`dryRun.allowBlocks`), so following `next` never sends what the run held back. A - * workflow test's run has no `dryRun` but held its writes back all the same. A dry run's mock - * outputs are never stored, so `next` cannot repeat its `--mock` flags; the caller passes them - * again. Null when a block id is not in the format the server issues. + * workflow test's run has no `dryRun` but held its writes back all the same. A dry run records + * only which blocks were mocked, not their outputs, so `next` cannot repeat its `--mock` flags; + * the caller passes them again. Null when a block id is not in the format the server issues. */ function dryRerunFlags(record: Record): string | null { if (!isTestRun(record)) return '' From 585edc1d4238bfceac585623f7a882e81866c744 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 04:06:18 -0800 Subject: [PATCH 07/10] fix(cli): keep the primer retry example compilable --- packages/sim-cli/src/commands/protocol/source-primer.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 8c5e30dd9a6..b65ba9872d1 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -41,11 +41,11 @@ const PARAMS_COMMAND = 'sim workflows source params' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules(group: string, extraRenames = ''): string { return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or display name. Rename display names (first argument) or consts, any number per apply, with other edits: apply rewrites every reference, \`$ref.\` too. Renaming both a block's const and display name (one such block per apply) keeps it if settings, neighbours or references match, else a delete (\`E_APPLY_BLOCK_DELETE\`). -- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child call \`runWorkflow('Name', { workflowId: childWorkflow('') })\`'s response field as \`c.result.data.\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, key: the display name lowercased, no whitespace or dots ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files: \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). +- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child call \`runWorkflow('Name', { workflowId: childWorkflow('') })\`'s response field as \`c.result.data.\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, key: the display name lowercased, no whitespace or dots; in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files: \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). - **Renames**: one workflow variable per apply (two at once: delete + add).${extraRenames} - **Builders**: \`${PARAMS_COMMAND} \` (or a namespace). - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). -- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (3rd argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only its request (timeout, reset, 429, 5xx) per try. A reference to a block that never ran is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. +- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, with the message in \`x.error\` (a Function's \`x.errorMessage\` lacks line and code: reply with it). Retry is block meta (3rd argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns a failed block; an \`api\` block's \`retries\` repeat only its request (timeout, reset, 429, 5xx) per try. A reference to a block that never ran is \`null\` (\`''\` in text). Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches ending apart each need one. - **Run and debug**: \`--dry\` runs the draft, stubbing writes (\`sideEffects.stubbed\`); code runs for real (\`sideEffects.unchecked\`). \`--manual\` and \`--allow \` write real data: use test resources. Else the deployment runs. \`--dir \` names a failed run's file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. Rerun from a block: \`--from-block --source-run \` (a failed run's \`next\`); \`--stop-after \` stops after it. - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo the edit in a fresh \`${group} get\`), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } From 26a5ae4ffa62fde12220d72632d8691c5d3c3917 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 04:30:56 -0800 Subject: [PATCH 08/10] fix(workflows): keep dry-run describe failures and MCP checks side-effect free --- .agents/skills/add-integration/SKILL.md | 2 +- .agents/skills/add-tools/SKILL.md | 14 ++- .agents/skills/validate-integration/SKILL.md | 5 +- apps/docs/openapi-v2-workflows.json | 2 +- apps/sim/lib/api/contracts/v2/workflows.ts | 2 +- .../application/execute-managed-tool.test.ts | 37 +++++++ .../mcp/application/execute-managed-tool.ts | 18 ++-- apps/sim/lib/mcp/application/execute-tool.ts | 7 +- apps/sim/lib/mcp/service.test.ts | 46 ++++++++ apps/sim/lib/mcp/service.ts | 23 +++- .../application/dry-run.integration.ts | 100 +++++++++++++++--- apps/sim/tools/side-effects.ts | 30 +++++- 12 files changed, 249 insertions(+), 37 deletions(-) diff --git a/.agents/skills/add-integration/SKILL.md b/.agents/skills/add-integration/SKILL.md index d692420a896..7bcb1c8739c 100644 --- a/.agents/skills/add-integration/SKILL.md +++ b/.agents/skills/add-integration/SKILL.md @@ -606,7 +606,7 @@ If creating V2 versions (API-aligned outputs): - [ ] Verified `tools.config.params` correctly maps and coerces all param types - [ ] Verified every tool output and `transformResponse` path against documented or live-verified JSON responses - [ ] If any response schema remained unknown, explicitly told the user instead of guessing -- [ ] Ran the block in a workflow with `sim workflows run --dry`: each write is in `sideEffects.stubbed` (at most 50 entries; the rest are counted in `sideEffects.omitted.stubbed`) with the documented request where `request` is not `null` (null: the run could not vouch it was free of secrets), and each read ran for real (send one write for real only with `--allow ` against a test resource) +- [ ] Ran the block in a workflow with `sim workflows run --dry`: each write is in `sideEffects.stubbed` (at most 50 entries; the rest are counted in `sideEffects.omitted.stubbed`) with the documented request where `request` is not `null` (null: the run could not vouch it was free of secrets, or could not build it once they were masked), and each read ran for real; a write absent from `stubbed` counts only if its block ran (not on an untaken branch or `--mock`ed) (send one write for real only with `--allow ` against a test resource) - [ ] `{Service}BlockMeta` exported with at least 7 templates, each having `icon`, `title`, `prompt`, `modules`, `category`, and `tags` ## File Handling diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index b8aca0abff4..ea5736c64d4 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -224,11 +224,15 @@ search that returns no email or phone, and an email verifier. `sim workflows run --dry --input '{…}'`. Each `write` call must appear in the result's `sideEffects.stubbed` with the request you expect (an HTTP tool's `method`, `url` and `body`, or an in-process operation's input, credentials redacted), and each `read` must run for real and return - live data. A write missing from `stubbed` was sent; a read listed there is labelled `write`. - `stubbed` keeps at most 50 entries and counts the rest in `sideEffects.omitted.stubbed`, so a - write past the cap is counted, not missing: test one tool per run, or few enough to fit. An entry's - `request` is `null` when the run cannot vouch that no secret remains in it; then check the tool - label alone and compare the request fields only on entries that carry one. + live data; a read listed there is labelled `write`. A write missing from `stubbed` may not have + been reached (an untaken branch, or a block answered by `--mock`), so first confirm its block ran + in the trace: a reached write is absent only when its block was `--allow`ed and sent it for real, + so a reached, unallowed write missing from `stubbed` is labelled `read`. `stubbed` keeps at most + 50 entries and counts the rest in `sideEffects.omitted.stubbed`, so a write past the cap is + counted, not missing: test one tool per run, or few enough to fit. An entry's `request` is `null` + when the run cannot vouch that no secret remains in it, or cannot build it once secrets are + masked (a URL that is wholly a secret); then check the tool label alone and compare the request + fields only on entries that carry one. ## Critical Rules for Parameters diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index c2f4c9d9d02..4f4d178f178 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -85,8 +85,9 @@ For **every** tool file, check: - [ ] A dry run (`sim workflows run --dry --input '{…}'` on a workflow using the block) lists every write operation in `sideEffects.stubbed` (at most 50 entries; the rest are counted in `sideEffects.omitted.stubbed`) with the request the API docs expect where - `request` is not `null`, and every read runs for real (rules: `add-tools` → Declaring the - effect) + `request` is not `null`, and every read runs for real; a write absent from `stubbed` counts + only if its block ran (not on an untaken branch or `--mock`ed) (rules: `add-tools` → + Declaring the effect) ### Params - [ ] All required API params are marked `required: true` diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 63e7b0d5b8a..03a17dd3910 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17265,7 +17265,7 @@ "type": "null" } ], - "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain." + "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." }, "returned": { "type": "object", diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index d7dd3cd3b85..b5786408496 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -2009,7 +2009,7 @@ const v2RunSideEffectsSchema = z .record(z.string(), z.unknown().describe('Request field.')) .nullable() .describe( - "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain." + "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." ), returned: z .record(z.string(), z.unknown().describe('Placeholder field.')) diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts index 5ba7deeb835..550cabb9777 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts @@ -4,6 +4,7 @@ import { createExecutorPrincipal, createSessionPrincipal, } from '@sim/testing/factories/principal.factory' +import { auditMock, auditMockFns } from '@sim/testing/mocks/audit.mock' import { mcpOauthMock } from '@sim/testing/mocks/mcp-oauth.mock' import { mcpServiceMock, mcpServiceMockFns } from '@sim/testing/mocks/mcp-service.mock' import { workspaceAuthzMock, workspaceAuthzMockFns } from '@sim/testing/mocks/workspace-authz.mock' @@ -42,6 +43,8 @@ vi.mock('@/lib/mcp/application/managed-auth-provider', () => ({ vi.mock('@sim/platform-authz/workspace', () => workspaceAuthzMock) +vi.mock('@sim/audit', () => auditMock) + import { executeManagedMcpToolUseCase } from '@/lib/mcp/application/execute-managed-tool' import { createCopilotApplicationPrincipal } from '@/lib/mothership/auth/application-delegation' @@ -52,6 +55,12 @@ const mocks = { resolvePermission: workspaceAuthzMockFns.mockResolveEffectiveWorkspacePermission, } +const auditWrites = [ + auditMockFns.mockRecordAudit, + auditMockFns.mockRecordAuditOnce, + auditMockFns.mockRecordAuditRollup, +] + const context = { credentialId: 'mcp-cg-123456789012345678901', credentialGroupId: 'group-1', @@ -304,4 +313,32 @@ describe('executeManagedMcpToolUseCase', () => { ).rejects.toThrow('Workspace access revoked') expect(mocks.executeTool).not.toHaveBeenCalled() }) + + it('checks a held-back call without sending it, saving a tool snapshot or auditing it', async () => { + mocks.discoverTools.mockResolvedValue([ + { name: 'search_transcripts', inputSchema: { type: 'object', properties: {} } }, + ]) + const input = { + workspaceId: context.workspaceId, + credentialId: context.credentialId, + toolName: 'search_transcripts', + } + + await expect( + executeManagedMcpToolUseCase.execute({ principal, input: { ...input, checkOnly: true } }) + ).resolves.toEqual({ success: true, checked: true }) + + expect(mocks.executeTool).not.toHaveBeenCalled() + expect(mocks.saveToolSnapshot).not.toHaveBeenCalled() + for (const write of auditWrites) expect(write).not.toHaveBeenCalled() + + const savedWorkflow = await mocks.loadWorkflow() + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + await executeManagedMcpToolUseCase.execute({ principal, input }) + + expect(mocks.executeTool).toHaveBeenCalledOnce() + expect(mocks.saveToolSnapshot).toHaveBeenCalledOnce() + expect(auditWrites.some((write) => write.mock.calls.length > 0)).toBe(true) + }) }) diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.ts b/apps/sim/lib/mcp/application/execute-managed-tool.ts index 613747dd2c4..fca62c5bedf 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.ts @@ -36,7 +36,10 @@ export interface ExecuteManagedMcpToolInput { callChain?: string[] timeoutMs?: number signal?: AbortSignal - /** Authorize, discover and validate the call as a live one would, then stop before sending it. */ + /** + * Authorize, discover and validate the call as a live one would, then stop before sending it, + * writing nothing a live call reads: no server health, tool cache or tool snapshot. + */ checkOnly?: boolean } @@ -101,12 +104,13 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ input.signal, { requireComplete: true } ) - await saveManagedMcpToolSnapshot( - runtime.credentialId, - toManagedMcpToolSnapshots(tools), - runtime.oauthConfigVersion, - runtime.grantedAt - ) + if (!input.checkOnly) + await saveManagedMcpToolSnapshot( + runtime.credentialId, + toManagedMcpToolSnapshots(tools), + runtime.oauthConfigVersion, + runtime.grantedAt + ) const discovered = tools.find((tool) => tool.name === input.toolName) if (!discovered) { throw new OrchestrationError('not_found', 'Tool not found on the managed MCP connection') diff --git a/apps/sim/lib/mcp/application/execute-tool.ts b/apps/sim/lib/mcp/application/execute-tool.ts index b905f07a921..cb318632e21 100644 --- a/apps/sim/lib/mcp/application/execute-tool.ts +++ b/apps/sim/lib/mcp/application/execute-tool.ts @@ -38,7 +38,10 @@ export interface ExecuteMcpToolInput { timeoutMs?: number signal?: AbortSignal onResolvedSecretTraceProvenance?: (provenance: ResolvedSecretTraceProvenanceV1) => void - /** Authorize, discover and validate the call as a live one would, then stop before sending it. */ + /** + * Authorize, discover and validate the call as a live one would, then stop before sending it, + * writing nothing a live call reads: no server health, tool cache or tool snapshot. + */ checkOnly?: boolean } @@ -168,7 +171,7 @@ export const executeMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ context.workspaceId, 'skip-cache', input.onResolvedSecretTraceProvenance, - { signal: input.signal, requireComplete: true } + { signal: input.signal, requireComplete: true, readOnly: input.checkOnly } ) const tool = tools.find((candidate) => candidate.name === input.toolName) if (!tool) throw new OrchestrationError('not_found', 'Tool not found on the specified server') diff --git a/apps/sim/lib/mcp/service.test.ts b/apps/sim/lib/mcp/service.test.ts index 25dbd999137..382b4f2e844 100644 --- a/apps/sim/lib/mcp/service.test.ts +++ b/apps/sim/lib/mcp/service.test.ts @@ -651,4 +651,50 @@ describe('McpService best-effort discovery', () => { expect.any(Number) ) }) + + describe('read-only, as a dry run checks a call', () => { + it('leaves status, cooldown and the cached tools as they were when discovery fails', async () => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) + mockListTools.mockResolvedValueOnce([tool('a1', 'mcp-a')]) + await mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID) + resetDbChainMock() + wireSelectsToWorkspaceRows() + mockCacheAdapter.set.mockClear() + mockCacheAdapter.delete.mockClear() + mockListTools.mockReset() + mockListTools.mockRejectedValueOnce(new Error('Connection refused')) + + await expect( + mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID, 'skip-cache', undefined, { + requireComplete: true, + readOnly: true, + }) + ).rejects.toThrow('Connection refused') + + expectNoSharedStateWrites() + const cached = await mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID) + expect(cached.map((t) => t.name)).toEqual(['a1']) + expect(mockListTools).toHaveBeenCalledOnce() + }) + + it('neither caches the tools it finds nor stamps status', async () => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) + mockListTools.mockResolvedValueOnce([tool('a1', 'mcp-a')]) + + await mcpService.discoverServerTools( + USER_ID, + 'mcp-a', + WORKSPACE_ID, + 'skip-cache', + undefined, + { + requireComplete: true, + readOnly: true, + } + ) + + expect(dbChainMockFns.set).not.toHaveBeenCalled() + expect(mockCacheAdapter.set).not.toHaveBeenCalled() + }) + }) }) diff --git a/apps/sim/lib/mcp/service.ts b/apps/sim/lib/mcp/service.ts index 468f0a6bbd4..cda085e0882 100644 --- a/apps/sim/lib/mcp/service.ts +++ b/apps/sim/lib/mcp/service.ts @@ -83,6 +83,12 @@ interface McpRequestOptions { * discovery left its tools cached, without connecting. */ bestEffort?: boolean + /** + * A discovery that checks a call without making it (a dry run's MCP write): it reads the cooldown + * as a live call would, but writes none of the server's shared state, so a check never changes + * what live calls see. No status, failure count, cooldown, or tool cache write or eviction. + */ + readOnly?: boolean } interface McpToolExecutionOptions extends McpRequestOptions { @@ -1192,7 +1198,12 @@ class McpService { onResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceCallback, options: McpRequestOptions = {} ): Promise { - if (onResolvedSecretTraceProvenance || options.signal || options.requireComplete) { + if ( + onResolvedSecretTraceProvenance || + options.signal || + options.requireComplete || + options.readOnly + ) { return this.discoverServerToolsImpl( userId, serverId, @@ -1231,7 +1242,12 @@ class McpService { workspaceId: string, refresh: McpDiscoveryRefresh, onResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceCallback, - { signal, requireComplete = false, bestEffort = false }: McpRequestOptions = {} + { + signal, + requireComplete = false, + bestEffort = false, + readOnly = false, + }: McpRequestOptions = {} ): Promise { signal?.throwIfAborted() const requestId = generateRequestId() @@ -1285,6 +1301,7 @@ class McpService { bestEffort ) logger.info(`Discovered ${tools.length} tools from server ${config.name}`, { requestId }) + if (readOnly) return tools const cacheWrite = this.cacheAdapter .set(serverCacheKey(workspaceId, serverId), tools, this.cacheTimeout) .catch((err) => logger.warn(`Cache write failed for ${config.name}:`, err, { requestId })) @@ -1317,7 +1334,7 @@ class McpService { signal?.throwIfAborted() continue } - if (bestEffort) throw error + if (bestEffort || readOnly) throw error // Drop positive cache so a follow-up doesn't return stale tools. const statusApplied = isOauthAuthorizationError(error, authType) ? await this.markServerOauthPending(serverId, workspaceId, discoveryStartedAt) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 1fbb0a3e84c..ff8a15150f8 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -1,18 +1,19 @@ /** * Dry runs against real PostgreSQL and Redis, through the manual run use cases and the v2 execute * route: a dry run writes no table row and sends no request, reports each write with the payload it - * would have sent (credentials, run secrets and password fields masked before the request is built) - * under the `test` trigger, and keeps nothing else: no Agent memory (which its Agents still read), - * no workspace event, no run count. An MCP write is authorized before it is answered. An allowed - * block writes for real while reads run for real; a child workflow's writes, an Agent's included, - * stay stubbed; custom and Wait blocks are answered whole; code runs and is listed unchecked, a - * Condition's expressions and a While loop's condition included; a mocked block steers a branch; a - * failed dry run keeps its side effects and is the source only of another dry run. A test run is - * never the source of a run that sends its writes (the v2 use case, Copilot and the editor route - * alike) and is never resumed; a mock, a dry run's or a workflow test's, is data that never - * controls the run, sets what it is billed or replaces a locked block; a rerun record keeps only - * the ids of mocked blocks, while the log shows a mocked output redacted like any other. Model - * calls are answered by a simulated Anthropic API. + * would have sent (credentials, run secrets and password fields masked before the request is built, + * and a write whose request cannot be built once masked still answered) under the `test` trigger, + * and keeps nothing else: no Agent memory (which its Agents still read), no workspace event, no run + * count. An MCP write is authorized before it is answered, and its check leaves the server's health + * as it found it. An allowed block writes for real while reads run for real; a child workflow's + * writes, an Agent's included, stay stubbed; custom and Wait blocks are answered whole; code runs + * and is listed unchecked, a Condition's expressions and a While loop's condition included; a + * mocked block steers a branch; a failed dry run keeps its side effects and is the source only of + * another dry run. A test run is never the source of a run that sends its writes (the v2 use case, + * Copilot and the editor route alike) and is never resumed; a mock, a dry run's or a workflow + * test's, is data that never controls the run, sets what it is billed or replaces a locked block; a + * rerun record keeps only the ids of mocked blocks, while the log shows a mocked output redacted + * like any other. Model calls are answered by a simulated Anthropic API. */ import { db } from '@sim/db' import { @@ -20,6 +21,7 @@ import { apiKey, customBlock, customTools, + mcpServers, memory, organization, pausedExecutions, @@ -107,6 +109,7 @@ const organizationId = generateId() const workspaceId = generateId() const SECRET = `dry-secret-${generateId()}` const UNREFERENCED_SECRET = `unreferenced-${generateId()}` +const SECRET_URL = `http://dry-run.invalid/hook/${generateId()}` const API_KEY = `sk-sim-fixture-${generateId()}` const principal = createDelegatedPrincipal({ subjectUserId: ownerId, @@ -423,6 +426,7 @@ beforeAll(async () => { variables: { DRY_SECRET: (await encryptSecret(SECRET)).encrypted, UNREFERENCED_SECRET: (await encryptSecret(UNREFERENCED_SECRET)).encrypted, + DRY_SECRET_URL: (await encryptSecret(SECRET_URL)).encrypted, }, }) await db.insert(apiKey).values({ @@ -685,6 +689,53 @@ describe('a dry run', () => { expect(result.sideEffects?.stubbed).toEqual([]) }) + it('checks an MCP write without changing the server’s health, which live calls read', async () => { + const serverId = generateId() + await db.insert(mcpServers).values({ + id: serverId, + workspaceId, + createdBy: ownerId, + name: 'Unreachable', + transport: 'streamable-http', + url: 'http://dry-run.invalid/mcp', + connectionStatus: 'connected', + statusConfig: { consecutiveFailures: 0 }, + }) + const serverHealth = () => + db + .select({ + connectionStatus: mcpServers.connectionStatus, + lastError: mcpServers.lastError, + statusConfig: mcpServers.statusConfig, + }) + .from(mcpServers) + .where(eq(mcpServers.id, serverId)) + const healthBefore = await serverHealth() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('remove', 'mcp', { + operation: 'run', + serverSelector: serverId, + serverReference: serverId, + toolSelector: 'delete_file', + toolReference: 'delete_file', + arguments: { path: '/reports/q3.csv' }, + }), + ], + [['start', 'remove']] + ).state + ) + + const first = await run(workflowId, { dry: true }) + const second = await run(workflowId, { dry: true }) + + expect(first.status).toBe('failed') + expect(await serverHealth()).toEqual(healthBefore) + expect(second.error).toEqual(first.error) + }) + it('masks a run secret before building a write’s request, so no encoding carries it', async () => { const knowledgeBaseId = generateId() const workflowId = await saveWorkflow( @@ -749,6 +800,31 @@ describe('a dry run', () => { expect(JSON.stringify(result.sideEffects)).not.toContain(routingKey) }) + it('answers a write whose request it cannot build once masked, so the run goes on', async () => { + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('hook', 'api', { url: '{{DRY_SECRET_URL}}', method: 'POST' }), + notify('notify'), + ], + [ + ['start', 'hook'], + ['hook', 'notify'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ block: 'hook', tool: 'http_request', request: null }), + expect.objectContaining({ block: 'notify', tool: 'http_request' }), + ]) + expect(JSON.stringify(result.sideEffects)).not.toContain(SECRET_URL) + }) + it('answers custom and Wait blocks whole, without running the publisher’s workflow or pausing', async () => { const tableId = await createTable() const sourceId = await saveWorkflow( diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index 01a96860365..2a88117c46b 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -261,7 +261,8 @@ export async function redactSideEffectPayload(input: { * The response answering a write tool call the run's side-effect policy does not send, after the * policy recorded the request it would have sent: `describe` builds it from params whose secrets * are already masked ({@link maskRequestParams}), and the result is redacted again as a payload - * ({@link redactSideEffectPayload}). Null when either step cannot vouch that no secret remains. + * ({@link redactSideEffectPayload}). The request is null when either step cannot vouch that no + * secret remains, or it cannot be built from the masked params; the write is answered either way. */ export async function answerUnsentWrite( write: UnsentWrite, @@ -281,9 +282,12 @@ export async function answerUnsentWrite( if (!(error instanceof SecretScanDepthError)) throw error maskedParams = null } - const request = maskedParams + const described = maskedParams + ? describeMaskedRequest(call.toolId, input.describe, maskedParams) + : null + const request = described ? await redactSideEffectPayload({ - payload: input.describe(maskedParams), + payload: described.payload, params: input.params, blockTypes, executionContext: write.executionContext, @@ -293,6 +297,26 @@ export async function answerUnsentWrite( return { success: true, output: write.policy.stubWrite({ ...call, request }) } } +/** + * The request a write would send, or null when it cannot be built from masked params (a URL that is + * wholly a masked secret fails URL validation): describing an unsent write never fails the run. + */ +function describeMaskedRequest( + toolId: string, + describe: (maskedParams: Record) => unknown, + maskedParams: Record +): { payload: unknown } | null { + try { + return { payload: describe(maskedParams) } + } catch (error) { + logger.warn('Could not describe an unsent write from its masked params; recording no request', { + toolId, + errorName: error instanceof Error ? error.name : 'UnknownError', + }) + return null + } +} + /** * {@link answerUnsentWrite} for a call that reaches an MCP server (a workspace MCP tool, or the MCP * block's operation): a JSON-string `arguments` param is read first, so a secret nested in it is From bbc427aadc78577f4580f3bc130fddb61b612475 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 04:38:29 -0800 Subject: [PATCH 09/10] fix(mcp): a read-only discovery preserves the OAuth grant --- .agents/skills/add-tools/SKILL.md | 3 +- apps/sim/lib/mcp/service.test.ts | 49 +++++++++++++++++++------------ apps/sim/lib/mcp/service.ts | 2 +- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index ea5736c64d4..955ff96b57c 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -220,7 +220,8 @@ search that returns no email or phone, and an email verifier. `read`, fails the audit unless the `effect` line carries `// tool-effect: ` on one of the two lines above it; use it only for a genuine exception such as a GET that writes in `postProcess`. - A factory that builds tools from definitions takes `effect` per definition and passes it through. -- Prove the labels with a dry run: put the block in a workflow and run +- Prove the labels with a dry run, against a test account or test resource (a `read` runs for real, + so a write mislabelled `read` is sent): put the block in a workflow and run `sim workflows run --dry --input '{…}'`. Each `write` call must appear in the result's `sideEffects.stubbed` with the request you expect (an HTTP tool's `method`, `url` and `body`, or an in-process operation's input, credentials redacted), and each `read` must run for real and return diff --git a/apps/sim/lib/mcp/service.test.ts b/apps/sim/lib/mcp/service.test.ts index 382b4f2e844..4b9454841e3 100644 --- a/apps/sim/lib/mcp/service.test.ts +++ b/apps/sim/lib/mcp/service.test.ts @@ -607,27 +607,38 @@ describe('McpService best-effort discovery', () => { expectNoSharedStateWrites() }) - it('connects an authorized OAuth server with a grant-preserving provider and writes nothing when it is rejected', async () => { - mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) - mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(true) - mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({ - id: 'oauth-row-1', - tokens: { access_token: 'expired', token_type: 'bearer' }, - }) - mockListTools.mockRejectedValueOnce(new UnauthorizedError('refresh rejected')) - MockMcpClient.mockClear() - - await expect( - mcpService.discoverServerTools(MEMBER_B, 'mcp-a', WORKSPACE_ID, 'cache-aside', undefined, { - bestEffort: true, + it.each([ + ['a best-effort', { bestEffort: true }], + ['a read-only', { readOnly: true }], + ])( + 'connects an authorized OAuth server in %s discovery with a grant-preserving provider and writes nothing when it is rejected', + async (_kind, options) => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) + mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(true) + mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({ + id: 'oauth-row-1', + tokens: { access_token: 'expired', token_type: 'bearer' }, }) - ).rejects.toThrow('refresh rejected') + mockListTools.mockRejectedValueOnce(new UnauthorizedError('refresh rejected')) + MockMcpClient.mockClear() - expect(MockMcpClient.mock.calls[0]?.[0]).toMatchObject({ - oauthCredentials: { initialProvider: { preserveGrant: true } }, - }) - expectNoSharedStateWrites() - }) + await expect( + mcpService.discoverServerTools( + MEMBER_B, + 'mcp-a', + WORKSPACE_ID, + 'cache-aside', + undefined, + options + ) + ).rejects.toThrow('refresh rejected') + + expect(MockMcpClient.mock.calls[0]?.[0]).toMatchObject({ + oauthCredentials: { initialProvider: { preserveGrant: true } }, + }) + expectNoSharedStateWrites() + } + ) it('warms the shared tool cache on success without stamping status', async () => { mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) diff --git a/apps/sim/lib/mcp/service.ts b/apps/sim/lib/mcp/service.ts index cda085e0882..9322f418214 100644 --- a/apps/sim/lib/mcp/service.ts +++ b/apps/sim/lib/mcp/service.ts @@ -1298,7 +1298,7 @@ class McpService { onResolvedSecretTraceProvenance, signal, requireComplete, - bestEffort + bestEffort || readOnly ) logger.info(`Discovered ${tools.length} tools from server ${config.name}`, { requestId }) if (readOnly) return tools From 31dd5cbc9785d1dd293baa5508b77671ff1b004d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 04:47:47 -0800 Subject: [PATCH 10/10] fix(mcp): read-only discovery takes every shared-state guard best-effort discovery takes --- apps/sim/lib/mcp/service.test.ts | 39 ++++++++++++++++++++------------ apps/sim/lib/mcp/service.ts | 8 ++++--- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/apps/sim/lib/mcp/service.test.ts b/apps/sim/lib/mcp/service.test.ts index 4b9454841e3..995f1ba4986 100644 --- a/apps/sim/lib/mcp/service.test.ts +++ b/apps/sim/lib/mcp/service.test.ts @@ -591,21 +591,32 @@ describe('McpService best-effort discovery', () => { expect(tools.map((t) => t.name)).toEqual(['a1']) }) - it('skips an OAuth server nobody authorized without creating its OAuth row or marking it pending', async () => { - mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) - mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(false) + it.each([ + ['a best-effort', { bestEffort: true }], + ['a read-only', { readOnly: true }], + ])( + 'skips an OAuth server nobody authorized in %s discovery without creating its OAuth row or marking it pending', + async (_kind, options) => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) + mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(false) - await expect( - mcpService.discoverServerTools(MEMBER_B, 'mcp-a', WORKSPACE_ID, 'cache-aside', undefined, { - bestEffort: true, - }) - ).rejects.toBeInstanceOf(McpOauthAuthorizationRequiredError) - expect(mcpOauthMockFns.mockGetOrCreateOauthRow).not.toHaveBeenCalled() - // loadOauthRow clears a column it cannot decrypt; the gate must not risk that. - expect(mcpOauthMockFns.mockLoadOauthRow).not.toHaveBeenCalled() - expect(mockConnect).not.toHaveBeenCalled() - expectNoSharedStateWrites() - }) + await expect( + mcpService.discoverServerTools( + MEMBER_B, + 'mcp-a', + WORKSPACE_ID, + 'cache-aside', + undefined, + options + ) + ).rejects.toBeInstanceOf(McpOauthAuthorizationRequiredError) + expect(mcpOauthMockFns.mockGetOrCreateOauthRow).not.toHaveBeenCalled() + // loadOauthRow clears a column it cannot decrypt; the gate must not risk that. + expect(mcpOauthMockFns.mockLoadOauthRow).not.toHaveBeenCalled() + expect(mockConnect).not.toHaveBeenCalled() + expectNoSharedStateWrites() + } + ) it.each([ ['a best-effort', { bestEffort: true }], diff --git a/apps/sim/lib/mcp/service.ts b/apps/sim/lib/mcp/service.ts index 9322f418214..f5828309afe 100644 --- a/apps/sim/lib/mcp/service.ts +++ b/apps/sim/lib/mcp/service.ts @@ -1254,8 +1254,10 @@ class McpService { const discoveryStartedAt = new Date() const maxRetries = 2 + // Best-effort and read-only discoveries both leave the server's shared state as they found it. + const preservesSharedState = bestEffort || readOnly // Before the cache: another member's cached tools never reach a requester who cannot call them. - const requesterConfig = bestEffort + const requesterConfig = preservesSharedState ? await this.loadAuthenticatableServerConfig(serverId, userId, workspaceId) : undefined @@ -1298,7 +1300,7 @@ class McpService { onResolvedSecretTraceProvenance, signal, requireComplete, - bestEffort || readOnly + preservesSharedState ) logger.info(`Discovered ${tools.length} tools from server ${config.name}`, { requestId }) if (readOnly) return tools @@ -1334,7 +1336,7 @@ class McpService { signal?.throwIfAborted() continue } - if (bestEffort || readOnly) throw error + if (preservesSharedState) throw error // Drop positive cache so a follow-up doesn't return stale tools. const statusApplied = isOauthAuthorizationError(error, authType) ? await this.markServerOauthPending(serverId, workspaceId, discoveryStartedAt)