Commit Graph

97 Commits

Author SHA1 Message Date
JJ Kasper f5ae600db4 fix(e2e): stabilize 5xx step_completed fault injection (#1046) 2026-02-13 14:03:06 -08:00
Pranay Prakash 8d117cd219 Retry 5xx errors from workflow-server in step handler (#1011)
* Retry 5xx errors from workflow-server in step handler

Add `withServerErrorRetry` helper that retries world calls on 5xx errors
with exponential backoff (500ms, 1s, 2s ≈ 3.5s total). Applied to all
`world.events.create` calls in the step handler so transient
workflow-server errors don't consume step attempts.

If retries are exhausted, the error is thrown to the queue for
higher-level retry without burning a step attempt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Address PR review comments on 5xx retry handling

- Fix misleading `maxAttempts` log field to `maxRetries` in withServerErrorRetry
- Update step-handler comment to accurately note that queue retries may
  still consume step attempts since step_started has already incremented
- Add unit tests for withServerErrorRetry (7 tests covering success,
  retry/backoff, exhaustion, and non-5xx passthrough)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add tests for 429/5xx retry handling

Unit tests for withThrottleRetry and withServerErrorRetry helpers, plus
an e2e test that exercises the 5xx retry codepath during step execution
via run-scoped fault injection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Wrap VQS errors in WorkflowAPIError and add retry to queueMessage

VQS throws its own error types (InternalServerError, ConsumerDiscoveryError,
ConsumerRegistryNotConfiguredError) that don't match WorkflowAPIError.is().
Wrapping them at the world-vercel boundary enables withServerErrorRetry in
queueMessage() to automatically retry transient queue failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update changeset to include @workflow/world-vercel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove queue retry logic per review feedback

Queue retrying will be handled natively by the @vercel/queue client
instead. Reverts VQS error wrapping and withServerErrorRetry in
queueMessage().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:42:36 -08:00
Nathan Rajlich fcfaf8bbaa Support step function serialization in client mode (#924) 2026-02-07 15:34:29 -08:00
Nathan Rajlich 5b5b36a03b [e2e] Remove /api/hook and /api/test-health-check endpoints, call APIs directly
- Remove debug logging from bench.bench.ts
- Remove awaitReturnValue() wrapper, use run.returnValue directly in benchmarks
- Add changeset for Nitro builder manifest fix
- Refactor hookWorkflow tests to call getHookByToken()/resumeHook() directly
  (pass hook object to resumeHook to avoid duplicate lookups)
- Refactor queue-based health check test to call healthCheck() directly
- Assert specific error message for invalid hook token test
- Remove /api/hook and /api/test-health-check endpoints from all workbench apps
  (nextjs-turbopack, nextjs-webpack, vite, hono, express, fastify, sveltekit,
  astro, nuxt, nitro-v2, nitro-v3, nest, example)
2026-02-07 09:00:19 -08:00
JJ Kasper 82c209c669 Add missing env for tests on deploy (#973) 2026-02-06 16:57:11 -08:00
Nathan Rajlich 86f62f2779 Refactor e2e tests to no longer use "trigger" endpoint (#958)
## Summary

Refactors the E2E tests to call `start()` from `workflow/api` directly instead of going through the `/api/trigger` HTTP endpoint in each workbench app. This removes a layer of indirection — the tests now use the same API that users would use to start workflows programmatically.

### Before

```ts
const run = await triggerWorkflow('addTenWorkflow', [123]);
const returnValue = await getWorkflowReturnValue(run.runId);
```

- `triggerWorkflow()` sent an HTTP POST to `/api/trigger` on the workbench app
- The workbench app looked up the workflow function, called `start()`, and returned the run ID
- `getWorkflowReturnValue()` polled `GET /api/trigger?runId=...` until the workflow completed

### After

```ts
const run = await start(await e2e('addTenWorkflow'), [123]);
const returnValue = await run.returnValue;
```

- `e2e()` / `getWorkflowMetadata()` fetches the manifest from `/.well-known/workflow/v1/manifest.json` to look up the correct `workflowId`
- `start()` is called directly from the test process via the configured World
- `run.returnValue` polls for completion via the World (no HTTP polling endpoint needed)

### Changes

**`packages/core/e2e/e2e.test.ts`**
- Removed `triggerWorkflow()` and `getWorkflowReturnValue()` helpers
- Added `fetchManifest()` to fetch and cache the workflow manifest from the deployment
- Added `getWorkflowMetadata(file, fn)` to look up `{ workflowId }` from the manifest
- Added `e2e(fn)` shorthand for the common case of `workflows/99_e2e.ts`
- All tests call `start()` and `run.returnValue` directly
- Error tests use `.catch()` to inspect `WorkflowRunFailedError`
- Output stream tests use `run.getReadable()` directly (skipped on local world where cross-process streaming isn't supported)
- `beforeAll` configures the local World with the correct data directory and base URL
- Pages Router tests use `startWorkflowViaHttp()` to specifically validate the HTTP trigger path

**Workbench apps (hono, express, fastify, nest)**
- Removed `/api/trigger` route handlers
- Kept `/api/hook`, `/api/test-direct-step-call`, `/api/test-health-check` endpoints
- Re-added `_workflows.js` side-effect import for hono/express/fastify to maintain Nitro's HMR dependency graph

**Deleted trigger-only route files** from: nextjs-turbopack, nextjs-webpack, vite, sveltekit, astro, nuxt, nitro-v2, nitro-v3, example

**`.github/workflows/tests.yml`**
- Added `WORKFLOW_PUBLIC_MANIFEST: '1'` to all E2E test jobs

### Dependencies

Stacked on #963 which adds `WORKFLOW_PUBLIC_MANIFEST` support to all framework builders.
2026-02-06 16:25:47 -08:00
Nathan Rajlich 661724c01e Expose workflow manifest via HTTP when WORKFLOW_PUBLIC_MANIFEST=1 (#963)
## Summary

When `WORKFLOW_PUBLIC_MANIFEST=1` is set, each framework builder exposes the workflow manifest at `/.well-known/workflow/v1/manifest.json` via the most appropriate mechanism for the framework:

- **Next.js**: Copies manifest to `public/.well-known/workflow/v1/manifest.json` (served as a static file)
- **SvelteKit**: Copies manifest to `static/.well-known/workflow/v1/manifest.json` (served as a static file)
- **Vercel Build Output API** (example workbench): Copies manifest to `.vercel/output/static/.well-known/workflow/v1/manifest.json` (served as a static file)
- **Nitro** (vite, hono, express, fastify, nuxt, nitro-v2, nitro-v3): Registers a virtual handler that reads and serves the manifest JSON
- **Astro**: Generates a `manifest.json.js` page route that returns the manifest JSON
- **NestJS**: Adds a `@Get('manifest.json')` endpoint on the `WorkflowController` (gated by the env var at runtime)

### Other changes

- `BaseBuilder.createManifest()` now returns the manifest JSON string so framework builders can use it
- Added `shouldExposePublicManifest` getter to `BaseBuilder`
- Fixed Astro `LocalBuilder` which was missing the `createManifest()` call that all other framework builders have
- Removed unused `public/` directory and static file copy from the example workbench build script
- Added `WORKFLOW_PUBLIC_MANIFEST` to `turbo.json` build task env so Vercel builds can access it
- Added generated manifest paths to `.gitignore`
2026-02-06 12:22:37 -08:00
Nathan Rajlich 2453b29426 Make wf build --manifest-file include steps / classes metadata (#931) 2026-02-04 09:22:11 -08:00
Pranay Prakash 6208616d06 Add sequential step benchmarks and fix broken benchmark infrastructure (#845)
* Add 50, 100, 500 concurrent step benchmarks

Enable Promise.all and Promise.race benchmarks for 50, 100, and 500
concurrent steps (previously 100+ were skipped).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add 50, 100, 500 sequential step benchmarks

Extends the sequential step benchmarks to test workflows with 50, 100,
and 500 sequential steps in addition to the existing 10 step test.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add full/quick benchmark suite toggle for CI

- Add BENCHMARK_FULL_SUITE env var to control which benchmarks run
- Quick suite (default for PRs): 10, 25, 50 step benchmarks
- Full suite (main branch, manual dispatch): adds 100, 500 step benchmarks
- Add workflow_dispatch input to manually trigger full suite from GitHub UI
- Skip 100+ sequential and concurrent step benchmarks by default

This keeps PR benchmarks fast while allowing full stress testing on demand.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add 25 sequential steps benchmark

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix benchmark API calls to use binary format

PR #853 changed the workflow trigger API to expect binary data
(application/octet-stream) instead of JSON. The e2e tests were updated
but the benchmark file was missed, causing all benchmarks to fail
silently since Jan 28.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Only run full benchmark suite on manual dispatch

Remove automatic full suite on main branch pushes - only run full suite
when manually triggered with full_suite=true.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 18:02:36 -08:00
Nathan Rajlich c1d7c8dbb4 Add support for "use step" functions in class instance methods (#777)
Added support for `"use step"` directive in class instance methods, allowing instance methods to be used as workflow steps.

### What changed?

- Modified the SWC plugin to recognize and transform instance methods with the "use step" directive
- Added registration logic for instance method steps using `ClassName.prototype.methodName`
- Implemented proper serialization of class instances to preserve the `this` context across workflow/step boundaries
- Added comprehensive end-to-end tests for instance method steps
- Updated error handling to allow "use step" in instance methods while still preventing "use workflow" in instance methods

### How to test?

The PR includes a new end-to-end test `instanceMethodStepWorkflow` that demonstrates the functionality:

1. Run the e2e tests to verify the new instance method step functionality
2. The test creates a `Counter` class with instance methods marked as steps
3. It verifies that the instance methods can be called as steps with proper serialization of the `this` context
4. It also verifies that multiple instances of the same class can be used independently

### Why make this change?

This change enables a more natural object-oriented programming model when working with workflows. Previously, only static methods, standalone functions, and object methods could be marked as steps. Now, developers can create classes with instance methods that are steps, allowing for better encapsulation and more intuitive code organization. This is particularly useful for complex workflows that need to maintain state across multiple step invocations.
2026-02-03 00:11:38 -08:00
Nathan Rajlich b5296a7a32 Add discovered serializable classes in all context modes (#874)
This PR ensures that all classes with custom serialization are automatically included in all bundle contexts (step, workflow, client) to ensure proper serialization/deserialization when crossing execution boundaries:

- Classes defined in any context can now be properly serialized when passing data between:
  - Client → Workflow (when starting workflows)
  - Workflow → Step (when calling steps)
  - Step → Workflow (when returning step results)
  - Workflow → Client (when returning workflow results)

- The build system now automatically discovers all files containing serializable classes and includes them in each bundle, regardless of where the class is originally defined.

- No manual configuration is required - cross-registration happens automatically during the build process.
2026-02-02 23:26:29 -08:00
Nathan Rajlich 1060f9d04a Change user input/output to be binary data at the World interface (#853) 2026-01-28 10:36:28 -08:00
Nathan Rajlich f2ab6ee179 Fix Nest workbench app build (#865)
* Use proper OpenAI import

```
Error: ../example/workflows/5_hooks.ts(36,22): error TS2351: This expression is not constructable.
  Type 'typeof import("/vercel/path0/node_modules/.pnpm/openai@6.1.0_ws@8.18.3_zod@4.1.11/node_modules/openai/index")' has no construct signatures.
```

* .
2026-01-27 00:21:33 -08:00
Pranay Prakash 4966b728a8 implement event-sourced architecture (#621)
* perf: implement event-sourced architecture

* Apply suggestions from code review

* Improve invalid event log handling in step/hook/wait

* Handle serialized workflow run errors correctly

* log error in failing test

* Handle queue idempotency in vercel world

* hotfix for error propogation

* Fix: Incorrect HTTP status code 409 should be 410 for terminal run state rejections in postgres storage

* Fix: The code attempts to pass an unsupported `fatal` property when creating a `step_failed` event. The TypeScript schema for `step_failed` events only allows `error` and `stack` properties, so the `fatal` property causes a compilation error.

This commit fixes the issue reported at packages/core/src/runtime/step-handler.ts:133-139

## TypeScript error: Invalid property 'fatal' in step_failed event

**What fails:** TypeScript compilation fails in `packages/core` due to an invalid property in the `step_failed` event creation.

**How to reproduce:**
```bash
cd /vercel/sandbox/primary
pnpm run -F @workflow/core build
```

**Result:**
```
src/runtime/step-handler.ts(133,32): error TS2769: No overload matches this call.
  Overload 1 of 2, '(runId: null, data: { eventType: "run_created"; ... }, gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'null'.
  Overload 2 of 2, '(runId: string, data: CreateEventRequest, params?: CreateEventParams | undefined): Promise<EventResult>', gave the following error.
    Object literal may only specify known properties, and 'fatal' does not exist in type '{ error: any; stack?: string | undefined; }'.
```

**Issue:** The code attempted to pass a `fatal: true` property in the `eventData` object when creating a `step_failed` event. However, the event schema defined in `packages/world/src/events.ts` for `StepFailedEventSchema` only allows `error` and `stack` properties - the `fatal` property is not part of the schema.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>

* Fix: Code silently skips updating workflowRun if result.run is undefined, causing workflows to be incorrectly skipped instead of throwing an error

* Add hook_conflict event type for duplicate token detection

Implements hook_conflict events across all world implementations to handle
cases where a workflow attempts to use a hook token already claimed by another
workflow. Instead of throwing errors, the system now records hook_conflict
events in the event log, enabling deterministic replay.

- Add HookConflictEvent schema to @workflow/world
- Implement hook_conflict in world-local, world-postgres, and suspension-handler
- Update hook consumer to reject promises with WorkflowRuntimeError on conflict
- Add HOOK_CONFLICT error slug with documentation
- Add e2e and unit tests for conflict scenarios

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add changeset for hook_conflict events

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add unit tests for hook_conflict handling

- Add tests for hook_conflict event in workflow.test.ts
- Fix world-postgres test to not expect removed message field

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Improve hook-conflict.mdx error guide

- Remove redundant third point in 'Why This Happens' section
- Add example showing how to handle WorkflowRuntimeError for hook conflicts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix docs validation: add hook-conflict to errors index

- Fix broken link in hook-conflict.mdx (/docs/foundations/webhooks -> /docs/api-reference/workflow/create-webhook)
- Add hook-conflict to errors index page so it's discoverable by the docs link validator

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix world-local tests for hook_conflict event behavior

Update tests to expect hook_conflict events instead of thrown errors when
duplicate hook tokens are used. This aligns with the new event-sourced
approach where conflicts are recorded as events rather than thrown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add specVersion property to World interface for backwards compatibility

- Add specVersion property to World interface to track world package version
- Add specVersion to WorkflowRun schema and run_created event data
- World implementations (vercel, local, postgres) set specVersion from npm version
- Server can use specVersion to route operations based on world version
- Add specVersion display to observability UI attribute panel
- Add spec_version column to postgres runs schema

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add migration for spec_version column in postgres schema

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add drizzle migration journal and snapshot for spec_version column

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Regenerate postgres migration using drizzle-kit

- Properly generates migration with drizzle-kit CLI
- Removes deprecated 'paused' status from enum
- Adds spec_version column

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add backwards compatibility for event-sourced runs

- Add RunNotSupportedError for runs requiring newer world versions
- Add semver-based version utilities (isLegacyVersion) to @workflow/world
- World implementations check specVersion and route to legacy handlers
- Legacy runs (< 4.1.0): run_cancelled skips event storage, wait_completed stores event only
- New runs always get current world version (4.1.0-beta.0)
- Make EventResult.event optional for legacy compatibility

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Refactor spec version from semver strings to integers

Replace semver-based version compatibility with explicit integer spec versions:
- SPEC_VERSION_LEGACY (1): pre-event-sourcing runs
- SPEC_VERSION_CURRENT (2): event-sourced architecture

Use branded SpecVersion type to enforce importing from @workflow/world.
Remove semver dependency from world, world-local, and world-postgres.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Store error as CBOR in postgres world for consistency with input/output

- Add error_cbor bytea columns to workflow_runs and workflow_steps tables
- Deprecate text error column, rename to errorJson with fallback parsing
- Remove JSON.stringify from error writes (run_failed, step_failed, step_retrying)
- Add parseErrorJson helper for backwards compatibility with legacy data

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use WorkflowRuntimeError and improve run entity handling in core runtime

- Replace generic Error with WorkflowRuntimeError for runtime assertions
- Add explicit check for run entity in run_created response
- Use run.runId instead of event.runId for consistency
- Use actual run status instead of hardcoded 'pending' in attributes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add specVersion to Step, Hook, and Event entities

- Add specVersion field to Step, Hook, and Event interfaces in @workflow/world
- Add spec_version column to steps, hooks, events tables in postgres schema
- Set specVersion to SPEC_VERSION_CURRENT when creating entities in all worlds
- Update migration to include spec_version columns for all entity tables

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Refactor world-local storage into modular files

Split storage.ts (1041 lines) into smaller, focused modules:
- storage/filters.ts: Data filtering helpers
- storage/helpers.ts: ULID and date utilities
- storage/hooks-storage.ts: Hook CRUD operations
- storage/legacy.ts: Legacy event handling
- storage/runs-storage.ts: Run get/list operations
- storage/steps-storage.ts: Step get/list operations
- storage/events-storage.ts: Event create/list operations
- storage/index.ts: Main composition

Also extracted test helpers to test-helpers.ts for reusability.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove genversion and World.specVersion property

The World.specVersion string property was never actually read - only
the numeric SPEC_VERSION_CURRENT is used for backwards compatibility.

- Remove genversion dependency and generated version.ts from @workflow/world
- Remove specVersion property from World interface and all implementations
- Minor fix: correct error message to reference 'workflow' package
- Minor fix: correct error source priority in world-vercel events.ts
- Minor fix: update comment in runtime.ts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove genversion from world-local, world-postgres, and world-vercel

These packages no longer need genversion since we removed the
World.specVersion property in the previous commit.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove version.ts from .gitignore files

No longer needed after removing genversion.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add legacy/backwards compatibility tests

Tests for world-local and world-postgres covering:
- Legacy runs (specVersion < 2 or null/undefined)
  - run_cancelled handling (updates run, no event stored)
  - wait_completed handling (stores event only)
  - Rejection of unsupported events
  - Hook cleanup on cancellation
- Future runs (specVersion > current)
  - Rejection with RunNotSupportedError
- Current version runs (normal processing)
- Legacy error parsing (errorJson field parsing)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add hook_received support for legacy runs

When resumeHook() is called on a legacy run (specVersion < 2), the
hook_received event was previously rejected. This adds support for
storing hook_received events on legacy runs without entity mutation,
matching the behavior of wait_completed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix missing genversion in world-vercel

Signed-off-by: Peter Wielander <mittgfu@gmail.com>

* Remove deprecated workflow_completed, workflow_failed, and workflow_started events

Replace with run_completed, run_failed, and run_started equivalents.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add specVersion to EventWithRefsSchema in world-vercel

The manually-created EventWithRefsSchema was missing the specVersion field,
which caused specVersion to be stripped when using lazy (refs) mode for events.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Wire specVersion from client through world backends

- Core runtime now sends specVersion in run_created eventData
- world-local accepts specVersion from eventData (defaults to current)
- world-postgres accepts specVersion from eventData (defaults to current)

This matches workflow-server behavior where v2 endpoints accept
specVersion from the client, while v1 endpoints default to legacy.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Move specVersion to event object level, propagate to entities

- Add specVersion to BaseEventSchema (event level, not eventData)
- Remove specVersion from RunCreatedEventSchema.eventData
- Core runtime sends specVersion on event object
- world-local reads specVersion from event, propagates to run/step/hook entities
- world-postgres reads specVersion from event, propagates to run/step/hook entities

This ensures specVersion flows from client through event to all created entities.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update specVersion to be optional in types for backwards compatibility

- specVersion is optional in all entity schemas (runs, steps, hooks, events)
  for backwards compatibility with legacy data in storage
- Runtime always sends specVersion on event requests
- world-local and world-postgres provide fallback to SPEC_VERSION_CURRENT
- Test helpers include specVersion in all event creation calls
- EventWithRefsSchema in world-vercel defaults specVersion to 1 for legacy

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix world-vercel queue tests missing VERCEL_DEPLOYMENT_ID setup

Two tests were calling queue.queue() without setting up
VERCEL_DEPLOYMENT_ID, causing them to fail with "No deploymentId
provided" error before reaching the code they were testing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add specVersion to all event creation calls in core package

The server's CreateEventSchemaV2 requires specVersion on all events,
but only run_created was sending it. This caused 400 Bad Request errors
for all other event types (run_started, run_completed, run_failed,
run_cancelled, step_created, step_started, step_completed, step_failed,
step_retrying, hook_created, hook_received, wait_created, wait_completed).

Now all event creation calls include specVersion: SPEC_VERSION_CURRENT.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Signed-off-by: Peter Wielander <mittgfu@gmail.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Peter Wielander <mittgfu@gmail.com>
2026-01-22 17:24:52 -08:00
Michael Han 0b5cc48140 fix(builders): manifest missing workflow-only files (no steps), add tests (#831)
* Fix manifest missing workflow-only files (no steps), add tests

Signed-off-by: voyager14 <21mh124@queensu.ca>

* Update packages/builders/src/base-builder.ts

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Signed-off-by: Michael Han <21mh124@queensu.ca>

---------

Signed-off-by: voyager14 <21mh124@queensu.ca>
Signed-off-by: Michael Han <21mh124@queensu.ca>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
2026-01-22 17:22:14 -08:00
Nathan Rajlich 1843704b83 Add support for custom class instance serialization (#762)
Added support for custom class instance serialization across workflow/step boundaries.

### What changed?

- Introduced a new `@workflow/serde` package with `WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE` symbols
- Enhanced the serialization system to handle custom class instances using these symbols
- Updated the SWC plugin to detect classes with serialization methods and register them
- Added class registry mechanism that works in both step and workflow contexts
- Implemented comprehensive tests for various serialization scenarios

### How to test?

The PR includes a new e2e test `customSerializationWorkflow` that demonstrates the feature:

```typescript
import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';

// Define a class with custom serialization
class Point {
  constructor(public x: number, public y: number) {}

  static [WORKFLOW_SERIALIZE](instance: Point) {
    return { x: instance.x, y: instance.y };
  }

  static [WORKFLOW_DESERIALIZE](data: { x: number; y: number }) {
    return new Point(data.x, data.y);
  }
}

// Use in workflow and steps
export async function customSerializationWorkflow(x: number, y: number) {
  'use workflow';
  const point = new Point(x, y);
  const scaled = await transformPoint(point, 2);
  // ...
}
```

Run the e2e test to verify that class instances are properly serialized and deserialized.

### Why make this change?

Previously, user-defined class instances couldn't be passed between workflows and steps without losing their prototype chain and methods. This change allows developers to define custom serialization/deserialization logic for their classes, enabling proper reconstruction of instances with their full functionality intact when crossing workflow/step boundaries.
2026-01-19 15:38:19 -08:00
Nathan Rajlich 7906429541 Add support for serializing this when invoking step functions (#754)
Added support for serializing `this` context when invoking step functions.

### What changed?

- Modified the step function implementation to capture and serialize the `this` context when it's defined and not the global object
- Updated the step invocation queue item interface to include an optional `thisVal` property
- Enhanced the step handler to apply the hydrated `thisVal` when executing step functions

### Why make this change?

This enhancement allows step functions to be invoked with an explicit context object using standard JavaScript methods like `.call()` and `.apply()`. This is particularly useful for step functions that need to access properties from a specific context, enabling more flexible and idiomatic JavaScript patterns within workflows.
2026-01-14 00:07:29 -08:00
Nathan Rajlich a2fc53a0dc Support class static methods with "use step" / "use workflow" (#753)
The SWC compiler plugin had logic to walk through class static methods
with "use step" / "use workflow", but no actual transformation was being
applied. This fixes that.
2026-01-13 23:52:26 -08:00
Nathan Rajlich 61fdb41e1b Add queue-based health check (#743)
* feat: add queue-based health check to bypass Deployment Protection

- Add HealthCheckPayloadSchema and HEALTH_CHECK_STREAM_PREFIX to @workflow/world
- Add healthCheck() method to Queue interface
- Update workflow and step handlers to detect and respond to health check messages
- Implement healthCheck() in world-local, world-vercel, and world-postgres

The queue-based health check sends a message through the queue pipeline,
which bypasses Vercel's Deployment Protection. The handler writes a response
to a stream that the caller reads to confirm health.

This complements the existing HTTP-based ?__health approach which still works
for local development and when bypass headers are available.

* refactor: move healthCheck to core package as utility function

Instead of adding healthCheck to the World interface (which duplicated
the same implementation across all worlds), this is now a utility function
in @workflow/core that takes the World as a parameter.

Usage:
  import { healthCheck } from '@workflow/core';
  const result = await healthCheck(world, 'workflow');

This is cleaner because:
- Single implementation instead of 3 identical ones
- World implementations remain simple
- No changes needed to the World interface

* .

* refactor: move health check types from world to core

Health check types (HealthCheckPayloadSchema, HealthCheckResult, etc.)
are now defined in @workflow/core since that's where they're used.

The HealthCheckPayloadSchema is still part of QueuePayloadSchema in
world (so the queue accepts health check messages), but it's not
exported from the public API.

* .

* Refactor health check implementation based on code review feedback (#746)

* Initial plan

* Address PR review comments: export types, fix race condition, improve error handling

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Add queue-based health check test and document security considerations

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Replace 'any' type with proper type guards for health check response

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Extract health check queue names as constants and improve type guards

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* .

* Fix e2e test

* .

* .

* .

* fix(ai): preserve providerMetadata as providerOptions in multi-turn tool calls (#733)

When tool calls are added to the conversation history, map providerMetadata
to providerOptions following the AI SDK convention. This fixes Gemini thinking
models that require thoughtSignature to be preserved across multi-turn tool calls,
preventing the error 'function call is missing a thought_signature'.

Fixes #727

* Local ui cli flag (#744)

* [web] Increase contrast on attribute items in sidebar (#736)

Signed-off-by: Peter Wielander <mittgfu@gmail.com>

* [world] Remove pause and resume events, actions and states (#751)

* Version Packages (beta) (#735)

* .

* .

* Update turbo inputs to include shared config (#752)

* Update turbo inputs to include shared config

* Apply suggestions from code review

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

* feat(web): add self-hosted mode for world configuration (#747)

* feat(web): add self-hosted mode for world configuration

When WORKFLOW_TARGET_WORLD env var is set, the web UI operates in
self-hosted mode where the world configuration is locked to server-side
environment variables and cannot be changed via query params or UI.

- Add getHardcodedConfig server action to detect self-hosted mode
- Modify getWorldFromEnv to use server env vars in hardcoded mode
- Create WorldConfigContext to provide config state app-wide
- Update settings sidebar to show locked state with disabled inputs
- Update connection status to show PostgreSQL backend info
- Mask sensitive values (postgres URL) in hardcoded mode UI

* fix: address PR review feedback

- Remove unused ConfigMode type export
- Fix postgres substring to undefined (tooltip has details)
- Extract buildEnvMapFromProcessEnv helper to reduce duplication
- Remove unused EnvMap import from layout-client
- Import HardcodedConfig from web-shared/server instead of re-defining

* Fix: PostgreSQL URL parameter missing from configParsers, causing loss of postgres URL configuration on page reload in dynamic mode

* fix(cli): clear WORKFLOW_TARGET_WORLD when spawning web server

The CLI sets WORKFLOW_TARGET_WORLD as an env var, which the spawned
Next.js server inherits. This caused the web UI to enter self-hosted
mode even when launched via CLI.

Now we explicitly clear WORKFLOW_TARGET_WORLD from the server's
environment so it starts in dynamic mode where config comes from
query params as intended.

* refactor(web): use server-side env vars for world config

BREAKING CHANGE: The web UI no longer supports configuring the world
backend via URL query parameters. Configuration is now read exclusively
from server-side environment variables.

Changes:
- Remove query param parsing from @workflow/web config.ts
- Add ServerConfig interface with non-sensitive display info
- Update all components to use useServerConfig() hook
- Settings sidebar is now read-only
- CLI passes env vars to spawned web server instead of query params
- Server actions use process.env directly (envMap param reserved for future use)

This simplifies the architecture and improves security by never sending
sensitive data (connection strings, auth tokens) to the client.

* fix(web): fix settings sidebar overflow and shorten data dir path

- Add truncate/overflow handling to settings sidebar config values
- Add shortenPath() helper to abbreviate long file paths:
  - Replaces home directory with ~
  - Shows .../last-two-segments if still too long
- Add title attributes for full path on hover

* Update changeest

---------

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>

* Version Packages (beta) (#755)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update packages/world/src/queue.ts

Co-authored-by: Pranay Prakash <pranay.gp@gmail.com>

* [web] Tidy wake-up and re-enqueue buttons (#737)


---------

Signed-off-by: Peter Wielander <mittgfu@gmail.com>

* [cli] Use dotenv to resolve .env and .env.local files on startup (#765)

* Use temporary workflow-server deployment URL

* feat: add queue-based health check to bypass Deployment Protection

- Add HealthCheckPayloadSchema and HEALTH_CHECK_STREAM_PREFIX to @workflow/world
- Add healthCheck() method to Queue interface
- Update workflow and step handlers to detect and respond to health check messages
- Implement healthCheck() in world-local, world-vercel, and world-postgres

The queue-based health check sends a message through the queue pipeline,
which bypasses Vercel's Deployment Protection. The handler writes a response
to a stream that the caller reads to confirm health.

This complements the existing HTTP-based ?__health approach which still works
for local development and when bypass headers are available.

* refactor: move healthCheck to core package as utility function

Instead of adding healthCheck to the World interface (which duplicated
the same implementation across all worlds), this is now a utility function
in @workflow/core that takes the World as a parameter.

Usage:
  import { healthCheck } from '@workflow/core';
  const result = await healthCheck(world, 'workflow');

This is cleaner because:
- Single implementation instead of 3 identical ones
- World implementations remain simple
- No changes needed to the World interface

* .

* refactor: move health check types from world to core

Health check types (HealthCheckPayloadSchema, HealthCheckResult, etc.)
are now defined in @workflow/core since that's where they're used.

The HealthCheckPayloadSchema is still part of QueuePayloadSchema in
world (so the queue accepts health check messages), but it's not
exported from the public API.

* .

* Refactor health check implementation based on code review feedback (#746)

* Initial plan

* Address PR review comments: export types, fix race condition, improve error handling

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Add queue-based health check test and document security considerations

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Replace 'any' type with proper type guards for health check response

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* Extract health check queue names as constants and improve type guards

Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>

* .

* Fix e2e test

* .

* .

* .

* .

* .

* Update packages/world/src/queue.ts

Co-authored-by: Pranay Prakash <pranay.gp@gmail.com>

* Use temporary workflow-server deployment URL

* .

* .

---------

Signed-off-by: Peter Wielander <mittgfu@gmail.com>
Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Co-authored-by: TooTallNate <71256+TooTallNate@users.noreply.github.com>
Co-authored-by: Pranay Prakash <pranay.gp@gmail.com>
Co-authored-by: Peter Wielander <mittgfu@gmail.com>
Co-authored-by: Vercel Release Bot <88769842+vercel-release-bot@users.noreply.github.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-12 14:57:10 -08:00
Pranay Prakash 4d6f797274 Fix step stack trace propogation and refactor e2e error tests (#720)
* Refactor e2e tests for errors

* Improve step error tests to check workflow return value

Step error workflows now catch the error and return message/stack,
making assertions cleaner. Tests verify both:
- Workflow return value (caught error message)
- CLI step result (original stack with function names)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add assertion for stack trace in caught step error

With the fix in step.ts that propagates original stack traces,
we can now verify that caught step errors include function names
directly in the workflow return value (not just via CLI).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* logging

* Fix: When a step handler is re-invoked after max retries are exhausted, the step_failed event doesn't include a stack trace, breaking stack trace propagation for this edge case.

This commit fixes the issue reported at packages/core/src/runtime/step-handler.ts:127-146

## Stack trace loss in step_failed event when max retries are exceeded

**What fails:** Step handler does not include stack property in step_failed event when step is re-invoked after max retries exhausted, causing FatalError in workflow to lose original stack trace

**How to reproduce:**
1. Create a step that always fails with an error that includes a stack trace
2. Exhaust all retry attempts (e.g., maxRetries = 3, so 4 total attempts)
3. The step handler is re-invoked (attempt > maxRetries + 1)
4. This triggers the edge case at lines 127-146 in step-handler.ts
5. A step_failed event is created with fatal: true but without stack property
6. When step.ts processes this event (lines 103-104), the stack remains unset since event.eventData.stack is undefined

**Result:** FatalError created in workflow has default stack (from step.ts) instead of original error stack from step execution

**Expected:** Stack trace should be propagated consistently across all error paths. All other step_failed events with fatal: true include stack property (lines 311-313 and 351-353), but edge case was missing it.

**Root cause:** When step handler is re-invoked after max retries exhausted (attempt > maxRetries + 1), the code creates a step_failed event without including step.error?.stack, which contains the previous error information from the last failed attempt. Other code paths capture this correctly.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>

* add withData

* Enable source maps for step bundles and validate in e2e tests

- Move sourcemap generation from intermediate workflow bundle to steps bundle
- Enhance step error tests to validate function names and source files in stack traces
- Remove isLocalDeployment() checks since source maps now work in dev mode

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add changeset for step bundle source maps

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add changeset for core package e2e test improvements

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Enable source maps in CI e2e tests

Add NODE_OPTIONS="--enable-source-maps" to all e2e test jobs to ensure
stack traces show original source file paths.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix step error source map checks for local prod builds

Add hasStepSourceMaps() helper that correctly identifies when source maps
are expected to work:
- Vercel prod: works (production builds have proper source maps)
- Local dev: works (DEV_TEST_CONFIG is set, uses step bundle with inline source maps)
- Local prod: doesn't work (nitro/bundler output doesn't preserve source maps)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add hasWorkflowSourceMaps() utility for vite-based framework exception

- Add isViteBasedFramework() helper to detect vite, sveltekit, astro apps
- Add hasWorkflowSourceMaps() to check if workflow errors have source maps
  (known issue: vite-based frameworks in local deployments don't preserve them)
- Refactor e2e.test.ts to use the new utility instead of inline check

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* prevent sourcemap checks in nextjs and sveltekit (known offenders)

* improve source maps matrix check

* fix matrix again

* ugh more matrix ignoring

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-01-05 14:12:24 -08:00
Pranay Prakash fdc1aa203c Revert "Refactor e2e tests for errors"
This reverts commit 1bab22cd2a.
2026-01-02 19:48:03 -08:00
Pranay Prakash 1bab22cd2a Refactor e2e tests for errors 2026-01-02 19:35:05 -08:00
Nathan Rajlich 7ff68d1753 Pass tsconfig to esbuild for support of "paths" aliases (#705) 2025-12-31 01:00:24 -08:00
Nathan Rajlich 9b1640d76e Do not include initial attempt in step function maxRetries count (#703)
Closes #592.
2025-12-31 00:59:50 -08:00
Karthik Kalyanaraman e3f0390469 Workflows graph extractor (#455)
---------

Signed-off-by: Karthik Kalyanaraman <karthik@scale3labs.com>
2025-12-27 16:52:19 +01:00
Pranay Prakash ee4fff6814 benchmarking: make steps simulate real work (+ misc improvements) (#565)
* perf: add 5s delay to benchmark steps to simulate real work

* perf: add realistic workloads to benchmark steps

Add realistic workloads to benchmark step functions:
- doWork() - 1 second delay to simulate real computation
- stressTestStep() - 1 second delay to simulate real computation
- genBenchStream() - generates ~5KB of data in 50 chunks
- transformStream() - uppercases stream content (renamed from doubleNumbers)

Add "Slurp Time" metric to stream benchmarks measuring time from
first byte to complete stream consumption, complementing TTFB.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(e2e): increase dev test timeouts for Windows

Windows file watching and rebuilding is slower than macOS/Linux,
causing the 10s timeouts to fail. Increased to 30s to accommodate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(ci): treat community world failures as warnings, not errors

Community world tests/benchmarks are now non-blocking:
- Removed from has_failures check in both tests.yml and benchmarks.yml
- Added separate has_warnings output for community failures
- Split PR comment notices: ❌ for failures, ⚠️ for community warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: apply PR review suggestions

- Fix chunk size calculation: chunkSize - 11 for ~100 bytes per chunk
- Remove redundant metadata check (always truthy)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-06 19:27:02 -08:00
Pranay Prakash 48b3a12fd0 Add stress test benchmarks for large concurrent step counts (#539)
Add new benchmark workflows to reproduce reported issues with Promise.race
and Promise.all falling over when array sizes exceed a few hundred.

New workflows:
- promiseAllStressTestWorkflow(count) - Tests Promise.all with many concurrent steps
- promiseRaceStressTestLargeWorkflow(count) - Tests Promise.race with Map pattern

New benchmarks at 100, 500, and 1000 concurrent step scales for both
Promise.all and Promise.race patterns.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 14:20:00 -08:00
Nathan Rajlich e339a2bc77 Add e2e test for spawning child workflows (#475) 2025-12-02 00:30:25 -08:00
Pranay Prakash 6e8e828252 Add stream benchmarks and slightly improve the benchmarking code (#470)
* Add stream benchmarks and cnealup for benchmark code

* 10m delay for local world race

* potential fix for first bute"

* Improve sticky comment stuff

* local world: ignore controller close errors

* show missing data in benchmark comment

* nitrpicks

* Improve leaderboard

* Add benchmark comparisons against main

* changeset
2025-11-30 23:49:37 -08:00
Pranay Prakash a8f48c5a08 add benchmarking (#460) 2025-11-29 21:21:49 -08:00
Pranay Prakash 3aee6d7efb Port Peter's Workbench UI to nextjs-turbopack (#458)
* Port Peter's Workspace UI

* Add symlinks for webpack workbench to share UI with turbopack

- Add symlinks for components, hooks, lib directories
- Add symlinks for app/workflows and app/api/workflows
- Install UI dependencies in webpack workbench package.json
- Both webpack and turbopack workbenches now share the same UI code

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Use allWorkflows from @/_workflows instead of custom examples.ts

- Update workflow definitions to include workflowFile field
- Change start route to use allWorkflows like trigger route
- Remove unused examples.ts file
- This allows accessing workflows from any workflow file, not just 99_e2e

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Dynamically generate workflow definitions from allWorkflows

- Remove manual workflow definitions, now auto-generated from _workflows.ts
- Add workflowFile path display in UI (tooltip and fallback description)
- Sort workflows by file name first, then by workflow name
- Fix duplicate key issue by using workflowFile:name as key
- Make description optional since it's inferred from file path

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add default arguments map for workflows that require parameters

- Create DEFAULT_ARGS_MAP to provide sensible defaults for workflows with parameters
- Includes defaults for: addTenWorkflow, hookWorkflow, webhookWorkflow, hookCleanupTestWorkflow, closureVariableWorkflow
- Workflows without entries in the map get empty args array

This allows all workflows to be started from the UI without needing manual argument input for now.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix terminal log colors for better visibility on black background

- Change info logs from text-primary (black in light mode) to text-cyan-400
- Change error logs from text-destructive to text-red-400
- Update stream logs to text-blue-400
- Update result logs to text-green-400
- Change prefix color from text-gray-500 to text-gray-400

All colors now work properly with the terminal's black background regardless of light/dark mode.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove toTitleCase transformation, use raw workflow names

- Display workflow names exactly as they are in code (e.g., "addTenWorkflow")
- Remove the toTitleCase helper function
- Simpler and more direct mapping from code to UI

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Use monospace font for workflow names

- Apply font-mono to workflow displayName in both card and tooltip
- Makes workflow names more readable and consistent with code style

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Filter out step functions using workflowId property

- Check for 'workflowId' property added by compiler to identify workflow functions
- More reliable than checking function name endings
- Only functions with "use workflow" directive have workflowId property
- Prevents step functions from appearing in the UI

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add symlinks for remaining workflow files and dependencies

- Add symlinks for 2_control_flow.ts, 4_ai.ts, 5_hooks.ts to both workbenches
- Install openai and mixpart dependencies needed by these workflows
- Update DEFAULT_ARGS_MAP with arguments for new workflows:
  - ai: sample weather prompt
  - agent: sample weather prompt for Muscat
  - handleUserSignup: example email address
- All 9 workflow files now available in both workbenches

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Group workflows by file with section headers in UI

- Group workflows by workflowFile and render each group separately
- Add section headers showing the file path for each group
- Use monospace font for file path headers
- Increase spacing between sections (space-y-4)
- Improves visual organization when browsing workflows

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Show default arguments instead of file path in workflow cards

- Display default arguments in the card description line (if present)
- Remove redundant file path since it's now shown in section headers
- Use monospace font for argument display
- Workflows without arguments show no description line

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Display default arguments with multi-line formatting

- Use JSON.stringify with indentation (null, 2) for better readability
- Change from <p> to <pre> with whitespace-pre-wrap
- Arguments now display across multiple lines when needed
- Easier to read complex arguments like webhook tokens

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add workflow runtime duration display with millisecond precision

- Add formatDuration helper to calculate and format runtime
- Show duration in ms, seconds, or minutes based on length
- Formats: "123ms", "5.234s", "2m 15.678s"
- Display duration in monospace font below end time
- Only shown when invocation has completed (endTime exists)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Update default arguments to match e2e test values

- Use arguments from packages/core/e2e/e2e.test.ts for accuracy
- addTenWorkflow: 123 (instead of 5) to match test expectations
- closureVariableWorkflow: 7 (instead of 42) to match test expectations
- Use Math.random().toString(36) for hook/webhook tokens (matches test pattern)
- Add comment referencing e2e test source

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-28 21:43:27 -08:00
Nathan Rajlich 07800c29ee Support closure variables for serialized step functions (#366) 2025-11-25 00:29:15 -08:00
Nathan Rajlich fb9fd0f893 Add support for closure scope vars in step functions (#358)
### What changed?

- Enhanced the SWC plugin to detect and collect closure variables from nested step functions
- Modified the workflow runtime to pass closure variables to step functions during execution
- Updated the serialization/deserialization logic to handle the new closure variable format
- Added a mechanism to access closure variables within step functions
- Added tests to verify closure variable functionality in nested step functions
- Closure variables are stored on the step function execution's `AsyncLocalStorage`​ context

### Example

```typescript
export async function myWorkflow(baseValue: number) {
  'use workflow';
  const multiplier = 3;
  const prefix = 'Result: ';

  const calculate = async () => {
    'use step';
    const result = baseValue * multiplier;
    return `${prefix}${result}`;
  };

  return await calculate();
}
```

### Why make this change?

Previously, nested step functions couldn't access variables from their parent workflow scope, limiting their usefulness and requiring workarounds like passing all needed values as parameters. This change enables a more natural programming model where step functions can access variables from their enclosing scope, making workflow code more intuitive and reducing the need for explicit parameter passing.
2025-11-25 00:21:05 -08:00
Gal Schlezinger 10ce313d56 postgres: fix tests (#394)
* postgres: use non-deprecated drizzle signatures

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* postgres: store metadata in the hook

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* core: do not rely on module cache for world config. instead, use a global and a symbol.

this makes sure that streamers can use in-memory event emitters and that it won't be compiled away into the different flow.js and step.js files.

this was figured out when i was adding a hooks tests to world-testing.

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* add postgres world to all workbench packages

we try to run them with the postgres world but it's not installed

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* Replace jsonb with cbor because zero byte does not work in jsonb :(

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* fix error handling: attempts start at 0 now, and not 1 like when we released. so initial attempt in postgres should reflect that.

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* drain stuff

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* fallback metadata to metadataJson

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* Make code more readable

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

* apply Vade fix

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>

---------

Signed-off-by: Gal Schlezinger <gal@spitfire.co.il>
2025-11-23 11:05:20 -08:00
Pranay Prakash 945a946812 Normalize Workbenches (#283)
* Normalize Workbenches

Normalize trigger scripts across workbenches
fix: include hono in local build test

test: include src dir for test

test: add workflow dir config in test to fix sveltekit dev tests

add temp 7_full in example wokrflow

format

fix(sveltekit): detecting workflow folders and customizable dir

Remove 7_full and 1_simple error
replace API symlink in webpack workbench
Fix sveltekit and vite tests
Fix sveltekit symlinks
Test fixes
Fix sveltekit workflows path
Dont symlink routes in vite
Include e2e tests for hono and vite

fix error tests post normalization

wip - attempted fixes

* Add claude demo command

* fix: normalize workbench tests (#292)

* Proper stacktrace propogation in world

Proper stacktrace propogation in world

* Standardize the error type in the world spec

* Normalize Workbenches

Normalize trigger scripts across workbenches
fix: include hono in local build test

test: include src dir for test

test: add workflow dir config in test to fix sveltekit dev tests

add temp 7_full in example wokrflow

format

fix(sveltekit): detecting workflow folders and customizable dir

Remove 7_full and 1_simple error
replace API symlink in webpack workbench
Fix sveltekit and vite tests
Fix sveltekit symlinks
Test fixes
Fix sveltekit workflows path
Dont symlink routes in vite
Include e2e tests for hono and vite

* fix error tests post normalization

* fix(sveltekit): reading file on hmr delete

* changeset

* fix(vite): add resolve symlink script

* fix(vite): missing building on hmr

* test local builder in vite

* test: increase timeout on hookWorkflow

* test: ignore vite based apps in crossFileWorkflow

* test: fix nitro based apps status codes

* fix: intercept default vite spa handler on 404 workflow routes

* fix: vite hook route returning 422

* test: use 422 for hookWorkflow expected

* test: fix hono returning 404

* chore: add comment to middleware to clarify

* make api route for duplicate case

* revert

* revert: nitro builder

* add back nitro unhandled rejection logic

* test: add hono

* changeset

* fix: unused method

* fix: remove duplicate import

* remove

* chore: add comments to clarify

* test remove vite symlink script

---------

Co-authored-by: Pranay Prakash <pranay.gp@gmail.com>

* refactor: add top level resolve symlinks script

* fix: cleanup builder directories (#319)

* fix: add sveltekit server routes to builder

* fix: remove root workflow dir check

* fix missing root level workflow route

* Fix: The constructor now hardcodes `dirs: ['src/routes', 'src/lib']` which silently ignores any user\-provided `dirs` option passed to the plugin\, breaking the documented API and removing support for custom workflow directories\.

* Fix: The test expectations don\'t match the new implementation of `getWorkflowDirs()`\. The mock provides `scanDirs` which the new code no longer uses\, and the new implementation adds scanning of `routesDir` and `apiDir` instead\.

* fix(nitro): use src dir

---------

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

* refactor(nitro): use suppressUndefinedRejections

* revert: sveltekit builder

---------

Co-authored-by: Adrian <me@adriandlam.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
2025-11-14 10:13:06 -08:00
Nathan Rajlich f8e5d10ffa Support passing step function references across serialization boundaries (#307)
---------

Co-authored-by: JJ Kasper <jj@jjsweb.site>
Signed-off-by: Nathan Rajlich <n@n8.io>
2025-11-12 17:54:09 -08:00
Nathan Rajlich 79480f2e25 Clean up Hook entities after a workflow run has completed (#311) 2025-11-12 10:42:21 -08:00
Pranay Prakash 00b0bb9346 Proper error stack propogating (#280)
* Proper stacktrace propogation in world

Proper stacktrace propogation in world

* Merge Reconciliation

* Standardize the error type in the world spec

* Deduplicate vercel world utils

* fix undefined type issue

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2025-11-11 15:34:04 -08:00
Copilot 8208b5320b Fix Sourcemap Tracking (#256)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2025-11-09 12:08:48 -08:00
Copilot 4f9ae4e8de Remove step function transformation in client mode (#271) 2025-11-07 22:32:29 -08:00
Nathan Rajlich 24243158b0 Remove sleep() overloads e2e tests (#235)
The overloads parsing logic is now covered in unit tests, so we only
need one e2e test for the specific sleep functionality.

Signed-off-by: Nathan Rajlich <n@n8.io>
2025-11-05 19:11:41 -08:00
David Khourshid 809e0feeca Allow specifying milliseconds to sleep() (#165)
Signed-off-by: David Khourshid <davidkpiano@gmail.com>
2025-11-05 13:56:44 -08:00
Pranay Prakash 9f56434631 Make getWritable work inside steps (#222) 2025-11-05 09:54:13 -08:00
Pooya Parsa e814dba6f2 feat: workflow/vite plugin (#172)
* feat: nitro+vite support and workbench

* update package.json files

* test: add local-build test for vite

* update to vite plugin

* fix imports

* dedup nitro

* update

* update nitro

* allow passing options via plugin

* Update packages/nitro/src/vite.ts

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

* test: add vite tests

* trigger ci

* fix: missing js extension from builder and rollup

* refactor: move debug => unenv under vite plugin

* alternative workaround

* Update packages/nitro/src/vite.ts

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

* rename plugin

* Update packages/cli/package.json

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>

* lockfile

---------

Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: Adrian Lam <me@adriandlam.com>
2025-11-03 13:24:03 -08:00
Pranay Prakash f973954bd3 Switching from MIT to Apache + DCO (#191)
* Switching from MIT to Apache + DCO

* Add DCO github app
2025-11-03 12:42:40 -08:00
Nathan Rajlich 796fafd58d Remove isInstanceOf() function and utilize is() method on Error subclasses instead (#148) 2025-10-30 13:08:52 -07:00
Gal Schlezinger 4ca9a3edbd Introducing Workflow DevKit
build durable, resilient, and observable workflows.

Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Pranay Prakash <pranay.gp@gmail.com>
Co-authored-by: Adrian <me@adriandlam.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Vercel Release Bot <88769842+vercel-release-bot@users.noreply.github.com>
Co-authored-by: Peter Wielander <mittgfu@gmail.com>
Co-authored-by: Hayden Bleasel <hello@haydenbleasel.com>
Co-authored-by: Gal Schlezinger <gal@spitfire.co.il>
Co-authored-by: Manuel Muñoz Solera <mamuso@mamuso.net>
Co-authored-by: Garrett <garrett.tolbert@vercel.com>
Co-authored-by: Lars Grammel <lars.grammel@gmail.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
Co-authored-by: Tom Dale <tom@tomdale.net>
Co-authored-by: Vishal Yathish <135551666+visyat@users.noreply.github.com>
Co-authored-by: josh <144584931+dancer@users.noreply.github.com>
2025-10-23 12:07:52 +03:00