run.watch()
The .watch()
function subscribes to state changes on a mastra run, allowing you to monitor execution progress and react to state updates.
Usage Example
import { Workflow } from "@mastra/core/workflows";
const workflow = new Workflow({
name: "document-processor"
});
const run = workflow.createRun();
// Subscribe to state changes
const unsubscribe = run.watch(({results, activePaths}) => {
console.log('Results:', results);
console.log('Active paths:', activePaths);
});
// Run the workflow
await run.start({
input: { text: "Process this document" }
});
// Stop watching
unsubscribe();
Parameters
callback:
(state: WorkflowState) => void
Function called whenever the workflow state changes
WorkflowState Properties
results:
Record<string, any>
Outputs from completed workflow steps
activePaths:
Map<string, { status: string; suspendPayload?: any; stepPath: string[] }>
Current status of each step
runId:
string
ID of the workflow run
timestamp:
number
Timestamp of the workflow run
Returns
unsubscribe:
() => void
Function to stop watching workflow state changes
Additional Examples
Monitor specific step completion:
run.watch(({results, activePaths}) => {
if (activePaths.get('processDocument')?.status === 'completed') {
console.log('Document processing output:', results['processDocument'].output);
}
});
Error handling:
run.watch(({results, activePaths}) => {
if (activePaths.get('processDocument')?.status === 'failed') {
console.error('Document processing failed:', results['processDocument'].error);
// Implement error recovery logic
}
});