<!-- Canonical HTML: https://docs.didro.ai/sap-ui-automation/guides/workflows -->

# Reusable workflows

An agent that finished a task in SAP (display an order, read a stock
level) can keep the steps that worked as a **workflow**: a `*.sap.ts`
test with named inputs and outputs. The next time, it, another agent or a
script runs the workflow with new values, with no model for the steps and
the same guard as any action. A recording keeps every step an agent took;
a workflow keeps the steps you choose, as code a person can read and edit.

The path:

1. **Do the task** with `sap_look` and `sap_act`.
2. **Review** what led to the result with `sap_history`.
3. **Write** the steps as a workflow: the SDK, an input for each value
   that changes, an assertion that proves the result, an output for each
   value to return.
4. **Save** it with `sap_workflow_save`, or as a file in your project.
5. **Find** it with `sap_library` and **run** it with `sap_workflow_run`
   or `sap-ui-automation test`.

Steps 4 and 5 through MCP need `SAP_CODE_TOOLS=on`. The
[`sap-ui-workflow-authoring`](https://github.com/DidroAI/sap-ui-mcp/blob/main/skills/sap-ui-workflow-authoring/SKILL.md)
skill walks an agent through them.

> **The agent writes code that runs on your machine**
>
> `SAP_CODE_TOOLS=on` lets an agent write code that the server then runs on
> your machine, with your rights. The agent reads SAP screens, and text on a
> screen (a long text, a material description, a workflow note) can carry
> instructions meant for it. Such text can reach the code the agent writes.
> The checks below make the obvious ways out of a test fail, but they are
> best effort, not a sandbox: the code runs in a worker thread of the
> server's own process, with Node's APIs. Only the actions it sends through
> the SDK (`sap.*`) go through the guard; code that gets past the checks can
> reach SAP or the machine another way. `sap-ui-automation test` and
> `test --list` import a workflow with no checks at all. Turn the tools on
> only where you would let the agent's author run scripts on that machine.
## 1. Review the run

On the MCP server that did the task:

```json
{"session": "<session-id>", "includeSdk": true}
```

`sap_history` answers the session's recent actions, oldest first, up to
200: each with the screen it led to, SAP's message or the error, and with
`includeSdk` the SDK statement that repeats it. Failed attempts are there
too, so the agent sees which actions led to the result and which were
detours. It answers a `source` reference: pass it to `sap_workflow_save`
to keep the reviewed actions with the workflow. Parameters:
[MCP tools](https://docs.didro.ai/sap-ui-automation/reference/tools#sap-history).

## 2. Write the workflow

A workflow imports `test` and `expect` from `sap-ui-automation/test`; the
runner hands it the session as `sap`, and `input` and `output` for its
values. The first line, `// @sap-workflow {...}`, says what it does, what
it takes, what it returns and what it proves:

```ts
// @sap-workflow {"description":"Display a sales order","inputs":{"order":"Sales order number"},"outputs":{"soldTo":"Sold-to party of the order"},"verifies":"VA03 shows the requested order"}
import { expect, test } from "sap-ui-automation/test";

test("Display a sales order", async ({ sap, input, output }) => {
  const order = input("order");
  await sap.okcode("/nVA03");
  await sap.set("ctxtVBAK-VBELN", order);
  await sap.key("Enter");
  await expect(sap).toHaveTitle(/Overview/);
  await expect(sap.field("ctxtVBAK-VBELN")).toHaveValue(order);
  output("soldTo", await sap.field("ctxtKUAGV-KUNNR").value());
});
```

(VA03 on SAP GUI; on your system, use the ids `sap_history` showed.)

- Replace each value that changes between runs (the order number) with an
  `input`. Every input is a required string: leading zeros stay.
- Assert what proves the task is done, while it is on the screen.
- Call `output` for each declared result exactly once, across the
  workflow's tests, while the value is on screen. A failed run returns no
  outputs.
- `await` every action and assertion: the save step flags a promise that
  is dropped.

The header's fields: [File formats](https://docs.didro.ai/sap-ui-automation/reference/file-formats#workflow-header-sap-workflow).

## 3. Save it

Through MCP, `sap_workflow_save` with the name, the code, and optionally
`workflow` (the header as an object, written for you) and `source` (from
`sap_history`). Or save the file in your project's test folder and run it
with the test runner.

What `sap_workflow_save` checks before it writes `<name>.sap.ts` in
`SAP_RECORD_DIR`:

- **Name, not path.** A `/`, `\`, `..`, a leading `.` or a drive letter is
  refused; the file name is the slug of the name.
- **TypeScript.** The code is checked against the installed SDK's types,
  in a temporary worker. A diagnostic names the line and column. Each
  `input("...")` needs its entry in the header's `inputs`. Correct the code
  or the header and save again.
- **Imports.** Static, named imports only: `expect`, `test` and
  `ExpectError` from `"sap-ui-automation/test"`, or `expect`,
  `ExpectError` and `Refused` from `"sap-ui-automation"`, plus `type`
  imports. No `connect`, no `import()`, no re-exports.
- **Words.** Outside strings and comments, no `process`, `require`, `eval`,
  `Function`, `globalThis`, `fetch`, `Bun`, `Deno`, `child_process`,
  `constructor`, `Reflect`, `Object` and the like, and none of a session's
  insides (`registry`, `policy`, `driver`, `recorder`, `options`,
  `surfaces`).
- **Computed member access.** Only a number in brackets (`rows[0]`).
- **Commit parity.** A call that may write (`sap.save()`, key 11, a Save
  button, `btn[11]`, `okcode("/11")`) is refused unless the recording of
  the same name has a write. This is read from the text; the guard at run
  time is what holds.

A rejected save answers the problems and keeps the previous file. Saving
under an existing name updates that workflow, and its library entry is
unverified until the new code passes.

## 4. Find and run it

Another MCP client with the same `SAP_RECORD_DIR` and `SAP_CODE_TOOLS=on`
finds it by task:

```json
{"query": "order"}
```

`sap_library` answers one line per workflow: purpose, inputs, what it
verifies, and the latest MCP attempt next to the last passing run of that
exact source. With `{"name": "display-a-sales-order"}` it answers the source
and its verification status. Then `sap_workflow_run`:

```json
{"name": "display-a-sales-order", "session": "<session-id>", "variables": {"order": "12345"}}
```

- The run checks the current file again (syntax, imports, words, writes)
  and the inputs: a missing or unknown input fails before the runner
  connects.
- Its SDK actions run under the server's `SAP_WRITE`, `SAP_ALLOW_SYSTEMS`,
  `SAP_ALLOW_TCODES`, `SAP_BLOCK_TCODES` and `SAP_ALLOW_LOGOFF`, on the
  session it names: the code cannot widen them through the SDK. What it does
  outside the SDK is not guarded (see the warning above).
- Each run has its own worker and 120 seconds for loading, its tests and
  cleanup. Runs on different sessions can overlap.
- A passing run answers `PASS` per test and the outputs as JSON
  (`structuredContent.outputs` with `SAP_STRUCTURED=on`). A failure
  answers the error, the line, the `sap.step` it was in, the trace file
  and the screen.
- After a timeout, look at the session before you repeat a posting: SAP
  can finish a command it already received.
- It is refused while a recording is on.

From a project with the SDK installed, the same workflow runs with the
test runner:

```sh
npx sap-ui-automation test display-a-sales-order --var order=12345
```

## Locks and verification

A workflow saved with a header is verified against a lock for that
revision of its source, under `SAP_RECORD_DIR/.workflows/`: what each
screen looked like on a run that passed. Before the first test,
`sap_workflow_run` checks the target session against the lock's system
and surface; a known mismatch stops the run. Where SAP answers otherwise
during a run, it fails with `Drift`: the step, the action and the screen.
A verification receipt needs every test to pass and at least one test to
use the `sap` fixture. Older scripts without a header use
`<name>.sap.lock.json` next to them. Lock files in general:
[Writing tests with the SDK](https://docs.didro.ai/sap-ui-automation/guides/sdk-tests#lock-files).

## Limits

- A workflow runs on a session that is open and logged on; it never logs
  on.
- The checks of `sap_workflow_save` are read from the text: they are not a
  sandbox (see the warning above).
- `sap_history` is the history of one server process: after a restart, or
  on another server, it is empty.
