Skip to content

fix(stream): prevent ERR_INVALID_STATE when pushing to closed stream#1894

Open
GdMacmillan wants to merge 5 commits intolangchain-ai:mainfrom
GdMacmillan:fix/stream-messages-handler-closed-check
Open

fix(stream): prevent ERR_INVALID_STATE when pushing to closed stream#1894
GdMacmillan wants to merge 5 commits intolangchain-ai:mainfrom
GdMacmillan:fix/stream-messages-handler-closed-check

Conversation

@GdMacmillan
Copy link

Summary

Add a guard check in IterableReadableWritableStream.push() to verify the stream is not closed before attempting to enqueue data.

Problem

When using graph.stream() with streamMode: ['messages'], a TypeError [ERR_INVALID_STATE]: Invalid state: Controller is already closed occurs if the stream consumer completes before the LLM finishes generating tokens.

This happens because IterableReadableWritableStream.push() doesn't check the _closed flag before calling controller.enqueue().

Solution

Add a simple guard: if (this._closed) return; at the start of the push() method.

The _closed flag already exists and is set by the close() method - it just wasn't being checked in push().

Testing

  • All existing tests pass (768 passed, 3 skipped)
  • Linting passes
  • Build succeeds

Fixes #1837

Add a guard check in IterableReadableWritableStream.push() to verify the
stream is not closed before attempting to enqueue data. This prevents
the "Controller is already closed" TypeError that occurs when
StreamMessagesHandler tries to emit tokens after the stream consumer
has completed.

Fixes langchain-ai#1837

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@changeset-bot
Copy link

changeset-bot bot commented Jan 14, 2026

⚠️ No Changeset found

Latest commit: 4648744

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

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.

StreamMessagesHandler throws ERR_INVALID_STATE when stream is closed

1 participant