Skip to content

fix(sandbox): a CLI run that fails while the stream's consumer waits is no unhandled rejection - #296

Merged
jddunn merged 3 commits into
masterfrom
fix/cli-bridge-followups-2
Oct 11, 2026
Merged

jddunn merged 3 commits into
masterfrom
fix/cli-bridge-followups-2

Conversation

@jddunn

@jddunn jddunn commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #289 (released in 0.13.45). #289 made CLISubprocessBridge.stream() handle the run's outcome when its consumer stops reading early. The same unhandled rejection is left open while the consumer is still reading but busy with the previous chunk: the run can fail then, and nothing handles it until the stream reaches its final await. This change handles the run's outcome from the moment the process starts.

The defect

stream() attaches a handler to the run (execa's subprocess, a native Promise: execa 10.0.1 lib/methods/promise.js L1-2) in only two places: the await subprocess after stdout has been read to its end, and the finally of #289 when the generator is closed early. Between the start and that await, nothing handles it.

execa settles the run once the process has exited and its stdio streams have finished. On a failed exit, waitForSuccessfulExit throws at the exit (lib/resolve/exit-async.js L41-49), and the error path then waits for the buffered stdio data (lib/resolve/wait-subprocess.js L115-125, lib/io/contents.js L105-111), which waits for the stream to end (lib/resolve/stdio.js L19-46, lib/resolve/wait-stream.js L6-21). The timeout and the caller's abort take the same path (lib/terminate/timeout.js L16-21, lib/terminate/cancel.js L15-20).

Node ends a stream whose EOF has already arrived on the tick after the read that empties it, without waiting for another read (Node v22.23.3 lib/internal/streams/readable.js L769-778, endReadable L1682-1690, endReadableNT L1692-1698). The bridge reads stdout through the stream's async iterator (createAsyncIterator, L1359-1407), which takes the whole buffer in one read. A consumer slower than the CLI therefore gets the CLI's last lines in one chunk, after the CLI has exited: the stream ends on the next tick, and execa rejects the run a few microtasks later, while the generator waits at a yield for the consumer to finish with an event of that chunk.

When the consumer awaits I/O there (a socket write, a TTS call, anything that crosses a macrotask), the rejection has no handler when Node checks for one. In Node's default mode (throw, since Node 15: https://nodejs.org/api/cli.html#--unhandled-rejectionsmode) the host process gets an uncaught exception. The failures that reach this path are the ones the providers already turn into error chunks: a non-zero exit after the result line, an error result the CLI exits non-zero after (the Gemini CLI's handleError, packages/cli/src/utils/errors.ts L66-93 at google-gemini/gemini-cli 9b6e0265; for Claude Code, @anthropic-ai/claude-agent-sdk 0.3.296 replaces the exit's error with an error result's text, "Replacing exit error with result text" in Query.readMessages, sdk.mjs L136), the bridge's timeout and the caller's abort.

The defect predates #277 and #289: from 5dd1e1b (March 2026) the final await subprocess was the stream's only handler. #289 closed it for the consumer that stops reading, and this closes it for the one that keeps reading.

The fix

stream() attaches a no-op handler to the run as soon as execa returns it: Promise.resolve(subprocess).catch(() => undefined). For execa's run, a native Promise, Promise.resolve returns the run itself, so the handler is on the run; any other value a test stubs execa with is taken as the final await takes it. The run is still awaited after stdout has been read to its end, so a consumer that reads to the end gets the classified failure as before; the handler only keeps Node from reporting the rejection in between. The finally of #289 keeps its kill() and no longer needs its own handler.

Test

