conversation_view.rs

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