Handle delegation when pending tool-result flush and retry save both fail #2188
Description
Summary
Handle the delegation failure path where flushPendingToolResultsToHistory() returns false and retrySaveApiConversationHistory() also fails. Delegation currently treats the failure as non-fatal and continues. When the parent resumes, its history can end with an assistant tool_use without the required tool_result, which can cause an Anthropic 400 error.
Requested by @PierrunoYT as a separate follow-up to #2113.
Failure path
- A parent task attempts to delegate through
delegateParentAndOpenChild. flushPendingToolResultsToHistory()fails. An assistant-persistence failure can cause it to return before adding pending results to history.- The retry save also fails. The caller warns and continues delegation.
- The parent later enters
resumeAfterDelegation()with no new user content. - The outgoing history can contain a trailing assistant
tool_usewithout itstool_result.
Saving existing history is not equivalent to flushing pending tool results.
Required changes
- Define safe delegation behavior when both the flush and retry save fail.
- Define the user-visible failure or recovery behavior, including whether the parent stays open and how delegation can be retried.
- Ensure the parent cannot send an unmatched trailing
tool_useafter this failure. - Preserve pending results for recovery and avoid duplicate tool results or duplicate child tasks during retries.
- Keep the generic send-time normalizer's handling of trailing tool calls unchanged: a trailing tool call can still have a result pending.
This issue does not prescribe throwing immediately after a transient write error. The delegation behavior needs a separate decision and dedicated tests.
Affected areas
src/core/webview/ClineProvider.ts:delegateParentAndOpenChildand delegation recovery.src/core/task/Task.ts:flushPendingToolResultsToHistory,retrySaveApiConversationHistory, andresumeAfterDelegation.- Delegation specifications and persistence-failure tests.
Acceptance criteria
- A regression test covers a failed flush followed by a failed retry save, including failure before pending results enter history.
- The selected behavior prevents an API request with an unmatched trailing assistant
tool_use. - Tests cover recovery or retry without lost results, duplicate results, or duplicate child tasks.
- Tests confirm that successful delegation remains unchanged.
- The user-visible failure and recovery behavior is documented.
Context
This is an existing delegation failure path, not a regression introduced by #2113. That PR repairs malformed outgoing history without changing delegation policy.
Activity