"a consumer that waits on each chunk: ends with the classified failed exit, which is no unhandled rejection while the consumer waits", for both providers, in src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts. Each provider runs on its real bridge with execa stubbed. stdout is a Readable that already holds the CLI's reply, its result line and its end, as Node's stream holds them once the CLI has exited, and the run rejects with execa 10's error for exit code 1 when that stream emits end, as execa settles it after the stdio streams finish. The consumer awaits setImmediate on each chunk. The test first asserts that the consumer got the reply chunk, so the case under test was reached; then an unhandledRejection listener must not have fired, and the stream must end with the CRASHED chunk. As in #289's early-close test, the run is a plain thenable so that vi.fn() cannot attach handlers of its own.

Docs

docs/features/CLI_ERROR_CODES.md (the bridge paragraph) and the JSDoc of CLISubprocessBridge.stream().

Linked issues

Follows #289.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only; nothing was run on a workstation. The test commit went up first, on master's code, and the fix after it.

  • Red, the test on master's code: CI run 38133357919 on 03dccc3, Tests 2 failed | 10043 passed | 64 skipped | 5 todo (10114). The two failures are the new test for each provider; in both, the unhandledRejection listener was called once with [Error: Command failed with exit code 1, Promise {}], the run's rejection while the consumer waited.
  • Green, the fix (4c71093) and the test's precondition check (e2e10cd, from a review thread): CI run 38133695283 on e2e10cd, Tests 10045 passed | 64 skipped | 5 todo (10114), cli-providers-subprocess.test.ts 34 tests; Batch-1 gated tests, the browser tests and the release dry run green. The run on 4c71093 alone (38133630293) was cancelled when e2e10cd superseded it.
  • The existing stream tests stub execa with plain objects that have no catch (CLISubprocessBridge.test.ts, ClaudeCodeCLIBridge.test.ts, GeminiCLIBridge.test.ts); Promise.resolve(subprocess) takes those as the final await does, and they pass unchanged in the green run.

Migration notes

None. No exported type changes, and a consumer that reads the stream to its end sees the same events and errors.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

…hunk of the stream

The CLI writes its reply and its result line and exits 1 before the bridge reads its stdout; the consumer awaits a macrotask on each chunk. The failed exit must reach the consumer as the classified error, and must not surface in the host as an unhandled rejection while the consumer waits.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 11, 2026 10:49
@sourcery-ai

sourcery-ai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR observes the execa subprocess promise as soon as streaming starts, preventing Node from reporting failures as unhandled while a consumer is processing a chunk, while preserving existing failure classification at stream completion and early-close cleanup. Regression tests simulate an exited CLI with buffered output for both providers, and documentation explains the behavior.

File-Level Changes

Change Details Files
Prevent premature subprocess rejections from being reported as unhandled while stream consumers process output.
  • Attach a no-op rejection handler immediately after the execa run is created.
  • Continue awaiting the subprocess after stdout completes so failures are still classified and emitted as the existing final error chunk.
  • Retain early-close cleanup while removing its redundant rejection handling.
src/core/llm/providers/cli-subprocess-bridge.ts
Add regression coverage for failures occurring while consumers await each streamed chunk.
  • Model an already-exited CLI with buffered stdout and a rejected execa-like thenable.
  • Exercise both configured stream providers with a macrotask delay per chunk.
  • Assert no unhandled rejection and preservation of the CRASHED final response.
src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts
Document the subprocess stream error-handling behavior.
  • Clarify that subprocess failures remain classified after stream consumption while intermediate rejections are observed.
  • Update the stream API documentation accordingly.
docs/features/CLI_ERROR_CODES.md
src/core/llm/providers/cli-subprocess-bridge.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T10:51:25.352111Z 03dccc3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 3d7b6524-bee0-4103-9fa5-885b52e35929


📥 Commits

Reviewing files that changed from the base of the PR and between 03dccc3 and e2e10cd.



📒 Files selected for processing (3)
  • docs/features/CLI_ERROR_CODES.md
  • src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts
  • src/safety/sandbox/subprocess/CLISubprocessBridge.ts


Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.




📝 Walkthrough
📝 Walkthrough

Walkthrough

