fix(middleware): prevent RemoveMessage streaming on every request #214
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Fixed a critical bug in
PatchToolCallsMiddlewarewhereRemoveMessageinstances were being returned on every request, causing them to be streamed to external clients and triggering message coercion errors in UIs.Context
The
PatchToolCallsMiddleware.before_agent()method was unconditionally returning a state update containingRemoveMessage(id=REMOVE_ALL_MESSAGES)on every agent invocation, even when there were no dangling tool calls to patch.This caused problems for:
type: "remove"messages and threw errorsThe issue was particularly visible on the first message of any conversation, where there are definitely no dangling tool calls yet the middleware still returned a RemoveMessage.
Changes
Modified
PatchToolCallsMiddleware.before_agent()insrc/deepagents/middleware/patch_tool_calls.py:Nonein the common case where no patches are neededUpdated test expectations in
tests/test_middleware.py:test_no_missing_tool_callsnow expectsNonewhen there are no missing tool callsImplementation notes
Before:
After:
The logic still correctly handles dangling tool calls when they occur, but avoids the overhead and streaming issues when they don't.
Breaking changes
Behavior change: The middleware now returns
Noneinstead of a state update when there are no dangling tool calls.This is not a breaking change for normal usage because:
RemoveMessagewas never meant to be visible to external clientsTests that explicitly checked for the RemoveMessage in all cases have been updated to match the corrected behavior.
Test plan
Unit tests
test_no_missing_tool_callsto expectNonereturn valueIntegration testing
Expected behavior
None, no RemoveMessage created or streamedRisks
Checklist