Skip to content

shell: throw on Response/Request stream body used as redirect instead of delivering zero bytes - #35314

Closed
robobun wants to merge 4 commits into
mainfrom
farm/4c6e73f6/shell-response-stream-stdin
Closed

robobun wants to merge 4 commits into
mainfrom
farm/4c6e73f6/shell-response-stream-stdin

Conversation

@robobun

@robobun robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

A Response whose body is a JS-driven ReadableStream (a start/pull source, TransformStream#readable, an async generator, pipeThrough(new CompressionStream(...))) used as a shell stdin redirect runs the command on zero bytes and reports success:

import { $ } from "bun";
const P = "hello-shell-stdin-0123456789";
const body = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(P)); c.close(); } });
console.log(await $`cat < ${new Response(body)} | wc -c`.text()); // "0", exit 0
console.log(await $`cat < ${new Response(new Blob([P]))} | wc -c`.text()); // "28"

The same Response's .text() returns the full payload. "Response as stdin" is the docs' headline shell example; the breakage is only the composed-stream case (string / Blob / blob.stream() / Bun.file / real fetch() bodies work).

Cause

Cmd::init_subproc_redirections (src/runtime/shell/states/Cmd.rs) and Builtin::init_redirections (src/runtime/shell/Builtin.rs) call Body::use_as_any_blob() / Body::use_() on the wrapped body. For a Value::Locked body whose stream is not backed by a synchronously-readable native source, to_any_blob_allow_promise() returns None and use_as_any_blob() falls back to .unwrap_or(Blob::default()) (src/runtime/webcore/Body.rs:1249-1251). Stdio::extract_blob then maps the empty blob to Stdio::Ignore. Value::Used and Value::Error took the same empty-blob fallback.

Fix

A new shell::util::check_body_for_redirect(body, global, stdin) runs to_blob_if_possible() (which converts native-backed streams to a Blob) and then throws instead of letting the caller substitute an empty blob:

  • Locked: ERR_INVALID_ARG_TYPE with Request/Response body is a ReadableStream, which cannot be redirected in Bun Shell yet. A stdin redirect appends Read it first: $`cmd < ${await response.bytes()}`; stdout/stderr get the bare sentence since a stream body can never be a write target.
  • Used: ERR_BODY_ALREADY_USED (Body already used), matching Bun.spawn({ stdin: response }) and the body mixin.
  • Error: the body's stored error is rethrown.

Both the spawned-subprocess path (used for cat on POSIX) and the builtin path (used for cat on Windows) call the helper. The branch now uses Body::from_request_or_response() so a Request is accepted alongside Response, matching what Builtin.rs and Bun.spawn already did (previously cat < ${request} threw Invalid JS object used in shell: [object Request]).

Body::use_as_any_blob() itself is unchanged; its other callers (fetch request bodies, wasm streaming, Response init) all sit after an explicit Locked/stream check of their own.

Known trade-off: $`echo ${request}` (a Request in argument position, not a redirect) now emits the parser's expected a command or assignment but got: "JSObjRef" instead of Invalid JS object used in shell: [object Request]. handle_template_value runs before parsing and cannot see the position, so registering Request as a redirect-capable value necessarily routes it there. Response, Blob, ReadableStream and ArrayBuffer already produce that parser message on main; a follow-up can improve the parser's JSObjRef-in-argument-position error for all of them at once.

Related

  • ai slop #30550 implements true ReadableStream pumping into shell stdin; once it lands this branch can route the Locked case through the same Stdio::ReadableStream path instead of throwing.
  • shell: throw instead of panic on ReadableStream redirect #33996 turns the bare ReadableStream redirect placeholder panic! into a throw and fixes the Yield::Failed trampoline so the builtin-path throw does not leave the interpreter keepalive pinned in a standalone script. (The test runner exits cleanly regardless.)
  • TODO SHELL READABLE STREAM #18262 tracks the bare ReadableStream stdin case.

How did you verify your code works?

Added to test/js/bun/shell/bunshell.test.ts under deno_task > redirects > stdin from Request/Response, parameterized over Response and Request:

  • ReadableStream start(), TransformStream#readable, async-generator bodies as stdin each reject with /body is a ReadableStream/
  • an already-consumed body rejects with /already used/
  • string and Blob body controls still deliver the full payload
  • echo hi > ${new Response(stream)} rejects with the stream-body message and without the stdin hint
USE_SYSTEM_BUN=1 bun test bunshell.test.ts -t "stdin from Request/Response"   # 11 fail
bun bd test bunshell.test.ts -t "stdin from Request/Response"                 # 13 pass
bun bd test bunshell.test.ts                                                  # 427 pass, 0 fail

no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/shell/bunshell.test.ts

… of silently delivering zero bytes

When a Response (or Request) whose body is a JS-driven ReadableStream
(start/pull source, TransformStream, async generator, a piped
CompressionStream) is used as a shell stdin redirect, the command
previously ran on an empty stdin and reported success.

Body::use_as_any_blob() returns an empty Blob for a Locked body it
cannot synchronously convert, and Stdio::extract_blob turns an empty
blob into Stdio::Ignore. The same substitution happened for an
already-consumed body (Value::Used) and an errored body
(Value::Error).