The bridge now handles subprocess rejection from startup. It still reports failures when the consumer reads stdout to the end and kills the process if the consumer stops early. Tests cover nonzero exits while the consumer waits between chunks.

Changes

CLI subprocess exit handling

Layer / File(s) Summary
Bridge subprocess outcome handling
src/safety/sandbox/subprocess/CLISubprocessBridge.ts, docs/features/CLI_ERROR_CODES.md
The stream registers a rejection handler immediately after spawning. It awaits the subprocess after fully consuming stdout and kills the process when the consumer stops early. The documentation describes these outcomes.
Buffered exit regression tests
src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts
A fixture settles the subprocess promise when stdout ends. Tests for both CLI providers verify that a nonzero exit delivers the reply and one final CRASHED chunk, with no unhandled rejection.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix



Merge Risk: ⚪ Minimal · up to e2e10

The stream now handles process rejection even while consumers pause between chunks, while still reporting classified failures when they read to the end. No actionable merge risk is identified beyond normal checks.

Pre-merge checks | Passed 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (1 skipped: 1 …
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 clearly identifies the primary bug fix: preventing an unhandled rejection when a CLI stream consumer waits between chunks. It uses a valid Conventional Commit format.
Description check Passed The description is complete and relevant. It explains the defect, fix, tests, documentation updates, verification results, migration impact, linked issue, change types, and checklist status.

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR







🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR



  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

test(providers): cover failed CLI exits while stream consumers wait

🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Adds regression coverage for CLI failures that settle while a stream consumer waits on a chunk.
• Verifies both providers emit a classified CRASHED chunk without an unhandled rejection.
• The supplied diff contains the test only; the described bridge fix and documentation changes are
 absent.
Diagram

graph TD
  A["CLI stub"] --> B["Readable stdout"] --> C["Shared bridge"] --> D["Provider streams"] --> E["Waiting consumer"] --> F["Regression assertions"]
  B --> G["Rejected run"] --> C
Loading
High-Level Assessment

Testing through both real provider-to-bridge paths with only execa stubbed is appropriate for this timing defect; a bridge-only unit test would miss provider behavior. The supplied diff does not attach a rejection handler when the subprocess starts, so this test alone does not implement the fix described in the PR.

Files changed (1) +65 / -0

Tests (1) +65 / -0
cli-providers-subprocess.test.tsTest failed CLI exits during slow stream consumption +65/-0

Test failed CLI exits during slow stream consumption

• Adds a buffered Readable-based run that rejects with an execa-shaped error when stdout ends. For both CLI providers, a consumer waits a macrotask after each chunk, then asserts a single CRASHED final chunk and no unhandled rejection.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Failed runs still go unhandled ✓ Resolved
Description
The new waiting-consumer test drives exitedRun to reject when stdout emits end, but
CLISubprocessBridge.stream() attaches subprocess.catch() only in its early-close cleanup path
and otherwise waits until await subprocess. When the consumer pauses at each yielded chunk while
stdout drains, the rejection has no handler and can fire unhandledRejection before the generator
resumes to classify the failed run as CRASHED, causing the CI test gate to fail.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[517]

+      expect(unhandled).not.toHaveBeenCalled();
Evidence
The changed test requires that no unhandledRejection event fire while the consumer waits and that
the failed exit be classified as CRASHED (PR Compliance ID 11). It creates a subprocess whose
outcome rejects when stdout emits end, while the consumer pauses after each yielded chunk with a
macrotask. The implementation only attaches subprocess.catch(() => undefined) in the !readToEnd
early-close cleanup path and reaches await subprocess only after stdout has fully drained, leaving
the waiting-consumer path without a rejection handler during the pause.

AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests: AGENTS.md: Pass Build, Lint, Typecheck, and Tests
src/core/llm/providers/tests/cli-providers-subprocess.test.ts[495-517]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[275-298]
src/core/llm/providers/tests/cli-providers-subprocess.test.ts[475-491]
src/core/llm/providers/tests/cli-providers-subprocess.test.ts[499-511]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[280-301]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The waiting-consumer regression test exposes that a subprocess rejection can occur while the async generator is paused at a yielded chunk after stdout emits `end`. `CLISubprocessBridge.stream()` does not observe that rejection until it later awaits the subprocess, leaving it unhandled during consumer I/O and causing the test to fail while preventing the failed run from being classified as `CRASHED`.
## Fix Focus Areas
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[239-302]
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[246-257]
- src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts[495-525]
- src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts[495-517]
## Recommended Fix
Attach a no-op rejection handler immediately after `execa()` returns and before stdout iteration begins, for example with `subprocess.catch(() => undefined)`. Retain the later `await subprocess` so failed exits are still classified and surfaced after stdout is fully consumed, and keep the early-close cleanup responsible for killing the process without adding redundant rejection handling there.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 03dccc3baf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

execa settles the run once the process has exited and its stdout has ended, and Node ends stdout on the tick after the read that empties it. A run that failed (a non-zero exit, the timeout, the caller's abort) could therefore reject while stream() waited at a yield for a consumer busy with an event of the last read, before the final await attached the only handler, and Node raised it as an uncaught exception. stream() now attaches a handler as soon as execa returns the run; the final await still throws the classified failure, and the early-close path keeps its kill().

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts" line_range="496" />
<code_context>
+}
+
+describe.each(STREAM_PROVIDERS)('$name: a consumer that waits on each chunk', ({ binary, model, create, fixture }) => {
+  it('ends with the classified failed exit, which is no unhandled rejection while the consumer waits', async () => {
+    // The CLI wrote its reply and its result line and exited 1 before the
+    // bridge read its stdout.
</code_context>
<issue_to_address>
**Failed CLI run crashes host**

When the CLI exits unsuccessfully after writing output while the consumer waits on work for a yielded chunk, `CLISubprocessBridge.stream()` leaves the subprocess rejection unhandled until stdout drains or the consumer closes the generator. Node reports the rejection, potentially crashing the host instead of delivering the provider’s classified error chunk.

Attach a rejection handler to the subprocess run before yielding stdout, then retain the result for classification after stdout is consumed.

Also at `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:499`, `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:511`, `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:517`.
</issue_to_address>

### Comment 2
<location path="src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts" line_range="519-522" />
<code_context>
+      // so this listener is where it shows.
+      expect(unhandled).not.toHaveBeenCalled();
+      const finals = chunks.filter((chunk) => chunk.isFinal);
+      expect(finals).toHaveLength(1);
+      expect(finals[0].choices).toEqual([]);
+      expect(finals[0].error).toMatchObject({ code: 'CRASHED' });
+    } finally {
+      process.off('unhandledRejection', unhandled);
+    }
</code_context>
<issue_to_address>
**Missing reply chunks bypass the wait**

When the bridge stops yielding parsed reply events while the provider still emits the classified terminal failure, the `finals` assertions at lines 518–521 never require a non-final reply chunk. If the bridges stop yielding parsed reply events but still emit the terminal `CRASHED` chunk, the consumer never pauses before the run settles and this test passes without exercising the unhandled-rejection window.

Assert that `chunks` contains a non-final reply chunk before checking the terminal failure.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

…d on a reply chunk

Without a chunk of the reply the consumer never waits before the run settles, and the test would pass without reaching the case it covers.
@jddunn
jddunn merged commit babc568 into master Oct 11, 2026
11 checks passed
@jddunn
jddunn deleted the fix/cli-bridge-followups-2 branch October 11, 2026 11:01
github-actions Bot pushed a commit that referenced this pull request Oct 11, 2026
## [0.13.48](v0.13.47...v0.13.48) (2026-10-11)

### fix

* **sandbox:** a CLI run that fails while the stream's consumer waits is no unhandled rejection (#296) ([babc568](babc568))
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.

1 participant