workflow 5.0.0-beta.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +68 -23
  2. package/dist/api-workflow.d.ts +3 -1
  3. package/dist/api-workflow.d.ts.map +1 -1
  4. package/dist/api-workflow.js +2 -1
  5. package/dist/api.d.ts +5 -4
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +6 -7
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +6 -1
  11. package/dist/internal/builtins.d.ts +4 -4
  12. package/dist/internal/builtins.js +6 -6
  13. package/dist/internal/errors.d.ts +1 -1
  14. package/dist/internal/errors.d.ts.map +1 -1
  15. package/dist/internal/errors.js +2 -2
  16. package/dist/nest-builder.d.ts +2 -0
  17. package/dist/nest-builder.d.ts.map +1 -0
  18. package/dist/nest-builder.js +2 -0
  19. package/dist/nest-vercel-builder.d.ts +2 -0
  20. package/dist/nest-vercel-builder.d.ts.map +1 -0
  21. package/dist/nest-vercel-builder.js +2 -0
  22. package/dist/runtime.d.ts +2 -1
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/runtime.js +4 -1
  25. package/docs/advanced/dynamic-workflows.mdx +224 -0
  26. package/docs/ai/chat-session-modeling.mdx +176 -422
  27. package/docs/ai/defining-tools.mdx +6 -7
  28. package/docs/ai/human-in-the-loop.mdx +11 -11
  29. package/docs/ai/index.mdx +67 -72
  30. package/docs/ai/message-queueing.mdx +71 -110
  31. package/docs/ai/meta.json +1 -0
  32. package/docs/ai/resumable-streams.mdx +40 -28
  33. package/docs/ai/sleep-and-delays.mdx +10 -10
  34. package/docs/ai/streaming-updates-from-tools.mdx +6 -6
  35. package/docs/api-reference/index.mdx +25 -1
  36. package/docs/api-reference/meta.json +8 -0
  37. package/docs/api-reference/vitest/index.mdx +68 -15
  38. package/docs/api-reference/workflow/create-hook.mdx +166 -10
  39. package/docs/api-reference/workflow/create-webhook.mdx +16 -15
  40. package/docs/api-reference/workflow/define-hook.mdx +37 -33
  41. package/docs/api-reference/workflow/fatal-error.mdx +30 -8
  42. package/docs/api-reference/workflow/fetch.mdx +14 -10
  43. package/docs/api-reference/workflow/get-step-metadata.mdx +2 -2
  44. package/docs/api-reference/workflow/get-workflow-metadata.mdx +3 -3
  45. package/docs/api-reference/workflow/get-writable.mdx +7 -7
  46. package/docs/api-reference/workflow/index.mdx +3 -3
  47. package/docs/api-reference/workflow/retryable-error.mdx +1 -1
  48. package/docs/api-reference/workflow/set-attributes.mdx +63 -0
  49. package/docs/api-reference/workflow/sleep.mdx +4 -4
  50. package/docs/api-reference/workflow-ai/durable-agent.mdx +63 -101
  51. package/docs/api-reference/workflow-ai/index.mdx +5 -5
  52. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +67 -24
  53. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +28 -12
  54. package/docs/api-reference/workflow-api/get-run.mdx +43 -8
  55. package/docs/api-reference/workflow-api/index.mdx +8 -9
  56. package/docs/api-reference/workflow-api/register-lifecycle-hooks.mdx +87 -0
  57. package/docs/api-reference/workflow-api/resume-hook.mdx +73 -12
  58. package/docs/api-reference/workflow-api/resume-webhook.mdx +11 -9
  59. package/docs/api-reference/workflow-api/start.mdx +107 -12
  60. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  61. package/docs/api-reference/workflow-astro/meta.json +4 -0
  62. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  63. package/docs/api-reference/workflow-errors/entity-conflict-error.mdx +4 -4
  64. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  65. package/docs/api-reference/workflow-errors/hook-force-claimed-error.mdx +70 -0
  66. package/docs/api-reference/workflow-errors/hook-not-found-error.mdx +8 -8
  67. package/docs/api-reference/workflow-errors/index.mdx +91 -0
  68. package/docs/api-reference/workflow-errors/meta.json +7 -0
  69. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
  70. package/docs/api-reference/workflow-errors/run-expired-error.mdx +2 -2
  71. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  72. package/docs/api-reference/workflow-errors/step-not-registered-error.mdx +5 -5
  73. package/docs/api-reference/workflow-errors/throttle-error.mdx +2 -2
  74. package/docs/api-reference/workflow-errors/too-early-error.mdx +2 -2
  75. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  76. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +5 -6
  77. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +13 -6
  78. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +12 -5
  79. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  80. package/docs/api-reference/workflow-errors/workflow-run-not-found-error.mdx +4 -4
  81. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  82. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +8 -8
  83. package/docs/api-reference/workflow-globals.mdx +15 -11
  84. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +37 -0
  85. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  86. package/docs/api-reference/workflow-nest/meta.json +9 -0
  87. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  88. package/docs/api-reference/workflow-nest/workflow-controller.mdx +46 -0
  89. package/docs/api-reference/workflow-nest/workflow-module.mdx +134 -0
  90. package/docs/api-reference/workflow-next/with-workflow.mdx +39 -17
  91. package/docs/api-reference/workflow-nitro/index.mdx +60 -0
  92. package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
  93. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  94. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  95. package/docs/api-reference/workflow-observability/index.mdx +62 -0
  96. package/docs/api-reference/workflow-observability/meta.json +11 -0
  97. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  98. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  99. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  100. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  101. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  102. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  103. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +11 -14
  104. package/docs/api-reference/workflow-runtime/health-check.mdx +51 -0
  105. package/docs/api-reference/workflow-runtime/index.mdx +41 -0
  106. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  107. package/docs/api-reference/workflow-runtime/set-world.mdx +51 -0
  108. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +43 -0
  109. package/docs/api-reference/workflow-runtime/world/analytics.mdx +315 -0
  110. package/docs/api-reference/workflow-runtime/world/index.mdx +60 -0
  111. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  112. package/docs/api-reference/workflow-runtime/world/queue.mdx +88 -0
  113. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +104 -35
  114. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +8 -8
  115. package/docs/api-reference/workflow-serde/index.mdx +1 -2
  116. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +3 -4
  117. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +8 -8
  118. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  119. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  120. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  121. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  122. package/docs/api-reference/workflow-vite/meta.json +4 -0
  123. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  124. package/docs/changelog/attributes-mvp.mdx +53 -41
  125. package/docs/changelog/batched-event-writes.mdx +79 -0
  126. package/docs/changelog/eager-processing.mdx +110 -436
  127. package/docs/changelog/index.mdx +4 -2
  128. package/docs/changelog/lazy-event-creation.md +127 -0
  129. package/docs/changelog/lazy-hook-resume.mdx +78 -0
  130. package/docs/changelog/meta.json +11 -1
  131. package/docs/changelog/resilient-resume.mdx +32 -0
  132. package/docs/changelog/resilient-start.mdx +33 -285
  133. package/docs/changelog/step-message-ownership.mdx +360 -0
  134. package/docs/changelog/turbo-mode.md +87 -0
  135. package/docs/comparisons/index.mdx +66 -0
  136. package/docs/comparisons/meta.json +11 -0
  137. package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
  138. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
  139. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
  140. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
  141. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
  142. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +104 -0
  143. package/docs/configuration/build-and-diagnostics.mdx +79 -0
  144. package/docs/configuration/cli-and-web-ui.mdx +241 -0
  145. package/docs/configuration/framework-options.mdx +165 -0
  146. package/docs/configuration/index.mdx +32 -0
  147. package/docs/configuration/meta.json +12 -0
  148. package/docs/configuration/runtime-tuning.mdx +399 -0
  149. package/docs/configuration/worlds.mdx +315 -0
  150. package/docs/cookbook/advanced/child-workflows.mdx +33 -25
  151. package/docs/cookbook/advanced/publishing-libraries.mdx +65 -56
  152. package/docs/cookbook/advanced/serializable-steps.mdx +48 -68
  153. package/docs/cookbook/advanced/upgrading-workflows.mdx +35 -31
  154. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +78 -60
  155. package/docs/cookbook/agent-patterns/durable-agent.mdx +23 -135
  156. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +180 -195
  157. package/docs/cookbook/common-patterns/batching.mdx +20 -14
  158. package/docs/cookbook/common-patterns/idempotency.mdx +41 -53
  159. package/docs/cookbook/common-patterns/rate-limiting.mdx +8 -4
  160. package/docs/cookbook/common-patterns/saga.mdx +23 -19
  161. package/docs/cookbook/common-patterns/scheduling.mdx +30 -22
  162. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +29 -25
  163. package/docs/cookbook/common-patterns/timeouts.mdx +26 -21
  164. package/docs/cookbook/common-patterns/webhooks.mdx +10 -6
  165. package/docs/cookbook/common-patterns/workflow-composition.mdx +27 -17
  166. package/docs/cookbook/index.mdx +22 -22
  167. package/docs/cookbook/integrations/ai-sdk.mdx +63 -48
  168. package/docs/cookbook/integrations/chat-sdk.mdx +46 -33
  169. package/docs/cookbook/integrations/sandbox.mdx +58 -45
  170. package/docs/deploying.mdx +106 -0
  171. package/docs/errors/abort-signal-timeout-in-workflow.mdx +16 -12
  172. package/docs/errors/corrupted-event-log.mdx +39 -18
  173. package/docs/errors/deployment-mismatch.mdx +71 -0
  174. package/docs/errors/fetch-in-workflow.mdx +15 -14
  175. package/docs/errors/hook-conflict.mdx +38 -11
  176. package/docs/errors/hook-force-claimed.mdx +96 -0
  177. package/docs/errors/index.mdx +24 -37
  178. package/docs/errors/node-js-module-in-workflow.mdx +9 -5
  179. package/docs/errors/replay-divergence.mdx +27 -0
  180. package/docs/errors/run-expired.mdx +85 -0
  181. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  182. package/docs/errors/serialization-failed.mdx +44 -12
  183. package/docs/errors/start-invalid-workflow-function.mdx +9 -5
  184. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  185. package/docs/errors/step-not-registered.mdx +6 -6
  186. package/docs/errors/timeout-in-workflow.mdx +12 -8
  187. package/docs/errors/webhook-invalid-respond-with-value.mdx +18 -18
  188. package/docs/errors/webhook-response-not-sent.mdx +20 -16
  189. package/docs/errors/workflow-not-registered.mdx +5 -5
  190. package/docs/foundations/cancellation.mdx +31 -32
  191. package/docs/foundations/errors-and-retries.mdx +54 -11
  192. package/docs/foundations/hooks.mdx +98 -35
  193. package/docs/foundations/idempotency.mdx +267 -12
  194. package/docs/foundations/index.mdx +1 -26
  195. package/docs/foundations/serialization.mdx +22 -22
  196. package/docs/foundations/starting-workflows.mdx +104 -30
  197. package/docs/foundations/streaming.mdx +108 -60
  198. package/docs/foundations/versioning.mdx +4 -4
  199. package/docs/foundations/workflows-and-steps.mdx +9 -9
  200. package/docs/getting-started/astro.mdx +22 -18
  201. package/docs/getting-started/express.mdx +15 -11
  202. package/docs/getting-started/fastify.mdx +15 -11
  203. package/docs/getting-started/hono.mdx +15 -11
  204. package/docs/getting-started/index.mdx +10 -3
  205. package/docs/getting-started/meta.json +3 -1
  206. package/docs/getting-started/nestjs.mdx +264 -21
  207. package/docs/getting-started/next.mdx +18 -14
  208. package/docs/getting-started/nitro.mdx +22 -18
  209. package/docs/getting-started/nuxt.mdx +15 -11
  210. package/docs/getting-started/python.mdx +190 -41
  211. package/docs/getting-started/react-router/index.mdx +33 -0
  212. package/docs/getting-started/react-router/meta.json +5 -0
  213. package/docs/getting-started/react-router/v7.mdx +237 -0
  214. package/docs/getting-started/react-router/v8.mdx +232 -0
  215. package/docs/getting-started/sveltekit.mdx +20 -16
  216. package/docs/getting-started/tanstack-start.mdx +17 -13
  217. package/docs/getting-started/vite.mdx +15 -11
  218. package/docs/how-it-works/cancellation.mdx +63 -63
  219. package/docs/how-it-works/code-transform.mdx +82 -66
  220. package/docs/how-it-works/encryption.mdx +30 -26
  221. package/docs/how-it-works/event-sourcing.mdx +132 -35
  222. package/docs/how-it-works/framework-integrations.mdx +96 -337
  223. package/docs/how-it-works/understanding-directives.mdx +22 -22
  224. package/docs/internal/index.mdx +6 -4
  225. package/docs/internal/meta.json +6 -1
  226. package/docs/internal/nitro-native-build.mdx +38 -0
  227. package/docs/internal/nitro-web-ui.mdx +24 -0
  228. package/docs/internal/serializable-abort-controller.mdx +7 -7
  229. package/docs/meta.json +4 -2
  230. package/docs/observability/attributes.mdx +91 -21
  231. package/docs/observability/index.mdx +29 -15
  232. package/docs/observability/lifecycle-hooks.mdx +95 -0
  233. package/docs/observability/meta.json +1 -1
  234. package/docs/observability/retention.mdx +95 -0
  235. package/docs/observability/tracing.mdx +124 -0
  236. package/docs/testing/index.mdx +120 -38
  237. package/docs/testing/server-based.mdx +10 -10
  238. package/docs/whats-new.mdx +190 -0
  239. package/docs/worlds/building-a-world.mdx +538 -0
  240. package/docs/worlds/local.mdx +129 -0
  241. package/docs/worlds/meta.json +10 -0
  242. package/docs/worlds/postgres.mdx +424 -0
  243. package/docs/worlds/upgrading-to-v5.mdx +162 -0
  244. package/docs/worlds/vercel.mdx +345 -0
  245. package/package.json +17 -14
  246. package/docs/api-reference/workflow/experimental-set-attributes.mdx +0 -63
  247. package/docs/api-reference/workflow-api/world/index.mdx +0 -58
  248. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  249. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  250. package/docs/api-reference/workflow-api/world/queue.mdx +0 -86
  251. package/docs/deploying/building-a-world.mdx +0 -251
  252. package/docs/deploying/index.mdx +0 -95
  253. package/docs/deploying/meta.json +0 -4
  254. package/docs/deploying/world/local-world.mdx +0 -84
  255. package/docs/deploying/world/meta.json +0 -4
  256. package/docs/deploying/world/postgres-world.mdx +0 -224
  257. package/docs/deploying/world/vercel-world.mdx +0 -181
  258. package/docs/migration-guides/index.mdx +0 -34
  259. package/docs/migration-guides/meta.json +0 -9
  260. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -358
  261. package/docs/migration-guides/migrating-from-inngest.mdx +0 -304
  262. package/docs/migration-guides/migrating-from-temporal.mdx +0 -313
  263. package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -328
@@ -0,0 +1,95 @@
1
+ ---
2
+ title: Lifecycle Hooks
3
+ description: Register global handlers that observe workflow runs completing or failing, for centralized reporting to services like Sentry.
4
+ type: guide
5
+ summary: Observe run completions and failures from a single place with registerLifecycleHooks.
6
+ prerequisites:
7
+ - /docs/foundations/workflows-and-steps
8
+ related:
9
+ - /docs/observability
10
+ - /docs/observability/tracing
11
+ - /docs/errors
12
+ ---
13
+
14
+ Lifecycle hooks let you register global handlers that observe workflow runs completing or failing on your app's compute. They can observe even the failures that never reach a `try/catch` in workflow code, such as a replay timing out or a run exhausting its queue deliveries. Use them for best-effort centralized error reporting, such as forwarding failed runs to Sentry without wrapping each workflow body.
15
+
16
+ ## Registering hooks
17
+
18
+ Call `registerLifecycleHooks` from `workflow/api` early in your application's lifecycle, so the handlers exist before the first run finishes. In Next.js, [`instrumentation.ts`](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation) is the natural place; in any other app, any module that loads at startup works.
19
+
20
+ ```typescript title="instrumentation.ts" lineNumbers
21
+ export async function register() {
22
+ if (process.env.NEXT_RUNTIME === "nodejs") {
23
+ const { registerLifecycleHooks } = await import("workflow/api")
24
+
25
+ registerLifecycleHooks({
26
+ async onRunCompleted({ run, workflowName }) {
27
+ console.log(`Run ${run.runId} (${workflowName}) completed`)
28
+ },
29
+ async onRunFailed({ run, workflowName, error }) {
30
+ console.error(
31
+ `Run ${run.runId} (${workflowName}) failed with ${error.errorCode}:`,
32
+ error.cause
33
+ )
34
+ },
35
+ })
36
+ }
37
+ }
38
+ ```
39
+
40
+ Keep the dynamic `workflow/api` import inside the `NEXT_RUNTIME === "nodejs"` guard. Next.js also compiles `instrumentation.ts` for the Edge runtime. A top-level static import pulls Node.js-only dependencies into that compilation and breaks webpack Edge builds, even if the registration call is guarded.
41
+
42
+ `registerLifecycleHooks` returns an unregister function. You can register multiple hook sets, and handlers run in registration order. Registrations are not deduplicated: register each hook set once per process, and call its unregister function before registering it again during hot reload or module re-evaluation. Otherwise, repeated registrations invoke the same handler multiple times for each transition.
43
+
44
+ ## Handler parameters
45
+
46
+ Both handlers receive a `workflowName` string and the [`Run`](/docs/api-reference/workflow-api/get-run) instance for the transitioned run. `workflowName` is the machine-readable workflow identifier, such as `workflow//./src/workflows/order//processOrder`. Use this parameter to filter runs without a backend read. `run.runId` is also available without a read.
47
+
48
+ The `Run` instance hydrates lazily. Accessors such as `run.workflowName`, `run.status`, and `run.returnValue` still fetch from the backend when used. In particular, `workflowName` is a string, while `run.workflowName` is a `Promise<string>`. Lazy access defers those reads; it does not make them free.
49
+
50
+ `onRunFailed` additionally receives a `WorkflowRunFailedError` hydrated for reporting. Unlike `run.returnValue`, it defers readable stream I/O and uses persisted abort snapshots:
51
+
52
+ - `error.errorCode`: the failure classification (`USER_ERROR`, `RUNTIME_ERROR`, `MAX_DELIVERIES_EXCEEDED`, and more). See [error codes](/docs/errors) for the full list.
53
+ - `error.cause`: the thrown value hydrated from the persisted error data, with registered Error subclass identity, message, stack, and cause chain preserved. Readable streams load lazily when consumed, and abort signals reflect their persisted state without live subscriptions. Writable streams retain their normal forwarding pipe and lock-polling setup during hydration. If hydration fails, the cause is a generic `Error`, matching `run.returnValue`'s fallback. Any JavaScript value can be thrown, so this is typed `unknown`.
54
+
55
+ In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead of awaiting `run.returnValue`.
56
+
57
+ The invocation's `waitUntil` scope includes background stream operations from the hydrated cause, even after a handler returns or throws. Close or release stream reader and writer locks when finished so that work can settle. Await other asynchronous reporting work in your handler, such as `Sentry.flush()` below, to keep it in the same lifetime scope.
58
+
59
+ ## Reporting failed runs to Sentry
60
+
61
+ This example reports failures for workflows named `processOrder`. Remove the filter to report failures from all workflows.
62
+
63
+ ```typescript title="instrumentation.ts" lineNumbers
64
+ export async function register() {
65
+ if (process.env.NEXT_RUNTIME === "nodejs") {
66
+ const { registerLifecycleHooks } = await import("workflow/api")
67
+ const Sentry = await import("@sentry/nextjs")
68
+
69
+ Sentry.init({ dsn: process.env.SENTRY_DSN })
70
+
71
+ registerLifecycleHooks({
72
+ async onRunFailed({ run, workflowName, error }) {
73
+ if (!workflowName.endsWith("//processOrder")) return
74
+
75
+ Sentry.captureException(error.cause ?? error, {
76
+ tags: {
77
+ workflowRunId: run.runId,
78
+ workflowName,
79
+ errorCode: error.errorCode,
80
+ },
81
+ })
82
+ await Sentry.flush(2000)
83
+ },
84
+ })
85
+ }
86
+ }
87
+ ```
88
+
89
+ ## How handlers behave
90
+
91
+ - **Host-only.** Handlers run with full Node.js access, never inside the workflow's sandboxed VM. Calling `registerLifecycleHooks` from workflow code throws.
92
+ - **Fire-and-forget.** Handlers cannot delay or change the run's outcome. The runtime logs and swallows a throwing handler, and the remaining handlers still run. On Vercel, `waitUntil` keeps the invocation alive while handlers finish, subject to the invocation's duration limit. On other hosts, handlers run as detached work. If the host freezes or terminates the process after the response, handlers may not complete.
93
+ - **Best-effort delivery.** Each registered handler is invoked at most once by the invocation that writes the terminal event. For a failure, this happens after any workflow or step retries are exhausted. Callbacks are not retried if they throw or the process dies, so a callback may never run or may stop before completing. The [event log](/docs/how-it-works/event-sourcing) is the system of record, not lifecycle callbacks.
94
+ - **Fires where the transition is recorded.** Terminal transitions recorded outside your app's compute do **not** fire handlers. For example, when you cancel a run from the CLI or the Vercel dashboard, the backend writes that transition, so no handler runs.
95
+ - **Register everywhere your workflows run.** The terminal write can happen in any function invocation that processes the run's queue messages, so registration must run at startup in every instance of the app (which `instrumentation.ts` guarantees).
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "title": "Observability",
3
- "pages": ["attributes"]
3
+ "pages": ["tracing", "attributes", "retention", "lifecycle-hooks"]
4
4
  }