The shell redirect setup now checks the body state after
to_blob_if_possible(): a Locked body throws ERR_INVALID_ARG_TYPE with a
hint to buffer it first; a Used body throws ERR_BODY_ALREADY_USED; an
Error body rethrows its stored error. Blob, string, InternalBlob and
Bun.file/native-stream bodies (which to_blob_if_possible converts)
continue to work.

Both the spawned-subprocess path (Cmd::init_subproc_redirections, used
for cat on POSIX) and the builtin path (Builtin::init_redirections,
used for cat on Windows) are covered, and Request is now accepted
alongside Response for parity with the builtin path and Bun.spawn.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Request and Response bodies are now supported as shell redirect sources through generic body extraction and validation. Invalid stream or consumed bodies fail redirects, while string, Blob, and Request bodies remain usable. Tests cover these cases.

Changes

Request/Response shell redirects

Layer / File(s) Summary
Generic Request/Response body routing
src/runtime/shell/shell_body.rs, src/runtime/shell/states/Cmd.rs
Template handling and subprocess redirections recognize generic Request and Response body values and route them through blob extraction.
Redirect validation and tests
src/runtime/shell/util.rs, src/runtime/shell/Builtin.rs, test/js/bun/shell/bunshell.test.ts
Redirect bodies reject locked, consumed, or errored states before wiring; tests cover stream, consumed, string, Blob, and Request bodies.

Possibly related PRs

  • oven-sh/bun#33994: Both changes modify subprocess stdin redirection handling for JavaScript body-like sources.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title accurately describes the main behavior change: shell redirects now throw for Request/Response stream bodies instead of silently using zero bytes.
Description check ✅ Passed The description matches the template and clearly explains the change and verification steps with relevant test commands.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:24 PM PT - Jul 23rd, 2026

✅ @robobun, your commit c91149d099342f6f2230630a70ac87fd3cf786ca passed in Build #78938! 🎉


🧪   To try this PR locally:

bunx bun-pr 35314

That installs a local version of the PR into your bun-35314 executable, so you can run:

bun-35314 --bun

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. shell: throw instead of panic on ReadableStream redirect #33996 - Same fix: replaces panic!("TODO SHELL READABLE STREAM") in Cmd.rs with a throw, also handles the Builtin.rs path and fixes Yield::Failed trampoline
  2. ai slop #30550 - Superset: replaces the same panic! in Cmd.rs but implements actual ReadableStream stdin pumping via Stdio::extract_readable_stream instead of throwing

🤖 Generated with Claude Code

@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

Not a duplicate of either. This PR does not touch the bare-ReadableStream branch or the panic!("TODO SHELL READABLE STREAM") placeholder at all; that line is unchanged in the diff.

PR JS shape Cmd.rs branch touched Behavior on main
#33996 cat < ${readableStream} ReadableStream::from_js → panic! process aborts
#30550 cat < ${readableStream} same, plus the stdin pump machinery process aborts
this PR cat < ${new Response(readableStream)} from_request_or_response → use_as_any_blob() command succeeds on zero bytes

Neither #33996 nor #30550 changes the Response/Request body branch or the silent unwrap_or(Blob::default()) fallback in Body::use_as_any_blob(), so the repro in this PR's description still delivers 0 bytes with either of them applied. The three PRs are complementary; the Related section of the description covers how they fit together.

Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/Builtin.rs Resolved
Addresses review: the Locked/Used/Error body check was duplicated
between Cmd::init_subproc_redirections (POSIX spawned-command path)
and Builtin::init_redirections (Windows builtin path).

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/shell/util.rs`:
- Around line 33-38: Update the BODY_ALREADY_USED error constructed in the
Value::Used branch to identify the consumed Request/Response body, state that it
cannot be redirected, and instruct callers to create a new body or redirect the
buffered bytes. Preserve the existing error code and throw behavior.

In `@test/js/bun/shell/bunshell.test.ts`:
- Around line 1670-1731: Add forced-subprocess coverage in the “stdin from
Request/Response” tests so Request inputs exercise
Cmd::init_subproc_redirections rather than builtin cat. Add rejection cases for
a Request backed by a ReadableStream and for an already-consumed Request body,
while preserving the existing successful Request stdin coverage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c21ecb31-bf6f-4224-8464-bfacc671f130

📥 Commits

Reviewing files that changed from the base of the PR and between f133f9d and 41f8fee.

📒 Files selected for processing (5)
  • src/runtime/shell/Builtin.rs
  • src/runtime/shell/shell_body.rs
  • src/runtime/shell/states/Cmd.rs
  • src/runtime/shell/util.rs
  • test/js/bun/shell/bunshell.test.ts

Comment thread src/runtime/shell/util.rs Resolved
Comment thread test/js/bun/shell/bunshell.test.ts Resolved
Comment thread src/runtime/shell/util.rs Resolved
Comment thread src/runtime/shell/util.rs Resolved
… redirect

The remedy 'Read it first: $`cmd < ${await response.bytes()}`' only
makes sense for an input redirect; a Response wrapping a ReadableStream
can never be a write target. check_body_for_redirect now takes the
redirect direction and drops the hint for stdout/stderr.

Also notes that the Value::Error arm is reached via fetch-driven bodies,
not user-constructed new Response().
Comment thread src/runtime/shell/shell_body.rs Resolved
@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-23 and it conflicts with main. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants