# Add Cancellation Handling to a Temporal Workflow

Yes. An agent makes your Temporal workflow cancellable, refunds a half-done transfer in a non-cancellable scope, adds a cancel script and tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-workflow-cancellation/temporal/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by reading how the workflow fails today. In a project like temporalio/money-transfer-project-template-ts, `src/workflows.ts` holds one workflow, `moneyTransfer`, which proxies three activities from `src/activities.ts` with a shared retry policy: `initialInterval` of one second, `maximumInterval` of one minute, `backoffCoefficient` 2, `maximumAttempts` 500, and `InvalidAccountError` and `InsufficientFundsError` as the non-retryable types, under a `startToCloseTimeout` of one minute. It calls `withdraw`, then `deposit`, and if the deposit throws it calls `refund` before failing. The activities wrap `BankingService` in `src/banking-client.ts`, a mock bank with two accounts, `85-150` holding 2000 and `43-812` holding 0, whose `depositThatFails` method exists so you can simulate an outage. `src/client.ts` starts the workflow as `pay-invoice-801` on the `money-transfer` task queue from `src/shared.ts` and awaits `handle.result()`. Nothing in the template cancels anything: with 500 attempts and a one-minute cap, a deposit against a bank that is down keeps retrying for hours, and the only way to stop it is to terminate the execution, which skips the refund.

The agent rewrites the workflow so a cancel request from a client does the right thing at every point. It imports `CancellationScope` and `isCancellation` from `@temporalio/workflow` and keeps the activity proxy as it is, so a cancel that arrives while `deposit` is retrying stops the retry loop at once. The deposit call is wrapped so that a cancellation error, not a bank error, is told apart with `isCancellation`: when the withdrawal already succeeded, the refund runs inside `CancellationScope.nonCancellable`, because a refund that could itself be cancelled would leave the money gone from the source account. After the refund the workflow rethrows the original cancellation, so the execution ends as cancelled rather than completed or failed, which is what the Temporal UI and `handle.result()` should report. A cancel that arrives before `withdraw` has run means there is nothing to undo, and one that arrives after `deposit` returned is too late to honour, so the workflow returns its result as before; the agent writes both cases out explicitly rather than leaving them to the default behaviour.

On the client side it adds `src/cancel.ts`, run as `npm run cancel -- <workflowId>`, which connects with the same `loadClientConnectConfig` from `@temporalio/envconfig` that `src/client.ts` uses, gets a handle by id and calls `handle.cancel()`. It also changes `src/client.ts` so that awaiting the result catches `WorkflowFailedError` and prints whether the cause is a `CancelledFailure` from `@temporalio/common` or a real failure, instead of a stack trace. The ESLint override in `.eslintrc.js` forbids Node built-ins other than `assert` inside `src/workflows.ts`, and the new workflow code imports only from `@temporalio/workflow` and `@temporalio/common`, so `npm run lint` stays clean.

The proof is in `src/mocha/workflows.test.ts`, which already starts a `TestWorkflowEnvironment.createLocal()` and a `Worker` with mocked activities. The agent adds three cases. The first mocks `deposit` to throw a retryable error forever and `refund` to record its calls, starts the workflow with `client.workflow.start`, cancels through the handle, and asserts that `refund` ran exactly once and that `handle.result()` rejects with a `WorkflowFailedError` whose `cause` is a `CancelledFailure`. The second cancels a workflow whose mocked `withdraw` has not yet returned and asserts that no refund happens. The third lets the transfer complete and then cancels, asserting the result string is unchanged. `npm test` runs the Mocha suite through `ts-node` on Node 18 from `.nvmrc`, and `npm run build` type-checks with the `@tsconfig/node18` base, both before the pull request opens.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add cancellation handling to the money transfer workflow in this Temporal TypeScript project. Read src/workflows.ts, src/activities.ts, src/banking-client.ts, src/client.ts, src/worker.ts, src/shared.ts, the Mocha tests under src/mocha, package.json and .eslintrc.js first. In the workflow, distinguish a cancellation from a bank error with isCancellation; if the withdrawal already succeeded, run the refund activity inside CancellationScope.nonCancellable, then rethrow the cancellation so the execution ends cancelled; if nothing was withdrawn yet, just propagate; if the deposit already completed, return the result. Add src/cancel.ts and an npm script that cancels a workflow by id using the same envconfig connection as src/client.ts, and make src/client.ts report a CancelledFailure cause plainly. Add Mocha tests with TestWorkflowEnvironment that cancel during a retrying deposit and assert exactly one refund and a WorkflowFailedError with a CancelledFailure cause, cancel before withdrawal and assert no refund, and cancel after completion and assert the result is unchanged. Run npm run lint, npm run build and npm test, and open a pull request that explains the three cancellation windows.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that edits `src/workflows.ts` and `src/client.ts`, adds `src/cancel.ts` and a `cancel` script in `package.json`, and extends `src/mocha/workflows.test.ts` with the three cancellation cases. The description walks through the three windows, before the withdrawal, between withdrawal and deposit, and after the deposit, and says what a cancel does in each.

