Skip to main content

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 { LegacyWorkflow } from "@mastra/core/workflows/legacy";

const workflow = new LegacyWorkflow({
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: LegacyWorkflowState) => void
Function called whenever the workflow state changes

LegacyWorkflowState 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
}
});