# agent_ui: Fix duplicate terminal when starting a new agent thread \(\#59586\) · gitcafe/zed

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

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

Visibility: public

Requested revision: af56cb75a8ef292e9cf9aba567983be98b385102

Requested commit: af56cb75a8ef292e9cf9aba567983be98b385102

Commit: af56cb75a8ef292e9cf9aba567983be98b385102

Tree: d4be06cd39be028631fa993887c2095fbbe71db7

Author: Richard Boisvert

Committer: GitHub

## Message

```
agent_ui: Fix duplicate terminal when starting a new agent thread (#59586)

# Objective

- Fixes #58097.
- Opening a new project and clicking `+` in the agent panel to start a
terminal thread creates two terminals instead of one. I am able to
replicate the issue on version 1.8.0 on macOS 27

## Solution

The new-thread action creates the terminal and then focuses the agent
panel. Focusing re-activates the panel (`Panel::set_active` then
`ensure_thread_initialized`) before the terminal, which is spawned
asynchronously, has registered. The panel still looks uninitialized at
that moment, so it spawns its own "initial" terminal too, and that is
the duplicate.

`spawn_terminal` now marks the spawn as in-flight
(`pending_terminal_spawn`) the moment it starts, the same way the
restore and initial-terminal paths already do, so the existing guard in
`ensure_thread_initialized` skips the redundant terminal.

This only affected new (unrestored) projects, since existing ones
restore their previous entry instead of auto-creating one. The auto-init
behavior was introduced in #57150.

## Testing

- Verified in a local dev build on macOS: opening a fresh project and
clicking `+` now creates one terminal, and clicking `+` again creates a
second, as expected. Reopening an existing project still restores a
single terminal.
- Added `test_explicit_terminal_blocks_redundant_auto_init`, which fails
without the fix.
- The change is platform-agnostic (no platform-specific code); I wasn't
able to test on Linux/Windows.

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [x] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

---

Release Notes:

- Fixed a duplicate terminal being created when starting an agent
terminal thread in a new project
```

## Parents

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

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