# agent_ui: Replace stale draft thread when selected agent changes \(\#54023\) · gitcafe/zed

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

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

Visibility: public

Requested revision: a9a77f1c6e82f8b7c02db7dd360fb5de3d61ab80

Requested commit: a9a77f1c6e82f8b7c02db7dd360fb5de3d61ab80

Commit: a9a77f1c6e82f8b7c02db7dd360fb5de3d61ab80

Tree: 966b9cb34878d0ea5a5306aeff90c675f54a2732

Author: Eric Holk

Committer: GitHub

## Message

```
agent_ui: Replace stale draft thread when selected agent changes (#54023)

## Problem

When creating a new agent thread from the sidebar's **+** button (or via
the `NewThread` / `NewThreadInGroup` actions), the panel always returned
the cached draft thread — even if the user had since switched to a
different agent. This meant the new thread would use the wrong agent
(typically the default Zed Agent instead of the last-used external
agent).

The root cause was in `ensure_draft()`: it cached the draft and returned
it unconditionally on subsequent calls without checking whether its
agent
matched the current `selected_agent`.

Meanwhile, **cmd-n from within the agent panel** dispatched
`NewExternalAgentThread`, which calls `create_thread()` — this always
creates a fresh thread with the correct `selected_agent`, so it worked
fine.

## Fix

`ensure_draft()` now compares the cached draft's agent against the
desired agent. When they differ and the draft's editor is empty, the
stale draft is discarded and a new one is created with the correct
agent.
If the draft has user-typed content, it is preserved to avoid losing
work.

## Test

Added `test_draft_replaced_when_selected_agent_changes` which verifies:
1. A draft created with `NativeAgent` gets replaced when
`selected_agent`
   changes to a custom agent
2. The replacement draft uses the correct agent
3. Calling `activate_draft` again with the same agent reuses the cached
   draft (no unnecessary replacement)

The test fails without the fix (returns the stale `NativeAgent` draft)
and passes with it.

Release Notes:

- N/A
```

## Parents

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

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