# Flows

> Chain saved requests with variables, conditions, loops, checks and JavaScript, then run a flow by hand, on a schedule, or when a webhook arrives.

Source: https://docs.subcloak.com/cloak-proxy/api-client/run/flows/

A flow chains saved requests and simple logic into a sequence of blocks, without writing a whole script. Each block's result becomes a variable that later blocks can use, so you can list items, loop over them, fetch each one, check the answers and output a result. Flows work like Postman Flows, laid out as a list of blocks that run top to bottom. A flow can also run on its own every few minutes or when a webhook arrives.

*[Screenshot: A flow named Create and fetch a pet with Send Request, Check, For Each and Output blocks, and a passing run with its steps and a lastPet output on the right. A flow that lists pets, checks the response, fetches each pet in a loop and outputs the last one.]*

## Create a flow

1. Click **Flows** in the left rail, then **+** at the top of the sidebar.

   A flow named **New Flow** opens. If you have a collection, it starts with three blocks: a **Send Request** for the first request in your first collection, a **Check** that `response.status < 400`, and an **Output** of `response.body`.

2. Click the name and give the flow a clear one.

3. Choose **Add Block** and pick a block type. Set its fields.

4. Click **Run**, or press <kbd>⌘</kbd> <kbd>↩</kbd>.

   The **Run** pane shows **Passed** or **Failed**, the duration, each step and the outputs.

