fix: filter orphan tool_results referencing already-paired tool_uses #10496
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
This PR attempts to address Issue #10494 - the race condition where deleted queued messages create duplicate tool_result blocks.
Problem
When a user queues a message during tool execution and then deletes it before completion, the deleted message text can persist and create a second
tool_resultblock in a subsequent user message that references atool_use_idthat was already paired in a previous message. This causes API protocol violations: "The number of toolResult blocks exceeds the number of toolUse blocks."Solution
Enhanced
validateAndFixToolResultIds()with cross-message orphan filtering:Scan conversation history after the previous assistant message to find which
tool_use_idshave already been paired withtool_resultblocks in previous user messagesFilter out orphaned tool_results in the current message that reference already-paired
tool_use_idsExclude already-paired IDs from "missing" tool_result calculations so we do not add placeholder results for tool_uses that are already satisfied
Changes
src/core/task/validateToolResultIds.ts: Added cross-message orphan filtering logicsrc/core/task/__tests__/validateToolResultIds.spec.ts: Added 5 comprehensive tests for cross-message scenariosTesting
All 32 tests pass, including the new cross-message orphan filtering tests.
Feedback and guidance are welcome!