agent_ui: Fix panic when multiple rewrite tool uses share a char offset counter (#52458)

## Context

The process_tool_use closure used a single chars_read_so_far counter
shared across all REWRITE_SECTION_TOOL_NAME tool use events. When the
LLM produced multiple separate rewrite tool uses (different IDs), the
counter from the first tool use carried over into the second. If the
second tool use had a shorter replacement_text, the slice indexing
panicked with index out of bounds.

(This caused my first ever Zed panic today.)

Fix by tracking bytes-read per tool use ID using a HashMap keyed on
LanguageModelToolUseId. Also replace the direct slice index with .get()
so any remaining out-of-bounds case is handled gracefully instead of
panicking.

Looks like it hasn't been reported yet. At least I couldn't find any
related issues.

## How to Review

I hope the fix is pretty self-explanatory. We keep track of multiple
rewrite tools, which explains the extra ceremony around getting the
right character count, but apart from that it's pretty straightforward.

The performance impact should be neglible because:

1. Once the completion stream ends (or the task is dropped/cancelled),
the entire Arc<Mutex<HashMap>> is freed.
2. The number of entries is tiny. In a single completion request the LLM
will produce at most a handful of
REWRITE_SECTION_TOOL_NAME tool uses. Each entry is just an Arc<str> key
+ usize value.

So the HashMap grows for the duration of one handle_completion call and
is then dropped wholesale.

## Self-Review Checklist

<!-- Check before requesting review: -->
- [X] I've reviewed my own diff for quality, security, and reliability
- [X] Unsafe blocks (if any) have justifying comments
- [X] The content is consistent with the [UI/UX
checklist](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
- [X] Tests cover the new/changed behavior
- [X] Performance impact has been considered and is acceptable

Release Notes:

- Fixed an out-of-bounds panic when the AI produced multiple inline
rewrites in a single completion.
064a17fd12Matthias Endler committed on 5/12/2026, 9:35:17 PM· committed by GitHubparentad916ca
1 file changedLine totals unavailable