Skip to content

fix(cli): answer 200 with JSON null when a route returns nothing - #718

Merged
blove merged 3 commits into
mainfrom
blove/runs-wait-undefined-output
Sep 18, 2026
Merged

blove merged 3 commits into
mainfrom
blove/runs-wait-undefined-output

Conversation

@blove

@blove blove commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #714. Same bug class as #711, which fixed the middleware-reject site.

The bug

POST /threads/:id/runs/wait serialized the run's result with:

return Response.json(result.output, { status: 200 })

result.output is literally the route function's return value (typed unknown), so a route that returns nothing arrives here as undefined — and Response.json(undefined) throws. The outer handler caught it and turned a run that had actually succeeded into:

500 {"error":{"kind":"execution_error","message":"Unexpected runtime server failure"}}

The same route over POST /threads/:id/runs/stream reported the run as done, so the two endpoints disagreed about the same run. Regressed in #373.

// reproduces it
export const workflow = async () => undefined

The decision: null, not the old empty body

The obvious move is restoring the pre-#373 behavior, which was sendJson(200, undefined) — a 200 with an empty body. That would be the wrong fix, and the repo says so itself.

normalizeServerResult is B4's own client for this endpoint. It parses every 200 body and has an explicit failure branch for one that will not parse: "Server returned a malformed JSON payload for /runs/wait". JSON.parse("") throws, so an empty body would trade the 500 for a server_transport_error.

null parses cleanly into the client's success path, and matches the runtime's own existing idiom for a synthesized terminal (output: null appears in four other places). ?? rather than ||, so falsy outputs (0, false, "") are untouched.

Second commit: the class was not actually closed

The first commit claimed it was. That was wrong, and an independent review caught it. undefined is only one of the values JSON.stringify refuses, and a route's output is unconstrained:

route returns before /runs/stream said
circular object 500 Unexpected runtime server failure 200, done
{ n: 1n } 500 Unexpected runtime server failure 200, done

Same symptom as #714, same line. Serialization now runs under its own catch and answers with a message naming the route and the reason, rather than the outer handler's catch-all.

Also from that review

  • docs/recipes/dispatch-from-route.mdx is the shipped route-to-route pattern third parties copy, and it read remoteState.messages?.at(-1). ?. guards the property, not the object it hangs off, so a null body would throw one line after the 200. Narrowed the type and the access.
  • Documented the response contract. It previously said only "200 final state JSON", covering neither the empty nor the unserializable case.
  • The parity test was vacuous. It asserted toContain("done") on the SSE text, and a route that throws also emits a done frame — so it passed for a genuinely failed run. It now parses the terminal frame and asserts the payload.
  • Drain deadline on the test handlers, so a failed assertion reports in milliseconds instead of waiting out the 30s default on an unconsumed SSE body.

Tests

packages/cli/test/runs-wait-output.test.ts, written first and watched fail (500 instead of 200; the client reporting failed instead of passed; the opaque message instead of a named one):

  • a route returning nothing answers 200 with the body null
  • that response normalizes to a success through B4's own client, which is the whole reason for choosing null
  • runs/wait and runs/stream agree about such a run
  • an unserializable output is named rather than reported as a crash
  • falsy outputs are not flattened, and ordinary object outputs are unchanged

Mutation-checked: reverting the fix fails 3, ?? → || fails the falsy guard, null → {} fails 2, and pointing the parity test at a throwing route fails it.

Scope

One fix covers all five build targets (node, edge, hono, vercel, static) — every emitter delegates to createRuntimeFetchHandler, with no emitter-local copy.

Verification

Node 24. pnpm lint, pnpm build, pnpm typecheck and the docs check pass. CLI suite: 2016 passed, 4 skipped.

Patch changeset for @b4run/cli included.

🤖 Generated with Claude Code

`POST /threads/:id/runs/wait` serialized the route's return value with
`Response.json(result.output)`. That value is literally whatever the route
function returned, so a route returning nothing reached `Response.json`
with `undefined`, which throws — and the outer handler turned a run that had
actually succeeded into `500 Unexpected runtime server failure`. The same
route over `/runs/stream` reported the run as done, so the two endpoints
disagreed about the same run.

Send `null` instead. Not the empty body the pre-fetch-core server sent:
`normalizeServerResult`, B4's own client for this endpoint, parses every 200
body and reads `""` as a malformed payload, which would trade the 500 for a
`server_transport_error`. `??` leaves falsy outputs (0, false, "") alone.

Closes #714. Same bug class as #711, which fixed the middleware-reject site;
with this, the two sites that could reach `Response.json(undefined)` in the
dev runtime are both closed — every other call there passes an object literal
or is guarded.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel

vercel Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
b4-run Ready Ready Preview Sep 17, 2026 11:58pm UTC

Request Review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated approval: this PR received an intelligent (AI) code review. See the review comments on this PR.

Review follow-up. The previous commit claimed the `Response.json(undefined)`
class was closed; it was not. `undefined` is only one of the values
`JSON.stringify` refuses, and `result.output` is `unknown` — a route can
return a circular object or a BigInt just as easily. Both reproduced the
exact symptom #714 is about: a run that executed fine answering
`500 Unexpected runtime server failure`, with `/runs/stream` reporting the
same run as done.

