Skip to content

Commit 6cbb549

Browse files
authored
feat(client-js): add cancel() method alias for Run class (#11417)
## Description Add a new cancel() method as a more concise alias for cancelRun() in the Run class. This provides better developer ergonomics while maintaining backward compatibility. Changes: - Add cancel() method to Run class with comprehensive JSDoc documentation - Mark cancelRun() as deprecated with pointer to cancel() - Document abort signal behavior with practical examples - Update client-js SDK documentation with cancel() method - Update Run.cancel() reference documentation - Add 'canceled' status to Run Status documentation The new method includes detailed documentation about: - How cancellation works (abort signal, status updates) - How steps can respond to cancellation - Practical examples of cancellation-aware steps ## Related Issue(s) slack ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Test update ## Checklist - [x] I have made corresponding changes to the documentation (if applicable) - [ ] I have added tests that prove my fix is effective or that my feature works <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a simplified cancel() action for workflow runs as the preferred cancellation API; legacy cancelRun() remains deprecated for compatibility. * Cancellation now returns a confirmation object (message) and sets run status to "canceled". * **Documentation** * Expanded docs on cancellation behavior, updated return details, and added guidance and examples for abort-signal-aware step cleanup and cancellation patterns. <sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 8f4cca0 commit 6cbb549

File tree

5 files changed

+147
-5
lines changed

5 files changed

+147
-5
lines changed

.changeset/twenty-worms-study.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@mastra/client-js': patch
3+
---
4+
5+
Add `cancel()` method as an alias for `cancelRun()` in the Run class. The new method provides a more concise API while maintaining backward compatibility. Includes comprehensive documentation about abort signals and how steps can respond to cancellation.

client-sdks/client-js/src/resources/run.ts

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,81 @@ export class Run extends BaseResource {
7171
/**
7272
* Cancels a specific workflow run by its ID
7373
* @returns Promise containing a success message
74+
* @deprecated Use `cancel()` instead
7475
*/
7576
cancelRun(): Promise<{ message: string }> {
7677
return this.request(`/api/workflows/${this.workflowId}/runs/${this.runId}/cancel`, {
7778
method: 'POST',
7879
});
7980
}
8081

82+
/**
83+
* Cancels a workflow run.
84+
*
85+
* This method aborts any running steps and updates the workflow status to 'canceled' .
86+
* It works for both actively running workflows and suspended/waiting workflows.
87+
*
88+
* ## How cancellation works
89+
*
90+
* When called, the workflow will:
91+
* 1. **Trigger the abort signal** - Uses the standard Web API AbortSignal to notify running steps
92+
* 2. **Prevent subsequent steps** - No further steps will be executed
93+
*
94+
* ## Abort signal behavior
95+
*
96+
* Steps that check the `abortSignal` parameter can respond to cancellation:
97+
* - Steps can listen to the 'abort' event: `abortSignal.addEventListener('abort', callback)`
98+
* - Steps can check if already aborted: `if (abortSignal.aborted) { ... }`
99+
* - Useful for canceling timeouts, network requests, or long-running operations
100+
*
101+
* **Note:** Steps must actively check the abort signal to be canceled mid-execution.
102+
* Steps that don't check the signal will run to completion, but subsequent steps won't execute.
103+
*
104+
* @returns Promise that resolves with `{ message: 'Workflow run canceled' }` when cancellation succeeds
105+
* @throws {HTTPException} 400 - If workflow ID or run ID is missing
106+
* @throws {HTTPException} 404 - If workflow or workflow run is not found
107+
*
108+
* @example
109+
* ```typescript
110+
* const run = await workflow.createRun({ runId: 'run-123' });
111+
* await run.cancel();
112+
* // Returns: { message: 'Workflow run canceled' }
113+
* ```
114+
*
115+
* @example
116+
* ```typescript
117+
* // Example of a step that responds to cancellation
118+
* const step = createStep({
119+
* id: 'long-running-step',
120+
* execute: async ({ inputData, abortSignal, abort }) => {
121+
* const timeout = new Promise((resolve) => {
122+
* const timer = setTimeout(() => resolve('done'), 10000);
123+
*
124+
* // Clean up if canceled
125+
* abortSignal.addEventListener('abort', () => {
126+
* clearTimeout(timer);
127+
* resolve('canceled');
128+
* });
129+
* });
130+
*
131+
* const result = await timeout;
132+
*
133+
* // Check if aborted after async operation
134+
* if (abortSignal.aborted) {
135+
* return abort(); // Stop execution
136+
* }
137+
*
138+
* return { result };
139+
* }
140+
* });
141+
* ```
142+
*/
143+
cancel(): Promise<{ message: string }> {
144+
return this.request(`/api/workflows/${this.workflowId}/runs/${this.runId}/cancel`, {
145+
method: 'POST',
146+
});
147+
}
148+
81149
/**
82150
* Starts a workflow run synchronously without waiting for the workflow to complete
83151
* @param params - Object containing the inputData, initialState and requestContext

docs/src/content/en/reference/client-js/workflows.mdx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,21 @@ await run.resume({
145145
});
146146
```
147147

148+
### cancel()
149+
150+
Cancel a running workflow:
151+
152+
```typescript
153+
const run = await workflow.createRun({ runId: existingRunId });
154+
155+
const result = await run.cancel();
156+
// Returns: { message: 'Workflow run canceled' }
157+
```
158+
159+
This method stops any running steps and prevents subsequent steps from executing. Steps that check the `abortSignal` parameter can respond to cancellation by cleaning up resources (timeouts, network requests, etc.).
160+
161+
See the [Run.cancel()](/reference/v1/workflows/run-methods/cancel) reference for detailed information about how cancellation works and how to write steps that respond to cancellation.
162+
148163
### stream()
149164

150165
Stream workflow execution for real-time updates:

docs/src/content/en/reference/workflows/run-methods/cancel.mdx

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@ description: Documentation for the `Run.cancel()` method in workflows, which can
77

88
The `.cancel()` method cancels a workflow run, stopping execution and cleaning up resources.
99

10+
This method aborts any running steps and updates the workflow status to 'canceled'. It works for both actively running workflows and suspended/waiting workflows.
11+
1012
## Usage example
1113

1214
```typescript
1315
const run = await workflow.createRun();
1416

1517
await run.cancel();
18+
// Returns: { message: 'Workflow run canceled' }
1619
```
1720

1821
## Parameters
@@ -34,14 +37,31 @@ await run.cancel();
3437
content={[
3538
{
3639
name: "result",
37-
type: "Promise<void>",
40+
type: "Promise<{ message: string }>",
3841
description:
39-
"A promise that resolves when the workflow run has been cancelled",
42+
"A promise that resolves with { message: 'Workflow run canceled' } when cancellation succeeds",
4043
},
4144
]}
4245
/>
4346

44-
## Extended usage example
47+
## How cancellation works
48+
49+
When called, the workflow will:
50+
1. **Trigger the abort signal** - Uses the standard Web API AbortSignal to notify running steps
51+
2. **Prevent subsequent steps** - No further steps will be executed
52+
53+
## Abort signal behavior
54+
55+
Steps that check the `abortSignal` parameter can respond to cancellation:
56+
- Steps can listen to the 'abort' event: `abortSignal.addEventListener('abort', callback)`
57+
- Steps can check if already aborted: `if (abortSignal.aborted) { ... }`
58+
- Useful for cancelling timeouts, network requests, or long-running operations
59+
60+
**Note:** Steps must actively check the abort signal to be canceled mid-execution. Steps that don't check the signal will run to completion, but subsequent steps won't execute.
61+
62+
## Extended usage examples
63+
64+
### Cancelling a workflow on error
4565

4666
```typescript
4767
const run = await workflow.createRun();
@@ -53,6 +73,34 @@ try {
5373
}
5474
```
5575

76+
### Creating a step that responds to cancellation
77+
78+
```typescript
79+
const step = createStep({
80+
id: 'long-running-step',
81+
execute: async ({ inputData, abortSignal, abort }) => {
82+
const timeout = new Promise((resolve) => {
83+
const timer = setTimeout(() => resolve('done'), 10000);
84+
85+
// Clean up if canceled
86+
abortSignal.addEventListener('abort', () => {
87+
clearTimeout(timer);
88+
resolve('canceled');
89+
});
90+
});
91+
92+
const result = await timeout;
93+
94+
// Check if aborted after async operation
95+
if (abortSignal.aborted) {
96+
return abort(); // Stop execution
97+
}
98+
99+
return { result };
100+
}
101+
});
102+
```
103+
56104
## Related
57105

58106
- [Workflows overview](/docs/v1/workflows/overview#running-workflows)

docs/src/content/en/reference/workflows/run.mdx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ if (result.status === "suspended") {
5353
},
5454
{
5555
name: "cancel",
56-
type: "() => Promise<void>",
57-
description: "Cancels the workflow execution",
56+
type: "() => Promise<{ message: string }>",
57+
description: "Cancels the workflow execution, stopping any running steps and preventing subsequent steps from executing",
5858
required: true,
5959
},
6060
{
@@ -102,6 +102,12 @@ A workflow run's `status` indicates its current execution state. The possible va
102102
description:
103103
"Workflow execution is paused waiting for resume, with suspended step information",
104104
},
105+
{
106+
name: "canceled",
107+
type: "string",
108+
description:
109+
"Workflow execution was canceled via the cancel() method, stopping any running steps and preventing subsequent steps from executing",
110+
},
105111
]}
106112
/>
107113

0 commit comments

Comments
 (0)