# agent_ui: Fix panic when multiple rewrite tool uses share a char offset counter \(\#52458\) · gitcafe/zed

[View on GitCafe](https://git.cafe/gitcafe/zed/commit/064a17fd124b6edacf59d34d7781f1cb46fd0408)

Repository: [gitcafe/zed](https://git.cafe/gitcafe/zed)

Visibility: public

Requested revision: 064a17fd124b6edacf59d34d7781f1cb46fd0408

Requested commit: 064a17fd124b6edacf59d34d7781f1cb46fd0408

Commit: 064a17fd124b6edacf59d34d7781f1cb46fd0408

Tree: eaa7f5bfd1f7abc7fd83a10522b56f7b7d5f6336

Author: Matthias Endler

Committer: GitHub

## Message

```
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.
```

## Parents

- [ad916ca1af828cf98ff92322b97fd3f02d849463](https://git.cafe/gitcafe/zed/commit/ad916ca1af828cf98ff92322b97fd3f02d849463?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zed/tree/064a17fd124b6edacf59d34d7781f1cb46fd0408?format=markdown)