Serialization now runs under its own catch and answers with a message naming
the route and the underlying reason, instead of falling through to the outer
handler's catch-all.

Also from the review:

- `docs/recipes/dispatch-from-route.mdx` is the shipped route-to-route
  pattern, and it read `remoteState.messages?.at(-1)`. `?.` guards the
  property, not the object, so a `null` body would throw one line after the
  200. Narrowed the type and the access.
- Documented the `runs/wait` response contract, which previously said only
  "200 final state JSON" and did not cover an empty or unserializable output.
- The parity test asserted `toContain("done")`, which also passes for a route
  that THROWS — it proved nothing. It now parses the terminal SSE frame and
  asserts the payload.
- Gave the test handlers a drain deadline so a failed assertion reports in
  milliseconds rather than waiting out the 30s default on an unconsumed SSE
  body.

Co-Authored-By: Claude Opus 5 <[email protected]>
The two MDX pages this branch touches are tracked by the SEO last-modified
manifest, so `generate-lastmod` failed the source-validate lane until the
manifest was regenerated. Only those two entries change.

Caught by CI rather than locally because I ran `--filter @b4run/cli test`
before pushing; the lane runs `pnpm test` across the whole monorepo, which
is what this branch is now verified against.

Co-Authored-By: Claude Opus 5 <[email protected]>
@blove
blove merged commit b090ad4 into main Sep 18, 2026
29 of 30 checks passed
@blove
blove deleted the blove/runs-wait-undefined-output branch September 18, 2026 00:17
blove added a commit that referenced this pull request Oct 21, 2026
…→ PR #1050) (#1051)

* fix(software-factory): the cli target's promotion set is pin-specific, and the builder searches only its package

The first live run at pin c221ce0 found two things. The cli target's
Dockerfile hard-codes the nested dependencies it promotes over the
root's; the lockfile at this pin nests a different set (ag-ui now nests
the TypeScript 6 compiler core also nests, and axe-core; commander and
hono no longer nest), so the image build failed. The set is now this
pin's, the comment says it is pin-specific, and a name two packages nest
at the same version is promoted once instead of failing the build.

The builder then ran a recursive grep over .., which followed the
node_modules links into the image's install and returned 1.7 MB in one
tool result; the model refused the next call at 513k input tokens. The
working rules now confine searches to the package's own directories and
cap what a search prints.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(software-factory): pre-check refuses a built path no source compiles to, and the CLI entry

Today's live run spent both intake attempts on guessed build paths: a check
importing packages/cli/dist/output.js (the file is dist/lib/output.js), then
one importing dist/index.js, the CLI entry, whose proof hung. Each cost a
two-minute oracle proof.

Rule (f) built-source: a location (static, import()/require()/new URL(), or a
path held in a variable built from join/resolve/process.cwd()/pathToFileURL)
under a target build prefix (snapshotIgnore entries ending dist/) must mirror a
source the pin holds: <pkg>/src/<file>.ts|.tsx|.js|.jsx (.mjs/.cjs likewise),
or <file>/index.ts|.tsx for an extensionless import. The refusal names the
path, the source looked for, and a same-named module under src/ or the
nearest directory's listing.

Rule (g) bin-entry: a location naming the built file a package bin runs
(read at the pin from package.json bin and the bin script's ../dist imports)
is refused.

The drafter prompt's target line now says the built path mirrors src/, to
verify with listDir/readFile under repo/<pkg>/src/, and never to import a bin
entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(software-factory): the drafter finds a built file by its source, and the cli target test names this pin's promotion set

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(software-factory): the cli target pins today's main and captures the test helper its tests import

At pin 765e6e1 the captured cli tests did not import
test/helpers/header-auth.ts; at main's tip eight of them do, and the
explicit capture omitted it, so the builder's visible suite failed to
load and the builder spent its turn hunting a helper that was never in
its workspace. The target now pins 84063ae, captures the helper, and
the generator's build order at that pin puts sdk before ag-ui.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(software-factory): a candidate never includes the framework's offloaded tool outputs

B4 spills an oversized tool result to tool-outputs/ in the thread's
workspace. The reader's observed set now leaves that prefix out, as it
does the target's build output: the first live run's correct repair was
refused as a scope violation for the one file the offload had written.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(software-factory): the #714 task re-seeds its defect by patch, now that the cli pin carries the fix

`cli-runs-wait-undefined` was repaired forward: its defect was the pinned
bytes at 765e6e1. The cli target now pins 84063ae, where #718's fix has
landed, so the task ships a defect.patch that reverses it and a reference
regenerated at that pin (same body, new offsets). The inspection test
names `tool-outputs/` as part of the ignored set.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs: record the rung 4 live run as landed

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>

This branch was successfully deployed

1 active and 1 inactive deployments
Preview — 77295aa6 Deployed Sep 17, 2026 by vercel[bot]
vercel-preview — 77295aa6 Deployed Sep 17, 2026 by blove via vercel-native #2044
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A route returning undefined makes POST /threads/:id/runs/wait answer 500

1 participant