Flows save automatically to `flows/<name>.flow.json` in the [workspace](https://docs.subcloak.com/cloak-proxy/api-client/workspace-and-git/). Right-click a flow in the sidebar to delete it.

> **Start from captured traffic:**
> To replay a journey your app made, such as log in, create an order and pay, select those requests in the traffic list, right-click and choose **Make Replayable Flow…**. Cloak Proxy builds the flow for you and chains the IDs and tokens between the steps. See [Replayable flows](https://docs.subcloak.com/cloak-proxy/api-client/run/replayable-flows/). (added in Cloak Proxy 0.2.1)

## How flows work

- **Blocks run from top to bottom.** Blocks with children (**If**, **Repeat** and **For Each**) run their nested blocks before moving on.
- **Results are variables.** A **Send Request** stores its response under the name you give it, **Set Variable** stores a value, and **For Each** stores the current item. Any later block can use them.
- **Expressions are JavaScript.** Fields such as a condition or a list are JavaScript expressions, evaluated with every flow variable in scope. Write `pets.body.length` or `` `Pet ${pet.body.name}` `` directly. All variables are also on an object named `vars`.
- **Flow variables reach requests.** Inside a request sent by a flow, every flow variable is available as `{{name}}`. Objects and arrays are inserted as JSON text.
- **Values are plain data.** Every value passes through JSON between blocks, so functions and `undefined` become `null`.

Expressions run in JavaScriptCore with no network access and no `pm` object. To call an API, use a **Send Request** block.

### The response variable

A **Send Request** block stores an object like this under its **Save as** name (default `response`):

| Field | Contents |
| --- | --- |
| `status` | The status code, such as `200`. `0` when the request couldn't be sent. |
| `headers` | Response headers as an object, with lowercase names: `response.headers["content-type"]`. |
| `body` | The body parsed as JSON when it is JSON, otherwise the text. |
| `time` | The response time in milliseconds. |
| `tests` | The request's test results, as `[{ "name": "…", "passed": true }]`. |
| `error` | Only when the request couldn't be sent: the error message. |

## Blocks

Every block has up and down buttons to move it within its list, and a trash button to delete it.

| Block | Fields | Default | What it does |
| --- | --- | --- | --- |
| **Send Request** | **Request**, **Save as** | `response` | Sends a saved request and stores the result. |
| **Set Variable** | **Name** = expression | `value` = `response.body` | Stores the value of an expression. |
| **If** | **Condition** | `response.status === 200` | Runs the **Then** blocks when the condition is true, otherwise the **Else** blocks. |
| **Repeat** | **Times** | `3` | Runs its **Do** blocks that many times. |
| **For Each** | **Item name**, **List expression** | `item`, `response.body.items` | Runs its **Do** blocks once for each item in a list. |
| **Delay** | **Wait** | 1000 ms | Pauses the flow. |
| **Log** | **Expression** | `` `Status: ${response.status}` `` | Writes a value to the run's steps. |
| **Check** | **Condition**, **Message** | `response.status < 400`, `Request should succeed` | Fails the run if the condition is false. |
| **Output** | **Output name**, **Expression** | `result`, `response.body` | Adds a named value to the run's outputs. |
| **Run Script** | Code | Increments `vars.count` | Runs JavaScript that can read and change any flow variable. |

### Send Request

Choose a saved request from the **Request** menu, which lists every request as **Collection / Folder / Request**. Type a variable name in **Save as**.

The request runs exactly as it does when you send it yourself: with its collection's variables, the active environment, globals, Vault secrets, auth and its pre-request and post-response scripts. Flow variables are added on top as local values, so `{{petId}}` in the request's URL uses the flow's `petId`. Changes scripts make to environment and global variables carry over to later blocks in the same run, but aren't saved to the workspace.

The step shows the method, request name, status, time and test count, for example `GET List pets → 200 in 84 ms · tests 3/3`. It's marked failed when the request couldn't be sent, the status is 400 or higher, or a test failed. The flow keeps going after a failed request, so a later **If** or **Check** can deal with it, but the run counts as failed. A **Send Request** with no request chosen stops the flow with **A Send Request block has no request**.

### Set Variable

Type a **Name**, then a JavaScript expression after the `=`. For example, `ids` = `pets.body.map(p => p.id)`. The step shows the name and a preview of the value.

### If

Type a **Condition**. When it's true, the blocks under **Then** run; otherwise the blocks under **Else** run. Use the small **Add Block** menus under each to add blocks. The step shows the condition and whether it was `true` or `false`.

A condition is false when it's `false`, `0`, an empty string or `null`, and true otherwise, including for any object or array.

### Repeat

Type how many **Times** to run the **Do** blocks. It can be a number or an expression, such as `pages.body.totalPages`. Inside the loop, `index` is the current pass, starting at `0`. A repeat runs at most 10,000 times.

### For Each

Type an **Item name** and a **List expression** that evaluates to an array, such as `pets.body`. The **Do** blocks run once per item, with the item stored under the item name (default `item`) and its position in `index`, starting at `0`. If the expression isn't an array, the step shows that it isn't a list and the flow stops with **For Each needs a list**.

### Delay

Set **Wait** to pause the flow, from 0 to 600,000 ms in steps of 250. Use it to space out requests or wait for a background job.

### Log

Type an **Expression**. Its value appears as an info step in the run, pretty-printed when it's an object. It doesn't change the result of the run.

### Check

Type a **Condition** and a **Message**. When the condition is true, the step passes and shows the message. When it's false, the step fails with the message followed by `— failed`, and the run is marked **Failed**. The flow keeps going after a failed check, so you see every problem in one run. If the message is empty, the condition is shown instead.

### Output

Type an **Output name** and an **Expression**. The value appears in the **Outputs** section of the run, pretty-printed. Use outputs for the values the flow exists to produce. Leave the name empty to call it `output`.

### Run Script

Write JavaScript in the code editor. Every flow variable is in scope and on the `vars` object. Assign to `vars` to create or change variables, and `delete vars.name` to remove one. When the script ends, `vars` becomes the flow's variables.

```js title="Run Script"
// Keep only the pets that need a vaccination
vars.due = pets.body.filter(p => !p.vaccinated);
vars.dueCount = vars.due.length;
```

> **Assign through vars:**
> Set new variables with `vars.name = value`. A bare `name = value` for a name that doesn't exist yet creates a JavaScript global that's thrown away when the script ends.

## Inputs

The **Inputs** table, below the blocks, sets variables before the first block runs. Each row is a **Variable** and a **Value**. A value that is valid JSON is parsed, so `42` is a number, `true` is a boolean and `{"id": 1}` is an object. Anything else is a string.

Use inputs for values you change between runs, such as an ID or a page size. AI assistants that run flows through the [MCP server](https://docs.subcloak.com/cloak-proxy/automation/mcp-server/) (the `run_flow` tool) can pass inputs too, and so can `cloakctl flow run` with `--input KEY=VALUE` (see [Run a flow from the command line](#run-a-flow-from-the-command-line)).

## Read the run results

The **Run** pane shows the latest run of the flow:

| Part | Meaning |
| --- | --- |
| **Passed** or **Failed** | Failed when any step failed or the flow stopped with an error. |
| Duration | How long the whole run took, in milliseconds. |
| Error | Why the flow stopped early, in red, when it did. |
| **Steps** | One line per block that ran, indented to show nesting. A green check is a passed step, a red cross is a failed step, and an info icon is a step that only reports something (**If**, **Repeat**, **For Each**, **Log**). Each step has a title such as **Send Request · pets** and a detail line you can select and copy. |
| **Outputs** | Each **Output** block's name and value. |

## Automate a flow

The **Automation** section at the bottom of a flow runs it without you, like Postman's Automation Flows.

| Setting | Default | What it does |
| --- | --- | --- |
| **Run every** N **minutes while Cloak Proxy is open** | Off, 60 minutes | Runs the flow on a schedule. The first scheduled run happens soon after you turn it on; after that, the interval counts from the last scheduled run. |
| **Run when a webhook arrives at** | Off, `/flows/<flow-name>` | Runs the flow when the [webhook receiver](https://docs.subcloak.com/cloak-proxy/api-client/run/monitors-and-webhooks/#receive-webhooks) gets a request on this path. |
| **Notify me when an automatic run fails** | On | Shows a macOS notification titled **Flow “name” failed** when a scheduled or webhook run fails. Manual runs never notify. |

### Run a flow from a webhook

1. Turn on **Run when a webhook arrives at**. Keep the suggested path (made from the flow's name, such as `/flows/create-and-fetch-a-pet`) or type your own.

2. If the receiver isn't running, click **Start Receiver**.

   The flow shows the address to call, for example `POST http://localhost:9999/flows/create-and-fetch-a-pet`.

3. Send a request to that address, or point a service's webhook at it (through a tunnel for services on the internet).

The path matches with or without a trailing slash, and the query string is ignored. Each delivery that matches runs the flow once, with the delivery available as the `trigger` variable:

| Field | Contents |
| --- | --- |
| `trigger.method` | The request method. |
| `trigger.path` | The path, without the query string. |
| `trigger.query` | Query parameters as an object. |
| `trigger.headers` | Headers as an object, with lowercase names. |
| `trigger.body` | The body, parsed as JSON when it's JSON, otherwise text. |

For example, a **For Each** over `trigger.body.orders` handles every order in a delivery. The sender gets the receiver's configured response; the flow's result doesn't change it.

### Recent runs

Under the automation settings, **Recent runs** lists the last 10 runs, newest first: a pass or fail icon, the date and time, how the run started (`manual`, `schedule` or `webhook`), the number of steps, the duration and the first failure. The flow keeps its last 100 runs. Manual runs are recorded once you've used the automation settings for the flow.

> **Note:**
> Scheduled and webhook runs only happen while Cloak Proxy is open, and webhook runs need the receiver to be listening. To run a flow on a schedule while the app is closed, call `cloakctl flow run` from cron or launchd. A flow that's still running isn't started again until it finishes.

### Run a flow from the command line

(added in Cloak Proxy 0.2.0)

[`cloakctl`](https://docs.subcloak.com/cloak-proxy/automation/cloakctl/#run-a-flow) runs flows without the app, so you can schedule them with cron or launchd, or run them in CI:

```bash title="Terminal"
cloakctl flow list
cloakctl flow run "Create and fetch a pet" --input petId=7 -e Staging
```

`--input KEY=VALUE` replaces one of the flow's inputs for that run; repeat it for several. `-e` picks an environment by name or Postman environment file. The command prints each step with `✓`, `✗` or `·`, then the outputs and whether the flow passed, and exits with `1` when it failed. Command-line runs aren't added to **Recent runs**.

On Linux, flows and their schedules and webhook triggers run in Cloak Proxy itself, so they keep going when you close the API client window; failed scheduled or webhook runs post a desktop notification.

## Limits and errors

| Message | Cause |
| --- | --- |
| **The flow ran more than 10,000 steps; check for an endless loop** | A flow can run at most 10,000 blocks in one run, counting every pass of every loop. |
| **A Send Request block has no request** | A **Send Request** block has no request chosen, or its request was deleted. |
| **For Each needs a list** | The list expression didn't evaluate to an array. |
| An expression followed by a JavaScript error | An expression threw an error, for example reading a property of `undefined`. The flow stops. |
| **Script:** followed by an error | A **Run Script** block threw an error. The flow stops. |

Use `?.` in expressions to avoid errors when a value might be missing, for example `response.body?.items ?? []`.

## Related

  - [Monitors and webhooks](https://docs.subcloak.com/cloak-proxy/api-client/run/monitors-and-webhooks/): Start the receiver that triggers flows.
  - [Collections and requests](https://docs.subcloak.com/cloak-proxy/api-client/collections-and-requests/): Build the requests a flow sends.
  - [Scripts and tests](https://docs.subcloak.com/cloak-proxy/api-client/scripts-and-tests/): Tests whose results flows can read.
  - [Replayable flows](https://docs.subcloak.com/cloak-proxy/api-client/run/replayable-flows/): Build a flow from captured requests, with IDs and tokens chained.
