Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/run-cancel-reason.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@workflow/core': patch
'@workflow/world': patch
'@workflow/world-vercel': patch
'@workflow/web-shared': patch
---

Add an optional reason to run cancellation (`run.cancel({ cancelReason })`), recorded on the cancellation event and shown in the run detail view.
19 changes: 19 additions & 0 deletions docs/content/docs/v5/api-reference/workflow-api/get-run.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,25 @@ const { stoppedCount } = await run.wakeUp({
});
```

### Cancel a Run

Cancel a workflow run. You can pass an optional free-text `cancelReason` (up to 512 characters) that is recorded on the run's cancellation event and shown in the run detail view:

```typescript lineNumbers
import { getRun } from "workflow/api";

export async function POST(req: Request) {
const { runId } = await req.json();
const run = getRun(runId);

await run.cancel({ cancelReason: "Superseded by a newer submission" }); // [!code highlight]

return Response.json({ cancelled: true });
}
```

The options object is optional — `await run.cancel()` cancels the run without recording a reason.

## Related Functions

- [`start()`](/docs/api-reference/workflow-api/start) - Start a new workflow and get its run ID.
1 change: 1 addition & 0 deletions packages/core/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export {
type WorkflowReadableStreamOptions,
} from './runtime/run.js';
export {
type CancelRunOptions,
cancelRun,
listStreams,
type ReadStreamOptions,
Expand Down
10 changes: 9 additions & 1 deletion packages/core/src/runtime/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { getWorkflowRunStreamId } from '../util.js';
import { getWorldLazy } from './get-world-lazy.js';
import {
type CancelRunOptions,
type StopSleepOptions,
type StopSleepResult,
wakeUpRun,
Expand Down Expand Up @@ -160,13 +161,20 @@ export class Run<TResult> {

/**
* Cancels the workflow run.
*
* @param options - Optional cancellation settings. `cancelReason` records a
* free-text reason (max 512 chars) on the run_cancelled event, surfaced in
* the run detail view.
*/
async cancel(): Promise<void> {
async cancel(options?: CancelRunOptions): Promise<void> {
'use step';
const world = await this.#lazyWorldPromise;
await world.events.create(this.runId, {
eventType: 'run_cancelled',
specVersion: SPEC_VERSION_CURRENT,
...(options?.cancelReason !== undefined
? { eventData: { cancelReason: options.cancelReason } }
: {}),
});
}

Expand Down
24 changes: 21 additions & 3 deletions packages/core/src/runtime/runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ export interface StopSleepOptions {
correlationIds?: string[];
}

export interface CancelRunOptions {
/**
* Optional free-text reason for the cancellation (max 512 chars), recorded
* on the run_cancelled event and surfaced in the run detail view.
*/
cancelReason?: string;
}

const normalizeWorkflowArgs = (args: unknown): unknown[] => {
return Array.isArray(args) ? args : [args];
};
Expand Down Expand Up @@ -85,17 +93,27 @@ export async function recreateRunFromExisting(

/**
* Cancel a workflow run.
*
* @param options - Optional cancellation settings. `cancelReason` records a
* free-text reason (max 512 chars) on the run_cancelled event.
*/
export async function cancelRun(world: World, runId: string): Promise<void> {
export async function cancelRun(
world: World,
runId: string,
options?: CancelRunOptions
): Promise<void> {
try {
const run = await world.runs.get(runId, { resolveData: 'none' });
const specVersion = run.specVersion ?? SPEC_VERSION_LEGACY;
const compatMode = isLegacySpecVersion(specVersion);
const eventData = {
const eventRequest = {
eventType: 'run_cancelled' as const,
specVersion,
...(options?.cancelReason !== undefined
? { eventData: { cancelReason: options.cancelReason } }
: {}),
};
await world.events.create(runId, eventData, { v1Compat: compatMode });
await world.events.create(runId, eventRequest, { v1Compat: compatMode });
} catch (err) {
throw new Error(
`Failed to cancel run ${runId}: ${err instanceof Error ? err.message : String(err)}`,
Expand Down
21 changes: 21 additions & 0 deletions packages/web-shared/src/components/event-list-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,27 @@ function PayloadBlock({
return <AttrSetEventBlock data={cleaned} />;
}

// Cancellation reason — render the free-text reason as a readable line
// instead of a raw JSON payload (the only field run_cancelled carries).
if (eventType === 'run_cancelled') {
const cancelReason =
cleaned != null &&
typeof cleaned === 'object' &&
typeof (cleaned as Record<string, unknown>).cancelReason === 'string'
? ((cleaned as Record<string, unknown>).cancelReason as string)
: null;
if (cancelReason) {
return (
<div className="p-2 text-xs" style={{ color: 'var(--ds-gray-1000)' }}>
<span style={{ color: 'var(--ds-gray-900)' }}>Reason: </span>
<span className="whitespace-pre-wrap break-words">
{cancelReason}
</span>
</div>
);
}
}

return (
<div className="relative group/payload">
<div
Expand Down
1 change: 1 addition & 0 deletions packages/workflow/src/api-workflow.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export type {
CancelRunOptions,
Event,
StartOptions,
StopSleepOptions,
Expand Down
1 change: 1 addition & 0 deletions packages/workflow/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import '@workflow/core/runtime/world-init';

export type {
CancelRunOptions,
Event,
StopSleepOptions,
StopSleepResult,
Expand Down
4 changes: 4 additions & 0 deletions packages/world-vercel/src/events-v4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ export interface CreateEventV4Input {
hookIsWebhook?: boolean;
hookIsSystem?: boolean;
errorCode?: string;
/** run_cancelled's optional free-text cancellation reason. Small plaintext
* metadata, capped at 512 chars by the @workflow/world schema. */
cancelReason?: string;
/** Arbitrary structured map; rides as a native CBOR object in the
* frame meta. Bounded by the server at 2 KB encoded. */
executionContext?: Record<string, unknown>;
Expand Down Expand Up @@ -226,6 +229,7 @@ function buildPostFrameMeta(
meta.hookIsWebhook = input.hookIsWebhook;
if (input.hookIsSystem !== undefined) meta.hookIsSystem = input.hookIsSystem;
if (input.errorCode !== undefined) meta.errorCode = input.errorCode;
if (input.cancelReason !== undefined) meta.cancelReason = input.cancelReason;
if (input.executionContext !== undefined) {
meta.executionContext = input.executionContext;
}
Expand Down
21 changes: 21 additions & 0 deletions packages/world-vercel/src/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,27 @@ describe('splitEventDataForV4 attribute fields', () => {
expect(started.meta.input).toBeUndefined();
});

it('carries the run_cancelled cancelReason in the frame meta, not the payload', () => {
const { payload, meta } = splitEventDataForV4({
eventType: 'run_cancelled',
specVersion: 4,
eventData: { cancelReason: 'superseded by newer run' },
} as AnyEventRequest);

expect(payload).toBeUndefined();
expect(meta.cancelReason).toBe('superseded by newer run');
});

it('omits cancelReason from meta when run_cancelled carries no reason', () => {
const { payload, meta } = splitEventDataForV4({
eventType: 'run_cancelled',
specVersion: 4,
} as AnyEventRequest);

expect(payload).toBeUndefined();
expect(meta.cancelReason).toBeUndefined();
});

it('carries latency telemetry (ttfs/stso/optimizations) in the frame meta on step terminal events', () => {
const completed = splitEventDataForV4({
eventType: 'step_completed',
Expand Down
7 changes: 7 additions & 0 deletions packages/world-vercel/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ interface SplitEventData {
hookIsWebhook?: boolean;
hookIsSystem?: boolean;
errorCode?: string;
cancelReason?: string;
/** Structured executionContext, included verbatim in frame meta. */
executionContext?: Record<string, unknown>;
/** Initial run attributes (run_created / resilient-start run_started). */
Expand Down Expand Up @@ -219,6 +220,7 @@ type MetaSourceField =
| 'isWebhook'
| 'isSystem'
| 'errorCode'
| 'cancelReason'
| 'executionContext'
| 'attributes'
| 'changes'
Expand Down Expand Up @@ -317,6 +319,11 @@ export function splitEventDataForV4(data: AnyEventRequest): SplitEventData {
if (typeof eventData.errorCode === 'string') {
meta.errorCode = eventData.errorCode;
}
// run_cancelled optionally carries a free-text cancellation reason. Small
// plaintext metadata, so it rides in the frame meta like errorCode.
if (typeof eventData.cancelReason === 'string') {
meta.cancelReason = eventData.cancelReason;
}
if (
eventData.executionContext !== undefined &&
eventData.executionContext !== null &&
Expand Down
50 changes: 50 additions & 0 deletions packages/world/src/events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import { CreateEventSchema, EventSchema } from './events';

describe('run_cancelled cancelReason', () => {
it('accepts a run_cancelled create request with no eventData', () => {
const parsed = CreateEventSchema.parse({
eventType: 'run_cancelled',
specVersion: 4,
});
expect(parsed.eventType).toBe('run_cancelled');
});

it('accepts an optional cancelReason on the create request', () => {
const parsed = CreateEventSchema.parse({
eventType: 'run_cancelled',
specVersion: 4,
eventData: { cancelReason: 'superseded by newer run' },
});
expect(parsed.eventType).toBe('run_cancelled');
// eventData is only present on the run_cancelled branch of the union.
expect(
(parsed as { eventData?: { cancelReason?: string } }).eventData
?.cancelReason
).toBe('superseded by newer run');
});

it('rejects a cancelReason longer than 512 chars', () => {
const result = CreateEventSchema.safeParse({
eventType: 'run_cancelled',
specVersion: 4,
eventData: { cancelReason: 'x'.repeat(513) },
});
expect(result.success).toBe(false);
});

it('retains cancelReason when reading back a stored run_cancelled event (not stripped)', () => {
const parsed = EventSchema.parse({
eventType: 'run_cancelled',
runId: 'wrun_00000000000000000000000000',
eventId: 'evnt_00000000000000000000000000',
createdAt: new Date().toISOString(),
specVersion: 4,
eventData: { cancelReason: 'operator cancelled' },
});
expect(
(parsed as { eventData?: { cancelReason?: string } }).eventData
?.cancelReason
).toBe('operator cancelled');
});
});
8 changes: 8 additions & 0 deletions packages/world/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,14 @@ const RunFailedEventSchema = BaseEventSchema.extend({
*/
const RunCancelledEventSchema = BaseEventSchema.extend({
eventType: z.literal('run_cancelled'),
eventData: z
.object({
// Optional free-text reason for the cancellation. Kept as small
// plaintext metadata (like run_failed's errorCode) so it survives
// resolveData: 'none' and can be displayed without decryption.
cancelReason: z.string().max(512).optional(),
})
.optional(),
});

// Discriminated union for user-creatable events (requests to world.events.create)
Expand Down
Loading