Add cancellation to this AI SDK WorkflowAgent. For hard cancellation, expose a server route that receives `runId` and calls `getRun(runId).cancel()` from `workflow/api`. For graceful cancellation, define `stopHook` with `defineHook()` from `workflow`, create it with a stable token such as the workflow run ID, and race `WorkflowAgent.stream()` against the stop hook using `Promise.race`. Pass an `AbortController` signal to the agent, forward the tool execution signal to cancellable I/O, and wait for the agent branch to settle after aborting before returning a stopped status. Wire the UI Stop button to the route that resumes the hook or falls back to `getRun(runId).cancel()`, and verify stale run IDs are handled.
Cancel a running agent from the outside through a Stop button in a chat user interface (UI), an admin cancellation endpoint, or a timeout fallback.
Create an AbortController in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, call controller.abort(), then wait for the agent branch to observe the signal and settle before the workflow returns. The signal cancels the underlying model stream and is passed to tool execution; each tool must forward it to cancellable I/O. The workflow return value records whether it completed or stopped; read that value through the run API or persist it in application state.
import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow";import { isStepCount, tool, type ModelMessage, type ToolExecutionOptions,} from "ai";import { defineHook, getWritable, getWorkflowMetadata } from "workflow";import { z } from "zod";export const stopHook = defineHook({ schema: z.object({ reason: z.string().optional() }),});async function searchWeb( { query }: { query: string }, { abortSignal }: ToolExecutionOptions<unknown>,) { "use step"; const response = await fetch( `https://api.example.com/search?q=${encodeURIComponent(query)}`, { signal: abortSignal }, ); return response.json();}async function analyzeData( { topic }: { topic: string }, { abortSignal }: ToolExecutionOptions<unknown>,) { "use step"; const response = await fetch("https://api.example.com/analyze", { method: "POST", body: JSON.stringify({ topic }), signal: abortSignal, }); return response.json();}export async function stoppableAgent(messages: ModelMessage[]) { "use workflow"; const { workflowRunId } = getWorkflowMetadata(); const controller = new AbortController(); const hook = stopHook.create({ token: `stop:${workflowRunId}` }); const agent = new WorkflowAgent({ model: "spacexai/grok-4.6", instructions: "You are a research assistant. Search and analyze data as needed.", tools: { searchWeb: tool({ description: "Search the web for information", inputSchema: z.object({ query: z.string() }), execute: searchWeb, }), analyzeData: tool({ description: "Analyze a piece of data", inputSchema: z.object({ topic: z.string() }), execute: analyzeData, }), }, }); const agentPromise = agent.stream({ messages, writable: getWritable<ModelCallStreamPart>(), abortSignal: controller.signal, stopWhen: isStepCount(15), }); const outcome = await Promise.race([ agentPromise.then((result) => ({ type: "complete" as const, messages: result.messages, })), hook.then(({ reason }) => ({ type: "stop-requested" as const, reason, })), ]); if (outcome.type === "stop-requested") { controller.abort(outcome.reason); await agentPromise; // Wait until the losing branch has stopped. return { type: "stopped" as const, reason: outcome.reason }; } return outcome;}
The workflow creates an AbortController when it starts.
The workflow creates a hook with the token stop:${workflowRunId}.
Promise.race runs the agent stream and the stop hook concurrently.
The agent receives controller.signal. When aborted, the signal cancels the active model stream, propagates to tool execution, and prevents another model step from starting. Tool implementations must forward it to operations such as fetch that support cancellation.
When the stop API resumes the hook, the race reports a stop request. The workflow aborts the controller and awaits agentPromise, so it does not return while that branch is still running.
After the agent branch settles, the workflow returns a stopped result. That return value is not written to the model-call stream automatically; the application can read run.returnValue or persist the status separately.