The run's record keeps the full `npm test` output with each Mocha case named, the `npm run lint` result, and the `tsc --build` output, so a reviewer can see the refund assertion passing against a deposit that never succeeds, which is the case the template cannot handle today.

Before merging, a reviewer reads the `nonCancellable` block and checks that the refund is the only thing inside it, runs a worker against a local Temporal server, starts a transfer with `src/activities.ts` switched to `depositThatFails`, cancels it with `npm run cancel -- pay-invoice-801`, and reads the event history: a refund activity completed, then a workflow execution cancelled event.

## Run it on every long-running workflow added

The setup is one `POST /o/{org}/sessions` with this body and the repository in `resources`, started from a terminal; the run keeps going in its sandbox after you close the window, and a follow-up through `POST /o/{org}/sessions/{id}/messages` can ask for a heartbeat in the activities or a different retry cap without starting over. A team with several workflow files sends one request per repository, each with a fresh UUID as `request_id`, so a retried script returns the run it already started.

A `webhook_url` on the API key receives `run.completed` or `run.failed` when the turn finishes, with the `session_url` your server reads to pick up the pull request link and the test output.

## Why run it on Rush?

Cancellation in Temporal is easy to get subtly wrong, and the mistakes only show up when a real cancel races a real retry: a refund placed outside the non-cancellable scope gets cancelled with everything else, a caught cancellation that is not rethrown leaves the execution marked completed, and an activity that does not heartbeat never learns it was cancelled. The agent runs the test server and the worker in its own sandbox and the Mocha cases say which of those happened, before a person reads the diff.

Every command and its output are kept with the run, so the pull request can point at the exact test that proves the refund ran once and the execution ended cancelled, and a reviewer who was not watching can check the claim against the log rather than against a sentence in the description.

## Frequently asked questions

### Does a cancel interrupt a bank call that is already in flight?

Not in this template. The activities call a mock bank that returns at once, so the real cancellation window is the retry loop between attempts, which the SDK stops as soon as the cancel arrives. For a bank client that blocks for seconds, the agent notes that the activity needs `heartbeat()` from `@temporalio/activity` and a `heartbeatTimeout` so cancellation reaches it mid-call.

### Why rethrow the cancellation after the refund instead of returning a message?

Returning would mark the execution completed, and anything watching the workflow, including `handle.result()` in `src/client.ts`, would read a successful transfer that never happened. Rethrowing ends it as cancelled, which is the state the Temporal UI, the history and the client all agree on.

### What if the refund itself fails during cancellation?

The refund keeps the proxy's retry policy, so transient errors retry inside the non-cancellable scope. If it exhausts its attempts the workflow fails with an `ApplicationFailure` naming both accounts, the same message the template already uses when a refund fails after a bad deposit, so an operator sees money that needs manual attention.

### Will the existing four Mocha tests still pass?

Yes. The success path and the three failure paths do not involve a cancel, and the agent runs the whole suite, not only the new cases. The retry policy, task queue and workflow id in `src/shared.ts` and `src/client.ts` are unchanged.

## More Temporal jobs

- [Add Timeouts to a Temporal TypeScript Workflow](https://getrush.ai/run/add-workflow-timeouts/temporal/)
- [Version a Running Temporal Workflow Safely](https://getrush.ai/run/add-workflow-versioning/temporal/)
- [Dockerize a Temporal TypeScript Worker](https://getrush.ai/run/dockerize-app/temporal/)

## More jobs like this: Hand off a long task

- [Set Up Workload Identity on GKE with Terraform](https://getrush.ai/run/add-workload-identity/gke/)
- [Add zizmor to CI for Your GitHub Actions Workflows](https://getrush.ai/run/add-zizmor-to-ci/github-actions/)
- [Turn an Asana Task into a Pull Request for a Laravel App](https://getrush.ai/run/asana-task-to-pr/laravel/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
