Test Workflows
Test pure Workflow contracts and directive behavior for durable agent runs.
Test three layers: package loop contracts, host behavior against a platform emulator, and real Workflow directives.
Tests whose import graph reaches workflow, and tests that execute steps with TestWorkflowWorld
(it loads the workflow runtime's serializer), must use Vitest's Node environment, not jsdom, because
Workflow 5 captures Node URL intrinsics when the module loads.
Behavioral platform emulator
@yolk-sdk/vercel-workflows/testing exports TestWorkflowWorld. Use it to exercise host code
against run lifecycle, append-only stream replay, HTTP 409-style conflicts for writes after close
(closing again succeeds, as on Vercel), step retry attempts, hooks/resume, cancellation, and the
SDK seam consumed by VercelWorkflows.layerFromSdk.
This is a test fragment; initialize one world per test and mock the ambient module before importing the host Workflow under test:
// @vitest-environment node
import { expect, it, vi } from 'vitest'
import { TestWorkflowWorld } from '@yolk-sdk/vercel-workflows/testing'
vi.mock('workflow', async () => {
const { testWorkflowModule } = await import('@yolk-sdk/vercel-workflows/testing')
return testWorkflowModule
})
it('runs host orchestration against Workflow behavior', async () => {
const world = new TestWorkflowWorld()
const doubledStep = world.step(async (value: number) => value * 2, 'double')
const { runId } = world.start(doubledStep, [21])
expect(world.status(runId)).toBe('pending')
await world.settled(runId)
expect(world.status(runId)).toBe('completed')
await expect(world.sdk.getRun<number>(runId).returnValue).resolves.toBe(42)
})testWorkflowModule delegates getWritable, getWorkflowMetadata, getStepMetadata, and
createHook to the active world's AsyncLocalStorage context, so host code runs unchanged. The
ambient mock does not apply platform retry policy by itself: wrap host step callbacks with
world.step(...) or call world.runStep(...) when the test must exercise retries and
getStepMetadata().attempt. Use world.inspect(runId) for stream closure, write-after-close
attempts, step attempts, status, run errors, unstorableStepErrors (stepName, attempt,
error), discardedStepExecutions (Speculative execution), and the
run's start attributes ({} without any; no $parentRunId/$rootRunId).
world.sdk.start checks them with the installed runtime's validator, so an attribute the platform
rejects fails the start there too. Use world.sdk with VercelWorkflows.layerFromSdk when testing
Effect route/service boundaries.
Hooks
Hooks behave as on the platform. world.resumeHook (and world.sdk.resumeHook) succeeds for every
payload sent to a live hook; await hook reads the first, and the rest are dropped when using
disposes the hook. Once the hook is disposed, or its run ended, resuming its token fails with
TestWorkflowHookNotFoundError until a hook of any run takes the token again. So a test can show a
second answer being accepted and never used, or a late duplicate reaching the next pause that
reuses a token (HITL resume).
A token is held by one live hook at a time. The platform creates a hook when its run next
suspends, applying the disposals the run made since first; the world decides once the code that
created the hook yields (for example at its first await). If another live hook, in another run or
the same one, still holds the token then, the new hook is refused: awaiting it fails with
TestWorkflowHookConflictError (named HookConflictError, with token, conflictingRunId, and
the platform's message without its docs link), disposing it changes nothing, and the holder keeps
the token and its answers. So creating the next hook and then disposing the previous one before
awaiting works, while a step or other suspension in between leaves the next hook refused. Once the
holder is disposed or its run ends, a new hook takes the token.
The world differs from Vercel in two ways: a non-suspending await (such as
await Promise.resolve()) between creating the next hook and disposing the previous one refuses
the next hook here while Vercel accepts it, and a disposed hook frees its token (and answers
TestWorkflowHookNotFoundError) at once, while Vercel records the disposal at the run's next
suspension. The world does not model reading one hook more than once, nor the platform hook's
getConflict().
Step errors
Step errors cross the platform boundary as they do in a deployment. world.runStep stores each
thrown value with the installed workflow runtime's step-error serializer and throws only the value
read back, so error tags, prototypes, and custom fields are gone and cause survives:
- A
FatalError(namedFatalError, or withfatal: true) is never retried; anAbortErroris promoted to one, as the platform does. - An exhausted step fails with the platform's
FatalErrorwhosecauseis the last thrown value; its message readsStep "<name>" failed after N retries: <message>. - A value the platform cannot store, such as an error with a class instance in its
causechain, never reaches the workflow body. The platform redelivers the step instead, so the world runs it again as the next attempt. Past the budget the step fails, without a cause, withStep "<name>" exceeded max retries (N retries).world.inspect(runId).unstorableStepErrorslists every such value.
Carry anything the workflow body must read across the boundary as plain data, for example in an
error's cause, and assert unstorableStepErrors is empty in tests of your step failures.
Speculative execution
Workflow 5.8 may start the body of a step with maxRetries > 0 before its start is recorded. When
that start is refused, the platform discards the body's outcome and runs the body again with the
same getStepMetadata(): same stepId, same attempt. Reproduce it with
new TestWorkflowWorld({ discardStepExecution }):
const world = new TestWorkflowWorld({ discardStepExecution: ({ attempt }) => attempt === 1 })Before each attempt of a step with maxRetries > 0 (never maxRetries: 0), the world calls
discardStepExecution with the step's metadata. On true it runs the body once and discards the
outcome: never stored, never retried, not counted in stepAttempts. That execution's stream writes
stay, as on the platform. The body then runs again with the same metadata, and that run is the
attempt; later attempts keep their numbers. At most one execution per attempt is discarded, and it
settles before the kept one starts, while the platform may run both at once, so a discarded body
that never settles blocks the step. world.inspect(runId).discardedStepExecutions lists them
(stepName, stepId, attempt, and outcome, an Effect Result: Success with the returned
value, Failure with the thrown one).
Use it to check that your model step's executionId differs between the two runs
(Emit replay-safe stream events).
Pure contract tests
Use normal Vitest tests for runVercelAgentWorkflow with fake callbacks.
import { expect, it } from 'vitest'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'
it('continues from tool results', async () => {
const result = await runVercelAgentWorkflow({
input: { request: 'request-1', context: 'ctx-1' },
runModelStep: async input =>
input.state.turn === 1
? {
done: false,
messages: ['user', 'assistant'],
createdMessages: ['assistant'],
toolCalls: ['tool-a'],
usage: { turns: 1 },
turn: 1
}
: {
done: true,
messages: ['user', 'assistant', 'tool-result', 'final'],
createdMessages: ['assistant', 'tool-result', 'final'],
toolCalls: [],
usage: { turns: 2 },
turn: 2
},
runToolBatchStep: async input => ({
messages: ['tool-result'],
createdMessages: [...input.createdMessages, 'tool-result']
}),
closeStream: async () => undefined,
writeError: async () => undefined
})
expect(result._tag).toBe('Completed')
})Directive tests
Use @workflow/vitest for files that exercise 'use workflow', 'use step', hooks, streams, and cancellation.
import { getRun, resumeHook, start } from 'workflow/api'
import { waitForHook } from '@workflow/vitest'Cover:
- starting host Workflow functions with
start - reading stream chunks and replaying with
getRun(runId).getReadable({ startIndex }) - waiting for hooks with
waitForHook - resuming with
resumeHook - cancellation with
getRun(runId).cancel()
Assertions to keep
- A
done: falsemodel result with no tool calls continues directly to the next model step. - One ordered tool-result message per tool call.
- HITL reruns the same tool batch with accumulated responses.
- Event sequence advances across model, tool, and HITL resume.
- Default retries are disabled, except the close step's (
defaultCloseStreamRetry). - Retried streamed steps have de-dupe-ready event ids; a model step's live events carry an
executionIdper execution, so a retry, or a speculative re-execution under the same attempt, never reuses an earlier execution's ids. - Terminal write happens only after durable commit succeeds.
AgentEndcloses throughcloseStream, and only there; a retried close re-closes harmlessly.- Failure paths use
writeError, notcloseStream; awriteErrorrejection preserves the original structured failure result. AgentAwaitingInputdoes not close before resume; resumed execution can append and eventually close.