feat: workflowState + andForEach selector/map#985
Conversation
🦋 Changeset detectedLatest commit: 128b2d8 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
This comment has been minimized.
This comment has been minimized.
📝 WalkthroughWalkthroughAdds a shared, persistent Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ServerAPI
participant WorkflowCore
participant MemoryStore
participant Step
Client->>ServerAPI: Execute request (options, workflowState?)
ServerAPI->>WorkflowCore: start execution (options, workflowState)
WorkflowCore->>WorkflowCore: initialize executionContext.workflowState
WorkflowCore->>Step: execute step (context with workflowState, setWorkflowState)
Step->>WorkflowCore: setWorkflowState(updater)
WorkflowCore->>WorkflowCore: apply updater -> new workflowState
WorkflowCore->>MemoryStore: persist checkpoint (data, state, workflowState)
Note over MemoryStore,WorkflowCore: on suspend/resume, workflowState restored from checkpoint
WorkflowCore->>Client: return result (including final workflowState snapshot)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @.changeset/bright-poems-read.md:
- Around line 5-11: The changeset text is in Turkish but the repository appears
to prefer a consistent language; update the .changeset/bright-poems-read.md
content to match the project's language standard: either translate the Turkish
lines to English (preserving the symbols workflowState, setWorkflowState,
andForEach, items, map) if the project uses English, or confirm and note in the
changeset that Turkish is acceptable; ensure the README-style heading and bullet
points are translated/adjusted accordingly so the mention of workflowState,
setWorkflowState, andForEach items/map remains accurate.
Deploying voltagent with
|
| Latest commit: |
128b2d8
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://be287781.voltagent.pages.dev |
| Branch Preview URL: | https://feat-workflowstate-and-forea.voltagent.pages.dev |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/src/workflow/core.ts`:
- Around line 1646-1652: setWorkflowState currently updates stateManager,
executionContext.workflowState, and stepContext.workflowState but leaves
stepContext.state.workflowState (and therefore context.state.workflowState)
stale; update the implementation of setWorkflowState (the setter assigned on
stepContext) to also assign the computed nextState to
stepContext.state.workflowState (and to executionContext.state.workflowState if
present) immediately after computing nextState so reads of
context.state.workflowState within the same step return the new value.
🧹 Nitpick comments (3)
website/docs/api/endpoints/workflows.md (1)
231-238: Clarify workflowState persistence/serialization in docs.Consider a short note that
workflowStateis persisted across suspend/resume and should contain JSON-serializable data (and avoid secrets/large payloads). This prevents confusion about what’s safe to store.✏️ Suggested doc tweak
| `context` | object | Additional context data | -| `workflowState` | object | Shared state available to workflow steps | +| `workflowState` | object | Shared state available to workflow steps (persisted across suspend/resume; JSON-serializable) |Also applies to: 243-250
packages/core/src/memory/types.ts (1)
131-135: Consider a JSON-serializable type forworkflowState.Since checkpoint data is typically persisted, using a JSON-safe type improves guarantees and prevents accidental storage of non-serializable values.
♻️ Proposed typing refinement
+type JsonValue = + | string + | number + | boolean + | null + | JsonValue[] + | { [key: string]: JsonValue }; + checkpoint?: { stepExecutionState?: any; completedStepsData?: any[]; - workflowState?: Record<string, unknown>; + workflowState?: Record<string, JsonValue>; };packages/core/src/workflow/internal/state.ts (1)
131-143: Consider cloning initial workflowState to avoid external mutation.
workflowStateis stored by reference from run options; a shallow clone prevents accidental mutations from outside the workflow lifecycle.♻️ Proposed tweak
- workflowState: config?.workflowState ?? {}, + workflowState: { ...(config?.workflowState ?? {}) },
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/src/workflow/core.ts`:
- Around line 813-814: The Workflow state from options (workflowStateStore /
options?.workflowState) is captured but never persisted into Memory V2 for runs
that never suspend; update the record creation path and the terminal-update
paths (completed, cancelled, error) to include and store the current
workflowState on create and on terminal updates so /state reflects the latest
shared state — locate where Memory V2 execution records are created/updated and
add the workflowState payload from workflowStateStore to those create and update
calls.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/workflow/core.ts (1)
1332-1355: Persist workflowState on suspension updates, not only in checkpoints.
Suspended executions update Memory V2 without the latest top‑levelworkflowState, so/statecan reflect stale data until completion. Consider persisting the current workflowState alongside the suspension update.🛠️ Suggested fix (persist top-level workflowState on suspend)
- const saveSuspensionState = async ( + const saveSuspensionState = async ( suspensionData: any, executionId: string, memory: MemoryV2, logger: Logger, events: Array<{ id: string; type: string; name?: string; from?: string; startTime: string; endTime?: string; status?: string; input?: any; output?: any; metadata?: Record<string, unknown>; context?: Record<string, unknown>; }>, + workflowState?: WorkflowStateStore, ): Promise<void> => { try { logger.trace(`Storing suspension checkpoint for execution ${executionId}`); await memory.updateWorkflowState(executionId, { status: "suspended", + workflowState, suspension: suspensionData ? { suspendedAt: suspensionData.suspendedAt, reason: suspensionData.reason, stepIndex: suspensionData.suspendedStepIndex, lastEventSequence: suspensionData.lastEventSequence, checkpoint: suspensionData.checkpoint, suspendData: suspensionData.suspendData, } : undefined, events, updatedAt: new Date(), }); logger.trace(`Successfully stored suspension checkpoint for execution ${executionId}`); } catch (error) { logger.error(`Failed to save suspension state for execution ${executionId}:`, { error }); } };- await saveSuspensionState( + await saveSuspensionState( suspensionData, executionId, executionMemory, runLogger, collectedEvents, + stateManager.state.workflowState, );- await saveSuspensionState( + await saveSuspensionState( suspensionMetadata, executionId, executionMemory, runLogger, collectedEvents, + stateManager.state.workflowState, );Also applies to: 1495-1502
PR Checklist
Please check if your PR fulfills the following requirements:
Bugs / Features
What is the current behavior?
What is the new behavior?
fixes (issue)
Notes for reviewers
Summary by cubic
Implement workflowState with setWorkflowState (shared state across steps, persisted across suspend/resume, passable via run options and REST) and enhance andForEach with an items selector and optional map. Update types, tests, and docs to support these features.
Written for commit 128b2d8. Summary will update on new commits.
Summary by CodeRabbit
New Features
Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.