Workflow.watch()

The .watch() function subscribes to state changes in a Mastra workflow, 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"
});
 
// Subscribe to state changes
const unsubscribe = workflow.watch((state) => {
  console.log('Current step:', state.currentStep);
  console.log('Step outputs:', state.stepOutputs);
});
 
// Run the workflow
await workflow.run({
  input: { text: "Process this document" }
});
 
// Stop watching
unsubscribe();

Parameters

callback:

(state: WorkflowState) => void
Function called whenever the workflow state changes

WorkflowState Properties

currentStep:

string
ID of the currently executing step

stepOutputs:

Record<string, any>
Outputs from completed workflow steps

status:

'running' | 'completed' | 'failed'
Current status of the workflow

error?:

Error | null
Error object if workflow failed

Returns

unsubscribe:

() => void
Function to stop watching workflow state changes

Additional Examples

Monitor specific step completion:

workflow.watch((state) => {
  if (state.currentStep === 'processDocument') {
    console.log('Document processing output:', state.stepOutputs.processDocument);
  }
});

Error handling:

workflow.watch((state) => {
  if (state.status === 'failed') {
    console.error('Workflow failed:', state.error);
    // Implement error recovery logic
  }
});