@@ -0,0 +1,95 @@
1
+ ---
2
+ title: Data retention
3
+ description: Control how long a run's data is kept after it finishes.
4
+ type: reference
5
+ summary: Control how long a run's data is kept after the run ends.
6
+ prerequisites:
7
+ - /docs/foundations/workflows-and-steps
8
+ related:
9
+ - /docs/observability
10
+ - /docs/api-reference/workflow-api/start
11
+ ---
12
+
13
+ A finished run leaves data behind: the inputs and outputs of the workflow and
14
+ each of its steps, the payloads on its event log, and anything written to its
15
+ streams. How long that data is kept is decided by the World you are running
16
+ on, not by the SDK.
17
+
18
+ `experimental_retention` on [`start()`](/docs/api-reference/workflow-api/start)
19
+ lets a run ask for a specific retention period, rather than the World's default.
20
+
21
+ ## Deleting a run's data as soon as it ends
22
+
23
+ {/* @skip-typecheck: abbreviated usage; processDocumentWorkflow is the reader's own workflow */}
24
+ ```typescript lineNumbers
25
+ const run = await start(processDocumentWorkflow, [documentId], {
26
+ experimental_retention: 0, // [!code highlight]
27
+ })
28
+ ```
29
+
30
+ `0` asks the World to delete the run's **user data** the moment the run
31
+ completes or fails, rather than keeping it for the World's default window.
32
+
33
+ Two values are accepted today:
34
+
35
+ | Value | Meaning |
36
+ | --- | --- |
37
+ | `0` | Delete user data as soon as the run reaches a terminal state. |
38
+ | `'default'` | Use the World's default. Identical to omitting the option. |
39
+
40
+ <Callout type="warn">
41
+ The option is prefixed `experimental_` because both its name and the set of
42
+ values it accepts are expected to change.
43
+ </Callout>
44
+
45
+ ## What is deleted, and what is not
46
+
47
+ **Deleted:** the run's input, output and error; every step's input, output and
48
+ error; the payloads on the event log; and stream contents.
49
+
50
+ **Kept:** the run, step and event records themselves — their ids, timestamps,
51
+ status, step names, and any [attributes](/docs/observability/attributes) you
52
+ set. They are kept for the World's default period so the run stays visible in
53
+ the CLI and web UI. A purged run is still listed and still traceable; its
54
+ payloads simply read back as expired.
55
+
56
+ Inspecting a purged run shows it as expired rather than failing. The Workflow
57
+ CLI renders the run's own input, output and error as `<data expired>`:
58
+
59
+ ```bash
60
+ workflow inspect runs wrun_...
61
+ ```
62
+
63
+ Step, hook and event payloads read back empty. On the Vercel World they also
64
+ render as `<data expired>`; on Worlds that clear the stored value outright
65
+ they simply show as empty. Either way the data is gone — the difference is
66
+ only in how the absence is labelled.
67
+
68
+ <Callout type="warn">
69
+ **You cannot read the return value of a run started with
70
+ `experimental_retention: 0`.** The deletion races your own read of the
71
+ result and generally wins, so `await run.returnValue` throws
72
+ [`RunExpiredError`](/docs/errors/run-expired) instead of resolving.
73
+
74
+ This is a known limitation. If you need the result, send it somewhere you
75
+ control, e.g. a step that writes it to your own store, rather than reading
76
+ it back off the run.
77
+ </Callout>
78
+
79
+ `RunExpiredError` is not specific to `experimental_retention: 0`. Any run read
80
+ after its retention window has passed throws it, and the error carries
81
+ `runId`, `runStatus` and `expiredAt` when the World still has them — so a
82
+ caller can tell a successful run whose result is gone from a failed one whose
83
+ error is gone. If the run's metadata is gone too, the World reports the run as
84
+ missing and you get `WorkflowRunNotFoundError` instead.
85
+
86
+ ## Retention is implemented by the World
87
+
88
+ The SDK records your preference; it does not enforce it. `start()` writes the
89
+ value onto the run as the reserved `$retention` attribute, and the World
90
+ decides what to do when the run ends. Attributes are a spec version 4 feature,
91
+ so `experimental_retention: 0` throws against an older World rather than being
92
+ recorded and ignored. A World that does implement spec version 4 but not
93
+ retention **keeps the data**. If you need certainty that a specific World
94
+ deletes your data, confirm it against that World's own documentation rather
95
+ than the presence of this option.
@@ -0,0 +1,124 @@
1
+ ---
2
+ title: Tracing
3
+ description: Distributed tracing with OpenTelemetry for workflow runs, steps, and queue deliveries.
4
+ type: guide
5
+ summary: Trace workflow execution end to end with OpenTelemetry.
6
+ prerequisites:
7
+ - /docs/foundations/workflows-and-steps
8
+ related:
9
+ - /docs/observability
10
+ - /docs/observability/attributes
11
+ - /docs/how-it-works/event-sourcing
12
+ ---
13
+
14
+ The Workflow SDK includes [OpenTelemetry](https://opentelemetry.io) instrumentation. It emits spans for workflow starts, every workflow and step invocation, and the HTTP calls it makes to the workflow backend, and it propagates trace context across queue deliveries so a run remains traceable end to end.
15
+
16
+ The SDK only depends on the OpenTelemetry **API**, never on an SDK or exporter. If your application does not register an OpenTelemetry SDK, all tracing code is a silent no-op with no overhead and no behavior change.
17
+
18
+ ## Enabling tracing
19
+
20
+ Register any OpenTelemetry Node SDK in your application. On Vercel with Next.js, the simplest setup is [`@vercel/otel`](https://vercel.com/docs/tracing/instrumentation) in `instrumentation.ts`:
21
+
22
+ ```typescript title="instrumentation.ts" lineNumbers
23
+ import { registerOTel } from "@vercel/otel"
24
+
25
+ export function register() {
26
+ registerOTel({ serviceName: "my-app" })
27
+ }
28
+ ```
29
+
30
+ No workflow-specific configuration is required. As soon as a tracer provider and propagator are registered, the SDK's spans, context propagation, and span links activate automatically.
31
+
32
+ <Callout>
33
+ `@opentelemetry/api` is an **optional peer dependency**. An OpenTelemetry SDK such as `@vercel/otel` normally pulls it in transitively, but installing it directly (`npm i @opentelemetry/api`) guarantees it is present in your build, particularly for bundled or serverless targets where the SDK's tracing is inlined at build time. If it can't be resolved, tracing is a silent no-op.
34
+ </Callout>
35
+
36
+ ## Spans
37
+
38
+ | Span name | Kind | Emitted when |
39
+ | --- | --- | --- |
40
+ | `workflow.start <name>` | internal | `start()` is called in your application code |
41
+ | `workflow.execute <name>` | consumer (root) | a queue delivery invokes the workflow; replay, orchestration, and inline steps run under it |
42
+ | `step.execute <name>` | internal (inline) / consumer + root (queue-delivered) | a step function executes |
43
+ | `http <method>` | client | the SDK calls the workflow backend (event reads/writes) |
44
+ | `workflow.stream.write` | client | a stream chunk (or the stream close) is flushed to the backend |
45
+ | `workflow.stream.flush` | client | a buffered batch of stream writes settles; back-dated to the batch's first `write()`, so its duration is the app-perceived batch latency (buffer dwell + RPC) |
46
+ | `workflow.stream.close` | client | the stream-close RPC; its duration is the close round trip |
47
+ | `workflow.stream.read.complete` | client | a stream read drains; back-dated to the read dispatch, so its duration is the total read (`workflow.stream.read.chunks` / `.bytes` carry throughput counts) |
48
+ | `workflow.stream.read.connect` | client | a live stream read opens; the span covers dispatch → response headers (network connect) |
49
+ | `workflow.stream.read` | client | a live stream read receives its first chunk; the span's duration is the end-to-end time-to-first-chunk (see `workflow.stream.read.ttfc_ms`) |
50
+
51
+ `<name>` is the short function name (for example `processOrder`); the full machine name, including the source module, is available in the `workflow.name` / `step.name` attributes.
52
+
53
+ Stream spans are emitted by the SDK's world backend on the client that writes or reads the stream, and (like all SDK spans) are no-ops when no OpenTelemetry SDK is registered. The `workflow.stream.read` span only appears once the first non-empty chunk arrives.
54
+
55
+ ## Key attributes
56
+
57
+ | Attribute | Description |
58
+ | --- | --- |
59
+ | `workflow.run.id` | The run ID (`wrun_...`). Present on every workflow and step span; the primary key for finding all spans of a run. |
60
+ | `workflow.name` | The workflow function name. |
61
+ | `workflow.trace.mode` | The active trace mode (`linked` or `continuous`). |
62
+ | `workflow.trace.propagated` | Whether the invocation received trace context from the queue message. |
63
+ | `workflow.queue.overhead_ms` | Time between the message being enqueued and the handler starting: queue dwell plus any cold start. |
64
+ | `workflow.stream.name` | The stream name, on stream write/read spans. |
65
+ | `workflow.stream.operation` | The stream operation: `write`, `write_multi`, `close`, `read`, or `flush`. |
66
+ | `workflow.stream.write.chunk_rtt` | Time between emission of a chunk to the wire, and receiving the `ack` message for that chunk. Also stamped on `workflow.stream.flush` (the batch's write RPC duration, network included). |
67
+ | `workflow.stream.flush.buffer_dwell_ms` | On `workflow.stream.flush`: time the batch's first chunk waited in the client-side write buffer (flush timer, run-ready barrier) before the request was dispatched. `workflow.stream.flush.chunks` / `.bytes` carry the batch shape. |
68
+ | `workflow.stream.read.ttfc_ms` | Time between opening a read connection and observing and receiving the first chunk back. |
69
+ | `workflow.stream.read.connect_ms` | On `workflow.stream.read`: the connect portion (read dispatch → stream handle/response headers), network included. |
70
+
71
+ ## Trace shape: one trace per invocation
72
+
73
+ A single workflow run can span hours or days across many separate function invocations: every `sleep()` wake-up, hook resume, retry, and queued step continuation is a new queue delivery. Stitching all of that into one trace produces giant, slow-loading traces that most tracing backends truncate.
74
+
75
+ Instead, the SDK creates **one bounded trace per invocation**. Each `workflow.execute` (or background `step.execute`) span starts a new trace root and attaches two **span links**:
76
+
77
+ - a link to the **enqueue site**, the span that queued the message which triggered this invocation, and
78
+ - a link to the **run origin**, the trace in which `start()` was originally called.
79
+
80
+ A span link is OpenTelemetry's relationship for "causally related, but in a different trace." It is the standard pattern for asynchronous messaging, where producing and consuming a message can be separated by arbitrary time.
81
+
82
+ ```mermaid
83
+ flowchart LR
84
+ O["start() request trace"]
85
+ A["invocation 1"]
86
+ B["invocation 2"]
87
+ C["invocation 3 ..."]
88
+ A -. "link" .-> O
89
+ B -. "link" .-> O
90
+ C -. "link" .-> O
91
+ B -. "link" .-> A
92
+ C -. "link" .-> B
93
+
94
+ style O fill:#a78bfa,stroke:#8b5cf6,color:#000
95
+ ```
96
+
97
+ Each invocation links back to the trace that enqueued it and to the run origin.
98
+
99
+ To see a whole run, query by attribute rather than by trace ID (for example `workflow.run.id = wrun_...` in your tracing backend), or follow the span links between invocation traces.
100
+
101
+ ## Trace modes
102
+
103
+ The `WORKFLOW_TRACE_MODE` environment variable controls the shape:
104
+
105
+ | Mode | Behavior |
106
+ | --- | --- |
107
+ | `linked` (default) | Each invocation is its own trace root with span links to the enqueue site and the run origin. Traces stay small; sampling is decided per invocation. |
108
+ | `continuous` | The run-origin context becomes the **parent** of every invocation, so the entire run shares one trace ID. |
109
+
110
+ <Callout type="warn">
111
+ This is a behavior change from v4, which always used `continuous`-style tracing. If you have dashboards or queries that assume one trace ID per run, either update them to use `workflow.run.id` and span links, or set `WORKFLOW_TRACE_MODE=continuous` to restore the previous shape. In `linked` mode, each invocation root makes its own sampling decision, and the number of root spans increases to one per invocation.
112
+ </Callout>
113
+
114
+ ## Context propagation
115
+
116
+ When tracing is enabled, the SDK propagates [W3C Trace Context](https://www.w3.org/TR/trace-context/) on its outbound calls:
117
+
118
+ - **Backend requests** carry `traceparent`, `tracestate`, and `baggage` headers, so backend spans can join your trace.
119
+ - **Queue messages** carry the run-origin trace context in the message payload, and the queue re-delivers the producer's context to the workflow handler, where it becomes the enqueue-site span link.
120
+ - **Baggage** carries `workflow.run_id` and `workflow.name` entries during workflow execution, allowing downstream services you call from steps to tag their own telemetry with the run ID.
121
+
122
+ <Callout>
123
+ Baggage entries set by your application are propagated as a `baggage` HTTP header on the SDK's backend requests, like any other OpenTelemetry-instrumented HTTP call. Avoid placing sensitive values in baggage.
124
+ </Callout>
@@ -3,18 +3,18 @@ title: Testing
3
3
  description: Unit test individual steps and integration test entire workflows using Vitest.
4
4
  ---
5
5
 
6
- Testing is a critical part of building reliable workflows. Because steps are just functions annotated with directives, they can be unit tested like any other JavaScript function. Workflow SDK also provides a Vitest plugin that runs full workflows in-process — no running server required.
6
+ Test steps like any other JavaScript function, or use the Workflow SDK Vitest plugin to run complete workflows in-process without a server.
7
7
 
8
8
  This guide covers two approaches:
9
9
 
10
- 1. **Unit testing** - Test individual steps as plain functions, without the workflow runtime.
11
- 2. **Integration testing** - Test entire workflows in-process using the `workflow()` Vitest plugin. Required when you want to test workflow specific code paths, like those using [hooks](/docs/foundations/hooks), webhooks, [`sleep()`](/docs/api-reference/workflow/sleep), retries, etc.
10
+ 1. **Unit testing**: Test individual steps as plain functions without the workflow runtime.
11
+ 2. **Integration testing**: Test entire workflows in-process using the `workflow()` Vitest plugin. Use integration tests for workflow-specific code paths that use [hooks](/docs/foundations/hooks), webhooks, [`sleep()`](/docs/api-reference/workflow/sleep), or retries.
12
12
 
13
- ## Unit Testing Steps
13
+ ## Unit testing steps
14
14
 
15
- Without the workflow compiler, the `"use step"` directive is a no-op. Your step functions run as regular JavaScript functions, making them straightforward to unit test with no special configuration.
15
+ Without the workflow compiler, the `"use step"` directive is a no-op. Your step functions run as regular JavaScript functions, so you can unit test them without special configuration.
16
16
 
17
- ### Example Steps
17
+ ### Example steps
18
18
 
19
19
  Given a workflow file with step functions like this:
20
20
 
@@ -49,7 +49,7 @@ export async function sendOnboardingEmail(user: { id: string; email: string }) {
49
49
  }
50
50
  ```
51
51
 
52
- ### Writing Unit Tests for Steps
52
+ ### Writing unit tests for steps
53
53
 
54
54
  You can import and test step functions directly with Vitest. No special configuration or workflow plugin is needed:
55
55
 
@@ -77,18 +77,30 @@ describe("sendWelcomeEmail step", () => {
77
77
  This approach is ideal for verifying the business logic inside individual steps in isolation.
78
78
 
79
79
  <Callout type="info">
80
- Unit testing works well for individual steps. A simple workflow that only calls steps can also be unit tested this way, since `"use workflow"` is similarly a no-op without the compiler. However, any workflow that uses runtime features like [`sleep()`](/docs/api-reference/workflow/sleep), [hooks](/docs/foundations/hooks), or [webhooks](/docs/foundations/hooks#understanding-webhooks) cannot be unit tested directly because those APIs require the workflow runtime. Use [integration testing](#integration-testing-with-the-vitest-plugin) for testing entire workflows, especially those that depend on workflow-only features.
80
+ Unit testing works well for individual steps. A workflow that only calls steps can also be unit tested this way, since `"use workflow"` is similarly a no-op without the compiler. However, any workflow that uses runtime features like [`sleep()`](/docs/api-reference/workflow/sleep), [hooks](/docs/foundations/hooks), or [webhooks](/docs/foundations/hooks#understanding-webhooks) cannot be unit tested directly because those APIs require the workflow runtime. Use [integration testing](#integration-testing-with-the-vitest-plugin) for testing entire workflows, especially those that depend on workflow-only features.
81
81
  </Callout>
82
82
 
83
- ## Integration Testing with the Vitest Plugin
83
+ ## Integration testing with the Vitest plugin
84
84
 
85
- For workflows that rely on runtime features like [hooks](/docs/foundations/hooks), [webhooks](/docs/foundations/hooks#understanding-webhooks), [`sleep()`](/docs/api-reference/workflow/sleep), or error retries, you need to test against a real workflow setup. The `@workflow/vitest` plugin handles everything automatically — it compiles your workflow directives, builds the runtime bundles, and executes workflows entirely in-process. No server required.
85
+ For workflows that rely on runtime features like [hooks](/docs/foundations/hooks), [webhooks](/docs/foundations/hooks#understanding-webhooks), [`sleep()`](/docs/api-reference/workflow/sleep), or error retries, you need to test against a real workflow setup. The `@workflow/vitest` plugin handles everything automatically: it compiles your workflow directives, builds the runtime bundles, and executes workflows entirely in-process. No server required.
86
86
 
87
87
  <Callout type="warn">
88
- `vi.mock()` and related calls do _not_ work inside workflow functions, only step functions. Your workflow functions cannot import third party code that needs to be mocked. Mocking works for npm packages imported in step functions. If something needs to be mocked, it likely belongs inside a step function either way.
88
+ `vi.mock()` cannot reach code inside workflow functions at all, and reaches step code only under specific conditions. Read [Mocking](#mocking) before reaching for it.
89
89
  </Callout>
90
90
 
91
- ### Vitest Configuration
91
+ ### Installation
92
+
93
+ ```package-install
94
+ npm i -D @workflow/vitest@beta
95
+ ```
96
+
97
+ <Callout type="warn">
98
+ **Workflow 5 needs the `beta` tag.** `@workflow/vitest@latest` is still the 4.x line, so a plain `npm i -D @workflow/vitest` installs a v4 plugin next to a v5 app. Install `@workflow/vitest@beta`, or pin the beta your app is on (for example `@workflow/vitest@5.0.0-beta.53`), and upgrade it together with `workflow`.
99
+
100
+ The plugin builds and runs your workflows against the copy of `@workflow/core` it was installed with, so it checks this for you. At the start of each run it compares that copy with the one your app resolves: a different major fails the run with the install command that fixes it, and any other difference logs a warning. Set [`WORKFLOW_VITEST_VERSION_CHECK=off`](/docs/configuration/build-and-diagnostics#workflow_vitest_version_check) to skip the check.
101
+ </Callout>
102
+
103
+ ### Vitest configuration
92
104
 
93
105
  Create a separate Vitest config for integration tests that includes the `workflow()` plugin:
94
106
 
@@ -109,15 +121,15 @@ That's it. The plugin automatically:
109
121
 
110
122
  1. Transforms `"use workflow"` and `"use step"` directives via SWC
111
123
  2. Builds workflow and step bundles before tests run
112
- 3. Sets up an in-process workflow runtime using a fresh [Local World](/docs/worlds/local) instance in each test worker — all workflow data is cleared automatically between test files for full isolation
124
+ 3. Sets up an in-process workflow runtime using a fresh [Local World](/worlds/local) instance in each test worker; all workflow data is cleared automatically between test files for full isolation
113
125
 
114
126
  <Callout type="info">
115
127
  Use a separate Vitest configuration and a distinct file naming convention (e.g. `*.integration.test.ts`) to keep unit tests and integration tests separate. Unit tests run with a standard Vitest config without the workflow plugin, while integration tests use the config above.
116
128
  </Callout>
117
129
 
118
- ### Writing Integration Tests
130
+ ### Writing integration tests
119
131
 
120
- Use [`start()`](/docs/api-reference/workflow-api/start) to trigger a workflow and [`run.returnValue`](/docs/api-reference/workflow-api/start#returnvalue) to get the result. `returnValue` is a promise that blocks until the workflow completes (or throws if it fails):
132
+ Use [`start()`](/docs/api-reference/workflow-api/start) to trigger a workflow and [`run.returnValue`](/docs/api-reference/workflow-api/start#returns) to get the result. `returnValue` is a promise that blocks until the workflow completes (or throws if it fails):
121
133
 
122
134
  ```typescript title="workflows/calculate.integration.test.ts" lineNumbers
123
135
  import { describe, it, expect } from "vitest";
@@ -144,9 +156,9 @@ describe("calculateWorkflow", () => {
144
156
  });
145
157
  ```
146
158
 
147
- ### Testing Hooks and Waits
159
+ ### Testing hooks and waits
148
160
 
149
- The real power of integration testing comes when testing workflow-only features. Hooks and waits can be resumed programmatically using the [`workflow/api`](/docs/api-reference/workflow-api) functions, making it straightforward to simulate external events in your tests.
161
+ Integration testing is most useful for workflow-only features. You can resume hooks and waits programmatically using the [`workflow/api`](/docs/api-reference/workflow-api) functions to simulate external events in your tests.
150
162
 
151
163
  Given a workflow that waits for approval via a hook, then sleeps before publishing:
152
164
 
@@ -228,7 +240,7 @@ describe("approvalWorkflow", () => {
228
240
  reviewer: "bob",
229
241
  });
230
242
 
231
- // No wakeUp() needed here — the rejected path has no sleep
243
+ // No wakeUp() needed here; the rejected path has no sleep
232
244
  const result = await run.returnValue;
233
245
  expect(result).toEqual({
234
246
  status: "rejected",
@@ -243,12 +255,12 @@ describe("approvalWorkflow", () => {
243
255
  </Callout>
244
256
 
245
257
  <Callout type="info">
246
- `waitForSleep()` returns the first **pending** sleep — one that has a `wait_created` event but no corresponding `wait_completed` event. If your workflow has multiple parallel sleeps, `waitForSleep()` returns whichever is found first. After waking one, call `waitForSleep()` again to get the next pending one. For sequential sleeps, `waitForSleep()` naturally returns each one as the workflow reaches it.
258
+ `waitForSleep()` returns the first **pending** sleep, one that has a `wait_created` event but no corresponding `wait_completed` event. If your workflow has multiple parallel sleeps, `waitForSleep()` returns whichever is found first. After waking one, call `waitForSleep()` again to get the next pending one. For sequential sleeps, `waitForSleep()` naturally returns each one as the workflow reaches it.
247
259
  </Callout>
248
260
 
249
- ### Testing Webhooks
261
+ ### Testing webhooks
250
262
 
251
- Webhooks are hooks that receive HTTP `Request` objects. In tests, resume them using [`resumeWebhook()`](/docs/api-reference/workflow-api/resume-webhook) with a `Request` payload — no HTTP server needed:
263
+ Webhooks are hooks that receive HTTP `Request` objects. In tests, resume them using [`resumeWebhook()`](/docs/api-reference/workflow-api/resume-webhook) with a `Request` payload, with no HTTP server needed:
252
264
 
253
265
  ```typescript title="workflows/ingest.ts" lineNumbers
254
266
  import { createWebhook } from "workflow";
@@ -256,7 +268,7 @@ import { createWebhook } from "workflow";
256
268
  export async function ingestWorkflow(endpointId: string) {
257
269
  "use workflow";
258
270
 
259
- // Webhook tokens are always randomly generated
271
+ // Webhook tokens are always generated for you
260
272
  using webhook = createWebhook(); // [!code highlight]
261
273
 
262
274
  const request = await webhook; // [!code highlight]
@@ -282,7 +294,7 @@ describe("ingestWorkflow", () => {
282
294
  it("should process webhook data", async () => {
283
295
  const run = await start(ingestWorkflow, ["ep-1"]);
284
296
 
285
- // Discover the randomly generated webhook token
297
+ // Discover the generated webhook token
286
298
  const hook = await waitForHook(run); // [!code highlight]
287
299
 
288
300
  // Resume the webhook with a Request object
@@ -303,7 +315,73 @@ describe("ingestWorkflow", () => {
303
315
  });
304
316
  ```
305
317
 
306
- ### Manual Setup
318
+ ### Referencing workflows by name
319
+
320
+ Importing the workflow function is the best way to start it: [`start()`](/docs/api-reference/workflow-api/start) keeps its argument and return types. When a test cannot import it, because the workflow lives in a module the test does not pull in or because the test drives runs by name, look it up with [`getWorkflowRef()`](/docs/api-reference/vitest#getworkflowref) instead of hand-writing the generated `workflow//...` id:
321
+
322
+ ```typescript title="workflows/approval.integration.test.ts" lineNumbers
323
+ import { describe, it, expect } from "vitest";
324
+ import { start } from "workflow/api";
325
+ import { getWorkflowRef, listWorkflowRefs } from "@workflow/vitest"; // [!code highlight]
326
+
327
+ describe("approvalWorkflow", () => {
328
+ it("is part of the test build", () => {
329
+ expect(listWorkflowRefs().map((ref) => ref.name)).toContain( // [!code highlight]
330
+ "approvalWorkflow"
331
+ );
332
+ });
333
+
334
+ it("can be started by name", async () => {
335
+ const run = await start(getWorkflowRef("approvalWorkflow"), ["doc-1"]); // [!code highlight]
336
+ expect(run.runId).toMatch(/^wrun_/);
337
+ });
338
+ });
339
+ ```
340
+
341
+ The names come from the manifest the test build writes next to its bundles, so they follow your code when files move. When one exported name appears in several files, qualify it with the file, `getWorkflowRef("workflows/approval.ts#approvalWorkflow")`, which also matches by path suffix. An unknown or ambiguous name throws with the workflows the build does contain.
342
+
343
+ <Callout type="info">
344
+ A reference is matched by name, so the run is typed as `Run<unknown>`. Import the workflow function when you want the argument and return types checked.
345
+ </Callout>
346
+
347
+ ### Mocking
348
+
349
+ Steps do not run from your test file's module graph. They run from the bundles the plugin builds, and workflow bodies run from a code string inside the sandboxed VM, so `vi.mock()` reaches less here than in an ordinary Vitest test:
350
+
351
+ | What you mock | Step code sees it | Workflow body sees it |
352
+ | --- | --- | --- |
353
+ | An npm package a step file imports | Only when the generated bundles load through Vitest's module runner (see below) | No |
354
+ | An npm package imported by a local module that a step file imports | Same as above | No |
355
+ | A project-local module a step file imports | No: it is bundled into the step bundle, so there is no module left to replace | No |
356
+ | A step function imported and called directly, with no `workflow()` plugin | Yes, ordinary Vitest rules | n/a |
357
+
358
+ Workflow bodies execute in a VM that has no module registry, so nothing can intercept their imports. That is the same reason side effects belong in steps: if a dependency needs mocking, it belongs on the step side.
359
+
360
+ Whether step code sees an npm mock depends on how Vitest loaded the plugin. In a normal install `@workflow/vitest` is external to Vitest, Node loads the generated bundle directly, and steps get the real package. Ask for the other behavior explicitly:
361
+
362
+ ```typescript title="vitest.integration.config.ts" lineNumbers
363
+ import { defineConfig } from "vitest/config";
364
+ import { workflow } from "@workflow/vitest";
365
+
366
+ export default defineConfig({
367
+ plugins: [workflow()],
368
+ test: {
369
+ // Route the generated bundles through Vitest's module runner, so vi.mock()
370
+ // applies to the npm packages your steps import.
371
+ server: { deps: { inline: [/@workflow\/vitest/] } }, // [!code highlight]
372
+ },
373
+ });
374
+ ```
375
+
376
+ The cost is that the generated bundle goes through Vite's transform pipeline in every test worker.
377
+
378
+ Three approaches work regardless of how the plugin was loaded:
379
+
380
+ - **Unit test the step directly.** Without the plugin, `"use step"` is a no-op and the function is an ordinary async function, so `vi.mock()` behaves normally.
381
+ - **Pass the dependency in.** A step that takes its collaborator as an argument is controlled by the caller, with no module interception involved.
382
+ - **Feed values through hooks.** Resume a [hook](/docs/foundations/hooks) with the data you want instead of mocking whatever would have produced it.
383
+
384
+ ### Manual setup
307
385
 
308
386
  If you need more control over the test lifecycle, the plugin also exports the individual setup functions:
309
387
 
@@ -354,11 +432,11 @@ afterAll(async () => {
354
432
  For advanced setups that require a running server (e.g. testing against your actual framework's HTTP layer), see [Server-based integration testing](/docs/testing/server-based).
355
433
  </Callout>
356
434
 
357
- ## Debugging Test Runs
435
+ ## Debugging test runs
358
436
 
359
- When integration tests fail, the [Workflow SDK CLI and Web UI](/docs/observability) can help you inspect what happened. Because integration tests persist workflow state locally, you can use the same observability tools you would use in development.
437
+ When integration tests fail, the [Workflow SDK CLI and web UI](/docs/observability) can help you inspect what happened. Because integration tests persist workflow state locally, you can use the same observability tools you use in development.
360
438
 
361
- Launch the Web UI to visually explore your test workflow runs:
439
+ Launch the web UI to explore your test workflow runs:
362
440
 
363
441
  ```bash
364
442
  npx workflow web
@@ -374,7 +452,7 @@ npx workflow inspect runs
374
452
  npx workflow inspect run <run-id>
375
453
  ```
376
454
 
377
- The Web UI shows each step, its inputs and outputs, retry attempts, hook state, and timing. This is especially useful for diagnosing issues with hooks that were not resumed, steps that failed unexpectedly, or workflows that timed out.
455
+ The web UI shows each step, its inputs and outputs, retry attempts, hook state, and timing. Use it to diagnose hooks that were not resumed, steps that failed unexpectedly, or workflows that timed out.
378
456
 
379
457
  ![Workflow SDK Web UI](/o11y-ui.png)
380
458
 
@@ -382,35 +460,39 @@ The Web UI shows each step, its inputs and outputs, retry attempts, hook state,
382
460
  See the [Observability](/docs/observability) docs for the full set of CLI commands and Web UI features.
383
461
  </Callout>
384
462
 
385
- ## Best Practices
463
+ ## Best practices
386
464
 
387
- ### Separate Unit and Integration Tests
465
+ ### Separate unit and integration tests
388
466
 
389
467
  Keep two test configurations:
390
468
 
391
- - **Unit tests** - Standard Vitest config, no workflow plugin. Fast, no infrastructure required.
392
- - **Integration tests** - Vitest config with `workflow()` plugin. Tests the full workflow lifecycle including hooks, sleeps, and retries.
469
+ - **Unit tests**: Standard Vitest config with no workflow plugin. These tests require no infrastructure.
470
+ - **Integration tests**: Vitest config with the `workflow()` plugin. These tests cover the full workflow lifecycle, including hooks, sleeps, and retries.
393
471
 
394
- ### Use Custom Hook Tokens for Deterministic Testing
472
+ ### Use custom hook tokens for deterministic testing
395
473
 
396
- When testing workflows with hooks, use [custom tokens](/docs/foundations/hooks#custom-tokens-for-deterministic-hooks) based on predictable values (like document IDs or test identifiers). This makes it easy to resume the correct hook in your test code.
474
+ When testing workflows with hooks, use [custom tokens](/docs/foundations/hooks#custom-tokens-for-deterministic-hooks) based on predictable values (like document IDs or test identifiers). This lets you resume the correct hook in your test code.
397
475
 
398
- ### Set Appropriate Timeouts
476
+ ### Set appropriate timeouts
399
477
 
400
478
  Workflows may take longer to execute than typical unit tests, especially when they involve multiple steps or retries. Set a generous `testTimeout` in your integration test config.
401
479
 
402
- ### Test Error and Retry Scenarios
480
+ ### Test error and retry scenarios
403
481
 
404
482
  Integration tests are the right place to verify that your workflows handle errors correctly, including retryable errors, fatal errors, and timeout scenarios.
405
483
 
406
- ## Further Reading
484
+ ### Upgrade `@workflow/vitest` with the SDK
485
+
486
+ `@workflow/vitest` carries its own copy of the Workflow runtime, so treat it as part of the same upgrade as `workflow`. While Workflow 5 is in beta, that means the `beta` tag on both. See [Installation](#installation).
487
+
488
+ ## Further reading
407
489
 
408
490
  - [Hooks & Webhooks](/docs/foundations/hooks) - Pausing and resuming workflows with external data
409
491
  - [`start()` API Reference](/docs/api-reference/workflow-api/start) - Start workflows programmatically
410
492
  - [`resumeHook()` API Reference](/docs/api-reference/workflow-api/resume-hook) - Resume hooks with data
411
493
  - [`resumeWebhook()` API Reference](/docs/api-reference/workflow-api/resume-webhook) - Resume webhooks with Request objects
412
494
  - [`getRun()` API Reference](/docs/api-reference/workflow-api/get-run) - Check workflow run status and wake up sleeping runs
413
- - [`@workflow/vitest` API Reference](/docs/api-reference/vitest) - Test helpers: `waitForSleep()`, `waitForHook()`, and plugin setup
495
+ - [`@workflow/vitest` API Reference](/docs/api-reference/vitest) - Test helpers: `waitForSleep()`, `waitForHook()`, `getWorkflowRef()`, and plugin setup
414
496
  - [Vite Integration](/docs/getting-started/vite) - Set up the Vite plugin
415
497
  - [Observability](/docs/observability) - Inspect and debug workflow runs with the CLI and Web UI
416
498
  - [Server-based testing](/docs/testing/server-based) - Integration testing with a running server