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