connection_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentSessionInfo, AgentThreadEntry, AssistantMessage,
   3    AssistantMessageChunk, AuthRequired, LoadError, MentionUri, PermissionOptionChoice,
   4    PermissionOptions, RetryStatus, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
   5    UserMessageId,
   6};
   7use acp_thread::{AgentConnection, Plan};
   8use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
   9use agent::{NativeAgentServer, NativeAgentSessionList, SharedThread, ThreadStore};
  10use agent_client_protocol::{self as acp, PromptCapabilities};
  11use agent_servers::AgentServer;
  12#[cfg(test)]
  13use agent_servers::AgentServerDelegate;
  14use agent_settings::{AgentProfileId, AgentSettings};
  15use anyhow::{Result, anyhow};
  16use arrayvec::ArrayVec;
  17use audio::{Audio, Sound};
  18use buffer_diff::BufferDiff;
  19use client::zed_urls;
  20use collections::{HashMap, HashSet, IndexMap};
  21use editor::scroll::Autoscroll;
  22use editor::{
  23    Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
  24};
  25use feature_flags::{AgentSharingFeatureFlag, AgentV2FeatureFlag, FeatureFlagAppExt as _};
  26use file_icons::FileIcons;
  27use fs::Fs;
  28use futures::FutureExt as _;
  29use gpui::{
  30    Action, Animation, AnimationExt, AnyView, App, ClickEvent, ClipboardItem, CursorStyle,
  31    ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, Hsla, ListOffset, ListState,
  32    ObjectFit, PlatformDisplay, ScrollHandle, SharedString, Subscription, Task, TextStyle,
  33    WeakEntity, Window, WindowHandle, div, ease_in_out, img, linear_color_stop, linear_gradient,
  34    list, point, pulsating_between,
  35};
  36use language::Buffer;
  37use language_model::LanguageModelRegistry;
  38use markdown::{Markdown, MarkdownElement, MarkdownFont, MarkdownStyle};
  39use project::{AgentServerStore, ExternalAgentServerName, Project, ProjectEntryId};
  40use prompt_store::{PromptId, PromptStore};
  41use rope::Point;
  42use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
  43use std::cell::RefCell;
  44use std::path::{Path, PathBuf};
  45use std::sync::Arc;
  46use std::time::Instant;
  47use std::{collections::BTreeMap, rc::Rc, time::Duration};
  48use terminal_view::terminal_panel::TerminalPanel;
  49use text::Anchor;
  50use theme::AgentFontSize;
  51use ui::{
  52    Callout, CircularProgress, CommonAnimationExt, ContextMenu, ContextMenuEntry, CopyButton,
  53    DecoratedIcon, DiffStat, Disclosure, Divider, DividerColor, IconDecoration, IconDecorationKind,
  54    KeyBinding, PopoverMenu, PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar,
  55    prelude::*, right_click_menu,
  56};
  57use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  58use util::{debug_panic, defer};
  59use workspace::{
  60    CollaboratorId, MultiWorkspace, NewTerminal, Toast, Workspace, notifications::NotificationId,
  61};
  62use zed_actions::agent::{Chat, ToggleModelSelector};
  63use zed_actions::assistant::OpenRulesLibrary;
  64
  65use super::config_options::ConfigOptionsView;
  66use super::entry_view_state::EntryViewState;
  67use super::thread_history::ThreadHistory;
  68use crate::ModeSelector;
  69use crate::ModelSelectorPopover;
  70use crate::agent_connection_store::{
  71    AgentConnectedState, AgentConnectionEntryEvent, AgentConnectionStore,
  72};
  73use crate::agent_diff::AgentDiff;
  74use crate::entry_view_state::{EntryViewEvent, ViewEvent};
  75use crate::message_editor::{MessageEditor, MessageEditorEvent};
  76use crate::profile_selector::{ProfileProvider, ProfileSelector};
  77use crate::ui::{AgentNotification, AgentNotificationEvent};
  78use crate::{
  79    Agent, AgentDiffPane, AgentInitialContent, AgentPanel, AllowAlways, AllowOnce,
  80    AuthorizeToolCall, ClearMessageQueue, CycleFavoriteModels, CycleModeSelector,
  81    CycleThinkingEffort, EditFirstQueuedMessage, ExpandMessageEditor, Follow, KeepAll, NewThread,
  82    OpenAddContextMenu, OpenAgentDiff, OpenHistory, RejectAll, RejectOnce,
  83    RemoveFirstQueuedMessage, SendImmediately, SendNextQueuedMessage, ToggleFastMode,
  84    ToggleProfileSelector, ToggleThinkingEffortMenu, ToggleThinkingMode, UndoLastReject,
  85};
  86
  87const STOPWATCH_THRESHOLD: Duration = Duration::from_secs(30);
  88const TOKEN_THRESHOLD: u64 = 250;
  89
  90mod thread_view;
  91pub use thread_view::*;
  92
  93pub struct QueuedMessage {
  94    pub content: Vec<acp::ContentBlock>,
  95    pub tracked_buffers: Vec<Entity<Buffer>>,
  96}
  97
  98#[derive(Copy, Clone, Debug, PartialEq, Eq)]
  99enum ThreadFeedback {
 100    Positive,
 101    Negative,
 102}
 103
 104#[derive(Debug)]
 105pub(crate) enum ThreadError {
 106    PaymentRequired,
 107    Refusal,
 108    AuthenticationRequired(SharedString),
 109    Other {
 110        message: SharedString,
 111        acp_error_code: Option<SharedString>,
 112    },
 113}
 114
 115impl From<anyhow::Error> for ThreadError {
 116    fn from(error: anyhow::Error) -> Self {
 117        if error.is::<language_model::PaymentRequiredError>() {
 118            Self::PaymentRequired
 119        } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
 120            && acp_error.code == acp::ErrorCode::AuthRequired
 121        {
 122            Self::AuthenticationRequired(acp_error.message.clone().into())
 123        } else {
 124            let message: SharedString = format!("{:#}", error).into();
 125
 126            // Extract ACP error code if available
 127            let acp_error_code = error
 128                .downcast_ref::<acp::Error>()
 129                .map(|acp_error| SharedString::from(acp_error.code.to_string()));
 130
 131            Self::Other {
 132                message,
 133                acp_error_code,
 134            }
 135        }
 136    }
 137}
 138
 139impl ProfileProvider for Entity<agent::Thread> {
 140    fn profile_id(&self, cx: &App) -> AgentProfileId {
 141        self.read(cx).profile().clone()
 142    }
 143
 144    fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
 145        self.update(cx, |thread, cx| {
 146            // Apply the profile and let the thread swap to its default model.
 147            thread.set_profile(profile_id, cx);
 148        });
 149    }
 150
 151    fn profiles_supported(&self, cx: &App) -> bool {
 152        self.read(cx)
 153            .model()
 154            .is_some_and(|model| model.supports_tools())
 155    }
 156}
 157
 158#[derive(Default)]
 159pub(crate) struct Conversation {
 160    threads: HashMap<acp::SessionId, Entity<AcpThread>>,
 161    permission_requests: IndexMap<acp::SessionId, Vec<acp::ToolCallId>>,
 162    subscriptions: Vec<Subscription>,
 163    /// Tracks the selected granularity index for each tool call's permission dropdown.
 164    /// The index corresponds to the position in the allow_options list.
 165    selected_permission_granularity: HashMap<acp::SessionId, HashMap<acp::ToolCallId, usize>>,
 166}
 167
 168impl Conversation {
 169    pub fn register_thread(&mut self, thread: Entity<AcpThread>, cx: &mut Context<Self>) {
 170        let session_id = thread.read(cx).session_id().clone();
 171        let subscription = cx.subscribe(&thread, move |this, _thread, event, _cx| match event {
 172            AcpThreadEvent::ToolAuthorizationRequested(id) => {
 173                this.permission_requests
 174                    .entry(session_id.clone())
 175                    .or_default()
 176                    .push(id.clone());
 177            }
 178            AcpThreadEvent::ToolAuthorizationReceived(id) => {
 179                if let Some(tool_calls) = this.permission_requests.get_mut(&session_id) {
 180                    tool_calls.retain(|tool_call_id| tool_call_id != id);
 181                    if tool_calls.is_empty() {
 182                        this.permission_requests.shift_remove(&session_id);
 183                    }
 184                }
 185            }
 186            AcpThreadEvent::NewEntry
 187            | AcpThreadEvent::TitleUpdated
 188            | AcpThreadEvent::TokenUsageUpdated
 189            | AcpThreadEvent::EntryUpdated(_)
 190            | AcpThreadEvent::EntriesRemoved(_)
 191            | AcpThreadEvent::Retry(_)
 192            | AcpThreadEvent::SubagentSpawned(_)
 193            | AcpThreadEvent::Stopped(_)
 194            | AcpThreadEvent::Error
 195            | AcpThreadEvent::LoadError(_)
 196            | AcpThreadEvent::PromptCapabilitiesUpdated
 197            | AcpThreadEvent::Refusal
 198            | AcpThreadEvent::AvailableCommandsUpdated(_)
 199            | AcpThreadEvent::ModeUpdated(_)
 200            | AcpThreadEvent::ConfigOptionsUpdated(_) => {}
 201        });
 202        self.subscriptions.push(subscription);
 203        self.threads
 204            .insert(thread.read(cx).session_id().clone(), thread);
 205    }
 206
 207    pub fn selected_permission_granularity(
 208        &self,
 209        session_id: &acp::SessionId,
 210        tool_call_id: &acp::ToolCallId,
 211    ) -> Option<usize> {
 212        self.selected_permission_granularity
 213            .get(session_id)
 214            .and_then(|map| map.get(tool_call_id))
 215            .copied()
 216    }
 217
 218    pub fn set_selected_permission_granularity(
 219        &mut self,
 220        session_id: acp::SessionId,
 221        tool_call_id: acp::ToolCallId,
 222        granularity: usize,
 223    ) {
 224        self.selected_permission_granularity
 225            .entry(session_id)
 226            .or_default()
 227            .insert(tool_call_id, granularity);
 228    }
 229
 230    pub fn pending_tool_call<'a>(
 231        &'a self,
 232        session_id: &acp::SessionId,
 233        cx: &'a App,
 234    ) -> Option<(acp::SessionId, acp::ToolCallId, &'a PermissionOptions)> {
 235        let thread = self.threads.get(session_id)?;
 236        let is_subagent = thread.read(cx).parent_session_id().is_some();
 237        let (thread, tool_id) = if is_subagent {
 238            let id = self.permission_requests.get(session_id)?.iter().next()?;
 239            (thread, id)
 240        } else {
 241            let (id, tool_calls) = self.permission_requests.first()?;
 242            let thread = self.threads.get(id)?;
 243            let id = tool_calls.iter().next()?;
 244            (thread, id)
 245        };
 246        let (_, tool_call) = thread.read(cx).tool_call(tool_id)?;
 247
 248        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
 249            return None;
 250        };
 251        Some((
 252            thread.read(cx).session_id().clone(),
 253            tool_id.clone(),
 254            options,
 255        ))
 256    }
 257
 258    pub fn authorize_pending_tool_call(
 259        &mut self,
 260        session_id: &acp::SessionId,
 261        kind: acp::PermissionOptionKind,
 262        cx: &mut Context<Self>,
 263    ) -> Option<()> {
 264        let (_, tool_call_id, options) = self.pending_tool_call(session_id, cx)?;
 265        let option = options.first_option_of_kind(kind)?;
 266        self.authorize_tool_call(
 267            session_id.clone(),
 268            tool_call_id,
 269            option.option_id.clone(),
 270            option.kind,
 271            cx,
 272        );
 273        Some(())
 274    }
 275
 276    pub fn authorize_tool_call(
 277        &mut self,
 278        session_id: acp::SessionId,
 279        tool_call_id: acp::ToolCallId,
 280        option_id: acp::PermissionOptionId,
 281        option_kind: acp::PermissionOptionKind,
 282        cx: &mut Context<Self>,
 283    ) {
 284        let Some(thread) = self.threads.get(&session_id) else {
 285            return;
 286        };
 287        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 288
 289        telemetry::event!(
 290            "Agent Tool Call Authorized",
 291            agent = agent_telemetry_id,
 292            session = session_id,
 293            option = option_kind
 294        );
 295
 296        thread.update(cx, |thread, cx| {
 297            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 298        });
 299        cx.notify();
 300    }
 301}
 302
 303pub enum AcpServerViewEvent {
 304    ActiveThreadChanged,
 305}
 306
 307impl EventEmitter<AcpServerViewEvent> for ConnectionView {}
 308
 309pub struct ConnectionView {
 310    agent: Rc<dyn AgentServer>,
 311    connection_store: Entity<AgentConnectionStore>,
 312    connection_key: Agent,
 313    agent_server_store: Entity<AgentServerStore>,
 314    workspace: WeakEntity<Workspace>,
 315    project: Entity<Project>,
 316    thread_store: Option<Entity<ThreadStore>>,
 317    prompt_store: Option<Entity<PromptStore>>,
 318    server_state: ServerState,
 319    focus_handle: FocusHandle,
 320    notifications: Vec<WindowHandle<AgentNotification>>,
 321    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 322    auth_task: Option<Task<()>>,
 323    _subscriptions: Vec<Subscription>,
 324}
 325
 326impl ConnectionView {
 327    pub fn has_auth_methods(&self) -> bool {
 328        self.as_connected().map_or(false, |connected| {
 329            !connected.connection.auth_methods().is_empty()
 330        })
 331    }
 332
 333    pub fn active_thread(&self) -> Option<&Entity<ThreadView>> {
 334        match &self.server_state {
 335            ServerState::Connected(connected) => connected.active_view(),
 336            _ => None,
 337        }
 338    }
 339
 340    pub fn pending_tool_call<'a>(
 341        &'a self,
 342        cx: &'a App,
 343    ) -> Option<(acp::SessionId, acp::ToolCallId, &'a PermissionOptions)> {
 344        let id = &self.active_thread()?.read(cx).id;
 345        self.as_connected()?
 346            .conversation
 347            .read(cx)
 348            .pending_tool_call(id, cx)
 349    }
 350
 351    pub fn parent_thread(&self, cx: &App) -> Option<Entity<ThreadView>> {
 352        match &self.server_state {
 353            ServerState::Connected(connected) => {
 354                let mut current = connected.active_view()?;
 355                while let Some(parent_id) = current.read(cx).parent_id.clone() {
 356                    if let Some(parent) = connected.threads.get(&parent_id) {
 357                        current = parent;
 358                    } else {
 359                        break;
 360                    }
 361                }
 362                Some(current.clone())
 363            }
 364            _ => None,
 365        }
 366    }
 367
 368    pub fn thread_view(&self, session_id: &acp::SessionId) -> Option<Entity<ThreadView>> {
 369        let connected = self.as_connected()?;
 370        connected.threads.get(session_id).cloned()
 371    }
 372
 373    pub fn as_connected(&self) -> Option<&ConnectedServerState> {
 374        match &self.server_state {
 375            ServerState::Connected(connected) => Some(connected),
 376            _ => None,
 377        }
 378    }
 379
 380    pub fn as_connected_mut(&mut self) -> Option<&mut ConnectedServerState> {
 381        match &mut self.server_state {
 382            ServerState::Connected(connected) => Some(connected),
 383            _ => None,
 384        }
 385    }
 386
 387    pub fn navigate_to_session(
 388        &mut self,
 389        session_id: acp::SessionId,
 390        window: &mut Window,
 391        cx: &mut Context<Self>,
 392    ) {
 393        let Some(connected) = self.as_connected_mut() else {
 394            return;
 395        };
 396
 397        connected.navigate_to_session(session_id);
 398        if let Some(view) = self.active_thread() {
 399            view.focus_handle(cx).focus(window, cx);
 400        }
 401        cx.emit(AcpServerViewEvent::ActiveThreadChanged);
 402        cx.notify();
 403    }
 404}
 405
 406enum ServerState {
 407    Loading(Entity<LoadingView>),
 408    LoadError {
 409        error: LoadError,
 410        session_id: Option<acp::SessionId>,
 411    },
 412    Connected(ConnectedServerState),
 413}
 414
 415// current -> Entity
 416// hashmap of threads, current becomes session_id
 417pub struct ConnectedServerState {
 418    auth_state: AuthState,
 419    active_id: Option<acp::SessionId>,
 420    threads: HashMap<acp::SessionId, Entity<ThreadView>>,
 421    connection: Rc<dyn AgentConnection>,
 422    history: Entity<ThreadHistory>,
 423    conversation: Entity<Conversation>,
 424    _connection_entry_subscription: Subscription,
 425}
 426
 427enum AuthState {
 428    Ok,
 429    Unauthenticated {
 430        description: Option<Entity<Markdown>>,
 431        configuration_view: Option<AnyView>,
 432        pending_auth_method: Option<acp::AuthMethodId>,
 433        _subscription: Option<Subscription>,
 434    },
 435}
 436
 437impl AuthState {
 438    pub fn is_ok(&self) -> bool {
 439        matches!(self, Self::Ok)
 440    }
 441}
 442
 443struct LoadingView {
 444    session_id: Option<acp::SessionId>,
 445    _load_task: Task<()>,
 446}
 447
 448impl ConnectedServerState {
 449    pub fn active_view(&self) -> Option<&Entity<ThreadView>> {
 450        self.active_id.as_ref().and_then(|id| self.threads.get(id))
 451    }
 452
 453    pub fn has_thread_error(&self, cx: &App) -> bool {
 454        self.active_view()
 455            .map_or(false, |view| view.read(cx).thread_error.is_some())
 456    }
 457
 458    pub fn navigate_to_session(&mut self, session_id: acp::SessionId) {
 459        if self.threads.contains_key(&session_id) {
 460            self.active_id = Some(session_id);
 461        }
 462    }
 463
 464    pub fn close_all_sessions(&self, cx: &mut App) -> Task<()> {
 465        let tasks = self.threads.keys().filter_map(|id| {
 466            if self.connection.supports_close_session() {
 467                Some(self.connection.clone().close_session(id, cx))
 468            } else {
 469                None
 470            }
 471        });
 472        let task = futures::future::join_all(tasks);
 473        cx.background_spawn(async move {
 474            task.await;
 475        })
 476    }
 477}
 478
 479impl ConnectionView {
 480    pub fn new(
 481        agent: Rc<dyn AgentServer>,
 482        connection_store: Entity<AgentConnectionStore>,
 483        connection_key: Agent,
 484        resume_session_id: Option<acp::SessionId>,
 485        cwd: Option<PathBuf>,
 486        title: Option<SharedString>,
 487        initial_content: Option<AgentInitialContent>,
 488        workspace: WeakEntity<Workspace>,
 489        project: Entity<Project>,
 490        thread_store: Option<Entity<ThreadStore>>,
 491        prompt_store: Option<Entity<PromptStore>>,
 492        window: &mut Window,
 493        cx: &mut Context<Self>,
 494    ) -> Self {
 495        let agent_server_store = project.read(cx).agent_server_store().clone();
 496        let subscriptions = vec![
 497            cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
 498            cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
 499            cx.subscribe_in(
 500                &agent_server_store,
 501                window,
 502                Self::handle_agent_servers_updated,
 503            ),
 504        ];
 505
 506        cx.on_release(|this, cx| {
 507            if let Some(connected) = this.as_connected() {
 508                connected.close_all_sessions(cx).detach();
 509            }
 510            for window in this.notifications.drain(..) {
 511                window
 512                    .update(cx, |_, window, _| {
 513                        window.remove_window();
 514                    })
 515                    .ok();
 516            }
 517        })
 518        .detach();
 519
 520        Self {
 521            agent: agent.clone(),
 522            connection_store: connection_store.clone(),
 523            connection_key: connection_key.clone(),
 524            agent_server_store,
 525            workspace,
 526            project: project.clone(),
 527            thread_store,
 528            prompt_store,
 529            server_state: Self::initial_state(
 530                agent.clone(),
 531                connection_store,
 532                connection_key,
 533                resume_session_id,
 534                cwd,
 535                title,
 536                project,
 537                initial_content,
 538                window,
 539                cx,
 540            ),
 541            notifications: Vec::new(),
 542            notification_subscriptions: HashMap::default(),
 543            auth_task: None,
 544            _subscriptions: subscriptions,
 545            focus_handle: cx.focus_handle(),
 546        }
 547    }
 548
 549    fn set_server_state(&mut self, state: ServerState, cx: &mut Context<Self>) {
 550        if let Some(connected) = self.as_connected() {
 551            connected.close_all_sessions(cx).detach();
 552        }
 553
 554        self.server_state = state;
 555        cx.emit(AcpServerViewEvent::ActiveThreadChanged);
 556        cx.notify();
 557    }
 558
 559    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 560        let (resume_session_id, cwd, title) = self
 561            .active_thread()
 562            .map(|thread_view| {
 563                let thread = thread_view.read(cx).thread.read(cx);
 564                (
 565                    Some(thread.session_id().clone()),
 566                    thread.cwd().cloned(),
 567                    Some(thread.title()),
 568                )
 569            })
 570            .unwrap_or((None, None, None));
 571
 572        let state = Self::initial_state(
 573            self.agent.clone(),
 574            self.connection_store.clone(),
 575            self.connection_key.clone(),
 576            resume_session_id,
 577            cwd,
 578            title,
 579            self.project.clone(),
 580            None,
 581            window,
 582            cx,
 583        );
 584        self.set_server_state(state, cx);
 585
 586        if let Some(view) = self.active_thread() {
 587            view.update(cx, |this, cx| {
 588                this.message_editor.update(cx, |editor, cx| {
 589                    editor.set_command_state(
 590                        this.prompt_capabilities.clone(),
 591                        this.available_commands.clone(),
 592                        cx,
 593                    );
 594                });
 595            });
 596        }
 597        cx.notify();
 598    }
 599
 600    fn initial_state(
 601        agent: Rc<dyn AgentServer>,
 602        connection_store: Entity<AgentConnectionStore>,
 603        connection_key: Agent,
 604        resume_session_id: Option<acp::SessionId>,
 605        cwd: Option<PathBuf>,
 606        title: Option<SharedString>,
 607        project: Entity<Project>,
 608        initial_content: Option<AgentInitialContent>,
 609        window: &mut Window,
 610        cx: &mut Context<Self>,
 611    ) -> ServerState {
 612        if project.read(cx).is_via_collab()
 613            && agent.clone().downcast::<NativeAgentServer>().is_none()
 614        {
 615            return ServerState::LoadError {
 616                error: LoadError::Other(
 617                    "External agents are not yet supported in shared projects.".into(),
 618                ),
 619                session_id: resume_session_id.clone(),
 620            };
 621        }
 622        let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 623        // Pick the first non-single-file worktree for the root directory if there are any,
 624        // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
 625        worktrees.sort_by(|l, r| {
 626            l.read(cx)
 627                .is_single_file()
 628                .cmp(&r.read(cx).is_single_file())
 629        });
 630        let worktree_roots: Vec<Arc<Path>> = worktrees
 631            .iter()
 632            .filter_map(|worktree| {
 633                let worktree = worktree.read(cx);
 634                if worktree.is_single_file() {
 635                    Some(worktree.abs_path().parent()?.into())
 636                } else {
 637                    Some(worktree.abs_path())
 638                }
 639            })
 640            .collect();
 641        let session_cwd = cwd
 642            .filter(|cwd| {
 643                // Validate with the normalized path (rejects `..` traversals),
 644                // but return the original cwd to preserve its path separators.
 645                // On Windows, `normalize_lexically` rebuilds the path with
 646                // backslashes via `PathBuf::push`, which would corrupt
 647                // forward-slash Linux paths used by WSL agents.
 648                util::paths::normalize_lexically(cwd)
 649                    .ok()
 650                    .is_some_and(|normalized| {
 651                        worktree_roots
 652                            .iter()
 653                            .any(|root| normalized.starts_with(root.as_ref()))
 654                    })
 655            })
 656            .map(|path| path.into())
 657            .or_else(|| worktree_roots.first().cloned())
 658            .unwrap_or_else(|| paths::home_dir().as_path().into());
 659
 660        let connection_entry = connection_store.update(cx, |store, cx| {
 661            store.request_connection(connection_key, agent.clone(), cx)
 662        });
 663
 664        let connection_entry_subscription =
 665            cx.subscribe(&connection_entry, |this, _entry, event, cx| match event {
 666                AgentConnectionEntryEvent::NewVersionAvailable(version) => {
 667                    if let Some(thread) = this.active_thread() {
 668                        thread.update(cx, |thread, cx| {
 669                            thread.new_server_version_available = Some(version.clone());
 670                            cx.notify();
 671                        });
 672                    }
 673                }
 674            });
 675
 676        let connect_result = connection_entry.read(cx).wait_for_connection();
 677
 678        let load_session_id = resume_session_id.clone();
 679        let load_task = cx.spawn_in(window, async move |this, cx| {
 680            let (connection, history) = match connect_result.await {
 681                Ok(AgentConnectedState {
 682                    connection,
 683                    history,
 684                }) => (connection, history),
 685                Err(err) => {
 686                    this.update_in(cx, |this, window, cx| {
 687                        this.handle_load_error(load_session_id.clone(), err, window, cx);
 688                        cx.notify();
 689                    })
 690                    .log_err();
 691                    return;
 692                }
 693            };
 694
 695            telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
 696
 697            let mut resumed_without_history = false;
 698            let result = if let Some(session_id) = load_session_id.clone() {
 699                cx.update(|_, cx| {
 700                    if connection.supports_load_session() {
 701                        connection.clone().load_session(
 702                            session_id,
 703                            project.clone(),
 704                            &session_cwd,
 705                            title,
 706                            cx,
 707                        )
 708                    } else if connection.supports_resume_session() {
 709                        resumed_without_history = true;
 710                        connection.clone().resume_session(
 711                            session_id,
 712                            project.clone(),
 713                            &session_cwd,
 714                            title,
 715                            cx,
 716                        )
 717                    } else {
 718                        Task::ready(Err(anyhow!(LoadError::Other(
 719                            "Loading or resuming sessions is not supported by this agent.".into()
 720                        ))))
 721                    }
 722                })
 723                .log_err()
 724            } else {
 725                cx.update(|_, cx| {
 726                    connection
 727                        .clone()
 728                        .new_session(project.clone(), session_cwd.as_ref(), cx)
 729                })
 730                .log_err()
 731            };
 732
 733            let Some(result) = result else {
 734                return;
 735            };
 736
 737            let result = match result.await {
 738                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 739                    Ok(err) => {
 740                        cx.update(|window, cx| {
 741                            Self::handle_auth_required(
 742                                this,
 743                                err,
 744                                agent.name(),
 745                                connection,
 746                                window,
 747                                cx,
 748                            )
 749                        })
 750                        .log_err();
 751                        return;
 752                    }
 753                    Err(err) => Err(err),
 754                },
 755                Ok(thread) => Ok(thread),
 756            };
 757
 758            this.update_in(cx, |this, window, cx| {
 759                match result {
 760                    Ok(thread) => {
 761                        let conversation = cx.new(|cx| {
 762                            let mut conversation = Conversation::default();
 763                            conversation.register_thread(thread.clone(), cx);
 764                            conversation
 765                        });
 766
 767                        let current = this.new_thread_view(
 768                            None,
 769                            thread,
 770                            conversation.clone(),
 771                            resumed_without_history,
 772                            initial_content,
 773                            history.clone(),
 774                            window,
 775                            cx,
 776                        );
 777
 778                        if this.focus_handle.contains_focused(window, cx) {
 779                            current
 780                                .read(cx)
 781                                .message_editor
 782                                .focus_handle(cx)
 783                                .focus(window, cx);
 784                        }
 785
 786                        let id = current.read(cx).thread.read(cx).session_id().clone();
 787                        this.set_server_state(
 788                            ServerState::Connected(ConnectedServerState {
 789                                connection,
 790                                auth_state: AuthState::Ok,
 791                                active_id: Some(id.clone()),
 792                                threads: HashMap::from_iter([(id, current)]),
 793                                conversation,
 794                                history,
 795                                _connection_entry_subscription: connection_entry_subscription,
 796                            }),
 797                            cx,
 798                        );
 799                    }
 800                    Err(err) => {
 801                        this.handle_load_error(
 802                            load_session_id.clone(),
 803                            LoadError::Other(err.to_string().into()),
 804                            window,
 805                            cx,
 806                        );
 807                    }
 808                };
 809            })
 810            .log_err();
 811        });
 812
 813        let loading_view = cx.new(|_cx| LoadingView {
 814            session_id: resume_session_id,
 815            _load_task: load_task,
 816        });
 817
 818        ServerState::Loading(loading_view)
 819    }
 820
 821    fn new_thread_view(
 822        &self,
 823        parent_id: Option<acp::SessionId>,
 824        thread: Entity<AcpThread>,
 825        conversation: Entity<Conversation>,
 826        resumed_without_history: bool,
 827        initial_content: Option<AgentInitialContent>,
 828        history: Entity<ThreadHistory>,
 829        window: &mut Window,
 830        cx: &mut Context<Self>,
 831    ) -> Entity<ThreadView> {
 832        let agent_name = self.agent.name();
 833        let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
 834        let available_commands = Rc::new(RefCell::new(vec![]));
 835
 836        let action_log = thread.read(cx).action_log().clone();
 837
 838        prompt_capabilities.replace(thread.read(cx).prompt_capabilities());
 839
 840        let entry_view_state = cx.new(|_| {
 841            EntryViewState::new(
 842                self.workspace.clone(),
 843                self.project.downgrade(),
 844                self.thread_store.clone(),
 845                history.downgrade(),
 846                self.prompt_store.clone(),
 847                prompt_capabilities.clone(),
 848                available_commands.clone(),
 849                self.agent.name(),
 850            )
 851        });
 852
 853        let count = thread.read(cx).entries().len();
 854        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 855        entry_view_state.update(cx, |view_state, cx| {
 856            for ix in 0..count {
 857                view_state.sync_entry(ix, &thread, window, cx);
 858            }
 859            list_state.splice_focusable(
 860                0..0,
 861                (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
 862            );
 863        });
 864
 865        if let Some(scroll_position) = thread.read(cx).ui_scroll_position() {
 866            list_state.scroll_to(scroll_position);
 867        }
 868
 869        AgentDiff::set_active_thread(&self.workspace, thread.clone(), window, cx);
 870
 871        let connection = thread.read(cx).connection().clone();
 872        let session_id = thread.read(cx).session_id().clone();
 873
 874        // Check for config options first
 875        // Config options take precedence over legacy mode/model selectors
 876        // (feature flag gating happens at the data layer)
 877        let config_options_provider = connection.session_config_options(&session_id, cx);
 878
 879        let config_options_view;
 880        let mode_selector;
 881        let model_selector;
 882        if let Some(config_options) = config_options_provider {
 883            // Use config options - don't create mode_selector or model_selector
 884            let agent_server = self.agent.clone();
 885            let fs = self.project.read(cx).fs().clone();
 886            config_options_view =
 887                Some(cx.new(|cx| {
 888                    ConfigOptionsView::new(config_options, agent_server, fs, window, cx)
 889                }));
 890            model_selector = None;
 891            mode_selector = None;
 892        } else {
 893            // Fall back to legacy mode/model selectors
 894            config_options_view = None;
 895            model_selector = connection.model_selector(&session_id).map(|selector| {
 896                let agent_server = self.agent.clone();
 897                let fs = self.project.read(cx).fs().clone();
 898                cx.new(|cx| {
 899                    ModelSelectorPopover::new(
 900                        selector,
 901                        agent_server,
 902                        fs,
 903                        PopoverMenuHandle::default(),
 904                        self.focus_handle(cx),
 905                        window,
 906                        cx,
 907                    )
 908                })
 909            });
 910
 911            mode_selector = connection
 912                .session_modes(&session_id, cx)
 913                .map(|session_modes| {
 914                    let fs = self.project.read(cx).fs().clone();
 915                    cx.new(|_cx| ModeSelector::new(session_modes, self.agent.clone(), fs))
 916                });
 917        }
 918
 919        let subscriptions = vec![
 920            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 921            cx.observe(&action_log, |_, _, cx| cx.notify()),
 922        ];
 923
 924        let parent_session_id = thread.read(cx).session_id().clone();
 925        let subagent_sessions = thread
 926            .read(cx)
 927            .entries()
 928            .iter()
 929            .filter_map(|entry| match entry {
 930                AgentThreadEntry::ToolCall(call) => call
 931                    .subagent_session_info
 932                    .as_ref()
 933                    .map(|i| i.session_id.clone()),
 934                _ => None,
 935            })
 936            .collect::<Vec<_>>();
 937
 938        if !subagent_sessions.is_empty() {
 939            cx.spawn_in(window, async move |this, cx| {
 940                this.update_in(cx, |this, window, cx| {
 941                    for subagent_id in subagent_sessions {
 942                        this.load_subagent_session(
 943                            subagent_id,
 944                            parent_session_id.clone(),
 945                            window,
 946                            cx,
 947                        );
 948                    }
 949                })
 950            })
 951            .detach();
 952        }
 953
 954        let profile_selector: Option<Rc<agent::NativeAgentConnection>> =
 955            connection.clone().downcast();
 956        let profile_selector = profile_selector
 957            .and_then(|native_connection| native_connection.thread(&session_id, cx))
 958            .map(|native_thread| {
 959                cx.new(|cx| {
 960                    ProfileSelector::new(
 961                        <dyn Fs>::global(cx),
 962                        Arc::new(native_thread),
 963                        self.focus_handle(cx),
 964                        cx,
 965                    )
 966                })
 967            });
 968
 969        let agent_display_name = self
 970            .agent_server_store
 971            .read(cx)
 972            .agent_display_name(&ExternalAgentServerName(agent_name.clone()))
 973            .unwrap_or_else(|| agent_name.clone());
 974
 975        let agent_icon = self.agent.logo();
 976        let agent_icon_from_external_svg = self
 977            .agent_server_store
 978            .read(cx)
 979            .agent_icon(&ExternalAgentServerName(self.agent.name()))
 980            .or_else(|| {
 981                project::AgentRegistryStore::try_global(cx).and_then(|store| {
 982                    store
 983                        .read(cx)
 984                        .agent(self.agent.name().as_ref())
 985                        .and_then(|a| a.icon_path().cloned())
 986                })
 987            });
 988
 989        let weak = cx.weak_entity();
 990        cx.new(|cx| {
 991            ThreadView::new(
 992                parent_id,
 993                thread,
 994                conversation,
 995                weak,
 996                agent_icon,
 997                agent_icon_from_external_svg,
 998                agent_name,
 999                agent_display_name,
1000                self.workspace.clone(),
1001                entry_view_state,
1002                config_options_view,
1003                mode_selector,
1004                model_selector,
1005                profile_selector,
1006                list_state,
1007                prompt_capabilities,
1008                available_commands,
1009                resumed_without_history,
1010                self.project.downgrade(),
1011                self.thread_store.clone(),
1012                history,
1013                self.prompt_store.clone(),
1014                initial_content,
1015                subscriptions,
1016                window,
1017                cx,
1018            )
1019        })
1020    }
1021
1022    fn handle_auth_required(
1023        this: WeakEntity<Self>,
1024        err: AuthRequired,
1025        agent_name: SharedString,
1026        connection: Rc<dyn AgentConnection>,
1027        window: &mut Window,
1028        cx: &mut App,
1029    ) {
1030        let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
1031            let registry = LanguageModelRegistry::global(cx);
1032
1033            let sub = window.subscribe(&registry, cx, {
1034                let provider_id = provider_id.clone();
1035                let this = this.clone();
1036                move |_, ev, window, cx| {
1037                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
1038                        && &provider_id == updated_provider_id
1039                        && LanguageModelRegistry::global(cx)
1040                            .read(cx)
1041                            .provider(&provider_id)
1042                            .map_or(false, |provider| provider.is_authenticated(cx))
1043                    {
1044                        this.update(cx, |this, cx| {
1045                            this.reset(window, cx);
1046                        })
1047                        .ok();
1048                    }
1049                }
1050            });
1051
1052            let view = registry.read(cx).provider(&provider_id).map(|provider| {
1053                provider.configuration_view(
1054                    language_model::ConfigurationViewTargetAgent::Other(agent_name),
1055                    window,
1056                    cx,
1057                )
1058            });
1059
1060            (view, Some(sub))
1061        } else {
1062            (None, None)
1063        };
1064
1065        this.update(cx, |this, cx| {
1066            let description = err
1067                .description
1068                .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx)));
1069            let auth_state = AuthState::Unauthenticated {
1070                pending_auth_method: None,
1071                configuration_view,
1072                description,
1073                _subscription: subscription,
1074            };
1075            if let Some(connected) = this.as_connected_mut() {
1076                connected.auth_state = auth_state;
1077                if let Some(view) = connected.active_view()
1078                    && view
1079                        .read(cx)
1080                        .message_editor
1081                        .focus_handle(cx)
1082                        .is_focused(window)
1083                {
1084                    this.focus_handle.focus(window, cx)
1085                }
1086            } else {
1087                this.set_server_state(
1088                    ServerState::Connected(ConnectedServerState {
1089                        auth_state,
1090                        active_id: None,
1091                        threads: HashMap::default(),
1092                        connection,
1093                        conversation: cx.new(|_cx| Conversation::default()),
1094                        history: cx.new(|cx| ThreadHistory::new(None, cx)),
1095                        _connection_entry_subscription: Subscription::new(|| {}),
1096                    }),
1097                    cx,
1098                );
1099            }
1100            cx.notify();
1101        })
1102        .ok();
1103    }
1104
1105    fn handle_load_error(
1106        &mut self,
1107        session_id: Option<acp::SessionId>,
1108        err: LoadError,
1109        window: &mut Window,
1110        cx: &mut Context<Self>,
1111    ) {
1112        if let Some(view) = self.active_thread() {
1113            if view
1114                .read(cx)
1115                .message_editor
1116                .focus_handle(cx)
1117                .is_focused(window)
1118            {
1119                self.focus_handle.focus(window, cx)
1120            }
1121        }
1122        self.emit_load_error_telemetry(&err);
1123        self.set_server_state(
1124            ServerState::LoadError {
1125                error: err,
1126                session_id,
1127            },
1128            cx,
1129        );
1130    }
1131
1132    fn handle_agent_servers_updated(
1133        &mut self,
1134        _agent_server_store: &Entity<project::AgentServerStore>,
1135        _event: &project::AgentServersUpdated,
1136        window: &mut Window,
1137        cx: &mut Context<Self>,
1138    ) {
1139        // If we're in a LoadError state OR have a thread_error set (which can happen
1140        // when agent.connect() fails during loading), retry loading the thread.
1141        // This handles the case where a thread is restored before authentication completes.
1142        let should_retry = match &self.server_state {
1143            ServerState::Loading(_) => false,
1144            ServerState::LoadError { .. } => true,
1145            ServerState::Connected(connected) => {
1146                connected.auth_state.is_ok() && connected.has_thread_error(cx)
1147            }
1148        };
1149
1150        if should_retry {
1151            if let Some(active) = self.active_thread() {
1152                active.update(cx, |active, cx| {
1153                    active.clear_thread_error(cx);
1154                });
1155            }
1156            self.reset(window, cx);
1157        }
1158    }
1159
1160    pub fn workspace(&self) -> &WeakEntity<Workspace> {
1161        &self.workspace
1162    }
1163
1164    pub fn title(&self, _cx: &App) -> SharedString {
1165        match &self.server_state {
1166            ServerState::Connected(_) => "New Thread".into(),
1167            ServerState::Loading(_) => "Loading…".into(),
1168            ServerState::LoadError { error, .. } => match error {
1169                LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
1170                LoadError::FailedToInstall(_) => {
1171                    format!("Failed to Install {}", self.agent.name()).into()
1172                }
1173                LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
1174                LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
1175            },
1176        }
1177    }
1178
1179    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
1180        if let Some(active) = self.active_thread() {
1181            active.update(cx, |active, cx| {
1182                active.cancel_generation(cx);
1183            });
1184        }
1185    }
1186
1187    // The parent ID is None if we haven't created a thread yet
1188    pub fn parent_id(&self, cx: &App) -> Option<acp::SessionId> {
1189        match &self.server_state {
1190            ServerState::Connected(_) => self
1191                .parent_thread(cx)
1192                .map(|thread| thread.read(cx).id.clone()),
1193            ServerState::Loading(loading) => loading.read(cx).session_id.clone(),
1194            ServerState::LoadError { session_id, .. } => session_id.clone(),
1195        }
1196    }
1197
1198    pub fn is_loading(&self) -> bool {
1199        matches!(self.server_state, ServerState::Loading { .. })
1200    }
1201
1202    fn update_turn_tokens(&mut self, cx: &mut Context<Self>) {
1203        if let Some(active) = self.active_thread() {
1204            active.update(cx, |active, cx| {
1205                active.update_turn_tokens(cx);
1206            });
1207        }
1208    }
1209
1210    fn send_queued_message_at_index(
1211        &mut self,
1212        index: usize,
1213        is_send_now: bool,
1214        window: &mut Window,
1215        cx: &mut Context<Self>,
1216    ) {
1217        if let Some(active) = self.active_thread() {
1218            active.update(cx, |active, cx| {
1219                active.send_queued_message_at_index(index, is_send_now, window, cx);
1220            });
1221        }
1222    }
1223
1224    fn move_queued_message_to_main_editor(
1225        &mut self,
1226        index: usize,
1227        inserted_text: Option<&str>,
1228        window: &mut Window,
1229        cx: &mut Context<Self>,
1230    ) {
1231        if let Some(active) = self.active_thread() {
1232            active.update(cx, |active, cx| {
1233                active.move_queued_message_to_main_editor(index, inserted_text, window, cx);
1234            });
1235        }
1236    }
1237
1238    fn handle_thread_event(
1239        &mut self,
1240        thread: &Entity<AcpThread>,
1241        event: &AcpThreadEvent,
1242        window: &mut Window,
1243        cx: &mut Context<Self>,
1244    ) {
1245        let thread_id = thread.read(cx).session_id().clone();
1246        let is_subagent = thread.read(cx).parent_session_id().is_some();
1247        match event {
1248            AcpThreadEvent::NewEntry => {
1249                let len = thread.read(cx).entries().len();
1250                let index = len - 1;
1251                if let Some(active) = self.thread_view(&thread_id) {
1252                    let entry_view_state = active.read(cx).entry_view_state.clone();
1253                    let list_state = active.read(cx).list_state.clone();
1254                    entry_view_state.update(cx, |view_state, cx| {
1255                        view_state.sync_entry(index, thread, window, cx);
1256                        list_state.splice_focusable(
1257                            index..index,
1258                            [view_state
1259                                .entry(index)
1260                                .and_then(|entry| entry.focus_handle(cx))],
1261                        );
1262                    });
1263                }
1264            }
1265            AcpThreadEvent::EntryUpdated(index) => {
1266                if let Some(entry_view_state) = self
1267                    .thread_view(&thread_id)
1268                    .map(|active| active.read(cx).entry_view_state.clone())
1269                {
1270                    entry_view_state.update(cx, |view_state, cx| {
1271                        view_state.sync_entry(*index, thread, window, cx)
1272                    });
1273                }
1274            }
1275            AcpThreadEvent::EntriesRemoved(range) => {
1276                if let Some(active) = self.thread_view(&thread_id) {
1277                    let entry_view_state = active.read(cx).entry_view_state.clone();
1278                    let list_state = active.read(cx).list_state.clone();
1279                    entry_view_state.update(cx, |view_state, _cx| view_state.remove(range.clone()));
1280                    list_state.splice(range.clone(), 0);
1281                }
1282            }
1283            AcpThreadEvent::SubagentSpawned(session_id) => self.load_subagent_session(
1284                session_id.clone(),
1285                thread.read(cx).session_id().clone(),
1286                window,
1287                cx,
1288            ),
1289            AcpThreadEvent::ToolAuthorizationRequested(_) => {
1290                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1291            }
1292            AcpThreadEvent::ToolAuthorizationReceived(_) => {}
1293            AcpThreadEvent::Retry(retry) => {
1294                if let Some(active) = self.thread_view(&thread_id) {
1295                    active.update(cx, |active, _cx| {
1296                        active.thread_retry_status = Some(retry.clone());
1297                    });
1298                }
1299            }
1300            AcpThreadEvent::Stopped(stop_reason) => {
1301                if let Some(active) = self.thread_view(&thread_id) {
1302                    active.update(cx, |active, _cx| {
1303                        active.thread_retry_status.take();
1304                    });
1305                }
1306                if is_subagent {
1307                    if *stop_reason == acp::StopReason::EndTurn {
1308                        thread.update(cx, |thread, cx| {
1309                            thread.mark_as_subagent_output(cx);
1310                        });
1311                    }
1312                    return;
1313                }
1314
1315                let used_tools = thread.read(cx).used_tools_since_last_user_message();
1316                self.notify_with_sound(
1317                    if used_tools {
1318                        "Finished running tools"
1319                    } else {
1320                        "New message"
1321                    },
1322                    IconName::ZedAssistant,
1323                    window,
1324                    cx,
1325                );
1326
1327                let should_send_queued = if let Some(active) = self.active_thread() {
1328                    active.update(cx, |active, cx| {
1329                        if active.skip_queue_processing_count > 0 {
1330                            active.skip_queue_processing_count -= 1;
1331                            false
1332                        } else if active.user_interrupted_generation {
1333                            // Manual interruption: don't auto-process queue.
1334                            // Reset the flag so future completions can process normally.
1335                            active.user_interrupted_generation = false;
1336                            false
1337                        } else {
1338                            let has_queued = !active.local_queued_messages.is_empty();
1339                            // Don't auto-send if the first message editor is currently focused
1340                            let is_first_editor_focused = active
1341                                .queued_message_editors
1342                                .first()
1343                                .is_some_and(|editor| editor.focus_handle(cx).is_focused(window));
1344                            has_queued && !is_first_editor_focused
1345                        }
1346                    })
1347                } else {
1348                    false
1349                };
1350                if should_send_queued {
1351                    self.send_queued_message_at_index(0, false, window, cx);
1352                }
1353            }
1354            AcpThreadEvent::Refusal => {
1355                let error = ThreadError::Refusal;
1356                if let Some(active) = self.thread_view(&thread_id) {
1357                    active.update(cx, |active, cx| {
1358                        active.handle_thread_error(error, cx);
1359                        active.thread_retry_status.take();
1360                    });
1361                }
1362                if !is_subagent {
1363                    let model_or_agent_name = self.current_model_name(cx);
1364                    let notification_message =
1365                        format!("{} refused to respond to this request", model_or_agent_name);
1366                    self.notify_with_sound(&notification_message, IconName::Warning, window, cx);
1367                }
1368            }
1369            AcpThreadEvent::Error => {
1370                if let Some(active) = self.thread_view(&thread_id) {
1371                    active.update(cx, |active, _cx| {
1372                        active.thread_retry_status.take();
1373                    });
1374                }
1375                if !is_subagent {
1376                    self.notify_with_sound(
1377                        "Agent stopped due to an error",
1378                        IconName::Warning,
1379                        window,
1380                        cx,
1381                    );
1382                }
1383            }
1384            AcpThreadEvent::LoadError(error) => {
1385                if let Some(view) = self.active_thread() {
1386                    if view
1387                        .read(cx)
1388                        .message_editor
1389                        .focus_handle(cx)
1390                        .is_focused(window)
1391                    {
1392                        self.focus_handle.focus(window, cx)
1393                    }
1394                }
1395                self.set_server_state(
1396                    ServerState::LoadError {
1397                        error: error.clone(),
1398                        session_id: Some(thread_id),
1399                    },
1400                    cx,
1401                );
1402            }
1403            AcpThreadEvent::TitleUpdated => {
1404                let title = thread.read(cx).title();
1405                if let Some(active_thread) = self.thread_view(&thread_id) {
1406                    let title_editor = active_thread.read(cx).title_editor.clone();
1407                    title_editor.update(cx, |editor, cx| {
1408                        if editor.text(cx) != title {
1409                            editor.set_text(title, window, cx);
1410                        }
1411                    });
1412                }
1413                cx.notify();
1414            }
1415            AcpThreadEvent::PromptCapabilitiesUpdated => {
1416                if let Some(active) = self.thread_view(&thread_id) {
1417                    active.update(cx, |active, _cx| {
1418                        active
1419                            .prompt_capabilities
1420                            .replace(thread.read(_cx).prompt_capabilities());
1421                    });
1422                }
1423            }
1424            AcpThreadEvent::TokenUsageUpdated => {
1425                self.update_turn_tokens(cx);
1426                self.emit_token_limit_telemetry_if_needed(thread, cx);
1427            }
1428            AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1429                let mut available_commands = available_commands.clone();
1430
1431                if thread
1432                    .read(cx)
1433                    .connection()
1434                    .auth_methods()
1435                    .iter()
1436                    .any(|method| method.id().0.as_ref() == "claude-login")
1437                {
1438                    available_commands.push(acp::AvailableCommand::new("login", "Authenticate"));
1439                    available_commands.push(acp::AvailableCommand::new("logout", "Authenticate"));
1440                }
1441
1442                let has_commands = !available_commands.is_empty();
1443                if let Some(active) = self.active_thread() {
1444                    active.update(cx, |active, _cx| {
1445                        active.available_commands.replace(available_commands);
1446                    });
1447                }
1448
1449                let agent_display_name = self
1450                    .agent_server_store
1451                    .read(cx)
1452                    .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1453                    .unwrap_or_else(|| self.agent.name());
1454
1455                if let Some(active) = self.active_thread() {
1456                    let new_placeholder =
1457                        placeholder_text(agent_display_name.as_ref(), has_commands);
1458                    active.update(cx, |active, cx| {
1459                        active.message_editor.update(cx, |editor, cx| {
1460                            editor.set_placeholder_text(&new_placeholder, window, cx);
1461                        });
1462                    });
1463                }
1464            }
1465            AcpThreadEvent::ModeUpdated(_mode) => {
1466                // The connection keeps track of the mode
1467                cx.notify();
1468            }
1469            AcpThreadEvent::ConfigOptionsUpdated(_) => {
1470                // The watch task in ConfigOptionsView handles rebuilding selectors
1471                cx.notify();
1472            }
1473        }
1474        cx.notify();
1475    }
1476
1477    fn authenticate(
1478        &mut self,
1479        method: acp::AuthMethodId,
1480        window: &mut Window,
1481        cx: &mut Context<Self>,
1482    ) {
1483        let Some(connected) = self.as_connected_mut() else {
1484            return;
1485        };
1486        let connection = connected.connection.clone();
1487
1488        let AuthState::Unauthenticated {
1489            configuration_view,
1490            pending_auth_method,
1491            ..
1492        } = &mut connected.auth_state
1493        else {
1494            return;
1495        };
1496
1497        let agent_telemetry_id = connection.telemetry_id();
1498
1499        // Check for the experimental "terminal-auth" _meta field
1500        let auth_method = connection.auth_methods().iter().find(|m| m.id() == &method);
1501
1502        if let Some(terminal_auth) = auth_method
1503            .and_then(|a| match a {
1504                acp::AuthMethod::EnvVar(env_var) => env_var.meta.as_ref(),
1505                acp::AuthMethod::Terminal(terminal) => terminal.meta.as_ref(),
1506                acp::AuthMethod::Agent(agent) => agent.meta.as_ref(),
1507                _ => None,
1508            })
1509            .and_then(|m| m.get("terminal-auth"))
1510        {
1511            // Extract terminal auth details from meta
1512            if let (Some(command), Some(label)) = (
1513                terminal_auth.get("command").and_then(|v| v.as_str()),
1514                terminal_auth.get("label").and_then(|v| v.as_str()),
1515            ) {
1516                let args = terminal_auth
1517                    .get("args")
1518                    .and_then(|v| v.as_array())
1519                    .map(|arr| {
1520                        arr.iter()
1521                            .filter_map(|v| v.as_str().map(String::from))
1522                            .collect()
1523                    })
1524                    .unwrap_or_default();
1525
1526                let env = terminal_auth
1527                    .get("env")
1528                    .and_then(|v| v.as_object())
1529                    .map(|obj| {
1530                        obj.iter()
1531                            .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
1532                            .collect::<HashMap<String, String>>()
1533                    })
1534                    .unwrap_or_default();
1535
1536                // Build SpawnInTerminal from _meta
1537                let login = task::SpawnInTerminal {
1538                    id: task::TaskId(format!("external-agent-{}-login", label)),
1539                    full_label: label.to_string(),
1540                    label: label.to_string(),
1541                    command: Some(command.to_string()),
1542                    args,
1543                    command_label: label.to_string(),
1544                    env,
1545                    use_new_terminal: true,
1546                    allow_concurrent_runs: true,
1547                    hide: task::HideStrategy::Always,
1548                    ..Default::default()
1549                };
1550
1551                configuration_view.take();
1552                pending_auth_method.replace(method.clone());
1553
1554                if let Some(workspace) = self.workspace.upgrade() {
1555                    let project = self.project.clone();
1556                    let authenticate = Self::spawn_external_agent_login(
1557                        login,
1558                        workspace,
1559                        project,
1560                        method.clone(),
1561                        false,
1562                        window,
1563                        cx,
1564                    );
1565                    cx.notify();
1566                    self.auth_task = Some(cx.spawn_in(window, {
1567                        async move |this, cx| {
1568                            let result = authenticate.await;
1569
1570                            match &result {
1571                                Ok(_) => telemetry::event!(
1572                                    "Authenticate Agent Succeeded",
1573                                    agent = agent_telemetry_id
1574                                ),
1575                                Err(_) => {
1576                                    telemetry::event!(
1577                                        "Authenticate Agent Failed",
1578                                        agent = agent_telemetry_id,
1579                                    )
1580                                }
1581                            }
1582
1583                            this.update_in(cx, |this, window, cx| {
1584                                if let Err(err) = result {
1585                                    if let Some(ConnectedServerState {
1586                                        auth_state:
1587                                            AuthState::Unauthenticated {
1588                                                pending_auth_method,
1589                                                ..
1590                                            },
1591                                        ..
1592                                    }) = this.as_connected_mut()
1593                                    {
1594                                        pending_auth_method.take();
1595                                    }
1596                                    if let Some(active) = this.active_thread() {
1597                                        active.update(cx, |active, cx| {
1598                                            active.handle_thread_error(err, cx);
1599                                        })
1600                                    }
1601                                } else {
1602                                    this.reset(window, cx);
1603                                }
1604                                this.auth_task.take()
1605                            })
1606                            .ok();
1607                        }
1608                    }));
1609                }
1610                return;
1611            }
1612        }
1613
1614        configuration_view.take();
1615        pending_auth_method.replace(method.clone());
1616
1617        let authenticate = connection.authenticate(method, cx);
1618        cx.notify();
1619        self.auth_task = Some(cx.spawn_in(window, {
1620            async move |this, cx| {
1621                let result = authenticate.await;
1622
1623                match &result {
1624                    Ok(_) => telemetry::event!(
1625                        "Authenticate Agent Succeeded",
1626                        agent = agent_telemetry_id
1627                    ),
1628                    Err(_) => {
1629                        telemetry::event!("Authenticate Agent Failed", agent = agent_telemetry_id,)
1630                    }
1631                }
1632
1633                this.update_in(cx, |this, window, cx| {
1634                    if let Err(err) = result {
1635                        if let Some(ConnectedServerState {
1636                            auth_state:
1637                                AuthState::Unauthenticated {
1638                                    pending_auth_method,
1639                                    ..
1640                                },
1641                            ..
1642                        }) = this.as_connected_mut()
1643                        {
1644                            pending_auth_method.take();
1645                        }
1646                        if let Some(active) = this.active_thread() {
1647                            active.update(cx, |active, cx| active.handle_thread_error(err, cx));
1648                        }
1649                    } else {
1650                        this.reset(window, cx);
1651                    }
1652                    this.auth_task.take()
1653                })
1654                .ok();
1655            }
1656        }));
1657    }
1658
1659    fn load_subagent_session(
1660        &mut self,
1661        subagent_id: acp::SessionId,
1662        parent_id: acp::SessionId,
1663        window: &mut Window,
1664        cx: &mut Context<Self>,
1665    ) {
1666        let Some(connected) = self.as_connected() else {
1667            return;
1668        };
1669        if connected.threads.contains_key(&subagent_id)
1670            || !connected.connection.supports_load_session()
1671        {
1672            return;
1673        }
1674        let root_dir = self
1675            .project
1676            .read(cx)
1677            .worktrees(cx)
1678            .filter_map(|worktree| {
1679                if worktree.read(cx).is_single_file() {
1680                    Some(worktree.read(cx).abs_path().parent()?.into())
1681                } else {
1682                    Some(worktree.read(cx).abs_path())
1683                }
1684            })
1685            .next();
1686        let cwd = root_dir.unwrap_or_else(|| paths::home_dir().as_path().into());
1687
1688        let subagent_thread_task = connected.connection.clone().load_session(
1689            subagent_id.clone(),
1690            self.project.clone(),
1691            &cwd,
1692            None,
1693            cx,
1694        );
1695
1696        cx.spawn_in(window, async move |this, cx| {
1697            let subagent_thread = subagent_thread_task.await?;
1698            this.update_in(cx, |this, window, cx| {
1699                let Some((conversation, history)) = this
1700                    .as_connected()
1701                    .map(|connected| (connected.conversation.clone(), connected.history.clone()))
1702                else {
1703                    return;
1704                };
1705                conversation.update(cx, |conversation, cx| {
1706                    conversation.register_thread(subagent_thread.clone(), cx);
1707                });
1708                let view = this.new_thread_view(
1709                    Some(parent_id),
1710                    subagent_thread,
1711                    conversation,
1712                    false,
1713                    None,
1714                    history,
1715                    window,
1716                    cx,
1717                );
1718                let Some(connected) = this.as_connected_mut() else {
1719                    return;
1720                };
1721                connected.threads.insert(subagent_id, view);
1722            })
1723        })
1724        .detach();
1725    }
1726
1727    fn spawn_external_agent_login(
1728        login: task::SpawnInTerminal,
1729        workspace: Entity<Workspace>,
1730        project: Entity<Project>,
1731        method: acp::AuthMethodId,
1732        previous_attempt: bool,
1733        window: &mut Window,
1734        cx: &mut App,
1735    ) -> Task<Result<()>> {
1736        let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1737            return Task::ready(Ok(()));
1738        };
1739
1740        window.spawn(cx, async move |cx| {
1741            let mut task = login.clone();
1742            if let Some(cmd) = &task.command {
1743                // Have "node" command use Zed's managed Node runtime by default
1744                if cmd == "node" {
1745                    let resolved_node_runtime = project
1746                        .update(cx, |project, cx| {
1747                            let agent_server_store = project.agent_server_store().clone();
1748                            agent_server_store.update(cx, |store, cx| {
1749                                store.node_runtime().map(|node_runtime| {
1750                                    cx.background_spawn(async move {
1751                                        node_runtime.binary_path().await
1752                                    })
1753                                })
1754                            })
1755                        });
1756
1757                    if let Some(resolve_task) = resolved_node_runtime {
1758                        if let Ok(node_path) = resolve_task.await {
1759                            task.command = Some(node_path.to_string_lossy().to_string());
1760                        }
1761                    }
1762                }
1763            }
1764            task.shell = task::Shell::WithArguments {
1765                program: task.command.take().expect("login command should be set"),
1766                args: std::mem::take(&mut task.args),
1767                title_override: None
1768            };
1769            task.full_label = task.label.clone();
1770            task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1771            task.command_label = task.label.clone();
1772            task.use_new_terminal = true;
1773            task.allow_concurrent_runs = true;
1774            task.hide = task::HideStrategy::Always;
1775
1776            let terminal = terminal_panel
1777                .update_in(cx, |terminal_panel, window, cx| {
1778                    terminal_panel.spawn_task(&task, window, cx)
1779                })?
1780                .await?;
1781
1782            let success_patterns = match method.0.as_ref() {
1783                "claude-login" | "spawn-gemini-cli" => vec![
1784                    "Login successful".to_string(),
1785                    "Type your message".to_string(),
1786                ],
1787                _ => Vec::new(),
1788            };
1789            if success_patterns.is_empty() {
1790                // No success patterns specified: wait for the process to exit and check exit code
1791                let exit_status = terminal
1792                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1793                    .await;
1794
1795                match exit_status {
1796                    Some(status) if status.success() => Ok(()),
1797                    Some(status) => Err(anyhow!(
1798                        "Login command failed with exit code: {:?}",
1799                        status.code()
1800                    )),
1801                    None => Err(anyhow!("Login command terminated without exit status")),
1802                }
1803            } else {
1804                // Look for specific output patterns to detect successful login
1805                let mut exit_status = terminal
1806                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1807                    .fuse();
1808
1809                let logged_in = cx
1810                    .spawn({
1811                        let terminal = terminal.clone();
1812                        async move |cx| {
1813                            loop {
1814                                cx.background_executor().timer(Duration::from_secs(1)).await;
1815                                let content =
1816                                    terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1817                                if success_patterns.iter().any(|pattern| content.contains(pattern))
1818                                {
1819                                    return anyhow::Ok(());
1820                                }
1821                            }
1822                        }
1823                    })
1824                    .fuse();
1825                futures::pin_mut!(logged_in);
1826                futures::select_biased! {
1827                    result = logged_in => {
1828                        if let Err(e) = result {
1829                            log::error!("{e}");
1830                            return Err(anyhow!("exited before logging in"));
1831                        }
1832                    }
1833                    _ = exit_status => {
1834                        if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server()) && login.label.contains("gemini") {
1835                            return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, project.clone(), method, true, window, cx))?.await
1836                        }
1837                        return Err(anyhow!("exited before logging in"));
1838                    }
1839                }
1840                terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1841                Ok(())
1842            }
1843        })
1844    }
1845
1846    pub fn has_user_submitted_prompt(&self, cx: &App) -> bool {
1847        self.active_thread().is_some_and(|active| {
1848            active
1849                .read(cx)
1850                .thread
1851                .read(cx)
1852                .entries()
1853                .iter()
1854                .any(|entry| {
1855                    matches!(
1856                        entry,
1857                        AgentThreadEntry::UserMessage(user_message) if user_message.id.is_some()
1858                    )
1859                })
1860        })
1861    }
1862
1863    fn render_auth_required_state(
1864        &self,
1865        connection: &Rc<dyn AgentConnection>,
1866        description: Option<&Entity<Markdown>>,
1867        configuration_view: Option<&AnyView>,
1868        pending_auth_method: Option<&acp::AuthMethodId>,
1869        window: &mut Window,
1870        cx: &Context<Self>,
1871    ) -> impl IntoElement {
1872        let auth_methods = connection.auth_methods();
1873
1874        let agent_display_name = self
1875            .agent_server_store
1876            .read(cx)
1877            .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1878            .unwrap_or_else(|| self.agent.name());
1879
1880        let show_fallback_description = auth_methods.len() > 1
1881            && configuration_view.is_none()
1882            && description.is_none()
1883            && pending_auth_method.is_none();
1884
1885        let auth_buttons = || {
1886            h_flex().justify_end().flex_wrap().gap_1().children(
1887                connection
1888                    .auth_methods()
1889                    .iter()
1890                    .enumerate()
1891                    .rev()
1892                    .map(|(ix, method)| {
1893                        let (method_id, name) = (method.id().0.clone(), method.name().to_string());
1894                        let agent_telemetry_id = connection.telemetry_id();
1895
1896                        Button::new(method_id.clone(), name)
1897                            .label_size(LabelSize::Small)
1898                            .map(|this| {
1899                                if ix == 0 {
1900                                    this.style(ButtonStyle::Tinted(TintColor::Accent))
1901                                } else {
1902                                    this.style(ButtonStyle::Outlined)
1903                                }
1904                            })
1905                            .when_some(method.description(), |this, description| {
1906                                this.tooltip(Tooltip::text(description.to_string()))
1907                            })
1908                            .on_click({
1909                                cx.listener(move |this, _, window, cx| {
1910                                    telemetry::event!(
1911                                        "Authenticate Agent Started",
1912                                        agent = agent_telemetry_id,
1913                                        method = method_id
1914                                    );
1915
1916                                    this.authenticate(
1917                                        acp::AuthMethodId::new(method_id.clone()),
1918                                        window,
1919                                        cx,
1920                                    )
1921                                })
1922                            })
1923                    }),
1924            )
1925        };
1926
1927        if pending_auth_method.is_some() {
1928            return Callout::new()
1929                .icon(IconName::Info)
1930                .title(format!("Authenticating to {}", agent_display_name))
1931                .actions_slot(
1932                    Icon::new(IconName::ArrowCircle)
1933                        .size(IconSize::Small)
1934                        .color(Color::Muted)
1935                        .with_rotate_animation(2)
1936                        .into_any_element(),
1937                )
1938                .into_any_element();
1939        }
1940
1941        Callout::new()
1942            .icon(IconName::Info)
1943            .title(format!("Authenticate to {}", agent_display_name))
1944            .when(auth_methods.len() == 1, |this| {
1945                this.actions_slot(auth_buttons())
1946            })
1947            .description_slot(
1948                v_flex()
1949                    .text_ui(cx)
1950                    .map(|this| {
1951                        if show_fallback_description {
1952                            this.child(
1953                                Label::new("Choose one of the following authentication options:")
1954                                    .size(LabelSize::Small)
1955                                    .color(Color::Muted),
1956                            )
1957                        } else {
1958                            this.children(
1959                                configuration_view
1960                                    .cloned()
1961                                    .map(|view| div().w_full().child(view)),
1962                            )
1963                            .children(description.map(|desc| {
1964                                self.render_markdown(
1965                                    desc.clone(),
1966                                    MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
1967                                )
1968                            }))
1969                        }
1970                    })
1971                    .when(auth_methods.len() > 1, |this| {
1972                        this.gap_1().child(auth_buttons())
1973                    }),
1974            )
1975            .into_any_element()
1976    }
1977
1978    fn emit_token_limit_telemetry_if_needed(
1979        &mut self,
1980        thread: &Entity<AcpThread>,
1981        cx: &mut Context<Self>,
1982    ) {
1983        let Some(active_thread) = self.active_thread() else {
1984            return;
1985        };
1986
1987        let (ratio, agent_telemetry_id, session_id) = {
1988            let thread_data = thread.read(cx);
1989            let Some(token_usage) = thread_data.token_usage() else {
1990                return;
1991            };
1992            (
1993                token_usage.ratio(),
1994                thread_data.connection().telemetry_id(),
1995                thread_data.session_id().clone(),
1996            )
1997        };
1998
1999        let kind = match ratio {
2000            acp_thread::TokenUsageRatio::Normal => {
2001                active_thread.update(cx, |active, _cx| {
2002                    active.last_token_limit_telemetry = None;
2003                });
2004                return;
2005            }
2006            acp_thread::TokenUsageRatio::Warning => "warning",
2007            acp_thread::TokenUsageRatio::Exceeded => "exceeded",
2008        };
2009
2010        let should_skip = active_thread
2011            .read(cx)
2012            .last_token_limit_telemetry
2013            .as_ref()
2014            .is_some_and(|last| *last >= ratio);
2015        if should_skip {
2016            return;
2017        }
2018
2019        active_thread.update(cx, |active, _cx| {
2020            active.last_token_limit_telemetry = Some(ratio);
2021        });
2022
2023        telemetry::event!(
2024            "Agent Token Limit Warning",
2025            agent = agent_telemetry_id,
2026            session_id = session_id,
2027            kind = kind,
2028        );
2029    }
2030
2031    fn emit_load_error_telemetry(&self, error: &LoadError) {
2032        let error_kind = match error {
2033            LoadError::Unsupported { .. } => "unsupported",
2034            LoadError::FailedToInstall(_) => "failed_to_install",
2035            LoadError::Exited { .. } => "exited",
2036            LoadError::Other(_) => "other",
2037        };
2038
2039        let agent_name = self.agent.name();
2040
2041        telemetry::event!(
2042            "Agent Panel Error Shown",
2043            agent = agent_name,
2044            kind = error_kind,
2045            message = error.to_string(),
2046        );
2047    }
2048
2049    fn render_load_error(
2050        &self,
2051        e: &LoadError,
2052        window: &mut Window,
2053        cx: &mut Context<Self>,
2054    ) -> AnyElement {
2055        let (title, message, action_slot): (_, SharedString, _) = match e {
2056            LoadError::Unsupported {
2057                command: path,
2058                current_version,
2059                minimum_version,
2060            } => {
2061                return self.render_unsupported(path, current_version, minimum_version, window, cx);
2062            }
2063            LoadError::FailedToInstall(msg) => (
2064                "Failed to Install",
2065                msg.into(),
2066                Some(self.create_copy_button(msg.to_string()).into_any_element()),
2067            ),
2068            LoadError::Exited { status } => (
2069                "Failed to Launch",
2070                format!("Server exited with status {status}").into(),
2071                None,
2072            ),
2073            LoadError::Other(msg) => (
2074                "Failed to Launch",
2075                msg.into(),
2076                Some(self.create_copy_button(msg.to_string()).into_any_element()),
2077            ),
2078        };
2079
2080        Callout::new()
2081            .severity(Severity::Error)
2082            .icon(IconName::XCircleFilled)
2083            .title(title)
2084            .description(message)
2085            .actions_slot(div().children(action_slot))
2086            .into_any_element()
2087    }
2088
2089    fn render_unsupported(
2090        &self,
2091        path: &SharedString,
2092        version: &SharedString,
2093        minimum_version: &SharedString,
2094        _window: &mut Window,
2095        cx: &mut Context<Self>,
2096    ) -> AnyElement {
2097        let (heading_label, description_label) = (
2098            format!("Upgrade {} to work with Zed", self.agent.name()),
2099            if version.is_empty() {
2100                format!(
2101                    "Currently using {}, which does not report a valid --version",
2102                    path,
2103                )
2104            } else {
2105                format!(
2106                    "Currently using {}, which is only version {} (need at least {minimum_version})",
2107                    path, version
2108                )
2109            },
2110        );
2111
2112        v_flex()
2113            .w_full()
2114            .p_3p5()
2115            .gap_2p5()
2116            .border_t_1()
2117            .border_color(cx.theme().colors().border)
2118            .bg(linear_gradient(
2119                180.,
2120                linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
2121                linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
2122            ))
2123            .child(
2124                v_flex().gap_0p5().child(Label::new(heading_label)).child(
2125                    Label::new(description_label)
2126                        .size(LabelSize::Small)
2127                        .color(Color::Muted),
2128                ),
2129            )
2130            .into_any_element()
2131    }
2132
2133    pub(crate) fn as_native_connection(
2134        &self,
2135        cx: &App,
2136    ) -> Option<Rc<agent::NativeAgentConnection>> {
2137        let acp_thread = self.active_thread()?.read(cx).thread.read(cx);
2138        acp_thread.connection().clone().downcast()
2139    }
2140
2141    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
2142        let acp_thread = self.active_thread()?.read(cx).thread.read(cx);
2143        self.as_native_connection(cx)?
2144            .thread(acp_thread.session_id(), cx)
2145    }
2146
2147    fn queued_messages_len(&self, cx: &App) -> usize {
2148        self.active_thread()
2149            .map(|thread| thread.read(cx).local_queued_messages.len())
2150            .unwrap_or_default()
2151    }
2152
2153    fn update_queued_message(
2154        &mut self,
2155        index: usize,
2156        content: Vec<acp::ContentBlock>,
2157        tracked_buffers: Vec<Entity<Buffer>>,
2158        cx: &mut Context<Self>,
2159    ) -> bool {
2160        match self.active_thread() {
2161            Some(thread) => thread.update(cx, |thread, _cx| {
2162                if index < thread.local_queued_messages.len() {
2163                    thread.local_queued_messages[index] = QueuedMessage {
2164                        content,
2165                        tracked_buffers,
2166                    };
2167                    true
2168                } else {
2169                    false
2170                }
2171            }),
2172            None => false,
2173        }
2174    }
2175
2176    fn queued_message_contents(&self, cx: &App) -> Vec<Vec<acp::ContentBlock>> {
2177        match self.active_thread() {
2178            None => Vec::new(),
2179            Some(thread) => thread
2180                .read(cx)
2181                .local_queued_messages
2182                .iter()
2183                .map(|q| q.content.clone())
2184                .collect(),
2185        }
2186    }
2187
2188    fn save_queued_message_at_index(&mut self, index: usize, cx: &mut Context<Self>) {
2189        let editor = match self.active_thread() {
2190            Some(thread) => thread.read(cx).queued_message_editors.get(index).cloned(),
2191            None => None,
2192        };
2193        let Some(editor) = editor else {
2194            return;
2195        };
2196
2197        let contents_task = editor.update(cx, |editor, cx| editor.contents(false, cx));
2198
2199        cx.spawn(async move |this, cx| {
2200            let Ok((content, tracked_buffers)) = contents_task.await else {
2201                return Ok::<(), anyhow::Error>(());
2202            };
2203
2204            this.update(cx, |this, cx| {
2205                this.update_queued_message(index, content, tracked_buffers, cx);
2206                cx.notify();
2207            })?;
2208
2209            Ok(())
2210        })
2211        .detach_and_log_err(cx);
2212    }
2213
2214    fn sync_queued_message_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2215        let needed_count = self.queued_messages_len(cx);
2216        let queued_messages = self.queued_message_contents(cx);
2217
2218        let agent_name = self.agent.name();
2219        let workspace = self.workspace.clone();
2220        let project = self.project.downgrade();
2221        let Some(connected) = self.as_connected() else {
2222            return;
2223        };
2224        let history = connected.history.downgrade();
2225        let Some(thread) = connected.active_view() else {
2226            return;
2227        };
2228        let prompt_capabilities = thread.read(cx).prompt_capabilities.clone();
2229        let available_commands = thread.read(cx).available_commands.clone();
2230
2231        let current_count = thread.read(cx).queued_message_editors.len();
2232        let last_synced = thread.read(cx).last_synced_queue_length;
2233
2234        if current_count == needed_count && needed_count == last_synced {
2235            return;
2236        }
2237
2238        if current_count > needed_count {
2239            thread.update(cx, |thread, _cx| {
2240                thread.queued_message_editors.truncate(needed_count);
2241                thread
2242                    .queued_message_editor_subscriptions
2243                    .truncate(needed_count);
2244            });
2245
2246            let editors = thread.read(cx).queued_message_editors.clone();
2247            for (index, editor) in editors.into_iter().enumerate() {
2248                if let Some(content) = queued_messages.get(index) {
2249                    editor.update(cx, |editor, cx| {
2250                        editor.set_read_only(true, cx);
2251                        editor.set_message(content.clone(), window, cx);
2252                    });
2253                }
2254            }
2255        }
2256
2257        while thread.read(cx).queued_message_editors.len() < needed_count {
2258            let index = thread.read(cx).queued_message_editors.len();
2259            let content = queued_messages.get(index).cloned().unwrap_or_default();
2260
2261            let editor = cx.new(|cx| {
2262                let mut editor = MessageEditor::new(
2263                    workspace.clone(),
2264                    project.clone(),
2265                    None,
2266                    history.clone(),
2267                    None,
2268                    prompt_capabilities.clone(),
2269                    available_commands.clone(),
2270                    agent_name.clone(),
2271                    "",
2272                    EditorMode::AutoHeight {
2273                        min_lines: 1,
2274                        max_lines: Some(10),
2275                    },
2276                    window,
2277                    cx,
2278                );
2279                editor.set_read_only(true, cx);
2280                editor.set_message(content, window, cx);
2281                editor
2282            });
2283
2284            let subscription = cx.subscribe_in(
2285                &editor,
2286                window,
2287                move |this, _editor, event, window, cx| match event {
2288                    MessageEditorEvent::InputAttempted(text) => this
2289                        .move_queued_message_to_main_editor(index, Some(text.as_ref()), window, cx),
2290                    MessageEditorEvent::LostFocus => {
2291                        this.save_queued_message_at_index(index, cx);
2292                    }
2293                    MessageEditorEvent::Cancel => {
2294                        window.focus(&this.focus_handle(cx), cx);
2295                    }
2296                    MessageEditorEvent::Send => {
2297                        window.focus(&this.focus_handle(cx), cx);
2298                    }
2299                    MessageEditorEvent::SendImmediately => {
2300                        this.send_queued_message_at_index(index, true, window, cx);
2301                    }
2302                    _ => {}
2303                },
2304            );
2305
2306            thread.update(cx, |thread, _cx| {
2307                thread.queued_message_editors.push(editor);
2308                thread
2309                    .queued_message_editor_subscriptions
2310                    .push(subscription);
2311            });
2312        }
2313
2314        if let Some(active) = self.active_thread() {
2315            active.update(cx, |active, _cx| {
2316                active.last_synced_queue_length = needed_count;
2317            });
2318        }
2319    }
2320
2321    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2322        let workspace = self.workspace.clone();
2323        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2324            crate::connection_view::thread_view::open_link(text, &workspace, window, cx);
2325        })
2326    }
2327
2328    fn notify_with_sound(
2329        &mut self,
2330        caption: impl Into<SharedString>,
2331        icon: IconName,
2332        window: &mut Window,
2333        cx: &mut Context<Self>,
2334    ) {
2335        self.play_notification_sound(window, cx);
2336        self.show_notification(caption, icon, window, cx);
2337    }
2338
2339    fn agent_panel_visible(&self, multi_workspace: &Entity<MultiWorkspace>, cx: &App) -> bool {
2340        let Some(workspace) = self.workspace.upgrade() else {
2341            return false;
2342        };
2343
2344        multi_workspace.read(cx).workspace() == &workspace && AgentPanel::is_visible(&workspace, cx)
2345    }
2346
2347    fn agent_status_visible(&self, window: &Window, cx: &App) -> bool {
2348        if !window.is_window_active() {
2349            return false;
2350        }
2351
2352        if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
2353            self.agent_panel_visible(&multi_workspace, cx)
2354        } else {
2355            self.workspace
2356                .upgrade()
2357                .is_some_and(|workspace| AgentPanel::is_visible(&workspace, cx))
2358        }
2359    }
2360
2361    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2362        let settings = AgentSettings::get_global(cx);
2363        let visible = window.is_window_active()
2364            && if let Some(mw) = window.root::<MultiWorkspace>().flatten() {
2365                self.agent_panel_visible(&mw, cx)
2366            } else {
2367                self.workspace
2368                    .upgrade()
2369                    .is_some_and(|workspace| AgentPanel::is_visible(&workspace, cx))
2370            };
2371        if settings.play_sound_when_agent_done && !visible {
2372            Audio::play_sound(Sound::AgentDone, cx);
2373        }
2374    }
2375
2376    fn show_notification(
2377        &mut self,
2378        caption: impl Into<SharedString>,
2379        icon: IconName,
2380        window: &mut Window,
2381        cx: &mut Context<Self>,
2382    ) {
2383        if !self.notifications.is_empty() {
2384            return;
2385        }
2386
2387        let settings = AgentSettings::get_global(cx);
2388
2389        let should_notify = !self.agent_status_visible(window, cx);
2390
2391        if !should_notify {
2392            return;
2393        }
2394
2395        // TODO: Change this once we have title summarization for external agents.
2396        let title = self.agent.name();
2397
2398        match settings.notify_when_agent_waiting {
2399            NotifyWhenAgentWaiting::PrimaryScreen => {
2400                if let Some(primary) = cx.primary_display() {
2401                    self.pop_up(icon, caption.into(), title, window, primary, cx);
2402                }
2403            }
2404            NotifyWhenAgentWaiting::AllScreens => {
2405                let caption = caption.into();
2406                for screen in cx.displays() {
2407                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2408                }
2409            }
2410            NotifyWhenAgentWaiting::Never => {
2411                // Don't show anything
2412            }
2413        }
2414    }
2415
2416    fn pop_up(
2417        &mut self,
2418        icon: IconName,
2419        caption: SharedString,
2420        title: SharedString,
2421        window: &mut Window,
2422        screen: Rc<dyn PlatformDisplay>,
2423        cx: &mut Context<Self>,
2424    ) {
2425        let options = AgentNotification::window_options(screen, cx);
2426
2427        let project_name = self.workspace.upgrade().and_then(|workspace| {
2428            workspace
2429                .read(cx)
2430                .project()
2431                .read(cx)
2432                .visible_worktrees(cx)
2433                .next()
2434                .map(|worktree| worktree.read(cx).root_name_str().to_string())
2435        });
2436
2437        if let Some(screen_window) = cx
2438            .open_window(options, |_window, cx| {
2439                cx.new(|_cx| {
2440                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2441                })
2442            })
2443            .log_err()
2444            && let Some(pop_up) = screen_window.entity(cx).log_err()
2445        {
2446            self.notification_subscriptions
2447                .entry(screen_window)
2448                .or_insert_with(Vec::new)
2449                .push(cx.subscribe_in(&pop_up, window, {
2450                    |this, _, event, window, cx| match event {
2451                        AgentNotificationEvent::Accepted => {
2452                            let Some(handle) = window.window_handle().downcast::<MultiWorkspace>()
2453                            else {
2454                                log::error!("root view should be a MultiWorkspace");
2455                                return;
2456                            };
2457                            cx.activate(true);
2458
2459                            let workspace_handle = this.workspace.clone();
2460
2461                            cx.defer(move |cx| {
2462                                handle
2463                                    .update(cx, |multi_workspace, window, cx| {
2464                                        window.activate_window();
2465                                        if let Some(workspace) = workspace_handle.upgrade() {
2466                                            multi_workspace.activate(workspace.clone(), cx);
2467                                            workspace.update(cx, |workspace, cx| {
2468                                                workspace.focus_panel::<AgentPanel>(window, cx);
2469                                            });
2470                                        }
2471                                    })
2472                                    .log_err();
2473                            });
2474
2475                            this.dismiss_notifications(cx);
2476                        }
2477                        AgentNotificationEvent::Dismissed => {
2478                            this.dismiss_notifications(cx);
2479                        }
2480                    }
2481                }));
2482
2483            self.notifications.push(screen_window);
2484
2485            // If the user manually refocuses the original window, dismiss the popup.
2486            self.notification_subscriptions
2487                .entry(screen_window)
2488                .or_insert_with(Vec::new)
2489                .push({
2490                    let pop_up_weak = pop_up.downgrade();
2491
2492                    cx.observe_window_activation(window, move |this, window, cx| {
2493                        if this.agent_status_visible(window, cx)
2494                            && let Some(pop_up) = pop_up_weak.upgrade()
2495                        {
2496                            pop_up.update(cx, |notification, cx| {
2497                                notification.dismiss(cx);
2498                            });
2499                        }
2500                    })
2501                });
2502        }
2503    }
2504
2505    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2506        for window in self.notifications.drain(..) {
2507            window
2508                .update(cx, |_, window, _| {
2509                    window.remove_window();
2510                })
2511                .ok();
2512
2513            self.notification_subscriptions.remove(&window);
2514        }
2515    }
2516
2517    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2518        if let Some(entry_view_state) = self
2519            .active_thread()
2520            .map(|active| active.read(cx).entry_view_state.clone())
2521        {
2522            entry_view_state.update(cx, |entry_view_state, cx| {
2523                entry_view_state.agent_ui_font_size_changed(cx);
2524            });
2525        }
2526    }
2527
2528    pub(crate) fn insert_dragged_files(
2529        &self,
2530        paths: Vec<project::ProjectPath>,
2531        added_worktrees: Vec<Entity<project::Worktree>>,
2532        window: &mut Window,
2533        cx: &mut Context<Self>,
2534    ) {
2535        if let Some(active_thread) = self.active_thread() {
2536            active_thread.update(cx, |thread, cx| {
2537                thread.message_editor.update(cx, |editor, cx| {
2538                    editor.insert_dragged_files(paths, added_worktrees, window, cx);
2539                    editor.focus_handle(cx).focus(window, cx);
2540                })
2541            });
2542        }
2543    }
2544
2545    /// Inserts the selected text into the message editor or the message being
2546    /// edited, if any.
2547    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
2548        if let Some(active_thread) = self.active_thread() {
2549            active_thread.update(cx, |thread, cx| {
2550                thread.active_editor(cx).update(cx, |editor, cx| {
2551                    editor.insert_selections(window, cx);
2552                })
2553            });
2554        }
2555    }
2556
2557    /// Inserts terminal text as a crease into the message editor.
2558    pub(crate) fn insert_terminal_text(
2559        &self,
2560        text: String,
2561        window: &mut Window,
2562        cx: &mut Context<Self>,
2563    ) {
2564        if let Some(active_thread) = self.active_thread() {
2565            active_thread.update(cx, |thread, cx| {
2566                thread.message_editor.update(cx, |editor, cx| {
2567                    editor.insert_terminal_crease(text, window, cx);
2568                })
2569            });
2570        }
2571    }
2572
2573    fn current_model_name(&self, cx: &App) -> SharedString {
2574        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
2575        // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
2576        // This provides better clarity about what refused the request
2577        if self.as_native_connection(cx).is_some() {
2578            self.active_thread()
2579                .and_then(|active| active.read(cx).model_selector.clone())
2580                .and_then(|selector| selector.read(cx).active_model(cx))
2581                .map(|model| model.name.clone())
2582                .unwrap_or_else(|| SharedString::from("The model"))
2583        } else {
2584            // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
2585            self.agent.name()
2586        }
2587    }
2588
2589    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2590        let message = message.into();
2591
2592        CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
2593    }
2594
2595    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2596        let agent_name = self.agent.name();
2597        if let Some(active) = self.active_thread() {
2598            active.update(cx, |active, cx| active.clear_thread_error(cx));
2599        }
2600        let this = cx.weak_entity();
2601        let Some(connection) = self.as_connected().map(|c| c.connection.clone()) else {
2602            debug_panic!("This should not be possible");
2603            return;
2604        };
2605        window.defer(cx, |window, cx| {
2606            Self::handle_auth_required(
2607                this,
2608                AuthRequired::new(),
2609                agent_name,
2610                connection,
2611                window,
2612                cx,
2613            );
2614        })
2615    }
2616
2617    pub fn history(&self) -> Option<&Entity<ThreadHistory>> {
2618        self.as_connected().map(|c| &c.history)
2619    }
2620
2621    pub fn delete_history_entry(&mut self, session_id: &acp::SessionId, cx: &mut Context<Self>) {
2622        let Some(connected) = self.as_connected() else {
2623            return;
2624        };
2625
2626        let task = connected
2627            .history
2628            .update(cx, |history, cx| history.delete_session(&session_id, cx));
2629        task.detach_and_log_err(cx);
2630    }
2631}
2632
2633fn loading_contents_spinner(size: IconSize) -> AnyElement {
2634    Icon::new(IconName::LoadCircle)
2635        .size(size)
2636        .color(Color::Accent)
2637        .with_rotate_animation(3)
2638        .into_any_element()
2639}
2640
2641fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
2642    if agent_name == "Zed Agent" {
2643        format!("Message the {} — @ to include context", agent_name)
2644    } else if has_commands {
2645        format!(
2646            "Message {} — @ to include context, / for commands",
2647            agent_name
2648        )
2649    } else {
2650        format!("Message {} — @ to include context", agent_name)
2651    }
2652}
2653
2654impl Focusable for ConnectionView {
2655    fn focus_handle(&self, cx: &App) -> FocusHandle {
2656        match self.active_thread() {
2657            Some(thread) => thread.read(cx).focus_handle(cx),
2658            None => self.focus_handle.clone(),
2659        }
2660    }
2661}
2662
2663#[cfg(any(test, feature = "test-support"))]
2664impl ConnectionView {
2665    /// Expands a tool call so its content is visible.
2666    /// This is primarily useful for visual testing.
2667    pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
2668        if let Some(active) = self.active_thread() {
2669            active.update(cx, |active, _cx| {
2670                active.expanded_tool_calls.insert(tool_call_id);
2671            });
2672            cx.notify();
2673        }
2674    }
2675}
2676
2677impl Render for ConnectionView {
2678    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2679        self.sync_queued_message_editors(window, cx);
2680        let v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
2681
2682        v_flex()
2683            .track_focus(&self.focus_handle)
2684            .size_full()
2685            .bg(cx.theme().colors().panel_background)
2686            .child(match &self.server_state {
2687                ServerState::Loading { .. } => v_flex()
2688                    .flex_1()
2689                    .when(v2_flag, |this| {
2690                        this.size_full().items_center().justify_center().child(
2691                            Label::new("Loading…").color(Color::Muted).with_animation(
2692                                "loading-agent-label",
2693                                Animation::new(Duration::from_secs(2))
2694                                    .repeat()
2695                                    .with_easing(pulsating_between(0.3, 0.7)),
2696                                |label, delta| label.alpha(delta),
2697                            ),
2698                        )
2699                    })
2700                    .into_any(),
2701                ServerState::LoadError { error: e, .. } => v_flex()
2702                    .flex_1()
2703                    .size_full()
2704                    .items_center()
2705                    .justify_end()
2706                    .child(self.render_load_error(e, window, cx))
2707                    .into_any(),
2708                ServerState::Connected(ConnectedServerState {
2709                    connection,
2710                    auth_state:
2711                        AuthState::Unauthenticated {
2712                            description,
2713                            configuration_view,
2714                            pending_auth_method,
2715                            _subscription,
2716                        },
2717                    ..
2718                }) => v_flex()
2719                    .flex_1()
2720                    .size_full()
2721                    .justify_end()
2722                    .child(self.render_auth_required_state(
2723                        connection,
2724                        description.as_ref(),
2725                        configuration_view.as_ref(),
2726                        pending_auth_method.as_ref(),
2727                        window,
2728                        cx,
2729                    ))
2730                    .into_any_element(),
2731                ServerState::Connected(connected) => {
2732                    if let Some(view) = connected.active_view() {
2733                        view.clone().into_any_element()
2734                    } else {
2735                        debug_panic!("This state should never be reached");
2736                        div().into_any_element()
2737                    }
2738                }
2739            })
2740    }
2741}
2742
2743fn plan_label_markdown_style(
2744    status: &acp::PlanEntryStatus,
2745    window: &Window,
2746    cx: &App,
2747) -> MarkdownStyle {
2748    let default_md_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
2749
2750    MarkdownStyle {
2751        base_text_style: TextStyle {
2752            color: cx.theme().colors().text_muted,
2753            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2754                Some(gpui::StrikethroughStyle {
2755                    thickness: px(1.),
2756                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2757                })
2758            } else {
2759                None
2760            },
2761            ..default_md_style.base_text_style
2762        },
2763        ..default_md_style
2764    }
2765}
2766
2767#[cfg(test)]
2768pub(crate) mod tests {
2769    use acp_thread::{
2770        AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
2771    };
2772    use action_log::ActionLog;
2773    use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
2774    use agent_client_protocol::SessionId;
2775    use assistant_text_thread::TextThreadStore;
2776    use editor::MultiBufferOffset;
2777    use fs::FakeFs;
2778    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
2779    use parking_lot::Mutex;
2780    use project::Project;
2781    use serde_json::json;
2782    use settings::SettingsStore;
2783    use std::any::Any;
2784    use std::path::{Path, PathBuf};
2785    use std::rc::Rc;
2786    use std::sync::Arc;
2787    use workspace::{Item, MultiWorkspace};
2788
2789    use crate::agent_panel;
2790
2791    use super::*;
2792
2793    #[gpui::test]
2794    async fn test_drop(cx: &mut TestAppContext) {
2795        init_test(cx);
2796
2797        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2798        let weak_view = thread_view.downgrade();
2799        drop(thread_view);
2800        assert!(!weak_view.is_upgradable());
2801    }
2802
2803    #[gpui::test]
2804    async fn test_external_source_prompt_requires_manual_send(cx: &mut TestAppContext) {
2805        init_test(cx);
2806
2807        let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2808            panic!("expected prompt from external source to sanitize successfully");
2809        };
2810        let initial_content = AgentInitialContent::FromExternalSource(prompt);
2811
2812        let (thread_view, cx) = setup_thread_view_with_initial_content(
2813            StubAgentServer::default_response(),
2814            initial_content,
2815            cx,
2816        )
2817        .await;
2818
2819        active_thread(&thread_view, cx).read_with(cx, |view, cx| {
2820            assert!(view.show_external_source_prompt_warning);
2821            assert_eq!(view.thread.read(cx).entries().len(), 0);
2822            assert_eq!(view.message_editor.read(cx).text(cx), "Write me a script");
2823        });
2824    }
2825
2826    #[gpui::test]
2827    async fn test_external_source_prompt_warning_clears_after_send(cx: &mut TestAppContext) {
2828        init_test(cx);
2829
2830        let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2831            panic!("expected prompt from external source to sanitize successfully");
2832        };
2833        let initial_content = AgentInitialContent::FromExternalSource(prompt);
2834
2835        let (thread_view, cx) = setup_thread_view_with_initial_content(
2836            StubAgentServer::default_response(),
2837            initial_content,
2838            cx,
2839        )
2840        .await;
2841
2842        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2843        cx.run_until_parked();
2844
2845        active_thread(&thread_view, cx).read_with(cx, |view, cx| {
2846            assert!(!view.show_external_source_prompt_warning);
2847            assert_eq!(view.message_editor.read(cx).text(cx), "");
2848            assert_eq!(view.thread.read(cx).entries().len(), 2);
2849        });
2850    }
2851
2852    #[gpui::test]
2853    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2854        init_test(cx);
2855
2856        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2857
2858        let message_editor = message_editor(&thread_view, cx);
2859        message_editor.update_in(cx, |editor, window, cx| {
2860            editor.set_text("Hello", window, cx);
2861        });
2862
2863        cx.deactivate_window();
2864
2865        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2866
2867        cx.run_until_parked();
2868
2869        assert!(
2870            cx.windows()
2871                .iter()
2872                .any(|window| window.downcast::<AgentNotification>().is_some())
2873        );
2874    }
2875
2876    #[gpui::test]
2877    async fn test_notification_for_error(cx: &mut TestAppContext) {
2878        init_test(cx);
2879
2880        let (thread_view, cx) =
2881            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2882
2883        let message_editor = message_editor(&thread_view, cx);
2884        message_editor.update_in(cx, |editor, window, cx| {
2885            editor.set_text("Hello", window, cx);
2886        });
2887
2888        cx.deactivate_window();
2889
2890        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2891
2892        cx.run_until_parked();
2893
2894        assert!(
2895            cx.windows()
2896                .iter()
2897                .any(|window| window.downcast::<AgentNotification>().is_some())
2898        );
2899    }
2900
2901    #[gpui::test]
2902    async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
2903        init_test(cx);
2904
2905        let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
2906        let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
2907
2908        let fs = FakeFs::new(cx.executor());
2909        let project = Project::test(fs, [], cx).await;
2910        let (multi_workspace, cx) =
2911            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2912        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2913
2914        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2915        let connection_store =
2916            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
2917
2918        let thread_view = cx.update(|window, cx| {
2919            cx.new(|cx| {
2920                ConnectionView::new(
2921                    Rc::new(StubAgentServer::default_response()),
2922                    connection_store,
2923                    Agent::Custom {
2924                        name: "Test".into(),
2925                    },
2926                    None,
2927                    None,
2928                    None,
2929                    None,
2930                    workspace.downgrade(),
2931                    project,
2932                    Some(thread_store),
2933                    None,
2934                    window,
2935                    cx,
2936                )
2937            })
2938        });
2939
2940        // Wait for connection to establish
2941        cx.run_until_parked();
2942
2943        let history = cx.update(|_window, cx| {
2944            thread_view
2945                .read(cx)
2946                .history()
2947                .expect("Missing history")
2948                .clone()
2949        });
2950
2951        // Initially empty because StubAgentConnection.session_list() returns None
2952        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2953            assert_eq!(view.recent_history_entries.len(), 0);
2954        });
2955
2956        // Now set the session list - this simulates external agents providing their history
2957        let list_a: Rc<dyn AgentSessionList> =
2958            Rc::new(StubSessionList::new(vec![session_a.clone()]));
2959        history.update(cx, |history, cx| {
2960            history.set_session_list(Some(list_a), cx);
2961        });
2962        cx.run_until_parked();
2963
2964        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2965            assert_eq!(view.recent_history_entries.len(), 1);
2966            assert_eq!(
2967                view.recent_history_entries[0].session_id,
2968                session_a.session_id
2969            );
2970        });
2971
2972        // Update to a different session list
2973        let list_b: Rc<dyn AgentSessionList> =
2974            Rc::new(StubSessionList::new(vec![session_b.clone()]));
2975        history.update(cx, |history, cx| {
2976            history.set_session_list(Some(list_b), cx);
2977        });
2978        cx.run_until_parked();
2979
2980        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2981            assert_eq!(view.recent_history_entries.len(), 1);
2982            assert_eq!(
2983                view.recent_history_entries[0].session_id,
2984                session_b.session_id
2985            );
2986        });
2987    }
2988
2989    #[gpui::test]
2990    async fn test_new_thread_creation_triggers_session_list_refresh(cx: &mut TestAppContext) {
2991        init_test(cx);
2992
2993        let session = AgentSessionInfo::new(SessionId::new("history-session"));
2994        let (thread_view, history, cx) = setup_thread_view_with_history(
2995            StubAgentServer::new(SessionHistoryConnection::new(vec![session.clone()])),
2996            cx,
2997        )
2998        .await;
2999
3000        history.read_with(cx, |history, _cx| {
3001            assert!(
3002                history.has_session_list(),
3003                "session list should be attached after thread creation"
3004            );
3005        });
3006
3007        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
3008            assert_eq!(view.recent_history_entries.len(), 1);
3009            assert_eq!(
3010                view.recent_history_entries[0].session_id,
3011                session.session_id
3012            );
3013        });
3014    }
3015
3016    #[gpui::test]
3017    async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
3018        init_test(cx);
3019
3020        let fs = FakeFs::new(cx.executor());
3021        let project = Project::test(fs, [], cx).await;
3022        let (multi_workspace, cx) =
3023            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3024        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3025
3026        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3027        let connection_store =
3028            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3029
3030        let thread_view = cx.update(|window, cx| {
3031            cx.new(|cx| {
3032                ConnectionView::new(
3033                    Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
3034                    connection_store,
3035                    Agent::Custom {
3036                        name: "Test".into(),
3037                    },
3038                    Some(SessionId::new("resume-session")),
3039                    None,
3040                    None,
3041                    None,
3042                    workspace.downgrade(),
3043                    project,
3044                    Some(thread_store),
3045                    None,
3046                    window,
3047                    cx,
3048                )
3049            })
3050        });
3051
3052        cx.run_until_parked();
3053
3054        thread_view.read_with(cx, |view, cx| {
3055            let state = view.active_thread().unwrap();
3056            assert!(state.read(cx).resumed_without_history);
3057            assert_eq!(state.read(cx).list_state.item_count(), 0);
3058        });
3059    }
3060
3061    #[gpui::test]
3062    async fn test_resume_thread_uses_session_cwd_when_inside_project(cx: &mut TestAppContext) {
3063        init_test(cx);
3064
3065        let fs = FakeFs::new(cx.executor());
3066        fs.insert_tree(
3067            "/project",
3068            json!({
3069                "subdir": {
3070                    "file.txt": "hello"
3071                }
3072            }),
3073        )
3074        .await;
3075        let project = Project::test(fs, [Path::new("/project")], cx).await;
3076        let (multi_workspace, cx) =
3077            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3078        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3079
3080        let connection = CwdCapturingConnection::new();
3081        let captured_cwd = connection.captured_cwd.clone();
3082
3083        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3084        let connection_store =
3085            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3086
3087        let _thread_view = cx.update(|window, cx| {
3088            cx.new(|cx| {
3089                ConnectionView::new(
3090                    Rc::new(StubAgentServer::new(connection)),
3091                    connection_store,
3092                    Agent::Custom {
3093                        name: "Test".into(),
3094                    },
3095                    Some(SessionId::new("session-1")),
3096                    Some(PathBuf::from("/project/subdir")),
3097                    None,
3098                    None,
3099                    workspace.downgrade(),
3100                    project,
3101                    Some(thread_store),
3102                    None,
3103                    window,
3104                    cx,
3105                )
3106            })
3107        });
3108
3109        cx.run_until_parked();
3110
3111        assert_eq!(
3112            captured_cwd.lock().as_deref(),
3113            Some(Path::new("/project/subdir")),
3114            "Should use session cwd when it's inside the project"
3115        );
3116    }
3117
3118    #[gpui::test]
3119    async fn test_resume_thread_uses_fallback_cwd_when_outside_project(cx: &mut TestAppContext) {
3120        init_test(cx);
3121
3122        let fs = FakeFs::new(cx.executor());
3123        fs.insert_tree(
3124            "/project",
3125            json!({
3126                "file.txt": "hello"
3127            }),
3128        )
3129        .await;
3130        let project = Project::test(fs, [Path::new("/project")], cx).await;
3131        let (multi_workspace, cx) =
3132            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3133        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3134
3135        let connection = CwdCapturingConnection::new();
3136        let captured_cwd = connection.captured_cwd.clone();
3137
3138        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3139        let connection_store =
3140            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3141
3142        let _thread_view = cx.update(|window, cx| {
3143            cx.new(|cx| {
3144                ConnectionView::new(
3145                    Rc::new(StubAgentServer::new(connection)),
3146                    connection_store,
3147                    Agent::Custom {
3148                        name: "Test".into(),
3149                    },
3150                    Some(SessionId::new("session-1")),
3151                    Some(PathBuf::from("/some/other/path")),
3152                    None,
3153                    None,
3154                    workspace.downgrade(),
3155                    project,
3156                    Some(thread_store),
3157                    None,
3158                    window,
3159                    cx,
3160                )
3161            })
3162        });
3163
3164        cx.run_until_parked();
3165
3166        assert_eq!(
3167            captured_cwd.lock().as_deref(),
3168            Some(Path::new("/project")),
3169            "Should use fallback project cwd when session cwd is outside the project"
3170        );
3171    }
3172
3173    #[gpui::test]
3174    async fn test_resume_thread_rejects_unnormalized_cwd_outside_project(cx: &mut TestAppContext) {
3175        init_test(cx);
3176
3177        let fs = FakeFs::new(cx.executor());
3178        fs.insert_tree(
3179            "/project",
3180            json!({
3181                "file.txt": "hello"
3182            }),
3183        )
3184        .await;
3185        let project = Project::test(fs, [Path::new("/project")], cx).await;
3186        let (multi_workspace, cx) =
3187            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3188        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3189
3190        let connection = CwdCapturingConnection::new();
3191        let captured_cwd = connection.captured_cwd.clone();
3192
3193        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3194        let connection_store =
3195            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3196
3197        let _thread_view = cx.update(|window, cx| {
3198            cx.new(|cx| {
3199                ConnectionView::new(
3200                    Rc::new(StubAgentServer::new(connection)),
3201                    connection_store,
3202                    Agent::Custom {
3203                        name: "Test".into(),
3204                    },
3205                    Some(SessionId::new("session-1")),
3206                    Some(PathBuf::from("/project/../outside")),
3207                    None,
3208                    None,
3209                    workspace.downgrade(),
3210                    project,
3211                    Some(thread_store),
3212                    None,
3213                    window,
3214                    cx,
3215                )
3216            })
3217        });
3218
3219        cx.run_until_parked();
3220
3221        assert_eq!(
3222            captured_cwd.lock().as_deref(),
3223            Some(Path::new("/project")),
3224            "Should reject unnormalized cwd that resolves outside the project and use fallback cwd"
3225        );
3226    }
3227
3228    #[gpui::test]
3229    async fn test_refusal_handling(cx: &mut TestAppContext) {
3230        init_test(cx);
3231
3232        let (thread_view, cx) =
3233            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
3234
3235        let message_editor = message_editor(&thread_view, cx);
3236        message_editor.update_in(cx, |editor, window, cx| {
3237            editor.set_text("Do something harmful", window, cx);
3238        });
3239
3240        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3241
3242        cx.run_until_parked();
3243
3244        // Check that the refusal error is set
3245        thread_view.read_with(cx, |thread_view, cx| {
3246            let state = thread_view.active_thread().unwrap();
3247            assert!(
3248                matches!(state.read(cx).thread_error, Some(ThreadError::Refusal)),
3249                "Expected refusal error to be set"
3250            );
3251        });
3252    }
3253
3254    #[gpui::test]
3255    async fn test_connect_failure_transitions_to_load_error(cx: &mut TestAppContext) {
3256        init_test(cx);
3257
3258        let (thread_view, cx) = setup_thread_view(FailingAgentServer, cx).await;
3259
3260        thread_view.read_with(cx, |view, cx| {
3261            let title = view.title(cx);
3262            assert_eq!(
3263                title.as_ref(),
3264                "Error Loading Codex CLI",
3265                "Tab title should show the agent name with an error prefix"
3266            );
3267            match &view.server_state {
3268                ServerState::LoadError {
3269                    error: LoadError::Other(msg),
3270                    ..
3271                } => {
3272                    assert!(
3273                        msg.contains("Invalid gzip header"),
3274                        "Error callout should contain the underlying extraction error, got: {msg}"
3275                    );
3276                }
3277                other => panic!(
3278                    "Expected LoadError::Other, got: {}",
3279                    match other {
3280                        ServerState::Loading(_) => "Loading (stuck!)",
3281                        ServerState::LoadError { .. } => "LoadError (wrong variant)",
3282                        ServerState::Connected(_) => "Connected",
3283                    }
3284                ),
3285            }
3286        });
3287    }
3288
3289    #[gpui::test]
3290    async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) {
3291        init_test(cx);
3292
3293        let connection = AuthGatedAgentConnection::new();
3294        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3295
3296        // When new_session returns AuthRequired, the server should transition
3297        // to Connected + Unauthenticated rather than getting stuck in Loading.
3298        thread_view.read_with(cx, |view, _cx| {
3299            let connected = view
3300                .as_connected()
3301                .expect("Should be in Connected state even though auth is required");
3302            assert!(
3303                !connected.auth_state.is_ok(),
3304                "Auth state should be Unauthenticated"
3305            );
3306            assert!(
3307                connected.active_id.is_none(),
3308                "There should be no active thread since no session was created"
3309            );
3310            assert!(
3311                connected.threads.is_empty(),
3312                "There should be no threads since no session was created"
3313            );
3314        });
3315
3316        thread_view.read_with(cx, |view, _cx| {
3317            assert!(
3318                view.active_thread().is_none(),
3319                "active_thread() should be None when unauthenticated without a session"
3320            );
3321        });
3322
3323        // Authenticate using the real authenticate flow on ConnectionView.
3324        // This calls connection.authenticate(), which flips the internal flag,
3325        // then on success triggers reset() -> new_session() which now succeeds.
3326        thread_view.update_in(cx, |view, window, cx| {
3327            view.authenticate(
3328                acp::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
3329                window,
3330                cx,
3331            );
3332        });
3333        cx.run_until_parked();
3334
3335        // After auth, the server should have an active thread in the Ok state.
3336        thread_view.read_with(cx, |view, cx| {
3337            let connected = view
3338                .as_connected()
3339                .expect("Should still be in Connected state after auth");
3340            assert!(connected.auth_state.is_ok(), "Auth state should be Ok");
3341            assert!(
3342                connected.active_id.is_some(),
3343                "There should be an active thread after successful auth"
3344            );
3345            assert_eq!(
3346                connected.threads.len(),
3347                1,
3348                "There should be exactly one thread"
3349            );
3350
3351            let active = view
3352                .active_thread()
3353                .expect("active_thread() should return the new thread");
3354            assert!(
3355                active.read(cx).thread_error.is_none(),
3356                "The new thread should have no errors"
3357            );
3358        });
3359    }
3360
3361    #[gpui::test]
3362    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3363        init_test(cx);
3364
3365        let tool_call_id = acp::ToolCallId::new("1");
3366        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
3367            .kind(acp::ToolKind::Edit)
3368            .content(vec!["hi".into()]);
3369        let connection =
3370            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3371                tool_call_id,
3372                PermissionOptions::Flat(vec![acp::PermissionOption::new(
3373                    "1",
3374                    "Allow",
3375                    acp::PermissionOptionKind::AllowOnce,
3376                )]),
3377            )]));
3378
3379        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3380
3381        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3382
3383        let message_editor = message_editor(&thread_view, cx);
3384        message_editor.update_in(cx, |editor, window, cx| {
3385            editor.set_text("Hello", window, cx);
3386        });
3387
3388        cx.deactivate_window();
3389
3390        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3391
3392        cx.run_until_parked();
3393
3394        assert!(
3395            cx.windows()
3396                .iter()
3397                .any(|window| window.downcast::<AgentNotification>().is_some())
3398        );
3399    }
3400
3401    #[gpui::test]
3402    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
3403        init_test(cx);
3404
3405        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3406
3407        add_to_workspace(thread_view.clone(), cx);
3408
3409        let message_editor = message_editor(&thread_view, cx);
3410
3411        message_editor.update_in(cx, |editor, window, cx| {
3412            editor.set_text("Hello", window, cx);
3413        });
3414
3415        // Window is active (don't deactivate), but panel will be hidden
3416        // Note: In the test environment, the panel is not actually added to the dock,
3417        // so is_agent_panel_hidden will return true
3418
3419        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3420
3421        cx.run_until_parked();
3422
3423        // Should show notification because window is active but panel is hidden
3424        assert!(
3425            cx.windows()
3426                .iter()
3427                .any(|window| window.downcast::<AgentNotification>().is_some()),
3428            "Expected notification when panel is hidden"
3429        );
3430    }
3431
3432    #[gpui::test]
3433    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
3434        init_test(cx);
3435
3436        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3437
3438        let message_editor = message_editor(&thread_view, cx);
3439        message_editor.update_in(cx, |editor, window, cx| {
3440            editor.set_text("Hello", window, cx);
3441        });
3442
3443        // Deactivate window - should show notification regardless of setting
3444        cx.deactivate_window();
3445
3446        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3447
3448        cx.run_until_parked();
3449
3450        // Should still show notification when window is inactive (existing behavior)
3451        assert!(
3452            cx.windows()
3453                .iter()
3454                .any(|window| window.downcast::<AgentNotification>().is_some()),
3455            "Expected notification when window is inactive"
3456        );
3457    }
3458
3459    #[gpui::test]
3460    async fn test_notification_when_workspace_is_background_in_multi_workspace(
3461        cx: &mut TestAppContext,
3462    ) {
3463        init_test(cx);
3464
3465        // Enable multi-workspace feature flag and init globals needed by AgentPanel
3466        let fs = FakeFs::new(cx.executor());
3467
3468        cx.update(|cx| {
3469            cx.update_flags(true, vec!["agent-v2".to_string()]);
3470            agent::ThreadStore::init_global(cx);
3471            language_model::LanguageModelRegistry::test(cx);
3472            <dyn Fs>::set_global(fs.clone(), cx);
3473        });
3474
3475        let project1 = Project::test(fs.clone(), [], cx).await;
3476
3477        // Create a MultiWorkspace window with one workspace
3478        let multi_workspace_handle =
3479            cx.add_window(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
3480
3481        // Get workspace 1 (the initial workspace)
3482        let workspace1 = multi_workspace_handle
3483            .read_with(cx, |mw, _cx| mw.workspace().clone())
3484            .unwrap();
3485
3486        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
3487
3488        workspace1.update_in(cx, |workspace, window, cx| {
3489            let text_thread_store =
3490                cx.new(|cx| TextThreadStore::fake(workspace.project().clone(), cx));
3491            let panel =
3492                cx.new(|cx| crate::AgentPanel::new(workspace, text_thread_store, None, window, cx));
3493            workspace.add_panel(panel, window, cx);
3494
3495            // Open the dock and activate the agent panel so it's visible
3496            workspace.focus_panel::<crate::AgentPanel>(window, cx);
3497        });
3498
3499        cx.run_until_parked();
3500
3501        cx.read(|cx| {
3502            assert!(
3503                crate::AgentPanel::is_visible(&workspace1, cx),
3504                "AgentPanel should be visible in workspace1's dock"
3505            );
3506        });
3507
3508        // Set up thread view in workspace 1
3509        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3510        let connection_store =
3511            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project1.clone(), cx)));
3512
3513        let agent = StubAgentServer::default_response();
3514        let thread_view = cx.update(|window, cx| {
3515            cx.new(|cx| {
3516                ConnectionView::new(
3517                    Rc::new(agent),
3518                    connection_store,
3519                    Agent::Custom {
3520                        name: "Test".into(),
3521                    },
3522                    None,
3523                    None,
3524                    None,
3525                    None,
3526                    workspace1.downgrade(),
3527                    project1.clone(),
3528                    Some(thread_store),
3529                    None,
3530                    window,
3531                    cx,
3532                )
3533            })
3534        });
3535        cx.run_until_parked();
3536
3537        let message_editor = message_editor(&thread_view, cx);
3538        message_editor.update_in(cx, |editor, window, cx| {
3539            editor.set_text("Hello", window, cx);
3540        });
3541
3542        // Create a second workspace and switch to it.
3543        // This makes workspace1 the "background" workspace.
3544        let project2 = Project::test(fs, [], cx).await;
3545        multi_workspace_handle
3546            .update(cx, |mw, window, cx| {
3547                mw.test_add_workspace(project2, window, cx);
3548            })
3549            .unwrap();
3550
3551        cx.run_until_parked();
3552
3553        // Verify workspace1 is no longer the active workspace
3554        multi_workspace_handle
3555            .read_with(cx, |mw, _cx| {
3556                assert_eq!(mw.active_workspace_index(), 1);
3557                assert_ne!(mw.workspace(), &workspace1);
3558            })
3559            .unwrap();
3560
3561        // Window is active, agent panel is visible in workspace1, but workspace1
3562        // is in the background. The notification should show because the user
3563        // can't actually see the agent panel.
3564        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3565
3566        cx.run_until_parked();
3567
3568        assert!(
3569            cx.windows()
3570                .iter()
3571                .any(|window| window.downcast::<AgentNotification>().is_some()),
3572            "Expected notification when workspace is in background within MultiWorkspace"
3573        );
3574
3575        // Also verify: clicking "View Panel" should switch to workspace1.
3576        cx.windows()
3577            .iter()
3578            .find_map(|window| window.downcast::<AgentNotification>())
3579            .unwrap()
3580            .update(cx, |window, _, cx| window.accept(cx))
3581            .unwrap();
3582
3583        cx.run_until_parked();
3584
3585        multi_workspace_handle
3586            .read_with(cx, |mw, _cx| {
3587                assert_eq!(
3588                    mw.workspace(),
3589                    &workspace1,
3590                    "Expected workspace1 to become the active workspace after accepting notification"
3591                );
3592            })
3593            .unwrap();
3594    }
3595
3596    #[gpui::test]
3597    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
3598        init_test(cx);
3599
3600        // Set notify_when_agent_waiting to Never
3601        cx.update(|cx| {
3602            AgentSettings::override_global(
3603                AgentSettings {
3604                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
3605                    ..AgentSettings::get_global(cx).clone()
3606                },
3607                cx,
3608            );
3609        });
3610
3611        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3612
3613        let message_editor = message_editor(&thread_view, cx);
3614        message_editor.update_in(cx, |editor, window, cx| {
3615            editor.set_text("Hello", window, cx);
3616        });
3617
3618        // Window is active
3619
3620        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3621
3622        cx.run_until_parked();
3623
3624        // Should NOT show notification because notify_when_agent_waiting is Never
3625        assert!(
3626            !cx.windows()
3627                .iter()
3628                .any(|window| window.downcast::<AgentNotification>().is_some()),
3629            "Expected no notification when notify_when_agent_waiting is Never"
3630        );
3631    }
3632
3633    #[gpui::test]
3634    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
3635        init_test(cx);
3636
3637        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3638
3639        let weak_view = thread_view.downgrade();
3640
3641        let message_editor = message_editor(&thread_view, cx);
3642        message_editor.update_in(cx, |editor, window, cx| {
3643            editor.set_text("Hello", window, cx);
3644        });
3645
3646        cx.deactivate_window();
3647
3648        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3649
3650        cx.run_until_parked();
3651
3652        // Verify notification is shown
3653        assert!(
3654            cx.windows()
3655                .iter()
3656                .any(|window| window.downcast::<AgentNotification>().is_some()),
3657            "Expected notification to be shown"
3658        );
3659
3660        // Drop the thread view (simulating navigation to a new thread)
3661        drop(thread_view);
3662        drop(message_editor);
3663        // Trigger an update to flush effects, which will call release_dropped_entities
3664        cx.update(|_window, _cx| {});
3665        cx.run_until_parked();
3666
3667        // Verify the entity was actually released
3668        assert!(
3669            !weak_view.is_upgradable(),
3670            "Thread view entity should be released after dropping"
3671        );
3672
3673        // The notification should be automatically closed via on_release
3674        assert!(
3675            !cx.windows()
3676                .iter()
3677                .any(|window| window.downcast::<AgentNotification>().is_some()),
3678            "Notification should be closed when thread view is dropped"
3679        );
3680    }
3681
3682    async fn setup_thread_view(
3683        agent: impl AgentServer + 'static,
3684        cx: &mut TestAppContext,
3685    ) -> (Entity<ConnectionView>, &mut VisualTestContext) {
3686        let (thread_view, _history, cx) =
3687            setup_thread_view_with_history_and_initial_content(agent, None, cx).await;
3688        (thread_view, cx)
3689    }
3690
3691    async fn setup_thread_view_with_history(
3692        agent: impl AgentServer + 'static,
3693        cx: &mut TestAppContext,
3694    ) -> (
3695        Entity<ConnectionView>,
3696        Entity<ThreadHistory>,
3697        &mut VisualTestContext,
3698    ) {
3699        let (thread_view, history, cx) =
3700            setup_thread_view_with_history_and_initial_content(agent, None, cx).await;
3701        (thread_view, history.expect("Missing history"), cx)
3702    }
3703
3704    async fn setup_thread_view_with_initial_content(
3705        agent: impl AgentServer + 'static,
3706        initial_content: AgentInitialContent,
3707        cx: &mut TestAppContext,
3708    ) -> (Entity<ConnectionView>, &mut VisualTestContext) {
3709        let (thread_view, _history, cx) =
3710            setup_thread_view_with_history_and_initial_content(agent, Some(initial_content), cx)
3711                .await;
3712        (thread_view, cx)
3713    }
3714
3715    async fn setup_thread_view_with_history_and_initial_content(
3716        agent: impl AgentServer + 'static,
3717        initial_content: Option<AgentInitialContent>,
3718        cx: &mut TestAppContext,
3719    ) -> (
3720        Entity<ConnectionView>,
3721        Option<Entity<ThreadHistory>>,
3722        &mut VisualTestContext,
3723    ) {
3724        let fs = FakeFs::new(cx.executor());
3725        let project = Project::test(fs, [], cx).await;
3726        let (multi_workspace, cx) =
3727            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3728        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3729
3730        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3731        let connection_store =
3732            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3733
3734        let agent_key = Agent::Custom {
3735            name: "Test".into(),
3736        };
3737
3738        let thread_view = cx.update(|window, cx| {
3739            cx.new(|cx| {
3740                ConnectionView::new(
3741                    Rc::new(agent),
3742                    connection_store.clone(),
3743                    agent_key.clone(),
3744                    None,
3745                    None,
3746                    None,
3747                    initial_content,
3748                    workspace.downgrade(),
3749                    project,
3750                    Some(thread_store),
3751                    None,
3752                    window,
3753                    cx,
3754                )
3755            })
3756        });
3757        cx.run_until_parked();
3758
3759        let history = cx.update(|_window, cx| {
3760            connection_store
3761                .read(cx)
3762                .entry(&agent_key)
3763                .and_then(|e| e.read(cx).history().cloned())
3764        });
3765
3766        (thread_view, history, cx)
3767    }
3768
3769    fn add_to_workspace(thread_view: Entity<ConnectionView>, cx: &mut VisualTestContext) {
3770        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3771
3772        workspace
3773            .update_in(cx, |workspace, window, cx| {
3774                workspace.add_item_to_active_pane(
3775                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
3776                    None,
3777                    true,
3778                    window,
3779                    cx,
3780                );
3781            })
3782            .unwrap();
3783    }
3784
3785    struct ThreadViewItem(Entity<ConnectionView>);
3786
3787    impl Item for ThreadViewItem {
3788        type Event = ();
3789
3790        fn include_in_nav_history() -> bool {
3791            false
3792        }
3793
3794        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3795            "Test".into()
3796        }
3797    }
3798
3799    impl EventEmitter<()> for ThreadViewItem {}
3800
3801    impl Focusable for ThreadViewItem {
3802        fn focus_handle(&self, cx: &App) -> FocusHandle {
3803            self.0.read(cx).focus_handle(cx)
3804        }
3805    }
3806
3807    impl Render for ThreadViewItem {
3808        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3809            // Render the title editor in the element tree too. In the real app
3810            // it is part of the agent panel
3811            let title_editor = self
3812                .0
3813                .read(cx)
3814                .active_thread()
3815                .map(|t| t.read(cx).title_editor.clone());
3816
3817            v_flex().children(title_editor).child(self.0.clone())
3818        }
3819    }
3820
3821    pub(crate) struct StubAgentServer<C> {
3822        connection: C,
3823    }
3824
3825    impl<C> StubAgentServer<C> {
3826        pub(crate) fn new(connection: C) -> Self {
3827            Self { connection }
3828        }
3829    }
3830
3831    impl StubAgentServer<StubAgentConnection> {
3832        pub(crate) fn default_response() -> Self {
3833            let conn = StubAgentConnection::new();
3834            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3835                acp::ContentChunk::new("Default response".into()),
3836            )]);
3837            Self::new(conn)
3838        }
3839    }
3840
3841    impl<C> AgentServer for StubAgentServer<C>
3842    where
3843        C: 'static + AgentConnection + Send + Clone,
3844    {
3845        fn logo(&self) -> ui::IconName {
3846            ui::IconName::Ai
3847        }
3848
3849        fn name(&self) -> SharedString {
3850            "Test".into()
3851        }
3852
3853        fn connect(
3854            &self,
3855            _delegate: AgentServerDelegate,
3856            _cx: &mut App,
3857        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3858            Task::ready(Ok(Rc::new(self.connection.clone())))
3859        }
3860
3861        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3862            self
3863        }
3864    }
3865
3866    struct FailingAgentServer;
3867
3868    impl AgentServer for FailingAgentServer {
3869        fn logo(&self) -> ui::IconName {
3870            ui::IconName::AiOpenAi
3871        }
3872
3873        fn name(&self) -> SharedString {
3874            "Codex CLI".into()
3875        }
3876
3877        fn connect(
3878            &self,
3879            _delegate: AgentServerDelegate,
3880            _cx: &mut App,
3881        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3882            Task::ready(Err(anyhow!(
3883                "extracting downloaded asset for \
3884                 https://github.com/zed-industries/codex-acp/releases/download/v0.9.4/\
3885                 codex-acp-0.9.4-aarch64-pc-windows-msvc.zip: \
3886                 failed to iterate over archive: Invalid gzip header"
3887            )))
3888        }
3889
3890        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3891            self
3892        }
3893    }
3894
3895    #[derive(Clone)]
3896    struct StubSessionList {
3897        sessions: Vec<AgentSessionInfo>,
3898    }
3899
3900    impl StubSessionList {
3901        fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3902            Self { sessions }
3903        }
3904    }
3905
3906    impl AgentSessionList for StubSessionList {
3907        fn list_sessions(
3908            &self,
3909            _request: AgentSessionListRequest,
3910            _cx: &mut App,
3911        ) -> Task<anyhow::Result<AgentSessionListResponse>> {
3912            Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
3913        }
3914
3915        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3916            self
3917        }
3918    }
3919
3920    #[derive(Clone)]
3921    struct SessionHistoryConnection {
3922        sessions: Vec<AgentSessionInfo>,
3923    }
3924
3925    impl SessionHistoryConnection {
3926        fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3927            Self { sessions }
3928        }
3929    }
3930
3931    fn build_test_thread(
3932        connection: Rc<dyn AgentConnection>,
3933        project: Entity<Project>,
3934        name: &'static str,
3935        session_id: SessionId,
3936        cx: &mut App,
3937    ) -> Entity<AcpThread> {
3938        let action_log = cx.new(|_| ActionLog::new(project.clone()));
3939        cx.new(|cx| {
3940            AcpThread::new(
3941                None,
3942                name,
3943                None,
3944                connection,
3945                project,
3946                action_log,
3947                session_id,
3948                watch::Receiver::constant(
3949                    acp::PromptCapabilities::new()
3950                        .image(true)
3951                        .audio(true)
3952                        .embedded_context(true),
3953                ),
3954                cx,
3955            )
3956        })
3957    }
3958
3959    impl AgentConnection for SessionHistoryConnection {
3960        fn telemetry_id(&self) -> SharedString {
3961            "history-connection".into()
3962        }
3963
3964        fn new_session(
3965            self: Rc<Self>,
3966            project: Entity<Project>,
3967            _cwd: &Path,
3968            cx: &mut App,
3969        ) -> Task<anyhow::Result<Entity<AcpThread>>> {
3970            let thread = build_test_thread(
3971                self,
3972                project,
3973                "SessionHistoryConnection",
3974                SessionId::new("history-session"),
3975                cx,
3976            );
3977            Task::ready(Ok(thread))
3978        }
3979
3980        fn supports_load_session(&self) -> bool {
3981            true
3982        }
3983
3984        fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
3985            Some(Rc::new(StubSessionList::new(self.sessions.clone())))
3986        }
3987
3988        fn auth_methods(&self) -> &[acp::AuthMethod] {
3989            &[]
3990        }
3991
3992        fn authenticate(
3993            &self,
3994            _method_id: acp::AuthMethodId,
3995            _cx: &mut App,
3996        ) -> Task<anyhow::Result<()>> {
3997            Task::ready(Ok(()))
3998        }
3999
4000        fn prompt(
4001            &self,
4002            _id: Option<acp_thread::UserMessageId>,
4003            _params: acp::PromptRequest,
4004            _cx: &mut App,
4005        ) -> Task<anyhow::Result<acp::PromptResponse>> {
4006            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4007        }
4008
4009        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4010
4011        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4012            self
4013        }
4014    }
4015
4016    #[derive(Clone)]
4017    struct ResumeOnlyAgentConnection;
4018
4019    impl AgentConnection for ResumeOnlyAgentConnection {
4020        fn telemetry_id(&self) -> SharedString {
4021            "resume-only".into()
4022        }
4023
4024        fn new_session(
4025            self: Rc<Self>,
4026            project: Entity<Project>,
4027            _cwd: &Path,
4028            cx: &mut gpui::App,
4029        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4030            let thread = build_test_thread(
4031                self,
4032                project,
4033                "ResumeOnlyAgentConnection",
4034                SessionId::new("new-session"),
4035                cx,
4036            );
4037            Task::ready(Ok(thread))
4038        }
4039
4040        fn supports_resume_session(&self) -> bool {
4041            true
4042        }
4043
4044        fn resume_session(
4045            self: Rc<Self>,
4046            session_id: acp::SessionId,
4047            project: Entity<Project>,
4048            _cwd: &Path,
4049            _title: Option<SharedString>,
4050            cx: &mut App,
4051        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4052            let thread =
4053                build_test_thread(self, project, "ResumeOnlyAgentConnection", session_id, cx);
4054            Task::ready(Ok(thread))
4055        }
4056
4057        fn auth_methods(&self) -> &[acp::AuthMethod] {
4058            &[]
4059        }
4060
4061        fn authenticate(
4062            &self,
4063            _method_id: acp::AuthMethodId,
4064            _cx: &mut App,
4065        ) -> Task<gpui::Result<()>> {
4066            Task::ready(Ok(()))
4067        }
4068
4069        fn prompt(
4070            &self,
4071            _id: Option<acp_thread::UserMessageId>,
4072            _params: acp::PromptRequest,
4073            _cx: &mut App,
4074        ) -> Task<gpui::Result<acp::PromptResponse>> {
4075            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4076        }
4077
4078        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4079
4080        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4081            self
4082        }
4083    }
4084
4085    /// Simulates an agent that requires authentication before a session can be
4086    /// created. `new_session` returns `AuthRequired` until `authenticate` is
4087    /// called with the correct method, after which sessions are created normally.
4088    #[derive(Clone)]
4089    struct AuthGatedAgentConnection {
4090        authenticated: Arc<Mutex<bool>>,
4091        auth_method: acp::AuthMethod,
4092    }
4093
4094    impl AuthGatedAgentConnection {
4095        const AUTH_METHOD_ID: &str = "test-login";
4096
4097        fn new() -> Self {
4098            Self {
4099                authenticated: Arc::new(Mutex::new(false)),
4100                auth_method: acp::AuthMethod::Agent(acp::AuthMethodAgent::new(
4101                    Self::AUTH_METHOD_ID,
4102                    "Test Login",
4103                )),
4104            }
4105        }
4106    }
4107
4108    impl AgentConnection for AuthGatedAgentConnection {
4109        fn telemetry_id(&self) -> SharedString {
4110            "auth-gated".into()
4111        }
4112
4113        fn new_session(
4114            self: Rc<Self>,
4115            project: Entity<Project>,
4116            cwd: &Path,
4117            cx: &mut gpui::App,
4118        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4119            if !*self.authenticated.lock() {
4120                return Task::ready(Err(acp_thread::AuthRequired::new()
4121                    .with_description("Sign in to continue".to_string())
4122                    .into()));
4123            }
4124
4125            let session_id = acp::SessionId::new("auth-gated-session");
4126            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4127            Task::ready(Ok(cx.new(|cx| {
4128                AcpThread::new(
4129                    None,
4130                    "AuthGatedAgent",
4131                    Some(cwd.to_path_buf()),
4132                    self,
4133                    project,
4134                    action_log,
4135                    session_id,
4136                    watch::Receiver::constant(
4137                        acp::PromptCapabilities::new()
4138                            .image(true)
4139                            .audio(true)
4140                            .embedded_context(true),
4141                    ),
4142                    cx,
4143                )
4144            })))
4145        }
4146
4147        fn auth_methods(&self) -> &[acp::AuthMethod] {
4148            std::slice::from_ref(&self.auth_method)
4149        }
4150
4151        fn authenticate(
4152            &self,
4153            method_id: acp::AuthMethodId,
4154            _cx: &mut App,
4155        ) -> Task<gpui::Result<()>> {
4156            if &method_id == self.auth_method.id() {
4157                *self.authenticated.lock() = true;
4158                Task::ready(Ok(()))
4159            } else {
4160                Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
4161            }
4162        }
4163
4164        fn prompt(
4165            &self,
4166            _id: Option<acp_thread::UserMessageId>,
4167            _params: acp::PromptRequest,
4168            _cx: &mut App,
4169        ) -> Task<gpui::Result<acp::PromptResponse>> {
4170            unimplemented!()
4171        }
4172
4173        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4174            unimplemented!()
4175        }
4176
4177        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4178            self
4179        }
4180    }
4181
4182    #[derive(Clone)]
4183    struct SaboteurAgentConnection;
4184
4185    impl AgentConnection for SaboteurAgentConnection {
4186        fn telemetry_id(&self) -> SharedString {
4187            "saboteur".into()
4188        }
4189
4190        fn new_session(
4191            self: Rc<Self>,
4192            project: Entity<Project>,
4193            cwd: &Path,
4194            cx: &mut gpui::App,
4195        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4196            Task::ready(Ok(cx.new(|cx| {
4197                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4198                AcpThread::new(
4199                    None,
4200                    "SaboteurAgentConnection",
4201                    Some(cwd.to_path_buf()),
4202                    self,
4203                    project,
4204                    action_log,
4205                    SessionId::new("test"),
4206                    watch::Receiver::constant(
4207                        acp::PromptCapabilities::new()
4208                            .image(true)
4209                            .audio(true)
4210                            .embedded_context(true),
4211                    ),
4212                    cx,
4213                )
4214            })))
4215        }
4216
4217        fn auth_methods(&self) -> &[acp::AuthMethod] {
4218            &[]
4219        }
4220
4221        fn authenticate(
4222            &self,
4223            _method_id: acp::AuthMethodId,
4224            _cx: &mut App,
4225        ) -> Task<gpui::Result<()>> {
4226            unimplemented!()
4227        }
4228
4229        fn prompt(
4230            &self,
4231            _id: Option<acp_thread::UserMessageId>,
4232            _params: acp::PromptRequest,
4233            _cx: &mut App,
4234        ) -> Task<gpui::Result<acp::PromptResponse>> {
4235            Task::ready(Err(anyhow::anyhow!("Error prompting")))
4236        }
4237
4238        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4239            unimplemented!()
4240        }
4241
4242        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4243            self
4244        }
4245    }
4246
4247    /// Simulates a model which always returns a refusal response
4248    #[derive(Clone)]
4249    struct RefusalAgentConnection;
4250
4251    impl AgentConnection for RefusalAgentConnection {
4252        fn telemetry_id(&self) -> SharedString {
4253            "refusal".into()
4254        }
4255
4256        fn new_session(
4257            self: Rc<Self>,
4258            project: Entity<Project>,
4259            cwd: &Path,
4260            cx: &mut gpui::App,
4261        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4262            Task::ready(Ok(cx.new(|cx| {
4263                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4264                AcpThread::new(
4265                    None,
4266                    "RefusalAgentConnection",
4267                    Some(cwd.to_path_buf()),
4268                    self,
4269                    project,
4270                    action_log,
4271                    SessionId::new("test"),
4272                    watch::Receiver::constant(
4273                        acp::PromptCapabilities::new()
4274                            .image(true)
4275                            .audio(true)
4276                            .embedded_context(true),
4277                    ),
4278                    cx,
4279                )
4280            })))
4281        }
4282
4283        fn auth_methods(&self) -> &[acp::AuthMethod] {
4284            &[]
4285        }
4286
4287        fn authenticate(
4288            &self,
4289            _method_id: acp::AuthMethodId,
4290            _cx: &mut App,
4291        ) -> Task<gpui::Result<()>> {
4292            unimplemented!()
4293        }
4294
4295        fn prompt(
4296            &self,
4297            _id: Option<acp_thread::UserMessageId>,
4298            _params: acp::PromptRequest,
4299            _cx: &mut App,
4300        ) -> Task<gpui::Result<acp::PromptResponse>> {
4301            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
4302        }
4303
4304        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4305            unimplemented!()
4306        }
4307
4308        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4309            self
4310        }
4311    }
4312
4313    #[derive(Clone)]
4314    struct CwdCapturingConnection {
4315        captured_cwd: Arc<Mutex<Option<PathBuf>>>,
4316    }
4317
4318    impl CwdCapturingConnection {
4319        fn new() -> Self {
4320            Self {
4321                captured_cwd: Arc::new(Mutex::new(None)),
4322            }
4323        }
4324    }
4325
4326    impl AgentConnection for CwdCapturingConnection {
4327        fn telemetry_id(&self) -> SharedString {
4328            "cwd-capturing".into()
4329        }
4330
4331        fn new_session(
4332            self: Rc<Self>,
4333            project: Entity<Project>,
4334            cwd: &Path,
4335            cx: &mut gpui::App,
4336        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4337            *self.captured_cwd.lock() = Some(cwd.to_path_buf());
4338            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4339            let thread = cx.new(|cx| {
4340                AcpThread::new(
4341                    None,
4342                    "CwdCapturingConnection",
4343                    Some(cwd.to_path_buf()),
4344                    self.clone(),
4345                    project,
4346                    action_log,
4347                    SessionId::new("new-session"),
4348                    watch::Receiver::constant(
4349                        acp::PromptCapabilities::new()
4350                            .image(true)
4351                            .audio(true)
4352                            .embedded_context(true),
4353                    ),
4354                    cx,
4355                )
4356            });
4357            Task::ready(Ok(thread))
4358        }
4359
4360        fn supports_load_session(&self) -> bool {
4361            true
4362        }
4363
4364        fn load_session(
4365            self: Rc<Self>,
4366            session_id: acp::SessionId,
4367            project: Entity<Project>,
4368            cwd: &Path,
4369            _title: Option<SharedString>,
4370            cx: &mut App,
4371        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4372            *self.captured_cwd.lock() = Some(cwd.to_path_buf());
4373            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4374            let thread = cx.new(|cx| {
4375                AcpThread::new(
4376                    None,
4377                    "CwdCapturingConnection",
4378                    Some(cwd.to_path_buf()),
4379                    self.clone(),
4380                    project,
4381                    action_log,
4382                    session_id,
4383                    watch::Receiver::constant(
4384                        acp::PromptCapabilities::new()
4385                            .image(true)
4386                            .audio(true)
4387                            .embedded_context(true),
4388                    ),
4389                    cx,
4390                )
4391            });
4392            Task::ready(Ok(thread))
4393        }
4394
4395        fn auth_methods(&self) -> &[acp::AuthMethod] {
4396            &[]
4397        }
4398
4399        fn authenticate(
4400            &self,
4401            _method_id: acp::AuthMethodId,
4402            _cx: &mut App,
4403        ) -> Task<gpui::Result<()>> {
4404            Task::ready(Ok(()))
4405        }
4406
4407        fn prompt(
4408            &self,
4409            _id: Option<acp_thread::UserMessageId>,
4410            _params: acp::PromptRequest,
4411            _cx: &mut App,
4412        ) -> Task<gpui::Result<acp::PromptResponse>> {
4413            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4414        }
4415
4416        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4417
4418        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4419            self
4420        }
4421    }
4422
4423    pub(crate) fn init_test(cx: &mut TestAppContext) {
4424        cx.update(|cx| {
4425            let settings_store = SettingsStore::test(cx);
4426            cx.set_global(settings_store);
4427            theme::init(theme::LoadThemes::JustBase, cx);
4428            editor::init(cx);
4429            agent_panel::init(cx);
4430            release_channel::init(semver::Version::new(0, 0, 0), cx);
4431            prompt_store::init(cx)
4432        });
4433    }
4434
4435    fn active_thread(
4436        thread_view: &Entity<ConnectionView>,
4437        cx: &TestAppContext,
4438    ) -> Entity<ThreadView> {
4439        cx.read(|cx| {
4440            thread_view
4441                .read(cx)
4442                .active_thread()
4443                .expect("No active thread")
4444                .clone()
4445        })
4446    }
4447
4448    fn message_editor(
4449        thread_view: &Entity<ConnectionView>,
4450        cx: &TestAppContext,
4451    ) -> Entity<MessageEditor> {
4452        let thread = active_thread(thread_view, cx);
4453        cx.read(|cx| thread.read(cx).message_editor.clone())
4454    }
4455
4456    #[gpui::test]
4457    async fn test_rewind_views(cx: &mut TestAppContext) {
4458        init_test(cx);
4459
4460        let fs = FakeFs::new(cx.executor());
4461        fs.insert_tree(
4462            "/project",
4463            json!({
4464                "test1.txt": "old content 1",
4465                "test2.txt": "old content 2"
4466            }),
4467        )
4468        .await;
4469        let project = Project::test(fs, [Path::new("/project")], cx).await;
4470        let (multi_workspace, cx) =
4471            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4472        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4473
4474        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
4475        let connection_store =
4476            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
4477
4478        let connection = Rc::new(StubAgentConnection::new());
4479        let thread_view = cx.update(|window, cx| {
4480            cx.new(|cx| {
4481                ConnectionView::new(
4482                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4483                    connection_store,
4484                    Agent::Custom {
4485                        name: "Test".into(),
4486                    },
4487                    None,
4488                    None,
4489                    None,
4490                    None,
4491                    workspace.downgrade(),
4492                    project.clone(),
4493                    Some(thread_store.clone()),
4494                    None,
4495                    window,
4496                    cx,
4497                )
4498            })
4499        });
4500
4501        cx.run_until_parked();
4502
4503        let thread = thread_view
4504            .read_with(cx, |view, cx| {
4505                view.active_thread().map(|r| r.read(cx).thread.clone())
4506            })
4507            .unwrap();
4508
4509        // First user message
4510        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4511            acp::ToolCall::new("tool1", "Edit file 1")
4512                .kind(acp::ToolKind::Edit)
4513                .status(acp::ToolCallStatus::Completed)
4514                .content(vec![acp::ToolCallContent::Diff(
4515                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
4516                )]),
4517        )]);
4518
4519        thread
4520            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4521            .await
4522            .unwrap();
4523        cx.run_until_parked();
4524
4525        thread.read_with(cx, |thread, _cx| {
4526            assert_eq!(thread.entries().len(), 2);
4527        });
4528
4529        thread_view.read_with(cx, |view, cx| {
4530            let entry_view_state = view
4531                .active_thread()
4532                .map(|active| active.read(cx).entry_view_state.clone())
4533                .unwrap();
4534            entry_view_state.read_with(cx, |entry_view_state, _| {
4535                assert!(
4536                    entry_view_state
4537                        .entry(0)
4538                        .unwrap()
4539                        .message_editor()
4540                        .is_some()
4541                );
4542                assert!(entry_view_state.entry(1).unwrap().has_content());
4543            });
4544        });
4545
4546        // Second user message
4547        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4548            acp::ToolCall::new("tool2", "Edit file 2")
4549                .kind(acp::ToolKind::Edit)
4550                .status(acp::ToolCallStatus::Completed)
4551                .content(vec![acp::ToolCallContent::Diff(
4552                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4553                )]),
4554        )]);
4555
4556        thread
4557            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4558            .await
4559            .unwrap();
4560        cx.run_until_parked();
4561
4562        let second_user_message_id = thread.read_with(cx, |thread, _| {
4563            assert_eq!(thread.entries().len(), 4);
4564            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4565                panic!();
4566            };
4567            user_message.id.clone().unwrap()
4568        });
4569
4570        thread_view.read_with(cx, |view, cx| {
4571            let entry_view_state = view
4572                .active_thread()
4573                .unwrap()
4574                .read(cx)
4575                .entry_view_state
4576                .clone();
4577            entry_view_state.read_with(cx, |entry_view_state, _| {
4578                assert!(
4579                    entry_view_state
4580                        .entry(0)
4581                        .unwrap()
4582                        .message_editor()
4583                        .is_some()
4584                );
4585                assert!(entry_view_state.entry(1).unwrap().has_content());
4586                assert!(
4587                    entry_view_state
4588                        .entry(2)
4589                        .unwrap()
4590                        .message_editor()
4591                        .is_some()
4592                );
4593                assert!(entry_view_state.entry(3).unwrap().has_content());
4594            });
4595        });
4596
4597        // Rewind to first message
4598        thread
4599            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4600            .await
4601            .unwrap();
4602
4603        cx.run_until_parked();
4604
4605        thread.read_with(cx, |thread, _| {
4606            assert_eq!(thread.entries().len(), 2);
4607        });
4608
4609        thread_view.read_with(cx, |view, cx| {
4610            let active = view.active_thread().unwrap();
4611            active
4612                .read(cx)
4613                .entry_view_state
4614                .read_with(cx, |entry_view_state, _| {
4615                    assert!(
4616                        entry_view_state
4617                            .entry(0)
4618                            .unwrap()
4619                            .message_editor()
4620                            .is_some()
4621                    );
4622                    assert!(entry_view_state.entry(1).unwrap().has_content());
4623
4624                    // Old views should be dropped
4625                    assert!(entry_view_state.entry(2).is_none());
4626                    assert!(entry_view_state.entry(3).is_none());
4627                });
4628        });
4629    }
4630
4631    #[gpui::test]
4632    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4633        init_test(cx);
4634
4635        let connection = StubAgentConnection::new();
4636
4637        // Each user prompt will result in a user message entry plus an agent message entry.
4638        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4639            acp::ContentChunk::new("Response 1".into()),
4640        )]);
4641
4642        let (thread_view, cx) =
4643            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4644
4645        let thread = thread_view
4646            .read_with(cx, |view, cx| {
4647                view.active_thread().map(|r| r.read(cx).thread.clone())
4648            })
4649            .unwrap();
4650
4651        thread
4652            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4653            .await
4654            .unwrap();
4655        cx.run_until_parked();
4656
4657        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4658            acp::ContentChunk::new("Response 2".into()),
4659        )]);
4660
4661        thread
4662            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4663            .await
4664            .unwrap();
4665        cx.run_until_parked();
4666
4667        // Move somewhere else first so we're not trivially already on the last user prompt.
4668        active_thread(&thread_view, cx).update(cx, |view, cx| {
4669            view.scroll_to_top(cx);
4670        });
4671        cx.run_until_parked();
4672
4673        active_thread(&thread_view, cx).update(cx, |view, cx| {
4674            view.scroll_to_most_recent_user_prompt(cx);
4675            let scroll_top = view.list_state.logical_scroll_top();
4676            // Entries layout is: [User1, Assistant1, User2, Assistant2]
4677            assert_eq!(scroll_top.item_ix, 2);
4678        });
4679    }
4680
4681    #[gpui::test]
4682    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4683        cx: &mut TestAppContext,
4684    ) {
4685        init_test(cx);
4686
4687        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4688
4689        // With no entries, scrolling should be a no-op and must not panic.
4690        active_thread(&thread_view, cx).update(cx, |view, cx| {
4691            view.scroll_to_most_recent_user_prompt(cx);
4692            let scroll_top = view.list_state.logical_scroll_top();
4693            assert_eq!(scroll_top.item_ix, 0);
4694        });
4695    }
4696
4697    #[gpui::test]
4698    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4699        init_test(cx);
4700
4701        let connection = StubAgentConnection::new();
4702
4703        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4704            acp::ContentChunk::new("Response".into()),
4705        )]);
4706
4707        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4708        add_to_workspace(thread_view.clone(), cx);
4709
4710        let message_editor = message_editor(&thread_view, cx);
4711        message_editor.update_in(cx, |editor, window, cx| {
4712            editor.set_text("Original message to edit", window, cx);
4713        });
4714        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4715
4716        cx.run_until_parked();
4717
4718        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4719            assert_eq!(
4720                view.active_thread()
4721                    .and_then(|active| active.read(cx).editing_message),
4722                None
4723            );
4724
4725            view.active_thread()
4726                .map(|active| &active.read(cx).entry_view_state)
4727                .as_ref()
4728                .unwrap()
4729                .read(cx)
4730                .entry(0)
4731                .unwrap()
4732                .message_editor()
4733                .unwrap()
4734                .clone()
4735        });
4736
4737        // Focus
4738        cx.focus(&user_message_editor);
4739        thread_view.read_with(cx, |view, cx| {
4740            assert_eq!(
4741                view.active_thread()
4742                    .and_then(|active| active.read(cx).editing_message),
4743                Some(0)
4744            );
4745        });
4746
4747        // Edit
4748        user_message_editor.update_in(cx, |editor, window, cx| {
4749            editor.set_text("Edited message content", window, cx);
4750        });
4751
4752        // Cancel
4753        user_message_editor.update_in(cx, |_editor, window, cx| {
4754            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4755        });
4756
4757        thread_view.read_with(cx, |view, cx| {
4758            assert_eq!(
4759                view.active_thread()
4760                    .and_then(|active| active.read(cx).editing_message),
4761                None
4762            );
4763        });
4764
4765        user_message_editor.read_with(cx, |editor, cx| {
4766            assert_eq!(editor.text(cx), "Original message to edit");
4767        });
4768    }
4769
4770    #[gpui::test]
4771    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4772        init_test(cx);
4773
4774        let connection = StubAgentConnection::new();
4775
4776        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4777        add_to_workspace(thread_view.clone(), cx);
4778
4779        let message_editor = message_editor(&thread_view, cx);
4780        message_editor.update_in(cx, |editor, window, cx| {
4781            editor.set_text("", window, cx);
4782        });
4783
4784        let thread = cx.read(|cx| {
4785            thread_view
4786                .read(cx)
4787                .active_thread()
4788                .unwrap()
4789                .read(cx)
4790                .thread
4791                .clone()
4792        });
4793        let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4794
4795        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
4796            view.send(window, cx);
4797        });
4798        cx.run_until_parked();
4799
4800        let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4801        assert_eq!(
4802            entries_before, entries_after,
4803            "No message should be sent when editor is empty"
4804        );
4805    }
4806
4807    #[gpui::test]
4808    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4809        init_test(cx);
4810
4811        let connection = StubAgentConnection::new();
4812
4813        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4814            acp::ContentChunk::new("Response".into()),
4815        )]);
4816
4817        let (thread_view, cx) =
4818            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4819        add_to_workspace(thread_view.clone(), cx);
4820
4821        let message_editor = message_editor(&thread_view, cx);
4822        message_editor.update_in(cx, |editor, window, cx| {
4823            editor.set_text("Original message to edit", window, cx);
4824        });
4825        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4826
4827        cx.run_until_parked();
4828
4829        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4830            assert_eq!(
4831                view.active_thread()
4832                    .and_then(|active| active.read(cx).editing_message),
4833                None
4834            );
4835            assert_eq!(
4836                view.active_thread()
4837                    .unwrap()
4838                    .read(cx)
4839                    .thread
4840                    .read(cx)
4841                    .entries()
4842                    .len(),
4843                2
4844            );
4845
4846            view.active_thread()
4847                .map(|active| &active.read(cx).entry_view_state)
4848                .as_ref()
4849                .unwrap()
4850                .read(cx)
4851                .entry(0)
4852                .unwrap()
4853                .message_editor()
4854                .unwrap()
4855                .clone()
4856        });
4857
4858        // Focus
4859        cx.focus(&user_message_editor);
4860
4861        // Edit
4862        user_message_editor.update_in(cx, |editor, window, cx| {
4863            editor.set_text("Edited message content", window, cx);
4864        });
4865
4866        // Send
4867        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4868            acp::ContentChunk::new("New Response".into()),
4869        )]);
4870
4871        user_message_editor.update_in(cx, |_editor, window, cx| {
4872            window.dispatch_action(Box::new(Chat), cx);
4873        });
4874
4875        cx.run_until_parked();
4876
4877        thread_view.read_with(cx, |view, cx| {
4878            assert_eq!(
4879                view.active_thread()
4880                    .and_then(|active| active.read(cx).editing_message),
4881                None
4882            );
4883
4884            let entries = view
4885                .active_thread()
4886                .unwrap()
4887                .read(cx)
4888                .thread
4889                .read(cx)
4890                .entries();
4891            assert_eq!(entries.len(), 2);
4892            assert_eq!(
4893                entries[0].to_markdown(cx),
4894                "## User\n\nEdited message content\n\n"
4895            );
4896            assert_eq!(
4897                entries[1].to_markdown(cx),
4898                "## Assistant\n\nNew Response\n\n"
4899            );
4900
4901            let entry_view_state = view
4902                .active_thread()
4903                .map(|active| &active.read(cx).entry_view_state)
4904                .unwrap();
4905            let new_editor = entry_view_state.read_with(cx, |state, _cx| {
4906                assert!(!state.entry(1).unwrap().has_content());
4907                state.entry(0).unwrap().message_editor().unwrap().clone()
4908            });
4909
4910            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4911        })
4912    }
4913
4914    #[gpui::test]
4915    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4916        init_test(cx);
4917
4918        let connection = StubAgentConnection::new();
4919
4920        let (thread_view, cx) =
4921            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4922        add_to_workspace(thread_view.clone(), cx);
4923
4924        let message_editor = message_editor(&thread_view, cx);
4925        message_editor.update_in(cx, |editor, window, cx| {
4926            editor.set_text("Original message to edit", window, cx);
4927        });
4928        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4929
4930        cx.run_until_parked();
4931
4932        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4933            let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
4934            assert_eq!(thread.entries().len(), 1);
4935
4936            let editor = view
4937                .active_thread()
4938                .map(|active| &active.read(cx).entry_view_state)
4939                .as_ref()
4940                .unwrap()
4941                .read(cx)
4942                .entry(0)
4943                .unwrap()
4944                .message_editor()
4945                .unwrap()
4946                .clone();
4947
4948            (editor, thread.session_id().clone())
4949        });
4950
4951        // Focus
4952        cx.focus(&user_message_editor);
4953
4954        thread_view.read_with(cx, |view, cx| {
4955            assert_eq!(
4956                view.active_thread()
4957                    .and_then(|active| active.read(cx).editing_message),
4958                Some(0)
4959            );
4960        });
4961
4962        // Edit
4963        user_message_editor.update_in(cx, |editor, window, cx| {
4964            editor.set_text("Edited message content", window, cx);
4965        });
4966
4967        thread_view.read_with(cx, |view, cx| {
4968            assert_eq!(
4969                view.active_thread()
4970                    .and_then(|active| active.read(cx).editing_message),
4971                Some(0)
4972            );
4973        });
4974
4975        // Finish streaming response
4976        cx.update(|_, cx| {
4977            connection.send_update(
4978                session_id.clone(),
4979                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
4980                cx,
4981            );
4982            connection.end_turn(session_id, acp::StopReason::EndTurn);
4983        });
4984
4985        thread_view.read_with(cx, |view, cx| {
4986            assert_eq!(
4987                view.active_thread()
4988                    .and_then(|active| active.read(cx).editing_message),
4989                Some(0)
4990            );
4991        });
4992
4993        cx.run_until_parked();
4994
4995        // Should still be editing
4996        cx.update(|window, cx| {
4997            assert!(user_message_editor.focus_handle(cx).is_focused(window));
4998            assert_eq!(
4999                thread_view
5000                    .read(cx)
5001                    .active_thread()
5002                    .and_then(|active| active.read(cx).editing_message),
5003                Some(0)
5004            );
5005            assert_eq!(
5006                user_message_editor.read(cx).text(cx),
5007                "Edited message content"
5008            );
5009        });
5010    }
5011
5012    struct GeneratingThreadSetup {
5013        thread_view: Entity<ConnectionView>,
5014        thread: Entity<AcpThread>,
5015        message_editor: Entity<MessageEditor>,
5016    }
5017
5018    async fn setup_generating_thread(
5019        cx: &mut TestAppContext,
5020    ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
5021        let connection = StubAgentConnection::new();
5022
5023        let (thread_view, cx) =
5024            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5025        add_to_workspace(thread_view.clone(), cx);
5026
5027        let message_editor = message_editor(&thread_view, cx);
5028        message_editor.update_in(cx, |editor, window, cx| {
5029            editor.set_text("Hello", window, cx);
5030        });
5031        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5032
5033        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5034            let thread = view
5035                .active_thread()
5036                .as_ref()
5037                .unwrap()
5038                .read(cx)
5039                .thread
5040                .clone();
5041            (thread.clone(), thread.read(cx).session_id().clone())
5042        });
5043
5044        cx.run_until_parked();
5045
5046        cx.update(|_, cx| {
5047            connection.send_update(
5048                session_id.clone(),
5049                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5050                    "Response chunk".into(),
5051                )),
5052                cx,
5053            );
5054        });
5055
5056        cx.run_until_parked();
5057
5058        thread.read_with(cx, |thread, _cx| {
5059            assert_eq!(thread.status(), ThreadStatus::Generating);
5060        });
5061
5062        (
5063            GeneratingThreadSetup {
5064                thread_view,
5065                thread,
5066                message_editor,
5067            },
5068            cx,
5069        )
5070    }
5071
5072    #[gpui::test]
5073    async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
5074        init_test(cx);
5075
5076        let (setup, cx) = setup_generating_thread(cx).await;
5077
5078        let focus_handle = setup
5079            .thread_view
5080            .read_with(cx, |view, cx| view.focus_handle(cx));
5081        cx.update(|window, cx| {
5082            window.focus(&focus_handle, cx);
5083        });
5084
5085        setup.thread_view.update_in(cx, |_, window, cx| {
5086            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5087        });
5088
5089        cx.run_until_parked();
5090
5091        setup.thread.read_with(cx, |thread, _cx| {
5092            assert_eq!(thread.status(), ThreadStatus::Idle);
5093        });
5094    }
5095
5096    #[gpui::test]
5097    async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
5098        init_test(cx);
5099
5100        let (setup, cx) = setup_generating_thread(cx).await;
5101
5102        let editor_focus_handle = setup
5103            .message_editor
5104            .read_with(cx, |editor, cx| editor.focus_handle(cx));
5105        cx.update(|window, cx| {
5106            window.focus(&editor_focus_handle, cx);
5107        });
5108
5109        setup.message_editor.update_in(cx, |_, window, cx| {
5110            window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
5111        });
5112
5113        cx.run_until_parked();
5114
5115        setup.thread.read_with(cx, |thread, _cx| {
5116            assert_eq!(thread.status(), ThreadStatus::Idle);
5117        });
5118    }
5119
5120    #[gpui::test]
5121    async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
5122        init_test(cx);
5123
5124        let (thread_view, cx) =
5125            setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
5126        add_to_workspace(thread_view.clone(), cx);
5127
5128        let thread = thread_view.read_with(cx, |view, cx| {
5129            view.active_thread().unwrap().read(cx).thread.clone()
5130        });
5131
5132        thread.read_with(cx, |thread, _cx| {
5133            assert_eq!(thread.status(), ThreadStatus::Idle);
5134        });
5135
5136        let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
5137        cx.update(|window, cx| {
5138            window.focus(&focus_handle, cx);
5139        });
5140
5141        thread_view.update_in(cx, |_, window, cx| {
5142            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5143        });
5144
5145        cx.run_until_parked();
5146
5147        thread.read_with(cx, |thread, _cx| {
5148            assert_eq!(thread.status(), ThreadStatus::Idle);
5149        });
5150    }
5151
5152    #[gpui::test]
5153    async fn test_interrupt(cx: &mut TestAppContext) {
5154        init_test(cx);
5155
5156        let connection = StubAgentConnection::new();
5157
5158        let (thread_view, cx) =
5159            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5160        add_to_workspace(thread_view.clone(), cx);
5161
5162        let message_editor = message_editor(&thread_view, cx);
5163        message_editor.update_in(cx, |editor, window, cx| {
5164            editor.set_text("Message 1", window, cx);
5165        });
5166        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5167
5168        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5169            let thread = view.active_thread().unwrap().read(cx).thread.clone();
5170
5171            (thread.clone(), thread.read(cx).session_id().clone())
5172        });
5173
5174        cx.run_until_parked();
5175
5176        cx.update(|_, cx| {
5177            connection.send_update(
5178                session_id.clone(),
5179                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5180                    "Message 1 resp".into(),
5181                )),
5182                cx,
5183            );
5184        });
5185
5186        cx.run_until_parked();
5187
5188        thread.read_with(cx, |thread, cx| {
5189            assert_eq!(
5190                thread.to_markdown(cx),
5191                indoc::indoc! {"
5192                        ## User
5193
5194                        Message 1
5195
5196                        ## Assistant
5197
5198                        Message 1 resp
5199
5200                    "}
5201            )
5202        });
5203
5204        message_editor.update_in(cx, |editor, window, cx| {
5205            editor.set_text("Message 2", window, cx);
5206        });
5207        active_thread(&thread_view, cx)
5208            .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
5209
5210        cx.update(|_, cx| {
5211            // Simulate a response sent after beginning to cancel
5212            connection.send_update(
5213                session_id.clone(),
5214                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
5215                cx,
5216            );
5217        });
5218
5219        cx.run_until_parked();
5220
5221        // Last Message 1 response should appear before Message 2
5222        thread.read_with(cx, |thread, cx| {
5223            assert_eq!(
5224                thread.to_markdown(cx),
5225                indoc::indoc! {"
5226                        ## User
5227
5228                        Message 1
5229
5230                        ## Assistant
5231
5232                        Message 1 response
5233
5234                        ## User
5235
5236                        Message 2
5237
5238                    "}
5239            )
5240        });
5241
5242        cx.update(|_, cx| {
5243            connection.send_update(
5244                session_id.clone(),
5245                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5246                    "Message 2 response".into(),
5247                )),
5248                cx,
5249            );
5250            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5251        });
5252
5253        cx.run_until_parked();
5254
5255        thread.read_with(cx, |thread, cx| {
5256            assert_eq!(
5257                thread.to_markdown(cx),
5258                indoc::indoc! {"
5259                        ## User
5260
5261                        Message 1
5262
5263                        ## Assistant
5264
5265                        Message 1 response
5266
5267                        ## User
5268
5269                        Message 2
5270
5271                        ## Assistant
5272
5273                        Message 2 response
5274
5275                    "}
5276            )
5277        });
5278    }
5279
5280    #[gpui::test]
5281    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
5282        init_test(cx);
5283
5284        let connection = StubAgentConnection::new();
5285        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5286            acp::ContentChunk::new("Response".into()),
5287        )]);
5288
5289        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5290        add_to_workspace(thread_view.clone(), cx);
5291
5292        let message_editor = message_editor(&thread_view, cx);
5293        message_editor.update_in(cx, |editor, window, cx| {
5294            editor.set_text("Original message to edit", window, cx)
5295        });
5296        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5297        cx.run_until_parked();
5298
5299        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
5300            thread_view
5301                .active_thread()
5302                .map(|active| &active.read(cx).entry_view_state)
5303                .as_ref()
5304                .unwrap()
5305                .read(cx)
5306                .entry(0)
5307                .expect("Should have at least one entry")
5308                .message_editor()
5309                .expect("Should have message editor")
5310                .clone()
5311        });
5312
5313        cx.focus(&user_message_editor);
5314        thread_view.read_with(cx, |view, cx| {
5315            assert_eq!(
5316                view.active_thread()
5317                    .and_then(|active| active.read(cx).editing_message),
5318                Some(0)
5319            );
5320        });
5321
5322        // Ensure to edit the focused message before proceeding otherwise, since
5323        // its content is not different from what was sent, focus will be lost.
5324        user_message_editor.update_in(cx, |editor, window, cx| {
5325            editor.set_text("Original message to edit with ", window, cx)
5326        });
5327
5328        // Create a simple buffer with some text so we can create a selection
5329        // that will then be added to the message being edited.
5330        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
5331            (thread_view.workspace.clone(), thread_view.project.clone())
5332        });
5333        let buffer = project.update(cx, |project, cx| {
5334            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5335        });
5336
5337        workspace
5338            .update_in(cx, |workspace, window, cx| {
5339                let editor = cx.new(|cx| {
5340                    let mut editor =
5341                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5342
5343                    editor.change_selections(Default::default(), window, cx, |selections| {
5344                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5345                    });
5346
5347                    editor
5348                });
5349                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5350            })
5351            .unwrap();
5352
5353        thread_view.update_in(cx, |view, window, cx| {
5354            assert_eq!(
5355                view.active_thread()
5356                    .and_then(|active| active.read(cx).editing_message),
5357                Some(0)
5358            );
5359            view.insert_selections(window, cx);
5360        });
5361
5362        user_message_editor.read_with(cx, |editor, cx| {
5363            let text = editor.editor().read(cx).text(cx);
5364            let expected_text = String::from("Original message to edit with selection ");
5365
5366            assert_eq!(text, expected_text);
5367        });
5368    }
5369
5370    #[gpui::test]
5371    async fn test_insert_selections(cx: &mut TestAppContext) {
5372        init_test(cx);
5373
5374        let connection = StubAgentConnection::new();
5375        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5376            acp::ContentChunk::new("Response".into()),
5377        )]);
5378
5379        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5380        add_to_workspace(thread_view.clone(), cx);
5381
5382        let message_editor = message_editor(&thread_view, cx);
5383        message_editor.update_in(cx, |editor, window, cx| {
5384            editor.set_text("Can you review this snippet ", window, cx)
5385        });
5386
5387        // Create a simple buffer with some text so we can create a selection
5388        // that will then be added to the message being edited.
5389        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
5390            (thread_view.workspace.clone(), thread_view.project.clone())
5391        });
5392        let buffer = project.update(cx, |project, cx| {
5393            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5394        });
5395
5396        workspace
5397            .update_in(cx, |workspace, window, cx| {
5398                let editor = cx.new(|cx| {
5399                    let mut editor =
5400                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5401
5402                    editor.change_selections(Default::default(), window, cx, |selections| {
5403                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5404                    });
5405
5406                    editor
5407                });
5408                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5409            })
5410            .unwrap();
5411
5412        thread_view.update_in(cx, |view, window, cx| {
5413            assert_eq!(
5414                view.active_thread()
5415                    .and_then(|active| active.read(cx).editing_message),
5416                None
5417            );
5418            view.insert_selections(window, cx);
5419        });
5420
5421        message_editor.read_with(cx, |editor, cx| {
5422            let text = editor.text(cx);
5423            let expected_txt = String::from("Can you review this snippet selection ");
5424
5425            assert_eq!(text, expected_txt);
5426        })
5427    }
5428
5429    #[gpui::test]
5430    async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
5431        init_test(cx);
5432
5433        let tool_call_id = acp::ToolCallId::new("terminal-1");
5434        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
5435            .kind(acp::ToolKind::Edit);
5436
5437        let permission_options = ToolPermissionContext::new(
5438            TerminalTool::NAME,
5439            vec!["cargo build --release".to_string()],
5440        )
5441        .build_permission_options();
5442
5443        let connection =
5444            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5445                tool_call_id.clone(),
5446                permission_options,
5447            )]));
5448
5449        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5450
5451        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5452
5453        // Disable notifications to avoid popup windows
5454        cx.update(|_window, cx| {
5455            AgentSettings::override_global(
5456                AgentSettings {
5457                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5458                    ..AgentSettings::get_global(cx).clone()
5459                },
5460                cx,
5461            );
5462        });
5463
5464        let message_editor = message_editor(&thread_view, cx);
5465        message_editor.update_in(cx, |editor, window, cx| {
5466            editor.set_text("Run cargo build", window, cx);
5467        });
5468
5469        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5470
5471        cx.run_until_parked();
5472
5473        // Verify the tool call is in WaitingForConfirmation state with the expected options
5474        thread_view.read_with(cx, |thread_view, cx| {
5475            let thread = thread_view
5476                .active_thread()
5477                .expect("Thread should exist")
5478                .read(cx)
5479                .thread
5480                .clone();
5481            let thread = thread.read(cx);
5482
5483            let tool_call = thread.entries().iter().find_map(|entry| {
5484                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5485                    Some(call)
5486                } else {
5487                    None
5488                }
5489            });
5490
5491            assert!(tool_call.is_some(), "Expected a tool call entry");
5492            let tool_call = tool_call.unwrap();
5493
5494            // Verify it's waiting for confirmation
5495            assert!(
5496                matches!(
5497                    tool_call.status,
5498                    acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
5499                ),
5500                "Expected WaitingForConfirmation status, got {:?}",
5501                tool_call.status
5502            );
5503
5504            // Verify the options count (granularity options only, no separate Deny option)
5505            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5506                &tool_call.status
5507            {
5508                let PermissionOptions::Dropdown(choices) = options else {
5509                    panic!("Expected dropdown permission options");
5510                };
5511
5512                assert_eq!(
5513                    choices.len(),
5514                    3,
5515                    "Expected 3 permission options (granularity only)"
5516                );
5517
5518                // Verify specific button labels (now using neutral names)
5519                let labels: Vec<&str> = choices
5520                    .iter()
5521                    .map(|choice| choice.allow.name.as_ref())
5522                    .collect();
5523                assert!(
5524                    labels.contains(&"Always for terminal"),
5525                    "Missing 'Always for terminal' option"
5526                );
5527                assert!(
5528                    labels.contains(&"Always for `cargo build` commands"),
5529                    "Missing pattern option"
5530                );
5531                assert!(
5532                    labels.contains(&"Only this time"),
5533                    "Missing 'Only this time' option"
5534                );
5535            }
5536        });
5537    }
5538
5539    #[gpui::test]
5540    async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5541        init_test(cx);
5542
5543        let tool_call_id = acp::ToolCallId::new("edit-file-1");
5544        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5545            .kind(acp::ToolKind::Edit);
5546
5547        let permission_options =
5548            ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5549                .build_permission_options();
5550
5551        let connection =
5552            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5553                tool_call_id.clone(),
5554                permission_options,
5555            )]));
5556
5557        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5558
5559        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5560
5561        // Disable notifications
5562        cx.update(|_window, cx| {
5563            AgentSettings::override_global(
5564                AgentSettings {
5565                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5566                    ..AgentSettings::get_global(cx).clone()
5567                },
5568                cx,
5569            );
5570        });
5571
5572        let message_editor = message_editor(&thread_view, cx);
5573        message_editor.update_in(cx, |editor, window, cx| {
5574            editor.set_text("Edit the main file", window, cx);
5575        });
5576
5577        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5578
5579        cx.run_until_parked();
5580
5581        // Verify the options
5582        thread_view.read_with(cx, |thread_view, cx| {
5583            let thread = thread_view
5584                .active_thread()
5585                .expect("Thread should exist")
5586                .read(cx)
5587                .thread
5588                .clone();
5589            let thread = thread.read(cx);
5590
5591            let tool_call = thread.entries().iter().find_map(|entry| {
5592                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5593                    Some(call)
5594                } else {
5595                    None
5596                }
5597            });
5598
5599            assert!(tool_call.is_some(), "Expected a tool call entry");
5600            let tool_call = tool_call.unwrap();
5601
5602            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5603                &tool_call.status
5604            {
5605                let PermissionOptions::Dropdown(choices) = options else {
5606                    panic!("Expected dropdown permission options");
5607                };
5608
5609                let labels: Vec<&str> = choices
5610                    .iter()
5611                    .map(|choice| choice.allow.name.as_ref())
5612                    .collect();
5613                assert!(
5614                    labels.contains(&"Always for edit file"),
5615                    "Missing 'Always for edit file' option"
5616                );
5617                assert!(
5618                    labels.contains(&"Always for `src/`"),
5619                    "Missing path pattern option"
5620                );
5621            } else {
5622                panic!("Expected WaitingForConfirmation status");
5623            }
5624        });
5625    }
5626
5627    #[gpui::test]
5628    async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5629        init_test(cx);
5630
5631        let tool_call_id = acp::ToolCallId::new("fetch-1");
5632        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5633            .kind(acp::ToolKind::Fetch);
5634
5635        let permission_options =
5636            ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5637                .build_permission_options();
5638
5639        let connection =
5640            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5641                tool_call_id.clone(),
5642                permission_options,
5643            )]));
5644
5645        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5646
5647        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5648
5649        // Disable notifications
5650        cx.update(|_window, cx| {
5651            AgentSettings::override_global(
5652                AgentSettings {
5653                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5654                    ..AgentSettings::get_global(cx).clone()
5655                },
5656                cx,
5657            );
5658        });
5659
5660        let message_editor = message_editor(&thread_view, cx);
5661        message_editor.update_in(cx, |editor, window, cx| {
5662            editor.set_text("Fetch the docs", window, cx);
5663        });
5664
5665        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5666
5667        cx.run_until_parked();
5668
5669        // Verify the options
5670        thread_view.read_with(cx, |thread_view, cx| {
5671            let thread = thread_view
5672                .active_thread()
5673                .expect("Thread should exist")
5674                .read(cx)
5675                .thread
5676                .clone();
5677            let thread = thread.read(cx);
5678
5679            let tool_call = thread.entries().iter().find_map(|entry| {
5680                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5681                    Some(call)
5682                } else {
5683                    None
5684                }
5685            });
5686
5687            assert!(tool_call.is_some(), "Expected a tool call entry");
5688            let tool_call = tool_call.unwrap();
5689
5690            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5691                &tool_call.status
5692            {
5693                let PermissionOptions::Dropdown(choices) = options else {
5694                    panic!("Expected dropdown permission options");
5695                };
5696
5697                let labels: Vec<&str> = choices
5698                    .iter()
5699                    .map(|choice| choice.allow.name.as_ref())
5700                    .collect();
5701                assert!(
5702                    labels.contains(&"Always for fetch"),
5703                    "Missing 'Always for fetch' option"
5704                );
5705                assert!(
5706                    labels.contains(&"Always for `docs.rs`"),
5707                    "Missing domain pattern option"
5708                );
5709            } else {
5710                panic!("Expected WaitingForConfirmation status");
5711            }
5712        });
5713    }
5714
5715    #[gpui::test]
5716    async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5717        init_test(cx);
5718
5719        let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5720        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5721            .kind(acp::ToolKind::Edit);
5722
5723        // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5724        let permission_options = ToolPermissionContext::new(
5725            TerminalTool::NAME,
5726            vec!["./deploy.sh --production".to_string()],
5727        )
5728        .build_permission_options();
5729
5730        let connection =
5731            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5732                tool_call_id.clone(),
5733                permission_options,
5734            )]));
5735
5736        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5737
5738        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5739
5740        // Disable notifications
5741        cx.update(|_window, cx| {
5742            AgentSettings::override_global(
5743                AgentSettings {
5744                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5745                    ..AgentSettings::get_global(cx).clone()
5746                },
5747                cx,
5748            );
5749        });
5750
5751        let message_editor = message_editor(&thread_view, cx);
5752        message_editor.update_in(cx, |editor, window, cx| {
5753            editor.set_text("Run the deploy script", window, cx);
5754        });
5755
5756        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5757
5758        cx.run_until_parked();
5759
5760        // Verify only 2 options (no pattern button when command doesn't match pattern)
5761        thread_view.read_with(cx, |thread_view, cx| {
5762            let thread = thread_view
5763                .active_thread()
5764                .expect("Thread should exist")
5765                .read(cx)
5766                .thread
5767                .clone();
5768            let thread = thread.read(cx);
5769
5770            let tool_call = thread.entries().iter().find_map(|entry| {
5771                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5772                    Some(call)
5773                } else {
5774                    None
5775                }
5776            });
5777
5778            assert!(tool_call.is_some(), "Expected a tool call entry");
5779            let tool_call = tool_call.unwrap();
5780
5781            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5782                &tool_call.status
5783            {
5784                let PermissionOptions::Dropdown(choices) = options else {
5785                    panic!("Expected dropdown permission options");
5786                };
5787
5788                assert_eq!(
5789                    choices.len(),
5790                    2,
5791                    "Expected 2 permission options (no pattern option)"
5792                );
5793
5794                let labels: Vec<&str> = choices
5795                    .iter()
5796                    .map(|choice| choice.allow.name.as_ref())
5797                    .collect();
5798                assert!(
5799                    labels.contains(&"Always for terminal"),
5800                    "Missing 'Always for terminal' option"
5801                );
5802                assert!(
5803                    labels.contains(&"Only this time"),
5804                    "Missing 'Only this time' option"
5805                );
5806                // Should NOT contain a pattern option
5807                assert!(
5808                    !labels.iter().any(|l| l.contains("commands")),
5809                    "Should not have pattern option"
5810                );
5811            } else {
5812                panic!("Expected WaitingForConfirmation status");
5813            }
5814        });
5815    }
5816
5817    #[gpui::test]
5818    async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5819        init_test(cx);
5820
5821        let tool_call_id = acp::ToolCallId::new("action-test-1");
5822        let tool_call =
5823            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5824
5825        let permission_options =
5826            ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
5827                .build_permission_options();
5828
5829        let connection =
5830            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5831                tool_call_id.clone(),
5832                permission_options,
5833            )]));
5834
5835        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5836
5837        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5838        add_to_workspace(thread_view.clone(), cx);
5839
5840        cx.update(|_window, cx| {
5841            AgentSettings::override_global(
5842                AgentSettings {
5843                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5844                    ..AgentSettings::get_global(cx).clone()
5845                },
5846                cx,
5847            );
5848        });
5849
5850        let message_editor = message_editor(&thread_view, cx);
5851        message_editor.update_in(cx, |editor, window, cx| {
5852            editor.set_text("Run tests", window, cx);
5853        });
5854
5855        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5856
5857        cx.run_until_parked();
5858
5859        // Verify tool call is waiting for confirmation
5860        thread_view.read_with(cx, |thread_view, cx| {
5861            let tool_call = thread_view.pending_tool_call(cx);
5862            assert!(
5863                tool_call.is_some(),
5864                "Expected a tool call waiting for confirmation"
5865            );
5866        });
5867
5868        // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
5869        thread_view.update_in(cx, |_, window, cx| {
5870            window.dispatch_action(
5871                crate::AuthorizeToolCall {
5872                    tool_call_id: "action-test-1".to_string(),
5873                    option_id: "allow".to_string(),
5874                    option_kind: "AllowOnce".to_string(),
5875                }
5876                .boxed_clone(),
5877                cx,
5878            );
5879        });
5880
5881        cx.run_until_parked();
5882
5883        // Verify tool call is no longer waiting for confirmation (was authorized)
5884        thread_view.read_with(cx, |thread_view, cx| {
5885            let tool_call = thread_view.pending_tool_call(cx);
5886            assert!(
5887                tool_call.is_none(),
5888                "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
5889            );
5890        });
5891    }
5892
5893    #[gpui::test]
5894    async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
5895        init_test(cx);
5896
5897        let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
5898        let tool_call =
5899            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5900
5901        let permission_options =
5902            ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5903                .build_permission_options();
5904
5905        let connection =
5906            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5907                tool_call_id.clone(),
5908                permission_options.clone(),
5909            )]));
5910
5911        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5912
5913        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5914        add_to_workspace(thread_view.clone(), cx);
5915
5916        cx.update(|_window, cx| {
5917            AgentSettings::override_global(
5918                AgentSettings {
5919                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5920                    ..AgentSettings::get_global(cx).clone()
5921                },
5922                cx,
5923            );
5924        });
5925
5926        let message_editor = message_editor(&thread_view, cx);
5927        message_editor.update_in(cx, |editor, window, cx| {
5928            editor.set_text("Install dependencies", window, cx);
5929        });
5930
5931        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5932
5933        cx.run_until_parked();
5934
5935        // Find the pattern option ID
5936        let pattern_option = match &permission_options {
5937            PermissionOptions::Dropdown(choices) => choices
5938                .iter()
5939                .find(|choice| {
5940                    choice
5941                        .allow
5942                        .option_id
5943                        .0
5944                        .starts_with("always_allow_pattern:")
5945                })
5946                .map(|choice| &choice.allow)
5947                .expect("Should have a pattern option for npm command"),
5948            _ => panic!("Expected dropdown permission options"),
5949        };
5950
5951        // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
5952        thread_view.update_in(cx, |_, window, cx| {
5953            window.dispatch_action(
5954                crate::AuthorizeToolCall {
5955                    tool_call_id: "pattern-action-test-1".to_string(),
5956                    option_id: pattern_option.option_id.0.to_string(),
5957                    option_kind: "AllowAlways".to_string(),
5958                }
5959                .boxed_clone(),
5960                cx,
5961            );
5962        });
5963
5964        cx.run_until_parked();
5965
5966        // Verify tool call was authorized
5967        thread_view.read_with(cx, |thread_view, cx| {
5968            let tool_call = thread_view.pending_tool_call(cx);
5969            assert!(
5970                tool_call.is_none(),
5971                "Tool call should be authorized after selecting pattern option"
5972            );
5973        });
5974    }
5975
5976    #[gpui::test]
5977    async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
5978        init_test(cx);
5979
5980        let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
5981        let tool_call =
5982            acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
5983
5984        let permission_options =
5985            ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
5986                .build_permission_options();
5987
5988        let connection =
5989            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5990                tool_call_id.clone(),
5991                permission_options.clone(),
5992            )]));
5993
5994        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5995
5996        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5997        add_to_workspace(thread_view.clone(), cx);
5998
5999        cx.update(|_window, cx| {
6000            AgentSettings::override_global(
6001                AgentSettings {
6002                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6003                    ..AgentSettings::get_global(cx).clone()
6004                },
6005                cx,
6006            );
6007        });
6008
6009        let message_editor = message_editor(&thread_view, cx);
6010        message_editor.update_in(cx, |editor, window, cx| {
6011            editor.set_text("Push changes", window, cx);
6012        });
6013
6014        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6015
6016        cx.run_until_parked();
6017
6018        // Use default granularity (last option = "Only this time")
6019        // Simulate clicking the Deny button
6020        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
6021            view.reject_once(&RejectOnce, window, cx)
6022        });
6023
6024        cx.run_until_parked();
6025
6026        // Verify tool call was rejected (no longer waiting for confirmation)
6027        thread_view.read_with(cx, |thread_view, cx| {
6028            let tool_call = thread_view.pending_tool_call(cx);
6029            assert!(
6030                tool_call.is_none(),
6031                "Tool call should be rejected after Deny"
6032            );
6033        });
6034    }
6035
6036    #[gpui::test]
6037    async fn test_option_id_transformation_for_allow() {
6038        let permission_options = ToolPermissionContext::new(
6039            TerminalTool::NAME,
6040            vec!["cargo build --release".to_string()],
6041        )
6042        .build_permission_options();
6043
6044        let PermissionOptions::Dropdown(choices) = permission_options else {
6045            panic!("Expected dropdown permission options");
6046        };
6047
6048        let allow_ids: Vec<String> = choices
6049            .iter()
6050            .map(|choice| choice.allow.option_id.0.to_string())
6051            .collect();
6052
6053        assert!(allow_ids.contains(&"always_allow:terminal".to_string()));
6054        assert!(allow_ids.contains(&"allow".to_string()));
6055        assert!(
6056            allow_ids
6057                .iter()
6058                .any(|id| id.starts_with("always_allow_pattern:terminal\n")),
6059            "Missing allow pattern option"
6060        );
6061    }
6062
6063    #[gpui::test]
6064    async fn test_option_id_transformation_for_deny() {
6065        let permission_options = ToolPermissionContext::new(
6066            TerminalTool::NAME,
6067            vec!["cargo build --release".to_string()],
6068        )
6069        .build_permission_options();
6070
6071        let PermissionOptions::Dropdown(choices) = permission_options else {
6072            panic!("Expected dropdown permission options");
6073        };
6074
6075        let deny_ids: Vec<String> = choices
6076            .iter()
6077            .map(|choice| choice.deny.option_id.0.to_string())
6078            .collect();
6079
6080        assert!(deny_ids.contains(&"always_deny:terminal".to_string()));
6081        assert!(deny_ids.contains(&"deny".to_string()));
6082        assert!(
6083            deny_ids
6084                .iter()
6085                .any(|id| id.starts_with("always_deny_pattern:terminal\n")),
6086            "Missing deny pattern option"
6087        );
6088    }
6089
6090    #[gpui::test]
6091    async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
6092        init_test(cx);
6093
6094        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6095        add_to_workspace(thread_view.clone(), cx);
6096
6097        let active = active_thread(&thread_view, cx);
6098        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6099        let thread = cx.read(|cx| active.read(cx).thread.clone());
6100
6101        title_editor.read_with(cx, |editor, cx| {
6102            assert!(!editor.read_only(cx));
6103        });
6104
6105        cx.focus(&thread_view);
6106        cx.focus(&title_editor);
6107
6108        cx.dispatch_action(editor::actions::DeleteLine);
6109        cx.simulate_input("My Custom Title");
6110
6111        cx.run_until_parked();
6112
6113        title_editor.read_with(cx, |editor, cx| {
6114            assert_eq!(editor.text(cx), "My Custom Title");
6115        });
6116        thread.read_with(cx, |thread, _cx| {
6117            assert_eq!(thread.title().as_ref(), "My Custom Title");
6118        });
6119    }
6120
6121    #[gpui::test]
6122    async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
6123        init_test(cx);
6124
6125        let (thread_view, cx) =
6126            setup_thread_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
6127
6128        let active = active_thread(&thread_view, cx);
6129        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6130
6131        title_editor.read_with(cx, |editor, cx| {
6132            assert!(
6133                editor.read_only(cx),
6134                "Title editor should be read-only when the connection does not support set_title"
6135            );
6136        });
6137    }
6138
6139    #[gpui::test]
6140    async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
6141        init_test(cx);
6142
6143        let connection = StubAgentConnection::new();
6144
6145        let (thread_view, cx) =
6146            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6147
6148        let message_editor = message_editor(&thread_view, cx);
6149        message_editor.update_in(cx, |editor, window, cx| {
6150            editor.set_text("Some prompt", window, cx);
6151        });
6152        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6153
6154        let session_id = thread_view.read_with(cx, |view, cx| {
6155            view.active_thread()
6156                .unwrap()
6157                .read(cx)
6158                .thread
6159                .read(cx)
6160                .session_id()
6161                .clone()
6162        });
6163
6164        cx.run_until_parked();
6165
6166        cx.update(|_, _cx| {
6167            connection.end_turn(session_id, acp::StopReason::MaxTokens);
6168        });
6169
6170        cx.run_until_parked();
6171
6172        thread_view.read_with(cx, |thread_view, cx| {
6173            let state = thread_view.active_thread().unwrap();
6174            let error = &state.read(cx).thread_error;
6175            match error {
6176                Some(ThreadError::Other { message, .. }) => {
6177                    assert!(
6178                        message.contains("Max tokens reached"),
6179                        "Expected 'Max tokens reached' error, got: {}",
6180                        message
6181                    );
6182                }
6183                other => panic!(
6184                    "Expected ThreadError::Other with 'Max tokens reached', got: {:?}",
6185                    other.is_some()
6186                ),
6187            }
6188        });
6189    }
6190
6191    fn create_test_acp_thread(
6192        parent_session_id: Option<acp::SessionId>,
6193        session_id: &str,
6194        connection: Rc<dyn AgentConnection>,
6195        project: Entity<Project>,
6196        cx: &mut App,
6197    ) -> Entity<AcpThread> {
6198        let action_log = cx.new(|_| ActionLog::new(project.clone()));
6199        cx.new(|cx| {
6200            AcpThread::new(
6201                parent_session_id,
6202                "Test Thread",
6203                None,
6204                connection,
6205                project,
6206                action_log,
6207                acp::SessionId::new(session_id),
6208                watch::Receiver::constant(acp::PromptCapabilities::new()),
6209                cx,
6210            )
6211        })
6212    }
6213
6214    fn request_test_tool_authorization(
6215        thread: &Entity<AcpThread>,
6216        tool_call_id: &str,
6217        option_id: &str,
6218        cx: &mut TestAppContext,
6219    ) -> Task<acp::RequestPermissionOutcome> {
6220        let tool_call_id = acp::ToolCallId::new(tool_call_id);
6221        let label = format!("Tool {tool_call_id}");
6222        let option_id = acp::PermissionOptionId::new(option_id);
6223        cx.update(|cx| {
6224            thread.update(cx, |thread, cx| {
6225                thread
6226                    .request_tool_call_authorization(
6227                        acp::ToolCall::new(tool_call_id, label)
6228                            .kind(acp::ToolKind::Edit)
6229                            .into(),
6230                        PermissionOptions::Flat(vec![acp::PermissionOption::new(
6231                            option_id,
6232                            "Allow",
6233                            acp::PermissionOptionKind::AllowOnce,
6234                        )]),
6235                        cx,
6236                    )
6237                    .unwrap()
6238            })
6239        })
6240    }
6241
6242    #[gpui::test]
6243    async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {
6244        init_test(cx);
6245
6246        let fs = FakeFs::new(cx.executor());
6247        let project = Project::test(fs, [], cx).await;
6248        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6249
6250        let (thread, conversation) = cx.update(|cx| {
6251            let thread =
6252                create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
6253            let conversation = cx.new(|cx| {
6254                let mut conversation = Conversation::default();
6255                conversation.register_thread(thread.clone(), cx);
6256                conversation
6257            });
6258            (thread, conversation)
6259        });
6260
6261        let _task1 = request_test_tool_authorization(&thread, "tc-1", "allow-1", cx);
6262        let _task2 = request_test_tool_authorization(&thread, "tc-2", "allow-2", cx);
6263
6264        cx.read(|cx| {
6265            let session_id = acp::SessionId::new("session-1");
6266            let (_, tool_call_id, _) = conversation
6267                .read(cx)
6268                .pending_tool_call(&session_id, cx)
6269                .expect("Expected a pending tool call");
6270            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
6271        });
6272
6273        cx.update(|cx| {
6274            conversation.update(cx, |conversation, cx| {
6275                conversation.authorize_tool_call(
6276                    acp::SessionId::new("session-1"),
6277                    acp::ToolCallId::new("tc-1"),
6278                    acp::PermissionOptionId::new("allow-1"),
6279                    acp::PermissionOptionKind::AllowOnce,
6280                    cx,
6281                );
6282            });
6283        });
6284
6285        cx.run_until_parked();
6286
6287        cx.read(|cx| {
6288            let session_id = acp::SessionId::new("session-1");
6289            let (_, tool_call_id, _) = conversation
6290                .read(cx)
6291                .pending_tool_call(&session_id, cx)
6292                .expect("Expected tc-2 to be pending after tc-1 was authorized");
6293            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
6294        });
6295
6296        cx.update(|cx| {
6297            conversation.update(cx, |conversation, cx| {
6298                conversation.authorize_tool_call(
6299                    acp::SessionId::new("session-1"),
6300                    acp::ToolCallId::new("tc-2"),
6301                    acp::PermissionOptionId::new("allow-2"),
6302                    acp::PermissionOptionKind::AllowOnce,
6303                    cx,
6304                );
6305            });
6306        });
6307
6308        cx.run_until_parked();
6309
6310        cx.read(|cx| {
6311            let session_id = acp::SessionId::new("session-1");
6312            assert!(
6313                conversation
6314                    .read(cx)
6315                    .pending_tool_call(&session_id, cx)
6316                    .is_none(),
6317                "Expected no pending tool calls after both were authorized"
6318            );
6319        });
6320    }
6321
6322    #[gpui::test]
6323    async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {
6324        init_test(cx);
6325
6326        let fs = FakeFs::new(cx.executor());
6327        let project = Project::test(fs, [], cx).await;
6328        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6329
6330        let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
6331            let parent_thread =
6332                create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
6333            let subagent_thread = create_test_acp_thread(
6334                Some(acp::SessionId::new("parent")),
6335                "subagent",
6336                connection.clone(),
6337                project.clone(),
6338                cx,
6339            );
6340            let conversation = cx.new(|cx| {
6341                let mut conversation = Conversation::default();
6342                conversation.register_thread(parent_thread.clone(), cx);
6343                conversation.register_thread(subagent_thread.clone(), cx);
6344                conversation
6345            });
6346            (parent_thread, subagent_thread, conversation)
6347        });
6348
6349        let _parent_task =
6350            request_test_tool_authorization(&parent_thread, "parent-tc", "allow-parent", cx);
6351        let _subagent_task =
6352            request_test_tool_authorization(&subagent_thread, "subagent-tc", "allow-subagent", cx);
6353
6354        // Querying with the subagent's session ID returns only the
6355        // subagent's own tool call (subagent path is scoped to its session)
6356        cx.read(|cx| {
6357            let subagent_id = acp::SessionId::new("subagent");
6358            let (session_id, tool_call_id, _) = conversation
6359                .read(cx)
6360                .pending_tool_call(&subagent_id, cx)
6361                .expect("Expected subagent's pending tool call");
6362            assert_eq!(session_id, acp::SessionId::new("subagent"));
6363            assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
6364        });
6365
6366        // Querying with the parent's session ID returns the first pending
6367        // request in FIFO order across all sessions
6368        cx.read(|cx| {
6369            let parent_id = acp::SessionId::new("parent");
6370            let (session_id, tool_call_id, _) = conversation
6371                .read(cx)
6372                .pending_tool_call(&parent_id, cx)
6373                .expect("Expected a pending tool call from parent query");
6374            assert_eq!(session_id, acp::SessionId::new("parent"));
6375            assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
6376        });
6377    }
6378
6379    #[gpui::test]
6380    async fn test_conversation_parent_pending_tool_call_returns_first_across_threads(
6381        cx: &mut TestAppContext,
6382    ) {
6383        init_test(cx);
6384
6385        let fs = FakeFs::new(cx.executor());
6386        let project = Project::test(fs, [], cx).await;
6387        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6388
6389        let (thread_a, thread_b, conversation) = cx.update(|cx| {
6390            let thread_a =
6391                create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
6392            let thread_b =
6393                create_test_acp_thread(None, "thread-b", connection.clone(), project.clone(), cx);
6394            let conversation = cx.new(|cx| {
6395                let mut conversation = Conversation::default();
6396                conversation.register_thread(thread_a.clone(), cx);
6397                conversation.register_thread(thread_b.clone(), cx);
6398                conversation
6399            });
6400            (thread_a, thread_b, conversation)
6401        });
6402
6403        let _task_a = request_test_tool_authorization(&thread_a, "tc-a", "allow-a", cx);
6404        let _task_b = request_test_tool_authorization(&thread_b, "tc-b", "allow-b", cx);
6405
6406        // Both threads are non-subagent, so pending_tool_call always returns
6407        // the first entry from permission_requests (FIFO across all sessions)
6408        cx.read(|cx| {
6409            let session_a = acp::SessionId::new("thread-a");
6410            let (session_id, tool_call_id, _) = conversation
6411                .read(cx)
6412                .pending_tool_call(&session_a, cx)
6413                .expect("Expected a pending tool call");
6414            assert_eq!(session_id, acp::SessionId::new("thread-a"));
6415            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6416        });
6417
6418        // Querying with thread-b also returns thread-a's tool call,
6419        // because non-subagent queries always use permission_requests.first()
6420        cx.read(|cx| {
6421            let session_b = acp::SessionId::new("thread-b");
6422            let (session_id, tool_call_id, _) = conversation
6423                .read(cx)
6424                .pending_tool_call(&session_b, cx)
6425                .expect("Expected a pending tool call from thread-b query");
6426            assert_eq!(
6427                session_id,
6428                acp::SessionId::new("thread-a"),
6429                "Non-subagent queries always return the first pending request in FIFO order"
6430            );
6431            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6432        });
6433
6434        // After authorizing thread-a's tool call, thread-b's becomes first
6435        cx.update(|cx| {
6436            conversation.update(cx, |conversation, cx| {
6437                conversation.authorize_tool_call(
6438                    acp::SessionId::new("thread-a"),
6439                    acp::ToolCallId::new("tc-a"),
6440                    acp::PermissionOptionId::new("allow-a"),
6441                    acp::PermissionOptionKind::AllowOnce,
6442                    cx,
6443                );
6444            });
6445        });
6446
6447        cx.run_until_parked();
6448
6449        cx.read(|cx| {
6450            let session_b = acp::SessionId::new("thread-b");
6451            let (session_id, tool_call_id, _) = conversation
6452                .read(cx)
6453                .pending_tool_call(&session_b, cx)
6454                .expect("Expected thread-b's tool call after thread-a's was authorized");
6455            assert_eq!(session_id, acp::SessionId::new("thread-b"));
6456            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
6457        });
6458    }
6459
6460    #[gpui::test]
6461    async fn test_move_queued_message_to_empty_main_editor(cx: &mut TestAppContext) {
6462        init_test(cx);
6463
6464        let (connection_view, cx) =
6465            setup_thread_view(StubAgentServer::default_response(), cx).await;
6466
6467        // Add a plain-text message to the queue directly.
6468        active_thread(&connection_view, cx).update_in(cx, |thread, window, cx| {
6469            thread.add_to_queue(
6470                vec![acp::ContentBlock::Text(acp::TextContent::new(
6471                    "queued message".to_string(),
6472                ))],
6473                vec![],
6474                cx,
6475            );
6476            // Main editor must be empty for this path — it is by default, but
6477            // assert to make the precondition explicit.
6478            assert!(thread.message_editor.read(cx).is_empty(cx));
6479            thread.move_queued_message_to_main_editor(0, None, window, cx);
6480        });
6481
6482        cx.run_until_parked();
6483
6484        // Queue should now be empty.
6485        let queue_len = active_thread(&connection_view, cx)
6486            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6487        assert_eq!(queue_len, 0, "Queue should be empty after move");
6488
6489        // Main editor should contain the queued message text.
6490        let text = message_editor(&connection_view, cx).update(cx, |editor, cx| editor.text(cx));
6491        assert_eq!(
6492            text, "queued message",
6493            "Main editor should contain the moved queued message"
6494        );
6495    }
6496
6497    #[gpui::test]
6498    async fn test_move_queued_message_to_non_empty_main_editor(cx: &mut TestAppContext) {
6499        init_test(cx);
6500
6501        let (connection_view, cx) =
6502            setup_thread_view(StubAgentServer::default_response(), cx).await;
6503
6504        // Seed the main editor with existing content.
6505        message_editor(&connection_view, cx).update_in(cx, |editor, window, cx| {
6506            editor.set_message(
6507                vec![acp::ContentBlock::Text(acp::TextContent::new(
6508                    "existing content".to_string(),
6509                ))],
6510                window,
6511                cx,
6512            );
6513        });
6514
6515        // Add a plain-text message to the queue.
6516        active_thread(&connection_view, cx).update_in(cx, |thread, window, cx| {
6517            thread.add_to_queue(
6518                vec![acp::ContentBlock::Text(acp::TextContent::new(
6519                    "queued message".to_string(),
6520                ))],
6521                vec![],
6522                cx,
6523            );
6524            thread.move_queued_message_to_main_editor(0, None, window, cx);
6525        });
6526
6527        cx.run_until_parked();
6528
6529        // Queue should now be empty.
6530        let queue_len = active_thread(&connection_view, cx)
6531            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6532        assert_eq!(queue_len, 0, "Queue should be empty after move");
6533
6534        // Main editor should contain existing content + separator + queued content.
6535        let text = message_editor(&connection_view, cx).update(cx, |editor, cx| editor.text(cx));
6536        assert_eq!(
6537            text, "existing content\n\nqueued message",
6538            "Main editor should have existing content and queued message separated by two newlines"
6539        );
6540    }
6541
6542    #[gpui::test]
6543    async fn test_close_all_sessions_skips_when_unsupported(cx: &mut TestAppContext) {
6544        init_test(cx);
6545
6546        let fs = FakeFs::new(cx.executor());
6547        let project = Project::test(fs, [], cx).await;
6548        let (multi_workspace, cx) =
6549            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6550        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
6551
6552        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
6553        let connection_store =
6554            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
6555
6556        // StubAgentConnection defaults to supports_close_session() -> false
6557        let thread_view = cx.update(|window, cx| {
6558            cx.new(|cx| {
6559                ConnectionView::new(
6560                    Rc::new(StubAgentServer::default_response()),
6561                    connection_store,
6562                    Agent::Custom {
6563                        name: "Test".into(),
6564                    },
6565                    None,
6566                    None,
6567                    None,
6568                    None,
6569                    workspace.downgrade(),
6570                    project,
6571                    Some(thread_store),
6572                    None,
6573                    window,
6574                    cx,
6575                )
6576            })
6577        });
6578
6579        cx.run_until_parked();
6580
6581        thread_view.read_with(cx, |view, _cx| {
6582            let connected = view.as_connected().expect("Should be connected");
6583            assert!(
6584                !connected.threads.is_empty(),
6585                "There should be at least one thread"
6586            );
6587            assert!(
6588                !connected.connection.supports_close_session(),
6589                "StubAgentConnection should not support close"
6590            );
6591        });
6592
6593        thread_view
6594            .update(cx, |view, cx| {
6595                view.as_connected()
6596                    .expect("Should be connected")
6597                    .close_all_sessions(cx)
6598            })
6599            .await;
6600    }
6601
6602    #[gpui::test]
6603    async fn test_close_all_sessions_calls_close_when_supported(cx: &mut TestAppContext) {
6604        init_test(cx);
6605
6606        let (thread_view, cx) =
6607            setup_thread_view(StubAgentServer::new(CloseCapableConnection::new()), cx).await;
6608
6609        cx.run_until_parked();
6610
6611        let close_capable = thread_view.read_with(cx, |view, _cx| {
6612            let connected = view.as_connected().expect("Should be connected");
6613            assert!(
6614                !connected.threads.is_empty(),
6615                "There should be at least one thread"
6616            );
6617            assert!(
6618                connected.connection.supports_close_session(),
6619                "CloseCapableConnection should support close"
6620            );
6621            connected
6622                .connection
6623                .clone()
6624                .into_any()
6625                .downcast::<CloseCapableConnection>()
6626                .expect("Should be CloseCapableConnection")
6627        });
6628
6629        thread_view
6630            .update(cx, |view, cx| {
6631                view.as_connected()
6632                    .expect("Should be connected")
6633                    .close_all_sessions(cx)
6634            })
6635            .await;
6636
6637        let closed_count = close_capable.closed_sessions.lock().len();
6638        assert!(
6639            closed_count > 0,
6640            "close_session should have been called for each thread"
6641        );
6642    }
6643
6644    #[gpui::test]
6645    async fn test_close_session_returns_error_when_unsupported(cx: &mut TestAppContext) {
6646        init_test(cx);
6647
6648        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6649
6650        cx.run_until_parked();
6651
6652        let result = thread_view
6653            .update(cx, |view, cx| {
6654                let connected = view.as_connected().expect("Should be connected");
6655                assert!(
6656                    !connected.connection.supports_close_session(),
6657                    "StubAgentConnection should not support close"
6658                );
6659                let session_id = connected
6660                    .threads
6661                    .keys()
6662                    .next()
6663                    .expect("Should have at least one thread")
6664                    .clone();
6665                connected.connection.clone().close_session(&session_id, cx)
6666            })
6667            .await;
6668
6669        assert!(
6670            result.is_err(),
6671            "close_session should return an error when close is not supported"
6672        );
6673        assert!(
6674            result.unwrap_err().to_string().contains("not supported"),
6675            "Error message should indicate that closing is not supported"
6676        );
6677    }
6678
6679    #[derive(Clone)]
6680    struct CloseCapableConnection {
6681        closed_sessions: Arc<Mutex<Vec<acp::SessionId>>>,
6682    }
6683
6684    impl CloseCapableConnection {
6685        fn new() -> Self {
6686            Self {
6687                closed_sessions: Arc::new(Mutex::new(Vec::new())),
6688            }
6689        }
6690    }
6691
6692    impl AgentConnection for CloseCapableConnection {
6693        fn telemetry_id(&self) -> SharedString {
6694            "close-capable".into()
6695        }
6696
6697        fn new_session(
6698            self: Rc<Self>,
6699            project: Entity<Project>,
6700            cwd: &Path,
6701            cx: &mut gpui::App,
6702        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6703            let action_log = cx.new(|_| ActionLog::new(project.clone()));
6704            let thread = cx.new(|cx| {
6705                AcpThread::new(
6706                    None,
6707                    "CloseCapableConnection",
6708                    Some(cwd.to_path_buf()),
6709                    self,
6710                    project,
6711                    action_log,
6712                    SessionId::new("close-capable-session"),
6713                    watch::Receiver::constant(
6714                        acp::PromptCapabilities::new()
6715                            .image(true)
6716                            .audio(true)
6717                            .embedded_context(true),
6718                    ),
6719                    cx,
6720                )
6721            });
6722            Task::ready(Ok(thread))
6723        }
6724
6725        fn supports_close_session(&self) -> bool {
6726            true
6727        }
6728
6729        fn close_session(
6730            self: Rc<Self>,
6731            session_id: &acp::SessionId,
6732            _cx: &mut App,
6733        ) -> Task<Result<()>> {
6734            self.closed_sessions.lock().push(session_id.clone());
6735            Task::ready(Ok(()))
6736        }
6737
6738        fn auth_methods(&self) -> &[acp::AuthMethod] {
6739            &[]
6740        }
6741
6742        fn authenticate(
6743            &self,
6744            _method_id: acp::AuthMethodId,
6745            _cx: &mut App,
6746        ) -> Task<gpui::Result<()>> {
6747            Task::ready(Ok(()))
6748        }
6749
6750        fn prompt(
6751            &self,
6752            _id: Option<acp_thread::UserMessageId>,
6753            _params: acp::PromptRequest,
6754            _cx: &mut App,
6755        ) -> Task<gpui::Result<acp::PromptResponse>> {
6756            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
6757        }
6758
6759        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
6760
6761        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6762            self
6763        }
6764    }
6765}