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
2726fn loading_contents_spinner(size: IconSize) -> AnyElement {
2727    Icon::new(IconName::LoadCircle)
2728        .size(size)
2729        .color(Color::Accent)
2730        .with_rotate_animation(3)
2731        .into_any_element()
2732}
2733
2734fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
2735    if agent_name == agent::ZED_AGENT_ID.as_ref() {
2736        format!("Message the {} — @ to include context", agent_name)
2737    } else if has_commands {
2738        format!(
2739            "Message {} — @ to include context, / for commands",
2740            agent_name
2741        )
2742    } else {
2743        format!("Message {} — @ to include context", agent_name)
2744    }
2745}
2746
2747impl Focusable for ConversationView {
2748    fn focus_handle(&self, cx: &App) -> FocusHandle {
2749        match self.active_thread() {
2750            Some(thread) => thread.read(cx).focus_handle(cx),
2751            None => self.focus_handle.clone(),
2752        }
2753    }
2754}
2755
2756#[cfg(any(test, feature = "test-support"))]
2757impl ConversationView {
2758    /// Expands a tool call so its content is visible.
2759    /// This is primarily useful for visual testing.
2760    pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
2761        if let Some(active) = self.active_thread() {
2762            active.update(cx, |active, _cx| {
2763                active.expanded_tool_calls.insert(tool_call_id);
2764            });
2765            cx.notify();
2766        }
2767    }
2768
2769    #[cfg(any(test, feature = "test-support"))]
2770    pub fn set_updated_at(&mut self, updated_at: Instant, cx: &mut Context<Self>) {
2771        let Some(connected) = self.as_connected_mut() else {
2772            return;
2773        };
2774
2775        connected.conversation.update(cx, |conversation, _cx| {
2776            conversation.updated_at = Some(updated_at);
2777        });
2778    }
2779}
2780
2781impl Render for ConversationView {
2782    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2783        self.sync_queued_message_editors(window, cx);
2784
2785        v_flex()
2786            .track_focus(&self.focus_handle)
2787            .size_full()
2788            .bg(cx.theme().colors().panel_background)
2789            .child(match &self.server_state {
2790                ServerState::Loading { .. } => v_flex()
2791                    .flex_1()
2792                    .size_full()
2793                    .items_center()
2794                    .justify_center()
2795                    .child(
2796                        Label::new("Loading…").color(Color::Muted).with_animation(
2797                            "loading-agent-label",
2798                            Animation::new(Duration::from_secs(2))
2799                                .repeat()
2800                                .with_easing(pulsating_between(0.3, 0.7)),
2801                            |label, delta| label.alpha(delta),
2802                        ),
2803                    )
2804                    .into_any(),
2805                ServerState::LoadError { error: e, .. } => v_flex()
2806                    .flex_1()
2807                    .size_full()
2808                    .items_center()
2809                    .justify_end()
2810                    .child(self.render_load_error(e, window, cx))
2811                    .into_any(),
2812                ServerState::Connected(ConnectedServerState {
2813                    connection,
2814                    auth_state:
2815                        AuthState::Unauthenticated {
2816                            description,
2817                            configuration_view,
2818                            pending_auth_method,
2819                            _subscription,
2820                        },
2821                    ..
2822                }) => v_flex()
2823                    .flex_1()
2824                    .size_full()
2825                    .justify_end()
2826                    .child(self.render_auth_required_state(
2827                        connection,
2828                        description.as_ref(),
2829                        configuration_view.as_ref(),
2830                        pending_auth_method.as_ref(),
2831                        window,
2832                        cx,
2833                    ))
2834                    .into_any_element(),
2835                ServerState::Connected(connected) => {
2836                    if let Some(view) = connected.active_view() {
2837                        view.clone().into_any_element()
2838                    } else {
2839                        debug_panic!("This state should never be reached");
2840                        div().into_any_element()
2841                    }
2842                }
2843            })
2844    }
2845}
2846
2847fn plan_label_markdown_style(
2848    status: &acp::PlanEntryStatus,
2849    window: &Window,
2850    cx: &App,
2851) -> MarkdownStyle {
2852    let default_md_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
2853
2854    MarkdownStyle {
2855        base_text_style: TextStyle {
2856            color: cx.theme().colors().text_muted,
2857            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2858                Some(gpui::StrikethroughStyle {
2859                    thickness: px(1.),
2860                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2861                })
2862            } else {
2863                None
2864            },
2865            ..default_md_style.base_text_style
2866        },
2867        ..default_md_style
2868    }
2869}
2870
2871#[cfg(test)]
2872pub(crate) mod tests {
2873    use acp_thread::StubAgentConnection;
2874    use action_log::ActionLog;
2875    use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
2876    use agent_client_protocol::SessionId;
2877    use editor::MultiBufferOffset;
2878    use fs::FakeFs;
2879    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
2880    use parking_lot::Mutex;
2881    use project::Project;
2882    use serde_json::json;
2883    use settings::SettingsStore;
2884    use std::any::Any;
2885    use std::path::{Path, PathBuf};
2886    use std::rc::Rc;
2887    use std::sync::Arc;
2888    use workspace::{Item, MultiWorkspace};
2889
2890    use crate::agent_panel;
2891    use crate::thread_metadata_store::ThreadMetadataStore;
2892
2893    use super::*;
2894
2895    #[gpui::test]
2896    async fn test_drop(cx: &mut TestAppContext) {
2897        init_test(cx);
2898
2899        let (conversation_view, _cx) =
2900            setup_conversation_view(StubAgentServer::default_response(), cx).await;
2901        let weak_view = conversation_view.downgrade();
2902        drop(conversation_view);
2903        assert!(!weak_view.is_upgradable());
2904    }
2905
2906    #[gpui::test]
2907    async fn test_external_source_prompt_requires_manual_send(cx: &mut TestAppContext) {
2908        init_test(cx);
2909
2910        let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2911            panic!("expected prompt from external source to sanitize successfully");
2912        };
2913        let initial_content = AgentInitialContent::FromExternalSource(prompt);
2914
2915        let (conversation_view, cx) = setup_conversation_view_with_initial_content(
2916            StubAgentServer::default_response(),
2917            initial_content,
2918            cx,
2919        )
2920        .await;
2921
2922        active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
2923            assert!(view.show_external_source_prompt_warning);
2924            assert_eq!(view.thread.read(cx).entries().len(), 0);
2925            assert_eq!(view.message_editor.read(cx).text(cx), "Write me a script");
2926        });
2927    }
2928
2929    #[gpui::test]
2930    async fn test_external_source_prompt_warning_clears_after_send(cx: &mut TestAppContext) {
2931        init_test(cx);
2932
2933        let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2934            panic!("expected prompt from external source to sanitize successfully");
2935        };
2936        let initial_content = AgentInitialContent::FromExternalSource(prompt);
2937
2938        let (conversation_view, cx) = setup_conversation_view_with_initial_content(
2939            StubAgentServer::default_response(),
2940            initial_content,
2941            cx,
2942        )
2943        .await;
2944
2945        active_thread(&conversation_view, cx)
2946            .update_in(cx, |view, window, cx| view.send(window, cx));
2947        cx.run_until_parked();
2948
2949        active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
2950            assert!(!view.show_external_source_prompt_warning);
2951            assert_eq!(view.message_editor.read(cx).text(cx), "");
2952            assert_eq!(view.thread.read(cx).entries().len(), 2);
2953        });
2954    }
2955
2956    #[gpui::test]
2957    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2958        init_test(cx);
2959
2960        let (conversation_view, cx) =
2961            setup_conversation_view(StubAgentServer::default_response(), cx).await;
2962
2963        let message_editor = message_editor(&conversation_view, cx);
2964        message_editor.update_in(cx, |editor, window, cx| {
2965            editor.set_text("Hello", window, cx);
2966        });
2967
2968        cx.deactivate_window();
2969
2970        active_thread(&conversation_view, cx)
2971            .update_in(cx, |view, window, cx| view.send(window, cx));
2972
2973        cx.run_until_parked();
2974
2975        assert!(
2976            cx.windows()
2977                .iter()
2978                .any(|window| window.downcast::<AgentNotification>().is_some())
2979        );
2980    }
2981
2982    #[gpui::test]
2983    async fn test_notification_for_error(cx: &mut TestAppContext) {
2984        init_test(cx);
2985
2986        let (conversation_view, cx) =
2987            setup_conversation_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2988
2989        let message_editor = message_editor(&conversation_view, cx);
2990        message_editor.update_in(cx, |editor, window, cx| {
2991            editor.set_text("Hello", window, cx);
2992        });
2993
2994        cx.deactivate_window();
2995
2996        active_thread(&conversation_view, cx)
2997            .update_in(cx, |view, window, cx| view.send(window, cx));
2998
2999        cx.run_until_parked();
3000
3001        assert!(
3002            cx.windows()
3003                .iter()
3004                .any(|window| window.downcast::<AgentNotification>().is_some())
3005        );
3006    }
3007
3008    #[gpui::test]
3009    async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
3010        init_test(cx);
3011
3012        let fs = FakeFs::new(cx.executor());
3013        let project = Project::test(fs, [], cx).await;
3014        let (multi_workspace, cx) =
3015            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3016        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3017
3018        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3019        let connection_store =
3020            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3021
3022        let conversation_view = cx.update(|window, cx| {
3023            cx.new(|cx| {
3024                ConversationView::new(
3025                    Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
3026                    connection_store,
3027                    Agent::Custom { id: "Test".into() },
3028                    Some(SessionId::new("resume-session")),
3029                    None,
3030                    None,
3031                    None,
3032                    workspace.downgrade(),
3033                    project,
3034                    Some(thread_store),
3035                    None,
3036                    window,
3037                    cx,
3038                )
3039            })
3040        });
3041
3042        cx.run_until_parked();
3043
3044        conversation_view.read_with(cx, |view, cx| {
3045            let state = view.active_thread().unwrap();
3046            assert!(state.read(cx).resumed_without_history);
3047            assert_eq!(state.read(cx).list_state.item_count(), 0);
3048        });
3049    }
3050
3051    #[derive(Clone)]
3052    struct RestoredAvailableCommandsConnection;
3053
3054    impl AgentConnection for RestoredAvailableCommandsConnection {
3055        fn agent_id(&self) -> AgentId {
3056            AgentId::new("restored-available-commands")
3057        }
3058
3059        fn telemetry_id(&self) -> SharedString {
3060            "restored-available-commands".into()
3061        }
3062
3063        fn new_session(
3064            self: Rc<Self>,
3065            project: Entity<Project>,
3066            _work_dirs: PathList,
3067            cx: &mut App,
3068        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3069            let thread = build_test_thread(
3070                self,
3071                project,
3072                "RestoredAvailableCommandsConnection",
3073                SessionId::new("new-session"),
3074                cx,
3075            );
3076            Task::ready(Ok(thread))
3077        }
3078
3079        fn supports_load_session(&self) -> bool {
3080            true
3081        }
3082
3083        fn load_session(
3084            self: Rc<Self>,
3085            session_id: acp::SessionId,
3086            project: Entity<Project>,
3087            _work_dirs: PathList,
3088            _title: Option<SharedString>,
3089            cx: &mut App,
3090        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3091            let thread = build_test_thread(
3092                self,
3093                project,
3094                "RestoredAvailableCommandsConnection",
3095                session_id,
3096                cx,
3097            );
3098
3099            thread
3100                .update(cx, |thread, cx| {
3101                    thread.handle_session_update(
3102                        acp::SessionUpdate::AvailableCommandsUpdate(
3103                            acp::AvailableCommandsUpdate::new(vec![acp::AvailableCommand::new(
3104                                "help", "Get help",
3105                            )]),
3106                        ),
3107                        cx,
3108                    )
3109                })
3110                .expect("available commands update should succeed");
3111
3112            Task::ready(Ok(thread))
3113        }
3114
3115        fn auth_methods(&self) -> &[acp::AuthMethod] {
3116            &[]
3117        }
3118
3119        fn authenticate(
3120            &self,
3121            _method_id: acp::AuthMethodId,
3122            _cx: &mut App,
3123        ) -> Task<gpui::Result<()>> {
3124            Task::ready(Ok(()))
3125        }
3126
3127        fn prompt(
3128            &self,
3129            _id: Option<acp_thread::UserMessageId>,
3130            _params: acp::PromptRequest,
3131            _cx: &mut App,
3132        ) -> Task<gpui::Result<acp::PromptResponse>> {
3133            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3134        }
3135
3136        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3137
3138        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3139            self
3140        }
3141    }
3142
3143    #[gpui::test]
3144    async fn test_restored_threads_keep_available_commands(cx: &mut TestAppContext) {
3145        init_test(cx);
3146
3147        let fs = FakeFs::new(cx.executor());
3148        let project = Project::test(fs, [], cx).await;
3149        let (multi_workspace, cx) =
3150            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3151        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3152
3153        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3154        let connection_store =
3155            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3156
3157        let conversation_view = cx.update(|window, cx| {
3158            cx.new(|cx| {
3159                ConversationView::new(
3160                    Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),
3161                    connection_store,
3162                    Agent::Custom { id: "Test".into() },
3163                    Some(SessionId::new("restored-session")),
3164                    None,
3165                    None,
3166                    None,
3167                    workspace.downgrade(),
3168                    project,
3169                    Some(thread_store),
3170                    None,
3171                    window,
3172                    cx,
3173                )
3174            })
3175        });
3176
3177        cx.run_until_parked();
3178
3179        let message_editor = message_editor(&conversation_view, cx);
3180        let editor =
3181            message_editor.update(cx, |message_editor, _cx| message_editor.editor().clone());
3182        let placeholder = editor.update(cx, |editor, cx| editor.placeholder_text(cx));
3183
3184        active_thread(&conversation_view, cx).read_with(cx, |view, _cx| {
3185            let available_commands = view
3186                .session_capabilities
3187                .read()
3188                .available_commands()
3189                .to_vec();
3190            assert_eq!(available_commands.len(), 1);
3191            assert_eq!(available_commands[0].name.as_str(), "help");
3192            assert_eq!(available_commands[0].description.as_str(), "Get help");
3193        });
3194
3195        assert_eq!(
3196            placeholder,
3197            Some("Message Test — @ to include context, / for commands".to_string())
3198        );
3199
3200        message_editor.update_in(cx, |editor, window, cx| {
3201            editor.set_text("/help", window, cx);
3202        });
3203
3204        let contents_result = message_editor
3205            .update(cx, |editor, cx| editor.contents(false, cx))
3206            .await;
3207
3208        assert!(contents_result.is_ok());
3209    }
3210
3211    #[gpui::test]
3212    async fn test_resume_thread_uses_session_cwd_when_inside_project(cx: &mut TestAppContext) {
3213        init_test(cx);
3214
3215        let fs = FakeFs::new(cx.executor());
3216        fs.insert_tree(
3217            "/project",
3218            json!({
3219                "subdir": {
3220                    "file.txt": "hello"
3221                }
3222            }),
3223        )
3224        .await;
3225        let project = Project::test(fs, [Path::new("/project")], cx).await;
3226        let (multi_workspace, cx) =
3227            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3228        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3229
3230        let connection = CwdCapturingConnection::new();
3231        let captured_cwd = connection.captured_work_dirs.clone();
3232
3233        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3234        let connection_store =
3235            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3236
3237        let _conversation_view = cx.update(|window, cx| {
3238            cx.new(|cx| {
3239                ConversationView::new(
3240                    Rc::new(StubAgentServer::new(connection)),
3241                    connection_store,
3242                    Agent::Custom { id: "Test".into() },
3243                    Some(SessionId::new("session-1")),
3244                    Some(PathList::new(&[PathBuf::from("/project/subdir")])),
3245                    None,
3246                    None,
3247                    workspace.downgrade(),
3248                    project,
3249                    Some(thread_store),
3250                    None,
3251                    window,
3252                    cx,
3253                )
3254            })
3255        });
3256
3257        cx.run_until_parked();
3258
3259        assert_eq!(
3260            captured_cwd.lock().as_ref().unwrap(),
3261            &PathList::new(&[Path::new("/project/subdir")]),
3262            "Should use session cwd when it's inside the project"
3263        );
3264    }
3265
3266    #[gpui::test]
3267    async fn test_refusal_handling(cx: &mut TestAppContext) {
3268        init_test(cx);
3269
3270        let (conversation_view, cx) =
3271            setup_conversation_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
3272
3273        let message_editor = message_editor(&conversation_view, cx);
3274        message_editor.update_in(cx, |editor, window, cx| {
3275            editor.set_text("Do something harmful", window, cx);
3276        });
3277
3278        active_thread(&conversation_view, cx)
3279            .update_in(cx, |view, window, cx| view.send(window, cx));
3280
3281        cx.run_until_parked();
3282
3283        // Check that the refusal error is set
3284        conversation_view.read_with(cx, |thread_view, cx| {
3285            let state = thread_view.active_thread().unwrap();
3286            assert!(
3287                matches!(state.read(cx).thread_error, Some(ThreadError::Refusal)),
3288                "Expected refusal error to be set"
3289            );
3290        });
3291    }
3292
3293    #[gpui::test]
3294    async fn test_connect_failure_transitions_to_load_error(cx: &mut TestAppContext) {
3295        init_test(cx);
3296
3297        let (conversation_view, cx) = setup_conversation_view(FailingAgentServer, cx).await;
3298
3299        conversation_view.read_with(cx, |view, cx| {
3300            let title = view.title(cx);
3301            assert_eq!(
3302                title.as_ref(),
3303                "Error Loading Codex CLI",
3304                "Tab title should show the agent name with an error prefix"
3305            );
3306            match &view.server_state {
3307                ServerState::LoadError {
3308                    error: LoadError::Other(msg),
3309                    ..
3310                } => {
3311                    assert!(
3312                        msg.contains("Invalid gzip header"),
3313                        "Error callout should contain the underlying extraction error, got: {msg}"
3314                    );
3315                }
3316                other => panic!(
3317                    "Expected LoadError::Other, got: {}",
3318                    match other {
3319                        ServerState::Loading(_) => "Loading (stuck!)",
3320                        ServerState::LoadError { .. } => "LoadError (wrong variant)",
3321                        ServerState::Connected(_) => "Connected",
3322                    }
3323                ),
3324            }
3325        });
3326    }
3327
3328    #[gpui::test]
3329    async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) {
3330        init_test(cx);
3331
3332        let connection = AuthGatedAgentConnection::new();
3333        let (conversation_view, cx) =
3334            setup_conversation_view(StubAgentServer::new(connection), cx).await;
3335
3336        // When new_session returns AuthRequired, the server should transition
3337        // to Connected + Unauthenticated rather than getting stuck in Loading.
3338        conversation_view.read_with(cx, |view, _cx| {
3339            let connected = view
3340                .as_connected()
3341                .expect("Should be in Connected state even though auth is required");
3342            assert!(
3343                !connected.auth_state.is_ok(),
3344                "Auth state should be Unauthenticated"
3345            );
3346            assert!(
3347                connected.active_id.is_none(),
3348                "There should be no active thread since no session was created"
3349            );
3350            assert!(
3351                connected.threads.is_empty(),
3352                "There should be no threads since no session was created"
3353            );
3354        });
3355
3356        conversation_view.read_with(cx, |view, _cx| {
3357            assert!(
3358                view.active_thread().is_none(),
3359                "active_thread() should be None when unauthenticated without a session"
3360            );
3361        });
3362
3363        // Authenticate using the real authenticate flow on ConnectionView.
3364        // This calls connection.authenticate(), which flips the internal flag,
3365        // then on success triggers reset() -> new_session() which now succeeds.
3366        conversation_view.update_in(cx, |view, window, cx| {
3367            view.authenticate(
3368                acp::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
3369                window,
3370                cx,
3371            );
3372        });
3373        cx.run_until_parked();
3374
3375        // After auth, the server should have an active thread in the Ok state.
3376        conversation_view.read_with(cx, |view, cx| {
3377            let connected = view
3378                .as_connected()
3379                .expect("Should still be in Connected state after auth");
3380            assert!(connected.auth_state.is_ok(), "Auth state should be Ok");
3381            assert!(
3382                connected.active_id.is_some(),
3383                "There should be an active thread after successful auth"
3384            );
3385            assert_eq!(
3386                connected.threads.len(),
3387                1,
3388                "There should be exactly one thread"
3389            );
3390
3391            let active = view
3392                .active_thread()
3393                .expect("active_thread() should return the new thread");
3394            assert!(
3395                active.read(cx).thread_error.is_none(),
3396                "The new thread should have no errors"
3397            );
3398        });
3399    }
3400
3401    #[gpui::test]
3402    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3403        init_test(cx);
3404
3405        let tool_call_id = acp::ToolCallId::new("1");
3406        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
3407            .kind(acp::ToolKind::Edit)
3408            .content(vec!["hi".into()]);
3409        let connection =
3410            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3411                tool_call_id,
3412                PermissionOptions::Flat(vec![acp::PermissionOption::new(
3413                    "1",
3414                    "Allow",
3415                    acp::PermissionOptionKind::AllowOnce,
3416                )]),
3417            )]));
3418
3419        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3420
3421        let (conversation_view, cx) =
3422            setup_conversation_view(StubAgentServer::new(connection), cx).await;
3423
3424        let message_editor = message_editor(&conversation_view, cx);
3425        message_editor.update_in(cx, |editor, window, cx| {
3426            editor.set_text("Hello", window, cx);
3427        });
3428
3429        cx.deactivate_window();
3430
3431        active_thread(&conversation_view, cx)
3432            .update_in(cx, |view, window, cx| view.send(window, cx));
3433
3434        cx.run_until_parked();
3435
3436        assert!(
3437            cx.windows()
3438                .iter()
3439                .any(|window| window.downcast::<AgentNotification>().is_some())
3440        );
3441    }
3442
3443    #[gpui::test]
3444    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
3445        init_test(cx);
3446
3447        let (conversation_view, cx) =
3448            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3449
3450        add_to_workspace(conversation_view.clone(), cx);
3451
3452        let message_editor = message_editor(&conversation_view, cx);
3453
3454        message_editor.update_in(cx, |editor, window, cx| {
3455            editor.set_text("Hello", window, cx);
3456        });
3457
3458        // Window is active (don't deactivate), but panel will be hidden
3459        // Note: In the test environment, the panel is not actually added to the dock,
3460        // so is_agent_panel_hidden will return true
3461
3462        active_thread(&conversation_view, cx)
3463            .update_in(cx, |view, window, cx| view.send(window, cx));
3464
3465        cx.run_until_parked();
3466
3467        // Should show notification because window is active but panel is hidden
3468        assert!(
3469            cx.windows()
3470                .iter()
3471                .any(|window| window.downcast::<AgentNotification>().is_some()),
3472            "Expected notification when panel is hidden"
3473        );
3474    }
3475
3476    #[gpui::test]
3477    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
3478        init_test(cx);
3479
3480        let (conversation_view, cx) =
3481            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3482
3483        let message_editor = message_editor(&conversation_view, cx);
3484        message_editor.update_in(cx, |editor, window, cx| {
3485            editor.set_text("Hello", window, cx);
3486        });
3487
3488        // Deactivate window - should show notification regardless of setting
3489        cx.deactivate_window();
3490
3491        active_thread(&conversation_view, cx)
3492            .update_in(cx, |view, window, cx| view.send(window, cx));
3493
3494        cx.run_until_parked();
3495
3496        // Should still show notification when window is inactive (existing behavior)
3497        assert!(
3498            cx.windows()
3499                .iter()
3500                .any(|window| window.downcast::<AgentNotification>().is_some()),
3501            "Expected notification when window is inactive"
3502        );
3503    }
3504
3505    #[gpui::test]
3506    async fn test_notification_when_different_conversation_is_active_in_visible_panel(
3507        cx: &mut TestAppContext,
3508    ) {
3509        init_test(cx);
3510
3511        let fs = FakeFs::new(cx.executor());
3512
3513        cx.update(|cx| {
3514            cx.update_flags(true, vec!["agent-v2".to_string()]);
3515            agent::ThreadStore::init_global(cx);
3516            language_model::LanguageModelRegistry::test(cx);
3517            <dyn Fs>::set_global(fs.clone(), cx);
3518        });
3519
3520        let project = Project::test(fs, [], cx).await;
3521        let multi_workspace_handle =
3522            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3523
3524        let workspace = multi_workspace_handle
3525            .read_with(cx, |mw, _cx| mw.workspace().clone())
3526            .unwrap();
3527
3528        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
3529
3530        let panel = workspace.update_in(cx, |workspace, window, cx| {
3531            let panel = cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx));
3532            workspace.add_panel(panel.clone(), window, cx);
3533            workspace.focus_panel::<crate::AgentPanel>(window, cx);
3534            panel
3535        });
3536
3537        cx.run_until_parked();
3538
3539        panel.update_in(cx, |panel, window, cx| {
3540            panel.open_external_thread_with_server(
3541                Rc::new(StubAgentServer::default_response()),
3542                window,
3543                cx,
3544            );
3545        });
3546
3547        cx.run_until_parked();
3548
3549        panel.read_with(cx, |panel, cx| {
3550            assert!(crate::AgentPanel::is_visible(&workspace, cx));
3551            assert!(panel.active_conversation_view().is_some());
3552        });
3553
3554        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3555        let connection_store =
3556            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3557
3558        let conversation_view = cx.update(|window, cx| {
3559            cx.new(|cx| {
3560                ConversationView::new(
3561                    Rc::new(StubAgentServer::default_response()),
3562                    connection_store,
3563                    Agent::Custom { id: "Test".into() },
3564                    None,
3565                    None,
3566                    None,
3567                    None,
3568                    workspace.downgrade(),
3569                    project.clone(),
3570                    Some(thread_store),
3571                    None,
3572                    window,
3573                    cx,
3574                )
3575            })
3576        });
3577
3578        cx.run_until_parked();
3579
3580        panel.read_with(cx, |panel, _cx| {
3581            assert_ne!(
3582                panel
3583                    .active_conversation_view()
3584                    .map(|view| view.entity_id()),
3585                Some(conversation_view.entity_id()),
3586                "The visible panel should still be showing a different conversation"
3587            );
3588        });
3589
3590        let message_editor = message_editor(&conversation_view, cx);
3591        message_editor.update_in(cx, |editor, window, cx| {
3592            editor.set_text("Hello", window, cx);
3593        });
3594
3595        active_thread(&conversation_view, cx)
3596            .update_in(cx, |view, window, cx| view.send(window, cx));
3597
3598        cx.run_until_parked();
3599
3600        assert!(
3601            cx.windows()
3602                .iter()
3603                .any(|window| window.downcast::<AgentNotification>().is_some()),
3604            "Expected notification when a different conversation is active in the visible panel"
3605        );
3606    }
3607
3608    #[gpui::test]
3609    async fn test_notification_when_workspace_is_background_in_multi_workspace(
3610        cx: &mut TestAppContext,
3611    ) {
3612        init_test(cx);
3613
3614        // Enable multi-workspace feature flag and init globals needed by AgentPanel
3615        let fs = FakeFs::new(cx.executor());
3616
3617        cx.update(|cx| {
3618            agent::ThreadStore::init_global(cx);
3619            language_model::LanguageModelRegistry::test(cx);
3620            <dyn Fs>::set_global(fs.clone(), cx);
3621        });
3622
3623        let project1 = Project::test(fs.clone(), [], cx).await;
3624
3625        // Create a MultiWorkspace window with one workspace
3626        let multi_workspace_handle =
3627            cx.add_window(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
3628
3629        // Get workspace 1 (the initial workspace)
3630        let workspace1 = multi_workspace_handle
3631            .read_with(cx, |mw, _cx| mw.workspace().clone())
3632            .unwrap();
3633
3634        let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
3635
3636        let panel = workspace1.update_in(cx, |workspace, window, cx| {
3637            let panel = cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx));
3638            workspace.add_panel(panel.clone(), window, cx);
3639
3640            // Open the dock and activate the agent panel so it's visible
3641            workspace.focus_panel::<crate::AgentPanel>(window, cx);
3642            panel
3643        });
3644
3645        cx.run_until_parked();
3646
3647        panel.update_in(cx, |panel, window, cx| {
3648            panel.open_external_thread_with_server(
3649                Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),
3650                window,
3651                cx,
3652            );
3653        });
3654
3655        cx.run_until_parked();
3656
3657        cx.read(|cx| {
3658            assert!(
3659                crate::AgentPanel::is_visible(&workspace1, cx),
3660                "AgentPanel should be visible in workspace1's dock"
3661            );
3662        });
3663
3664        // Set up thread view in workspace 1
3665        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3666        let connection_store =
3667            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project1.clone(), cx)));
3668
3669        let conversation_view = cx.update(|window, cx| {
3670            cx.new(|cx| {
3671                ConversationView::new(
3672                    Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),
3673                    connection_store,
3674                    Agent::Custom { id: "Test".into() },
3675                    None,
3676                    None,
3677                    None,
3678                    None,
3679                    workspace1.downgrade(),
3680                    project1.clone(),
3681                    Some(thread_store),
3682                    None,
3683                    window,
3684                    cx,
3685                )
3686            })
3687        });
3688        cx.run_until_parked();
3689
3690        let root_session_id = conversation_view
3691            .read_with(cx, |view, cx| {
3692                view.root_thread(cx)
3693                    .map(|thread| thread.read(cx).thread.read(cx).session_id().clone())
3694            })
3695            .expect("Conversation view should have a root thread");
3696
3697        let message_editor = message_editor(&conversation_view, cx);
3698        message_editor.update_in(cx, |editor, window, cx| {
3699            editor.set_text("Hello", window, cx);
3700        });
3701
3702        // Create a second workspace and switch to it.
3703        // This makes workspace1 the "background" workspace.
3704        let project2 = Project::test(fs, [], cx).await;
3705        multi_workspace_handle
3706            .update(cx, |mw, window, cx| {
3707                mw.test_add_workspace(project2, window, cx);
3708            })
3709            .unwrap();
3710
3711        cx.run_until_parked();
3712
3713        // Verify workspace1 is no longer the active workspace
3714        multi_workspace_handle
3715            .read_with(cx, |mw, _cx| {
3716                assert_ne!(mw.workspace(), &workspace1);
3717            })
3718            .unwrap();
3719
3720        // Window is active, agent panel is visible in workspace1, but workspace1
3721        // is in the background. The notification should show because the user
3722        // can't actually see the agent panel.
3723        active_thread(&conversation_view, cx)
3724            .update_in(cx, |view, window, cx| view.send(window, cx));
3725
3726        cx.run_until_parked();
3727
3728        assert!(
3729            cx.windows()
3730                .iter()
3731                .any(|window| window.downcast::<AgentNotification>().is_some()),
3732            "Expected notification when workspace is in background within MultiWorkspace"
3733        );
3734
3735        // Also verify: clicking "View Panel" should switch to workspace1.
3736        cx.windows()
3737            .iter()
3738            .find_map(|window| window.downcast::<AgentNotification>())
3739            .unwrap()
3740            .update(cx, |window, _, cx| window.accept(cx))
3741            .unwrap();
3742
3743        cx.run_until_parked();
3744
3745        multi_workspace_handle
3746            .read_with(cx, |mw, _cx| {
3747                assert_eq!(
3748                    mw.workspace(),
3749                    &workspace1,
3750                    "Expected workspace1 to become the active workspace after accepting notification"
3751                );
3752            })
3753            .unwrap();
3754
3755        panel.read_with(cx, |panel, cx| {
3756            let active_session_id = panel
3757                .active_agent_thread(cx)
3758                .map(|thread| thread.read(cx).session_id().clone());
3759            assert_eq!(
3760                active_session_id,
3761                Some(root_session_id),
3762                "Expected accepting the notification to load the notified thread in AgentPanel"
3763            );
3764        });
3765    }
3766
3767    #[gpui::test]
3768    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
3769        init_test(cx);
3770
3771        // Set notify_when_agent_waiting to Never
3772        cx.update(|cx| {
3773            AgentSettings::override_global(
3774                AgentSettings {
3775                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
3776                    ..AgentSettings::get_global(cx).clone()
3777                },
3778                cx,
3779            );
3780        });
3781
3782        let (conversation_view, cx) =
3783            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3784
3785        let message_editor = message_editor(&conversation_view, cx);
3786        message_editor.update_in(cx, |editor, window, cx| {
3787            editor.set_text("Hello", window, cx);
3788        });
3789
3790        // Window is active
3791
3792        active_thread(&conversation_view, cx)
3793            .update_in(cx, |view, window, cx| view.send(window, cx));
3794
3795        cx.run_until_parked();
3796
3797        // Should NOT show notification because notify_when_agent_waiting is Never
3798        assert!(
3799            !cx.windows()
3800                .iter()
3801                .any(|window| window.downcast::<AgentNotification>().is_some()),
3802            "Expected no notification when notify_when_agent_waiting is Never"
3803        );
3804    }
3805
3806    #[gpui::test]
3807    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
3808        init_test(cx);
3809
3810        let (conversation_view, cx) =
3811            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3812
3813        let weak_view = conversation_view.downgrade();
3814
3815        let message_editor = message_editor(&conversation_view, cx);
3816        message_editor.update_in(cx, |editor, window, cx| {
3817            editor.set_text("Hello", window, cx);
3818        });
3819
3820        cx.deactivate_window();
3821
3822        active_thread(&conversation_view, cx)
3823            .update_in(cx, |view, window, cx| view.send(window, cx));
3824
3825        cx.run_until_parked();
3826
3827        // Verify notification is shown
3828        assert!(
3829            cx.windows()
3830                .iter()
3831                .any(|window| window.downcast::<AgentNotification>().is_some()),
3832            "Expected notification to be shown"
3833        );
3834
3835        // Drop the thread view (simulating navigation to a new thread)
3836        drop(conversation_view);
3837        drop(message_editor);
3838        // Trigger an update to flush effects, which will call release_dropped_entities
3839        cx.update(|_window, _cx| {});
3840        cx.run_until_parked();
3841
3842        // Verify the entity was actually released
3843        assert!(
3844            !weak_view.is_upgradable(),
3845            "Thread view entity should be released after dropping"
3846        );
3847
3848        // The notification should be automatically closed via on_release
3849        assert!(
3850            !cx.windows()
3851                .iter()
3852                .any(|window| window.downcast::<AgentNotification>().is_some()),
3853            "Notification should be closed when thread view is dropped"
3854        );
3855    }
3856
3857    async fn setup_conversation_view(
3858        agent: impl AgentServer + 'static,
3859        cx: &mut TestAppContext,
3860    ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3861        let (conversation_view, _history, cx) =
3862            setup_conversation_view_with_history_and_initial_content(agent, None, cx).await;
3863        (conversation_view, cx)
3864    }
3865
3866    async fn setup_conversation_view_with_initial_content(
3867        agent: impl AgentServer + 'static,
3868        initial_content: AgentInitialContent,
3869        cx: &mut TestAppContext,
3870    ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3871        let (conversation_view, _history, cx) =
3872            setup_conversation_view_with_history_and_initial_content(
3873                agent,
3874                Some(initial_content),
3875                cx,
3876            )
3877            .await;
3878        (conversation_view, cx)
3879    }
3880
3881    async fn setup_conversation_view_with_history_and_initial_content(
3882        agent: impl AgentServer + 'static,
3883        initial_content: Option<AgentInitialContent>,
3884        cx: &mut TestAppContext,
3885    ) -> (
3886        Entity<ConversationView>,
3887        Option<Entity<ThreadHistory>>,
3888        &mut VisualTestContext,
3889    ) {
3890        let fs = FakeFs::new(cx.executor());
3891        let project = Project::test(fs, [], cx).await;
3892        let (multi_workspace, cx) =
3893            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3894        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3895
3896        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3897        let connection_store =
3898            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3899
3900        let agent_key = Agent::Custom { id: "Test".into() };
3901
3902        let conversation_view = cx.update(|window, cx| {
3903            cx.new(|cx| {
3904                ConversationView::new(
3905                    Rc::new(agent),
3906                    connection_store.clone(),
3907                    agent_key.clone(),
3908                    None,
3909                    None,
3910                    None,
3911                    initial_content,
3912                    workspace.downgrade(),
3913                    project,
3914                    Some(thread_store),
3915                    None,
3916                    window,
3917                    cx,
3918                )
3919            })
3920        });
3921        cx.run_until_parked();
3922
3923        let history = cx.update(|_window, cx| {
3924            connection_store
3925                .read(cx)
3926                .entry(&agent_key)
3927                .and_then(|e| e.read(cx).history().cloned())
3928        });
3929
3930        (conversation_view, history, cx)
3931    }
3932
3933    fn add_to_workspace(conversation_view: Entity<ConversationView>, cx: &mut VisualTestContext) {
3934        let workspace =
3935            conversation_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3936
3937        workspace
3938            .update_in(cx, |workspace, window, cx| {
3939                workspace.add_item_to_active_pane(
3940                    Box::new(cx.new(|_| ThreadViewItem(conversation_view.clone()))),
3941                    None,
3942                    true,
3943                    window,
3944                    cx,
3945                );
3946            })
3947            .unwrap();
3948    }
3949
3950    struct ThreadViewItem(Entity<ConversationView>);
3951
3952    impl Item for ThreadViewItem {
3953        type Event = ();
3954
3955        fn include_in_nav_history() -> bool {
3956            false
3957        }
3958
3959        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3960            "Test".into()
3961        }
3962    }
3963
3964    impl EventEmitter<()> for ThreadViewItem {}
3965
3966    impl Focusable for ThreadViewItem {
3967        fn focus_handle(&self, cx: &App) -> FocusHandle {
3968            self.0.read(cx).focus_handle(cx)
3969        }
3970    }
3971
3972    impl Render for ThreadViewItem {
3973        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3974            // Render the title editor in the element tree too. In the real app
3975            // it is part of the agent panel
3976            let title_editor = self
3977                .0
3978                .read(cx)
3979                .active_thread()
3980                .map(|t| t.read(cx).title_editor.clone());
3981
3982            v_flex().children(title_editor).child(self.0.clone())
3983        }
3984    }
3985
3986    pub(crate) struct StubAgentServer<C> {
3987        connection: C,
3988    }
3989
3990    impl<C> StubAgentServer<C> {
3991        pub(crate) fn new(connection: C) -> Self {
3992            Self { connection }
3993        }
3994    }
3995
3996    impl StubAgentServer<StubAgentConnection> {
3997        pub(crate) fn default_response() -> Self {
3998            let conn = StubAgentConnection::new();
3999            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4000                acp::ContentChunk::new("Default response".into()),
4001            )]);
4002            Self::new(conn)
4003        }
4004    }
4005
4006    impl<C> AgentServer for StubAgentServer<C>
4007    where
4008        C: 'static + AgentConnection + Send + Clone,
4009    {
4010        fn logo(&self) -> ui::IconName {
4011            ui::IconName::ZedAgent
4012        }
4013
4014        fn agent_id(&self) -> AgentId {
4015            "Test".into()
4016        }
4017
4018        fn connect(
4019            &self,
4020            _delegate: AgentServerDelegate,
4021            _project: Entity<Project>,
4022            _cx: &mut App,
4023        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4024            Task::ready(Ok(Rc::new(self.connection.clone())))
4025        }
4026
4027        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4028            self
4029        }
4030    }
4031
4032    struct FailingAgentServer;
4033
4034    impl AgentServer for FailingAgentServer {
4035        fn logo(&self) -> ui::IconName {
4036            ui::IconName::AiOpenAi
4037        }
4038
4039        fn agent_id(&self) -> AgentId {
4040            AgentId::new("Codex CLI")
4041        }
4042
4043        fn connect(
4044            &self,
4045            _delegate: AgentServerDelegate,
4046            _project: Entity<Project>,
4047            _cx: &mut App,
4048        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4049            Task::ready(Err(anyhow!(
4050                "extracting downloaded asset for \
4051                 https://github.com/zed-industries/codex-acp/releases/download/v0.9.4/\
4052                 codex-acp-0.9.4-aarch64-pc-windows-msvc.zip: \
4053                 failed to iterate over archive: Invalid gzip header"
4054            )))
4055        }
4056
4057        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4058            self
4059        }
4060    }
4061
4062    fn build_test_thread(
4063        connection: Rc<dyn AgentConnection>,
4064        project: Entity<Project>,
4065        name: &'static str,
4066        session_id: SessionId,
4067        cx: &mut App,
4068    ) -> Entity<AcpThread> {
4069        let action_log = cx.new(|_| ActionLog::new(project.clone()));
4070        cx.new(|cx| {
4071            AcpThread::new(
4072                None,
4073                Some(name.into()),
4074                None,
4075                connection,
4076                project,
4077                action_log,
4078                session_id,
4079                watch::Receiver::constant(
4080                    acp::PromptCapabilities::new()
4081                        .image(true)
4082                        .audio(true)
4083                        .embedded_context(true),
4084                ),
4085                cx,
4086            )
4087        })
4088    }
4089
4090    #[derive(Clone)]
4091    struct ResumeOnlyAgentConnection;
4092
4093    impl AgentConnection for ResumeOnlyAgentConnection {
4094        fn agent_id(&self) -> AgentId {
4095            AgentId::new("resume-only")
4096        }
4097
4098        fn telemetry_id(&self) -> SharedString {
4099            "resume-only".into()
4100        }
4101
4102        fn new_session(
4103            self: Rc<Self>,
4104            project: Entity<Project>,
4105            _work_dirs: PathList,
4106            cx: &mut gpui::App,
4107        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4108            let thread = build_test_thread(
4109                self,
4110                project,
4111                "ResumeOnlyAgentConnection",
4112                SessionId::new("new-session"),
4113                cx,
4114            );
4115            Task::ready(Ok(thread))
4116        }
4117
4118        fn supports_resume_session(&self) -> bool {
4119            true
4120        }
4121
4122        fn resume_session(
4123            self: Rc<Self>,
4124            session_id: acp::SessionId,
4125            project: Entity<Project>,
4126            _work_dirs: PathList,
4127            _title: Option<SharedString>,
4128            cx: &mut App,
4129        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4130            let thread =
4131                build_test_thread(self, project, "ResumeOnlyAgentConnection", session_id, cx);
4132            Task::ready(Ok(thread))
4133        }
4134
4135        fn auth_methods(&self) -> &[acp::AuthMethod] {
4136            &[]
4137        }
4138
4139        fn authenticate(
4140            &self,
4141            _method_id: acp::AuthMethodId,
4142            _cx: &mut App,
4143        ) -> Task<gpui::Result<()>> {
4144            Task::ready(Ok(()))
4145        }
4146
4147        fn prompt(
4148            &self,
4149            _id: Option<acp_thread::UserMessageId>,
4150            _params: acp::PromptRequest,
4151            _cx: &mut App,
4152        ) -> Task<gpui::Result<acp::PromptResponse>> {
4153            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4154        }
4155
4156        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4157
4158        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4159            self
4160        }
4161    }
4162
4163    /// Simulates an agent that requires authentication before a session can be
4164    /// created. `new_session` returns `AuthRequired` until `authenticate` is
4165    /// called with the correct method, after which sessions are created normally.
4166    #[derive(Clone)]
4167    struct AuthGatedAgentConnection {
4168        authenticated: Arc<Mutex<bool>>,
4169        auth_method: acp::AuthMethod,
4170    }
4171
4172    impl AuthGatedAgentConnection {
4173        const AUTH_METHOD_ID: &str = "test-login";
4174
4175        fn new() -> Self {
4176            Self {
4177                authenticated: Arc::new(Mutex::new(false)),
4178                auth_method: acp::AuthMethod::Agent(acp::AuthMethodAgent::new(
4179                    Self::AUTH_METHOD_ID,
4180                    "Test Login",
4181                )),
4182            }
4183        }
4184    }
4185
4186    impl AgentConnection for AuthGatedAgentConnection {
4187        fn agent_id(&self) -> AgentId {
4188            AgentId::new("auth-gated")
4189        }
4190
4191        fn telemetry_id(&self) -> SharedString {
4192            "auth-gated".into()
4193        }
4194
4195        fn new_session(
4196            self: Rc<Self>,
4197            project: Entity<Project>,
4198            work_dirs: PathList,
4199            cx: &mut gpui::App,
4200        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4201            if !*self.authenticated.lock() {
4202                return Task::ready(Err(acp_thread::AuthRequired::new()
4203                    .with_description("Sign in to continue".to_string())
4204                    .into()));
4205            }
4206
4207            let session_id = acp::SessionId::new("auth-gated-session");
4208            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4209            Task::ready(Ok(cx.new(|cx| {
4210                AcpThread::new(
4211                    None,
4212                    None,
4213                    Some(work_dirs),
4214                    self,
4215                    project,
4216                    action_log,
4217                    session_id,
4218                    watch::Receiver::constant(
4219                        acp::PromptCapabilities::new()
4220                            .image(true)
4221                            .audio(true)
4222                            .embedded_context(true),
4223                    ),
4224                    cx,
4225                )
4226            })))
4227        }
4228
4229        fn auth_methods(&self) -> &[acp::AuthMethod] {
4230            std::slice::from_ref(&self.auth_method)
4231        }
4232
4233        fn authenticate(
4234            &self,
4235            method_id: acp::AuthMethodId,
4236            _cx: &mut App,
4237        ) -> Task<gpui::Result<()>> {
4238            if &method_id == self.auth_method.id() {
4239                *self.authenticated.lock() = true;
4240                Task::ready(Ok(()))
4241            } else {
4242                Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
4243            }
4244        }
4245
4246        fn prompt(
4247            &self,
4248            _id: Option<acp_thread::UserMessageId>,
4249            _params: acp::PromptRequest,
4250            _cx: &mut App,
4251        ) -> Task<gpui::Result<acp::PromptResponse>> {
4252            unimplemented!()
4253        }
4254
4255        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4256            unimplemented!()
4257        }
4258
4259        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4260            self
4261        }
4262    }
4263
4264    #[derive(Clone)]
4265    struct SaboteurAgentConnection;
4266
4267    impl AgentConnection for SaboteurAgentConnection {
4268        fn agent_id(&self) -> AgentId {
4269            AgentId::new("saboteur")
4270        }
4271
4272        fn telemetry_id(&self) -> SharedString {
4273            "saboteur".into()
4274        }
4275
4276        fn new_session(
4277            self: Rc<Self>,
4278            project: Entity<Project>,
4279            work_dirs: PathList,
4280            cx: &mut gpui::App,
4281        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4282            Task::ready(Ok(cx.new(|cx| {
4283                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4284                AcpThread::new(
4285                    None,
4286                    None,
4287                    Some(work_dirs),
4288                    self,
4289                    project,
4290                    action_log,
4291                    SessionId::new("test"),
4292                    watch::Receiver::constant(
4293                        acp::PromptCapabilities::new()
4294                            .image(true)
4295                            .audio(true)
4296                            .embedded_context(true),
4297                    ),
4298                    cx,
4299                )
4300            })))
4301        }
4302
4303        fn auth_methods(&self) -> &[acp::AuthMethod] {
4304            &[]
4305        }
4306
4307        fn authenticate(
4308            &self,
4309            _method_id: acp::AuthMethodId,
4310            _cx: &mut App,
4311        ) -> Task<gpui::Result<()>> {
4312            unimplemented!()
4313        }
4314
4315        fn prompt(
4316            &self,
4317            _id: Option<acp_thread::UserMessageId>,
4318            _params: acp::PromptRequest,
4319            _cx: &mut App,
4320        ) -> Task<gpui::Result<acp::PromptResponse>> {
4321            Task::ready(Err(anyhow::anyhow!("Error prompting")))
4322        }
4323
4324        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4325            unimplemented!()
4326        }
4327
4328        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4329            self
4330        }
4331    }
4332
4333    /// Simulates a model which always returns a refusal response
4334    #[derive(Clone)]
4335    struct RefusalAgentConnection;
4336
4337    impl AgentConnection for RefusalAgentConnection {
4338        fn agent_id(&self) -> AgentId {
4339            AgentId::new("refusal")
4340        }
4341
4342        fn telemetry_id(&self) -> SharedString {
4343            "refusal".into()
4344        }
4345
4346        fn new_session(
4347            self: Rc<Self>,
4348            project: Entity<Project>,
4349            work_dirs: PathList,
4350            cx: &mut gpui::App,
4351        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4352            Task::ready(Ok(cx.new(|cx| {
4353                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4354                AcpThread::new(
4355                    None,
4356                    None,
4357                    Some(work_dirs),
4358                    self,
4359                    project,
4360                    action_log,
4361                    SessionId::new("test"),
4362                    watch::Receiver::constant(
4363                        acp::PromptCapabilities::new()
4364                            .image(true)
4365                            .audio(true)
4366                            .embedded_context(true),
4367                    ),
4368                    cx,
4369                )
4370            })))
4371        }
4372
4373        fn auth_methods(&self) -> &[acp::AuthMethod] {
4374            &[]
4375        }
4376
4377        fn authenticate(
4378            &self,
4379            _method_id: acp::AuthMethodId,
4380            _cx: &mut App,
4381        ) -> Task<gpui::Result<()>> {
4382            unimplemented!()
4383        }
4384
4385        fn prompt(
4386            &self,
4387            _id: Option<acp_thread::UserMessageId>,
4388            _params: acp::PromptRequest,
4389            _cx: &mut App,
4390        ) -> Task<gpui::Result<acp::PromptResponse>> {
4391            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
4392        }
4393
4394        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4395            unimplemented!()
4396        }
4397
4398        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4399            self
4400        }
4401    }
4402
4403    #[derive(Clone)]
4404    struct CwdCapturingConnection {
4405        captured_work_dirs: Arc<Mutex<Option<PathList>>>,
4406    }
4407
4408    impl CwdCapturingConnection {
4409        fn new() -> Self {
4410            Self {
4411                captured_work_dirs: Arc::new(Mutex::new(None)),
4412            }
4413        }
4414    }
4415
4416    impl AgentConnection for CwdCapturingConnection {
4417        fn agent_id(&self) -> AgentId {
4418            AgentId::new("cwd-capturing")
4419        }
4420
4421        fn telemetry_id(&self) -> SharedString {
4422            "cwd-capturing".into()
4423        }
4424
4425        fn new_session(
4426            self: Rc<Self>,
4427            project: Entity<Project>,
4428            work_dirs: PathList,
4429            cx: &mut gpui::App,
4430        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4431            *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4432            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4433            let thread = cx.new(|cx| {
4434                AcpThread::new(
4435                    None,
4436                    None,
4437                    Some(work_dirs),
4438                    self.clone(),
4439                    project,
4440                    action_log,
4441                    SessionId::new("new-session"),
4442                    watch::Receiver::constant(
4443                        acp::PromptCapabilities::new()
4444                            .image(true)
4445                            .audio(true)
4446                            .embedded_context(true),
4447                    ),
4448                    cx,
4449                )
4450            });
4451            Task::ready(Ok(thread))
4452        }
4453
4454        fn supports_load_session(&self) -> bool {
4455            true
4456        }
4457
4458        fn load_session(
4459            self: Rc<Self>,
4460            session_id: acp::SessionId,
4461            project: Entity<Project>,
4462            work_dirs: PathList,
4463            _title: Option<SharedString>,
4464            cx: &mut App,
4465        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4466            *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4467            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4468            let thread = cx.new(|cx| {
4469                AcpThread::new(
4470                    None,
4471                    None,
4472                    Some(work_dirs),
4473                    self.clone(),
4474                    project,
4475                    action_log,
4476                    session_id,
4477                    watch::Receiver::constant(
4478                        acp::PromptCapabilities::new()
4479                            .image(true)
4480                            .audio(true)
4481                            .embedded_context(true),
4482                    ),
4483                    cx,
4484                )
4485            });
4486            Task::ready(Ok(thread))
4487        }
4488
4489        fn auth_methods(&self) -> &[acp::AuthMethod] {
4490            &[]
4491        }
4492
4493        fn authenticate(
4494            &self,
4495            _method_id: acp::AuthMethodId,
4496            _cx: &mut App,
4497        ) -> Task<gpui::Result<()>> {
4498            Task::ready(Ok(()))
4499        }
4500
4501        fn prompt(
4502            &self,
4503            _id: Option<acp_thread::UserMessageId>,
4504            _params: acp::PromptRequest,
4505            _cx: &mut App,
4506        ) -> Task<gpui::Result<acp::PromptResponse>> {
4507            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4508        }
4509
4510        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4511
4512        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4513            self
4514        }
4515    }
4516
4517    pub(crate) fn init_test(cx: &mut TestAppContext) {
4518        cx.update(|cx| {
4519            let settings_store = SettingsStore::test(cx);
4520            cx.set_global(settings_store);
4521            ThreadMetadataStore::init_global(cx);
4522            theme_settings::init(theme::LoadThemes::JustBase, cx);
4523            editor::init(cx);
4524            agent_panel::init(cx);
4525            release_channel::init(semver::Version::new(0, 0, 0), cx);
4526            prompt_store::init(cx)
4527        });
4528    }
4529
4530    fn active_thread(
4531        conversation_view: &Entity<ConversationView>,
4532        cx: &TestAppContext,
4533    ) -> Entity<ThreadView> {
4534        cx.read(|cx| {
4535            conversation_view
4536                .read(cx)
4537                .active_thread()
4538                .expect("No active thread")
4539                .clone()
4540        })
4541    }
4542
4543    fn message_editor(
4544        conversation_view: &Entity<ConversationView>,
4545        cx: &TestAppContext,
4546    ) -> Entity<MessageEditor> {
4547        let thread = active_thread(conversation_view, cx);
4548        cx.read(|cx| thread.read(cx).message_editor.clone())
4549    }
4550
4551    #[gpui::test]
4552    async fn test_rewind_views(cx: &mut TestAppContext) {
4553        init_test(cx);
4554
4555        let fs = FakeFs::new(cx.executor());
4556        fs.insert_tree(
4557            "/project",
4558            json!({
4559                "test1.txt": "old content 1",
4560                "test2.txt": "old content 2"
4561            }),
4562        )
4563        .await;
4564        let project = Project::test(fs, [Path::new("/project")], cx).await;
4565        let (multi_workspace, cx) =
4566            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4567        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4568
4569        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
4570        let connection_store =
4571            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
4572
4573        let connection = Rc::new(StubAgentConnection::new());
4574        let conversation_view = cx.update(|window, cx| {
4575            cx.new(|cx| {
4576                ConversationView::new(
4577                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4578                    connection_store,
4579                    Agent::Custom { id: "Test".into() },
4580                    None,
4581                    None,
4582                    None,
4583                    None,
4584                    workspace.downgrade(),
4585                    project.clone(),
4586                    Some(thread_store.clone()),
4587                    None,
4588                    window,
4589                    cx,
4590                )
4591            })
4592        });
4593
4594        cx.run_until_parked();
4595
4596        let thread = conversation_view
4597            .read_with(cx, |view, cx| {
4598                view.active_thread().map(|r| r.read(cx).thread.clone())
4599            })
4600            .unwrap();
4601
4602        // First user message
4603        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4604            acp::ToolCall::new("tool1", "Edit file 1")
4605                .kind(acp::ToolKind::Edit)
4606                .status(acp::ToolCallStatus::Completed)
4607                .content(vec![acp::ToolCallContent::Diff(
4608                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
4609                )]),
4610        )]);
4611
4612        thread
4613            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4614            .await
4615            .unwrap();
4616        cx.run_until_parked();
4617
4618        thread.read_with(cx, |thread, _cx| {
4619            assert_eq!(thread.entries().len(), 2);
4620        });
4621
4622        conversation_view.read_with(cx, |view, cx| {
4623            let entry_view_state = view
4624                .active_thread()
4625                .map(|active| active.read(cx).entry_view_state.clone())
4626                .unwrap();
4627            entry_view_state.read_with(cx, |entry_view_state, _| {
4628                assert!(
4629                    entry_view_state
4630                        .entry(0)
4631                        .unwrap()
4632                        .message_editor()
4633                        .is_some()
4634                );
4635                assert!(entry_view_state.entry(1).unwrap().has_content());
4636            });
4637        });
4638
4639        // Second user message
4640        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4641            acp::ToolCall::new("tool2", "Edit file 2")
4642                .kind(acp::ToolKind::Edit)
4643                .status(acp::ToolCallStatus::Completed)
4644                .content(vec![acp::ToolCallContent::Diff(
4645                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4646                )]),
4647        )]);
4648
4649        thread
4650            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4651            .await
4652            .unwrap();
4653        cx.run_until_parked();
4654
4655        let second_user_message_id = thread.read_with(cx, |thread, _| {
4656            assert_eq!(thread.entries().len(), 4);
4657            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4658                panic!();
4659            };
4660            user_message.id.clone().unwrap()
4661        });
4662
4663        conversation_view.read_with(cx, |view, cx| {
4664            let entry_view_state = view
4665                .active_thread()
4666                .unwrap()
4667                .read(cx)
4668                .entry_view_state
4669                .clone();
4670            entry_view_state.read_with(cx, |entry_view_state, _| {
4671                assert!(
4672                    entry_view_state
4673                        .entry(0)
4674                        .unwrap()
4675                        .message_editor()
4676                        .is_some()
4677                );
4678                assert!(entry_view_state.entry(1).unwrap().has_content());
4679                assert!(
4680                    entry_view_state
4681                        .entry(2)
4682                        .unwrap()
4683                        .message_editor()
4684                        .is_some()
4685                );
4686                assert!(entry_view_state.entry(3).unwrap().has_content());
4687            });
4688        });
4689
4690        // Rewind to first message
4691        thread
4692            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4693            .await
4694            .unwrap();
4695
4696        cx.run_until_parked();
4697
4698        thread.read_with(cx, |thread, _| {
4699            assert_eq!(thread.entries().len(), 2);
4700        });
4701
4702        conversation_view.read_with(cx, |view, cx| {
4703            let active = view.active_thread().unwrap();
4704            active
4705                .read(cx)
4706                .entry_view_state
4707                .read_with(cx, |entry_view_state, _| {
4708                    assert!(
4709                        entry_view_state
4710                            .entry(0)
4711                            .unwrap()
4712                            .message_editor()
4713                            .is_some()
4714                    );
4715                    assert!(entry_view_state.entry(1).unwrap().has_content());
4716
4717                    // Old views should be dropped
4718                    assert!(entry_view_state.entry(2).is_none());
4719                    assert!(entry_view_state.entry(3).is_none());
4720                });
4721        });
4722    }
4723
4724    #[gpui::test]
4725    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4726        init_test(cx);
4727
4728        let connection = StubAgentConnection::new();
4729
4730        // Each user prompt will result in a user message entry plus an agent message entry.
4731        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4732            acp::ContentChunk::new("Response 1".into()),
4733        )]);
4734
4735        let (conversation_view, cx) =
4736            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4737
4738        let thread = conversation_view
4739            .read_with(cx, |view, cx| {
4740                view.active_thread().map(|r| r.read(cx).thread.clone())
4741            })
4742            .unwrap();
4743
4744        thread
4745            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4746            .await
4747            .unwrap();
4748        cx.run_until_parked();
4749
4750        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4751            acp::ContentChunk::new("Response 2".into()),
4752        )]);
4753
4754        thread
4755            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4756            .await
4757            .unwrap();
4758        cx.run_until_parked();
4759
4760        // Move somewhere else first so we're not trivially already on the last user prompt.
4761        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4762            view.scroll_to_top(cx);
4763        });
4764        cx.run_until_parked();
4765
4766        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4767            view.scroll_to_most_recent_user_prompt(cx);
4768            let scroll_top = view.list_state.logical_scroll_top();
4769            // Entries layout is: [User1, Assistant1, User2, Assistant2]
4770            assert_eq!(scroll_top.item_ix, 2);
4771        });
4772    }
4773
4774    #[gpui::test]
4775    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4776        cx: &mut TestAppContext,
4777    ) {
4778        init_test(cx);
4779
4780        let (conversation_view, cx) =
4781            setup_conversation_view(StubAgentServer::default_response(), cx).await;
4782
4783        // With no entries, scrolling should be a no-op and must not panic.
4784        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4785            view.scroll_to_most_recent_user_prompt(cx);
4786            let scroll_top = view.list_state.logical_scroll_top();
4787            assert_eq!(scroll_top.item_ix, 0);
4788        });
4789    }
4790
4791    #[gpui::test]
4792    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4793        init_test(cx);
4794
4795        let connection = StubAgentConnection::new();
4796
4797        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4798            acp::ContentChunk::new("Response".into()),
4799        )]);
4800
4801        let (conversation_view, cx) =
4802            setup_conversation_view(StubAgentServer::new(connection), cx).await;
4803        add_to_workspace(conversation_view.clone(), cx);
4804
4805        let message_editor = message_editor(&conversation_view, cx);
4806        message_editor.update_in(cx, |editor, window, cx| {
4807            editor.set_text("Original message to edit", window, cx);
4808        });
4809        active_thread(&conversation_view, cx)
4810            .update_in(cx, |view, window, cx| view.send(window, cx));
4811
4812        cx.run_until_parked();
4813
4814        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4815            assert_eq!(
4816                view.active_thread()
4817                    .and_then(|active| active.read(cx).editing_message),
4818                None
4819            );
4820
4821            view.active_thread()
4822                .map(|active| &active.read(cx).entry_view_state)
4823                .as_ref()
4824                .unwrap()
4825                .read(cx)
4826                .entry(0)
4827                .unwrap()
4828                .message_editor()
4829                .unwrap()
4830                .clone()
4831        });
4832
4833        // Focus
4834        cx.focus(&user_message_editor);
4835        conversation_view.read_with(cx, |view, cx| {
4836            assert_eq!(
4837                view.active_thread()
4838                    .and_then(|active| active.read(cx).editing_message),
4839                Some(0)
4840            );
4841        });
4842
4843        // Edit
4844        user_message_editor.update_in(cx, |editor, window, cx| {
4845            editor.set_text("Edited message content", window, cx);
4846        });
4847
4848        // Cancel
4849        user_message_editor.update_in(cx, |_editor, window, cx| {
4850            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4851        });
4852
4853        conversation_view.read_with(cx, |view, cx| {
4854            assert_eq!(
4855                view.active_thread()
4856                    .and_then(|active| active.read(cx).editing_message),
4857                None
4858            );
4859        });
4860
4861        user_message_editor.read_with(cx, |editor, cx| {
4862            assert_eq!(editor.text(cx), "Original message to edit");
4863        });
4864    }
4865
4866    #[gpui::test]
4867    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4868        init_test(cx);
4869
4870        let connection = StubAgentConnection::new();
4871
4872        let (conversation_view, cx) =
4873            setup_conversation_view(StubAgentServer::new(connection), cx).await;
4874        add_to_workspace(conversation_view.clone(), cx);
4875
4876        let message_editor = message_editor(&conversation_view, cx);
4877        message_editor.update_in(cx, |editor, window, cx| {
4878            editor.set_text("", window, cx);
4879        });
4880
4881        let thread = cx.read(|cx| {
4882            conversation_view
4883                .read(cx)
4884                .active_thread()
4885                .unwrap()
4886                .read(cx)
4887                .thread
4888                .clone()
4889        });
4890        let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4891
4892        active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
4893            view.send(window, cx);
4894        });
4895        cx.run_until_parked();
4896
4897        let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4898        assert_eq!(
4899            entries_before, entries_after,
4900            "No message should be sent when editor is empty"
4901        );
4902    }
4903
4904    #[gpui::test]
4905    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4906        init_test(cx);
4907
4908        let connection = StubAgentConnection::new();
4909
4910        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4911            acp::ContentChunk::new("Response".into()),
4912        )]);
4913
4914        let (conversation_view, cx) =
4915            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4916        add_to_workspace(conversation_view.clone(), cx);
4917
4918        let message_editor = message_editor(&conversation_view, cx);
4919        message_editor.update_in(cx, |editor, window, cx| {
4920            editor.set_text("Original message to edit", window, cx);
4921        });
4922        active_thread(&conversation_view, cx)
4923            .update_in(cx, |view, window, cx| view.send(window, cx));
4924
4925        cx.run_until_parked();
4926
4927        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4928            assert_eq!(
4929                view.active_thread()
4930                    .and_then(|active| active.read(cx).editing_message),
4931                None
4932            );
4933            assert_eq!(
4934                view.active_thread()
4935                    .unwrap()
4936                    .read(cx)
4937                    .thread
4938                    .read(cx)
4939                    .entries()
4940                    .len(),
4941                2
4942            );
4943
4944            view.active_thread()
4945                .map(|active| &active.read(cx).entry_view_state)
4946                .as_ref()
4947                .unwrap()
4948                .read(cx)
4949                .entry(0)
4950                .unwrap()
4951                .message_editor()
4952                .unwrap()
4953                .clone()
4954        });
4955
4956        // Focus
4957        cx.focus(&user_message_editor);
4958
4959        // Edit
4960        user_message_editor.update_in(cx, |editor, window, cx| {
4961            editor.set_text("Edited message content", window, cx);
4962        });
4963
4964        // Send
4965        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4966            acp::ContentChunk::new("New Response".into()),
4967        )]);
4968
4969        user_message_editor.update_in(cx, |_editor, window, cx| {
4970            window.dispatch_action(Box::new(Chat), cx);
4971        });
4972
4973        cx.run_until_parked();
4974
4975        conversation_view.read_with(cx, |view, cx| {
4976            assert_eq!(
4977                view.active_thread()
4978                    .and_then(|active| active.read(cx).editing_message),
4979                None
4980            );
4981
4982            let entries = view
4983                .active_thread()
4984                .unwrap()
4985                .read(cx)
4986                .thread
4987                .read(cx)
4988                .entries();
4989            assert_eq!(entries.len(), 2);
4990            assert_eq!(
4991                entries[0].to_markdown(cx),
4992                "## User\n\nEdited message content\n\n"
4993            );
4994            assert_eq!(
4995                entries[1].to_markdown(cx),
4996                "## Assistant\n\nNew Response\n\n"
4997            );
4998
4999            let entry_view_state = view
5000                .active_thread()
5001                .map(|active| &active.read(cx).entry_view_state)
5002                .unwrap();
5003            let new_editor = entry_view_state.read_with(cx, |state, _cx| {
5004                assert!(!state.entry(1).unwrap().has_content());
5005                state.entry(0).unwrap().message_editor().unwrap().clone()
5006            });
5007
5008            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5009        })
5010    }
5011
5012    #[gpui::test]
5013    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5014        init_test(cx);
5015
5016        let connection = StubAgentConnection::new();
5017
5018        let (conversation_view, cx) =
5019            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5020        add_to_workspace(conversation_view.clone(), cx);
5021
5022        let message_editor = message_editor(&conversation_view, cx);
5023        message_editor.update_in(cx, |editor, window, cx| {
5024            editor.set_text("Original message to edit", window, cx);
5025        });
5026        active_thread(&conversation_view, cx)
5027            .update_in(cx, |view, window, cx| view.send(window, cx));
5028
5029        cx.run_until_parked();
5030
5031        let (user_message_editor, session_id) = conversation_view.read_with(cx, |view, cx| {
5032            let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
5033            assert_eq!(thread.entries().len(), 1);
5034
5035            let editor = view
5036                .active_thread()
5037                .map(|active| &active.read(cx).entry_view_state)
5038                .as_ref()
5039                .unwrap()
5040                .read(cx)
5041                .entry(0)
5042                .unwrap()
5043                .message_editor()
5044                .unwrap()
5045                .clone();
5046
5047            (editor, thread.session_id().clone())
5048        });
5049
5050        // Focus
5051        cx.focus(&user_message_editor);
5052
5053        conversation_view.read_with(cx, |view, cx| {
5054            assert_eq!(
5055                view.active_thread()
5056                    .and_then(|active| active.read(cx).editing_message),
5057                Some(0)
5058            );
5059        });
5060
5061        // Edit
5062        user_message_editor.update_in(cx, |editor, window, cx| {
5063            editor.set_text("Edited message content", window, cx);
5064        });
5065
5066        conversation_view.read_with(cx, |view, cx| {
5067            assert_eq!(
5068                view.active_thread()
5069                    .and_then(|active| active.read(cx).editing_message),
5070                Some(0)
5071            );
5072        });
5073
5074        // Finish streaming response
5075        cx.update(|_, cx| {
5076            connection.send_update(
5077                session_id.clone(),
5078                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
5079                cx,
5080            );
5081            connection.end_turn(session_id, acp::StopReason::EndTurn);
5082        });
5083
5084        conversation_view.read_with(cx, |view, cx| {
5085            assert_eq!(
5086                view.active_thread()
5087                    .and_then(|active| active.read(cx).editing_message),
5088                Some(0)
5089            );
5090        });
5091
5092        cx.run_until_parked();
5093
5094        // Should still be editing
5095        cx.update(|window, cx| {
5096            assert!(user_message_editor.focus_handle(cx).is_focused(window));
5097            assert_eq!(
5098                conversation_view
5099                    .read(cx)
5100                    .active_thread()
5101                    .and_then(|active| active.read(cx).editing_message),
5102                Some(0)
5103            );
5104            assert_eq!(
5105                user_message_editor.read(cx).text(cx),
5106                "Edited message content"
5107            );
5108        });
5109    }
5110
5111    #[gpui::test]
5112    async fn test_stale_stop_does_not_disable_follow_tail_during_regenerate(
5113        cx: &mut TestAppContext,
5114    ) {
5115        init_test(cx);
5116
5117        let connection = StubAgentConnection::new();
5118
5119        let (conversation_view, cx) =
5120            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5121        add_to_workspace(conversation_view.clone(), cx);
5122
5123        let message_editor = message_editor(&conversation_view, cx);
5124        message_editor.update_in(cx, |editor, window, cx| {
5125            editor.set_text("Original message to edit", window, cx);
5126        });
5127        active_thread(&conversation_view, cx)
5128            .update_in(cx, |view, window, cx| view.send(window, cx));
5129
5130        cx.run_until_parked();
5131
5132        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
5133            view.active_thread()
5134                .map(|active| &active.read(cx).entry_view_state)
5135                .as_ref()
5136                .unwrap()
5137                .read(cx)
5138                .entry(0)
5139                .unwrap()
5140                .message_editor()
5141                .unwrap()
5142                .clone()
5143        });
5144
5145        cx.focus(&user_message_editor);
5146        user_message_editor.update_in(cx, |editor, window, cx| {
5147            editor.set_text("Edited message content", window, cx);
5148        });
5149
5150        user_message_editor.update_in(cx, |_editor, window, cx| {
5151            window.dispatch_action(Box::new(Chat), cx);
5152        });
5153
5154        cx.run_until_parked();
5155
5156        conversation_view.read_with(cx, |view, cx| {
5157            let active = view.active_thread().unwrap();
5158            let active = active.read(cx);
5159
5160            assert_eq!(active.thread.read(cx).status(), ThreadStatus::Generating);
5161            assert!(
5162                active.list_state.is_following_tail(),
5163                "stale stop events from the cancelled turn must not disable follow-tail for the new turn"
5164            );
5165        });
5166    }
5167
5168    struct GeneratingThreadSetup {
5169        conversation_view: Entity<ConversationView>,
5170        thread: Entity<AcpThread>,
5171        message_editor: Entity<MessageEditor>,
5172    }
5173
5174    async fn setup_generating_thread(
5175        cx: &mut TestAppContext,
5176    ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
5177        let connection = StubAgentConnection::new();
5178
5179        let (conversation_view, cx) =
5180            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5181        add_to_workspace(conversation_view.clone(), cx);
5182
5183        let message_editor = message_editor(&conversation_view, cx);
5184        message_editor.update_in(cx, |editor, window, cx| {
5185            editor.set_text("Hello", window, cx);
5186        });
5187        active_thread(&conversation_view, cx)
5188            .update_in(cx, |view, window, cx| view.send(window, cx));
5189
5190        let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
5191            let thread = view
5192                .active_thread()
5193                .as_ref()
5194                .unwrap()
5195                .read(cx)
5196                .thread
5197                .clone();
5198            (thread.clone(), thread.read(cx).session_id().clone())
5199        });
5200
5201        cx.run_until_parked();
5202
5203        cx.update(|_, cx| {
5204            connection.send_update(
5205                session_id.clone(),
5206                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5207                    "Response chunk".into(),
5208                )),
5209                cx,
5210            );
5211        });
5212
5213        cx.run_until_parked();
5214
5215        thread.read_with(cx, |thread, _cx| {
5216            assert_eq!(thread.status(), ThreadStatus::Generating);
5217        });
5218
5219        (
5220            GeneratingThreadSetup {
5221                conversation_view,
5222                thread,
5223                message_editor,
5224            },
5225            cx,
5226        )
5227    }
5228
5229    #[gpui::test]
5230    async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
5231        init_test(cx);
5232
5233        let (setup, cx) = setup_generating_thread(cx).await;
5234
5235        let focus_handle = setup
5236            .conversation_view
5237            .read_with(cx, |view, cx| view.focus_handle(cx));
5238        cx.update(|window, cx| {
5239            window.focus(&focus_handle, cx);
5240        });
5241
5242        setup.conversation_view.update_in(cx, |_, window, cx| {
5243            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5244        });
5245
5246        cx.run_until_parked();
5247
5248        setup.thread.read_with(cx, |thread, _cx| {
5249            assert_eq!(thread.status(), ThreadStatus::Idle);
5250        });
5251    }
5252
5253    #[gpui::test]
5254    async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
5255        init_test(cx);
5256
5257        let (setup, cx) = setup_generating_thread(cx).await;
5258
5259        let editor_focus_handle = setup
5260            .message_editor
5261            .read_with(cx, |editor, cx| editor.focus_handle(cx));
5262        cx.update(|window, cx| {
5263            window.focus(&editor_focus_handle, cx);
5264        });
5265
5266        setup.message_editor.update_in(cx, |_, window, cx| {
5267            window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
5268        });
5269
5270        cx.run_until_parked();
5271
5272        setup.thread.read_with(cx, |thread, _cx| {
5273            assert_eq!(thread.status(), ThreadStatus::Idle);
5274        });
5275    }
5276
5277    #[gpui::test]
5278    async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
5279        init_test(cx);
5280
5281        let (conversation_view, cx) =
5282            setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
5283        add_to_workspace(conversation_view.clone(), cx);
5284
5285        let thread = conversation_view.read_with(cx, |view, cx| {
5286            view.active_thread().unwrap().read(cx).thread.clone()
5287        });
5288
5289        thread.read_with(cx, |thread, _cx| {
5290            assert_eq!(thread.status(), ThreadStatus::Idle);
5291        });
5292
5293        let focus_handle = conversation_view.read_with(cx, |view, _cx| view.focus_handle.clone());
5294        cx.update(|window, cx| {
5295            window.focus(&focus_handle, cx);
5296        });
5297
5298        conversation_view.update_in(cx, |_, window, cx| {
5299            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5300        });
5301
5302        cx.run_until_parked();
5303
5304        thread.read_with(cx, |thread, _cx| {
5305            assert_eq!(thread.status(), ThreadStatus::Idle);
5306        });
5307    }
5308
5309    #[gpui::test]
5310    async fn test_interrupt(cx: &mut TestAppContext) {
5311        init_test(cx);
5312
5313        let connection = StubAgentConnection::new();
5314
5315        let (conversation_view, cx) =
5316            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5317        add_to_workspace(conversation_view.clone(), cx);
5318
5319        let message_editor = message_editor(&conversation_view, cx);
5320        message_editor.update_in(cx, |editor, window, cx| {
5321            editor.set_text("Message 1", window, cx);
5322        });
5323        active_thread(&conversation_view, cx)
5324            .update_in(cx, |view, window, cx| view.send(window, cx));
5325
5326        let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
5327            let thread = view.active_thread().unwrap().read(cx).thread.clone();
5328
5329            (thread.clone(), thread.read(cx).session_id().clone())
5330        });
5331
5332        cx.run_until_parked();
5333
5334        cx.update(|_, cx| {
5335            connection.send_update(
5336                session_id.clone(),
5337                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5338                    "Message 1 resp".into(),
5339                )),
5340                cx,
5341            );
5342        });
5343
5344        cx.run_until_parked();
5345
5346        thread.read_with(cx, |thread, cx| {
5347            assert_eq!(
5348                thread.to_markdown(cx),
5349                indoc::indoc! {"
5350                        ## User
5351
5352                        Message 1
5353
5354                        ## Assistant
5355
5356                        Message 1 resp
5357
5358                    "}
5359            )
5360        });
5361
5362        message_editor.update_in(cx, |editor, window, cx| {
5363            editor.set_text("Message 2", window, cx);
5364        });
5365        active_thread(&conversation_view, cx)
5366            .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
5367
5368        cx.update(|_, cx| {
5369            // Simulate a response sent after beginning to cancel
5370            connection.send_update(
5371                session_id.clone(),
5372                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
5373                cx,
5374            );
5375        });
5376
5377        cx.run_until_parked();
5378
5379        // Last Message 1 response should appear before Message 2
5380        thread.read_with(cx, |thread, cx| {
5381            assert_eq!(
5382                thread.to_markdown(cx),
5383                indoc::indoc! {"
5384                        ## User
5385
5386                        Message 1
5387
5388                        ## Assistant
5389
5390                        Message 1 response
5391
5392                        ## User
5393
5394                        Message 2
5395
5396                    "}
5397            )
5398        });
5399
5400        cx.update(|_, cx| {
5401            connection.send_update(
5402                session_id.clone(),
5403                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5404                    "Message 2 response".into(),
5405                )),
5406                cx,
5407            );
5408            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5409        });
5410
5411        cx.run_until_parked();
5412
5413        thread.read_with(cx, |thread, cx| {
5414            assert_eq!(
5415                thread.to_markdown(cx),
5416                indoc::indoc! {"
5417                        ## User
5418
5419                        Message 1
5420
5421                        ## Assistant
5422
5423                        Message 1 response
5424
5425                        ## User
5426
5427                        Message 2
5428
5429                        ## Assistant
5430
5431                        Message 2 response
5432
5433                    "}
5434            )
5435        });
5436    }
5437
5438    #[gpui::test]
5439    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
5440        init_test(cx);
5441
5442        let connection = StubAgentConnection::new();
5443        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5444            acp::ContentChunk::new("Response".into()),
5445        )]);
5446
5447        let (conversation_view, cx) =
5448            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5449        add_to_workspace(conversation_view.clone(), cx);
5450
5451        let message_editor = message_editor(&conversation_view, cx);
5452        message_editor.update_in(cx, |editor, window, cx| {
5453            editor.set_text("Original message to edit", window, cx)
5454        });
5455        active_thread(&conversation_view, cx)
5456            .update_in(cx, |view, window, cx| view.send(window, cx));
5457        cx.run_until_parked();
5458
5459        let user_message_editor = conversation_view.read_with(cx, |conversation_view, cx| {
5460            conversation_view
5461                .active_thread()
5462                .map(|active| &active.read(cx).entry_view_state)
5463                .as_ref()
5464                .unwrap()
5465                .read(cx)
5466                .entry(0)
5467                .expect("Should have at least one entry")
5468                .message_editor()
5469                .expect("Should have message editor")
5470                .clone()
5471        });
5472
5473        cx.focus(&user_message_editor);
5474        conversation_view.read_with(cx, |view, cx| {
5475            assert_eq!(
5476                view.active_thread()
5477                    .and_then(|active| active.read(cx).editing_message),
5478                Some(0)
5479            );
5480        });
5481
5482        // Ensure to edit the focused message before proceeding otherwise, since
5483        // its content is not different from what was sent, focus will be lost.
5484        user_message_editor.update_in(cx, |editor, window, cx| {
5485            editor.set_text("Original message to edit with ", window, cx)
5486        });
5487
5488        // Create a simple buffer with some text so we can create a selection
5489        // that will then be added to the message being edited.
5490        let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5491            (
5492                conversation_view.workspace.clone(),
5493                conversation_view.project.clone(),
5494            )
5495        });
5496        let buffer = project.update(cx, |project, cx| {
5497            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5498        });
5499
5500        workspace
5501            .update_in(cx, |workspace, window, cx| {
5502                let editor = cx.new(|cx| {
5503                    let mut editor =
5504                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5505
5506                    editor.change_selections(Default::default(), window, cx, |selections| {
5507                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5508                    });
5509
5510                    editor
5511                });
5512                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5513            })
5514            .unwrap();
5515
5516        conversation_view.update_in(cx, |view, window, cx| {
5517            assert_eq!(
5518                view.active_thread()
5519                    .and_then(|active| active.read(cx).editing_message),
5520                Some(0)
5521            );
5522            view.insert_selections(window, cx);
5523        });
5524
5525        user_message_editor.read_with(cx, |editor, cx| {
5526            let text = editor.editor().read(cx).text(cx);
5527            let expected_text = String::from("Original message to edit with selection ");
5528
5529            assert_eq!(text, expected_text);
5530        });
5531    }
5532
5533    #[gpui::test]
5534    async fn test_insert_selections(cx: &mut TestAppContext) {
5535        init_test(cx);
5536
5537        let connection = StubAgentConnection::new();
5538        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5539            acp::ContentChunk::new("Response".into()),
5540        )]);
5541
5542        let (conversation_view, cx) =
5543            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5544        add_to_workspace(conversation_view.clone(), cx);
5545
5546        let message_editor = message_editor(&conversation_view, cx);
5547        message_editor.update_in(cx, |editor, window, cx| {
5548            editor.set_text("Can you review this snippet ", window, cx)
5549        });
5550
5551        // Create a simple buffer with some text so we can create a selection
5552        // that will then be added to the message being edited.
5553        let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5554            (
5555                conversation_view.workspace.clone(),
5556                conversation_view.project.clone(),
5557            )
5558        });
5559        let buffer = project.update(cx, |project, cx| {
5560            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5561        });
5562
5563        workspace
5564            .update_in(cx, |workspace, window, cx| {
5565                let editor = cx.new(|cx| {
5566                    let mut editor =
5567                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5568
5569                    editor.change_selections(Default::default(), window, cx, |selections| {
5570                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5571                    });
5572
5573                    editor
5574                });
5575                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5576            })
5577            .unwrap();
5578
5579        conversation_view.update_in(cx, |view, window, cx| {
5580            assert_eq!(
5581                view.active_thread()
5582                    .and_then(|active| active.read(cx).editing_message),
5583                None
5584            );
5585            view.insert_selections(window, cx);
5586        });
5587
5588        message_editor.read_with(cx, |editor, cx| {
5589            let text = editor.text(cx);
5590            let expected_txt = String::from("Can you review this snippet selection ");
5591
5592            assert_eq!(text, expected_txt);
5593        })
5594    }
5595
5596    #[gpui::test]
5597    async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
5598        init_test(cx);
5599
5600        let tool_call_id = acp::ToolCallId::new("terminal-1");
5601        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
5602            .kind(acp::ToolKind::Edit);
5603
5604        let permission_options = ToolPermissionContext::new(
5605            TerminalTool::NAME,
5606            vec!["cargo build --release".to_string()],
5607        )
5608        .build_permission_options();
5609
5610        let connection =
5611            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5612                tool_call_id.clone(),
5613                permission_options,
5614            )]));
5615
5616        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5617
5618        let (conversation_view, cx) =
5619            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5620
5621        // Disable notifications to avoid popup windows
5622        cx.update(|_window, cx| {
5623            AgentSettings::override_global(
5624                AgentSettings {
5625                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5626                    ..AgentSettings::get_global(cx).clone()
5627                },
5628                cx,
5629            );
5630        });
5631
5632        let message_editor = message_editor(&conversation_view, cx);
5633        message_editor.update_in(cx, |editor, window, cx| {
5634            editor.set_text("Run cargo build", window, cx);
5635        });
5636
5637        active_thread(&conversation_view, cx)
5638            .update_in(cx, |view, window, cx| view.send(window, cx));
5639
5640        cx.run_until_parked();
5641
5642        // Verify the tool call is in WaitingForConfirmation state with the expected options
5643        conversation_view.read_with(cx, |conversation_view, cx| {
5644            let thread = conversation_view
5645                .active_thread()
5646                .expect("Thread should exist")
5647                .read(cx)
5648                .thread
5649                .clone();
5650            let thread = thread.read(cx);
5651
5652            let tool_call = thread.entries().iter().find_map(|entry| {
5653                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5654                    Some(call)
5655                } else {
5656                    None
5657                }
5658            });
5659
5660            assert!(tool_call.is_some(), "Expected a tool call entry");
5661            let tool_call = tool_call.unwrap();
5662
5663            // Verify it's waiting for confirmation
5664            assert!(
5665                matches!(
5666                    tool_call.status,
5667                    acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
5668                ),
5669                "Expected WaitingForConfirmation status, got {:?}",
5670                tool_call.status
5671            );
5672
5673            // Verify the options count (granularity options only, no separate Deny option)
5674            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5675                &tool_call.status
5676            {
5677                let PermissionOptions::Dropdown(choices) = options else {
5678                    panic!("Expected dropdown permission options");
5679                };
5680
5681                assert_eq!(
5682                    choices.len(),
5683                    3,
5684                    "Expected 3 permission options (granularity only)"
5685                );
5686
5687                // Verify specific button labels (now using neutral names)
5688                let labels: Vec<&str> = choices
5689                    .iter()
5690                    .map(|choice| choice.allow.name.as_ref())
5691                    .collect();
5692                assert!(
5693                    labels.contains(&"Always for terminal"),
5694                    "Missing 'Always for terminal' option"
5695                );
5696                assert!(
5697                    labels.contains(&"Always for `cargo build` commands"),
5698                    "Missing pattern option"
5699                );
5700                assert!(
5701                    labels.contains(&"Only this time"),
5702                    "Missing 'Only this time' option"
5703                );
5704            }
5705        });
5706    }
5707
5708    #[gpui::test]
5709    async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5710        init_test(cx);
5711
5712        let tool_call_id = acp::ToolCallId::new("edit-file-1");
5713        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5714            .kind(acp::ToolKind::Edit);
5715
5716        let permission_options =
5717            ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5718                .build_permission_options();
5719
5720        let connection =
5721            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5722                tool_call_id.clone(),
5723                permission_options,
5724            )]));
5725
5726        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5727
5728        let (conversation_view, cx) =
5729            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5730
5731        // Disable notifications
5732        cx.update(|_window, cx| {
5733            AgentSettings::override_global(
5734                AgentSettings {
5735                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5736                    ..AgentSettings::get_global(cx).clone()
5737                },
5738                cx,
5739            );
5740        });
5741
5742        let message_editor = message_editor(&conversation_view, cx);
5743        message_editor.update_in(cx, |editor, window, cx| {
5744            editor.set_text("Edit the main file", window, cx);
5745        });
5746
5747        active_thread(&conversation_view, cx)
5748            .update_in(cx, |view, window, cx| view.send(window, cx));
5749
5750        cx.run_until_parked();
5751
5752        // Verify the options
5753        conversation_view.read_with(cx, |conversation_view, cx| {
5754            let thread = conversation_view
5755                .active_thread()
5756                .expect("Thread should exist")
5757                .read(cx)
5758                .thread
5759                .clone();
5760            let thread = thread.read(cx);
5761
5762            let tool_call = thread.entries().iter().find_map(|entry| {
5763                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5764                    Some(call)
5765                } else {
5766                    None
5767                }
5768            });
5769
5770            assert!(tool_call.is_some(), "Expected a tool call entry");
5771            let tool_call = tool_call.unwrap();
5772
5773            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5774                &tool_call.status
5775            {
5776                let PermissionOptions::Dropdown(choices) = options else {
5777                    panic!("Expected dropdown permission options");
5778                };
5779
5780                let labels: Vec<&str> = choices
5781                    .iter()
5782                    .map(|choice| choice.allow.name.as_ref())
5783                    .collect();
5784                assert!(
5785                    labels.contains(&"Always for edit file"),
5786                    "Missing 'Always for edit file' option"
5787                );
5788                assert!(
5789                    labels.contains(&"Always for `src/`"),
5790                    "Missing path pattern option"
5791                );
5792            } else {
5793                panic!("Expected WaitingForConfirmation status");
5794            }
5795        });
5796    }
5797
5798    #[gpui::test]
5799    async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5800        init_test(cx);
5801
5802        let tool_call_id = acp::ToolCallId::new("fetch-1");
5803        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5804            .kind(acp::ToolKind::Fetch);
5805
5806        let permission_options =
5807            ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5808                .build_permission_options();
5809
5810        let connection =
5811            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5812                tool_call_id.clone(),
5813                permission_options,
5814            )]));
5815
5816        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5817
5818        let (conversation_view, cx) =
5819            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5820
5821        // Disable notifications
5822        cx.update(|_window, cx| {
5823            AgentSettings::override_global(
5824                AgentSettings {
5825                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5826                    ..AgentSettings::get_global(cx).clone()
5827                },
5828                cx,
5829            );
5830        });
5831
5832        let message_editor = message_editor(&conversation_view, cx);
5833        message_editor.update_in(cx, |editor, window, cx| {
5834            editor.set_text("Fetch the docs", window, cx);
5835        });
5836
5837        active_thread(&conversation_view, cx)
5838            .update_in(cx, |view, window, cx| view.send(window, cx));
5839
5840        cx.run_until_parked();
5841
5842        // Verify the options
5843        conversation_view.read_with(cx, |conversation_view, cx| {
5844            let thread = conversation_view
5845                .active_thread()
5846                .expect("Thread should exist")
5847                .read(cx)
5848                .thread
5849                .clone();
5850            let thread = thread.read(cx);
5851
5852            let tool_call = thread.entries().iter().find_map(|entry| {
5853                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5854                    Some(call)
5855                } else {
5856                    None
5857                }
5858            });
5859
5860            assert!(tool_call.is_some(), "Expected a tool call entry");
5861            let tool_call = tool_call.unwrap();
5862
5863            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5864                &tool_call.status
5865            {
5866                let PermissionOptions::Dropdown(choices) = options else {
5867                    panic!("Expected dropdown permission options");
5868                };
5869
5870                let labels: Vec<&str> = choices
5871                    .iter()
5872                    .map(|choice| choice.allow.name.as_ref())
5873                    .collect();
5874                assert!(
5875                    labels.contains(&"Always for fetch"),
5876                    "Missing 'Always for fetch' option"
5877                );
5878                assert!(
5879                    labels.contains(&"Always for `docs.rs`"),
5880                    "Missing domain pattern option"
5881                );
5882            } else {
5883                panic!("Expected WaitingForConfirmation status");
5884            }
5885        });
5886    }
5887
5888    #[gpui::test]
5889    async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5890        init_test(cx);
5891
5892        let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5893        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5894            .kind(acp::ToolKind::Edit);
5895
5896        // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5897        let permission_options = ToolPermissionContext::new(
5898            TerminalTool::NAME,
5899            vec!["./deploy.sh --production".to_string()],
5900        )
5901        .build_permission_options();
5902
5903        let connection =
5904            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5905                tool_call_id.clone(),
5906                permission_options,
5907            )]));
5908
5909        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5910
5911        let (conversation_view, cx) =
5912            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5913
5914        // Disable notifications
5915        cx.update(|_window, cx| {
5916            AgentSettings::override_global(
5917                AgentSettings {
5918                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5919                    ..AgentSettings::get_global(cx).clone()
5920                },
5921                cx,
5922            );
5923        });
5924
5925        let message_editor = message_editor(&conversation_view, cx);
5926        message_editor.update_in(cx, |editor, window, cx| {
5927            editor.set_text("Run the deploy script", window, cx);
5928        });
5929
5930        active_thread(&conversation_view, cx)
5931            .update_in(cx, |view, window, cx| view.send(window, cx));
5932
5933        cx.run_until_parked();
5934
5935        // Verify only 2 options (no pattern button when command doesn't match pattern)
5936        conversation_view.read_with(cx, |conversation_view, cx| {
5937            let thread = conversation_view
5938                .active_thread()
5939                .expect("Thread should exist")
5940                .read(cx)
5941                .thread
5942                .clone();
5943            let thread = thread.read(cx);
5944
5945            let tool_call = thread.entries().iter().find_map(|entry| {
5946                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5947                    Some(call)
5948                } else {
5949                    None
5950                }
5951            });
5952
5953            assert!(tool_call.is_some(), "Expected a tool call entry");
5954            let tool_call = tool_call.unwrap();
5955
5956            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5957                &tool_call.status
5958            {
5959                let PermissionOptions::Dropdown(choices) = options else {
5960                    panic!("Expected dropdown permission options");
5961                };
5962
5963                assert_eq!(
5964                    choices.len(),
5965                    2,
5966                    "Expected 2 permission options (no pattern option)"
5967                );
5968
5969                let labels: Vec<&str> = choices
5970                    .iter()
5971                    .map(|choice| choice.allow.name.as_ref())
5972                    .collect();
5973                assert!(
5974                    labels.contains(&"Always for terminal"),
5975                    "Missing 'Always for terminal' option"
5976                );
5977                assert!(
5978                    labels.contains(&"Only this time"),
5979                    "Missing 'Only this time' option"
5980                );
5981                // Should NOT contain a pattern option
5982                assert!(
5983                    !labels.iter().any(|l| l.contains("commands")),
5984                    "Should not have pattern option"
5985                );
5986            } else {
5987                panic!("Expected WaitingForConfirmation status");
5988            }
5989        });
5990    }
5991
5992    #[gpui::test]
5993    async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5994        init_test(cx);
5995
5996        let tool_call_id = acp::ToolCallId::new("action-test-1");
5997        let tool_call =
5998            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5999
6000        let permission_options =
6001            ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
6002                .build_permission_options();
6003
6004        let connection =
6005            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6006                tool_call_id.clone(),
6007                permission_options,
6008            )]));
6009
6010        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6011
6012        let (conversation_view, cx) =
6013            setup_conversation_view(StubAgentServer::new(connection), cx).await;
6014        add_to_workspace(conversation_view.clone(), cx);
6015
6016        cx.update(|_window, cx| {
6017            AgentSettings::override_global(
6018                AgentSettings {
6019                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6020                    ..AgentSettings::get_global(cx).clone()
6021                },
6022                cx,
6023            );
6024        });
6025
6026        let message_editor = message_editor(&conversation_view, cx);
6027        message_editor.update_in(cx, |editor, window, cx| {
6028            editor.set_text("Run tests", window, cx);
6029        });
6030
6031        active_thread(&conversation_view, cx)
6032            .update_in(cx, |view, window, cx| view.send(window, cx));
6033
6034        cx.run_until_parked();
6035
6036        // Verify tool call is waiting for confirmation
6037        conversation_view.read_with(cx, |conversation_view, cx| {
6038            let tool_call = conversation_view.pending_tool_call(cx);
6039            assert!(
6040                tool_call.is_some(),
6041                "Expected a tool call waiting for confirmation"
6042            );
6043        });
6044
6045        // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
6046        conversation_view.update_in(cx, |_, window, cx| {
6047            window.dispatch_action(
6048                crate::AuthorizeToolCall {
6049                    tool_call_id: "action-test-1".to_string(),
6050                    option_id: "allow".to_string(),
6051                    option_kind: "AllowOnce".to_string(),
6052                }
6053                .boxed_clone(),
6054                cx,
6055            );
6056        });
6057
6058        cx.run_until_parked();
6059
6060        // Verify tool call is no longer waiting for confirmation (was authorized)
6061        conversation_view.read_with(cx, |conversation_view, cx| {
6062            let tool_call = conversation_view.pending_tool_call(cx);
6063            assert!(
6064                tool_call.is_none(),
6065                "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
6066            );
6067        });
6068    }
6069
6070    #[gpui::test]
6071    async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
6072        init_test(cx);
6073
6074        let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
6075        let tool_call =
6076            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
6077
6078        let permission_options =
6079            ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
6080                .build_permission_options();
6081
6082        let connection =
6083            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6084                tool_call_id.clone(),
6085                permission_options.clone(),
6086            )]));
6087
6088        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6089
6090        let (conversation_view, cx) =
6091            setup_conversation_view(StubAgentServer::new(connection), cx).await;
6092        add_to_workspace(conversation_view.clone(), cx);
6093
6094        cx.update(|_window, cx| {
6095            AgentSettings::override_global(
6096                AgentSettings {
6097                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6098                    ..AgentSettings::get_global(cx).clone()
6099                },
6100                cx,
6101            );
6102        });
6103
6104        let message_editor = message_editor(&conversation_view, cx);
6105        message_editor.update_in(cx, |editor, window, cx| {
6106            editor.set_text("Install dependencies", window, cx);
6107        });
6108
6109        active_thread(&conversation_view, cx)
6110            .update_in(cx, |view, window, cx| view.send(window, cx));
6111
6112        cx.run_until_parked();
6113
6114        // Find the pattern option ID (the choice with non-empty sub_patterns)
6115        let pattern_option = match &permission_options {
6116            PermissionOptions::Dropdown(choices) => choices
6117                .iter()
6118                .find(|choice| !choice.sub_patterns.is_empty())
6119                .map(|choice| &choice.allow)
6120                .expect("Should have a pattern option for npm command"),
6121            _ => panic!("Expected dropdown permission options"),
6122        };
6123
6124        // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
6125        conversation_view.update_in(cx, |_, window, cx| {
6126            window.dispatch_action(
6127                crate::AuthorizeToolCall {
6128                    tool_call_id: "pattern-action-test-1".to_string(),
6129                    option_id: pattern_option.option_id.0.to_string(),
6130                    option_kind: "AllowAlways".to_string(),
6131                }
6132                .boxed_clone(),
6133                cx,
6134            );
6135        });
6136
6137        cx.run_until_parked();
6138
6139        // Verify tool call was authorized
6140        conversation_view.read_with(cx, |conversation_view, cx| {
6141            let tool_call = conversation_view.pending_tool_call(cx);
6142            assert!(
6143                tool_call.is_none(),
6144                "Tool call should be authorized after selecting pattern option"
6145            );
6146        });
6147    }
6148
6149    #[gpui::test]
6150    async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
6151        init_test(cx);
6152
6153        let tool_call_id = acp::ToolCallId::new("granularity-test-1");
6154        let tool_call =
6155            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
6156
6157        let permission_options =
6158            ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".to_string()])
6159                .build_permission_options();
6160
6161        let connection =
6162            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6163                tool_call_id.clone(),
6164                permission_options.clone(),
6165            )]));
6166
6167        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6168
6169        let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
6170        add_to_workspace(thread_view.clone(), cx);
6171
6172        cx.update(|_window, cx| {
6173            AgentSettings::override_global(
6174                AgentSettings {
6175                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6176                    ..AgentSettings::get_global(cx).clone()
6177                },
6178                cx,
6179            );
6180        });
6181
6182        let message_editor = message_editor(&thread_view, cx);
6183        message_editor.update_in(cx, |editor, window, cx| {
6184            editor.set_text("Build the project", window, cx);
6185        });
6186
6187        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6188
6189        cx.run_until_parked();
6190
6191        // Verify default granularity is the last option (index 2 = "Only this time")
6192        thread_view.read_with(cx, |thread_view, cx| {
6193            let state = thread_view.active_thread().unwrap();
6194            let selected = state.read(cx).permission_selections.get(&tool_call_id);
6195            assert!(
6196                selected.is_none(),
6197                "Should have no selection initially (defaults to last)"
6198            );
6199        });
6200
6201        // Select the first option (index 0 = "Always for terminal")
6202        thread_view.update_in(cx, |_, window, cx| {
6203            window.dispatch_action(
6204                crate::SelectPermissionGranularity {
6205                    tool_call_id: "granularity-test-1".to_string(),
6206                    index: 0,
6207                }
6208                .boxed_clone(),
6209                cx,
6210            );
6211        });
6212
6213        cx.run_until_parked();
6214
6215        // Verify the selection was updated
6216        thread_view.read_with(cx, |thread_view, cx| {
6217            let state = thread_view.active_thread().unwrap();
6218            let selected = state.read(cx).permission_selections.get(&tool_call_id);
6219            assert_eq!(
6220                selected.and_then(|s| s.choice_index()),
6221                Some(0),
6222                "Should have selected index 0"
6223            );
6224        });
6225    }
6226
6227    #[gpui::test]
6228    async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
6229        init_test(cx);
6230
6231        let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
6232        let tool_call =
6233            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
6234
6235        let permission_options =
6236            ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
6237                .build_permission_options();
6238
6239        // Verify we have the expected options
6240        let PermissionOptions::Dropdown(choices) = &permission_options else {
6241            panic!("Expected dropdown permission options");
6242        };
6243
6244        assert_eq!(choices.len(), 3);
6245        assert!(
6246            choices[0]
6247                .allow
6248                .option_id
6249                .0
6250                .contains("always_allow:terminal")
6251        );
6252        assert!(
6253            choices[1]
6254                .allow
6255                .option_id
6256                .0
6257                .contains("always_allow:terminal")
6258        );
6259        assert!(!choices[1].sub_patterns.is_empty());
6260        assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
6261
6262        let connection =
6263            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6264                tool_call_id.clone(),
6265                permission_options.clone(),
6266            )]));
6267
6268        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6269
6270        let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
6271        add_to_workspace(thread_view.clone(), cx);
6272
6273        cx.update(|_window, cx| {
6274            AgentSettings::override_global(
6275                AgentSettings {
6276                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6277                    ..AgentSettings::get_global(cx).clone()
6278                },
6279                cx,
6280            );
6281        });
6282
6283        let message_editor = message_editor(&thread_view, cx);
6284        message_editor.update_in(cx, |editor, window, cx| {
6285            editor.set_text("Install dependencies", window, cx);
6286        });
6287
6288        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6289
6290        cx.run_until_parked();
6291
6292        // Select the pattern option (index 1 = "Always for `npm` commands")
6293        thread_view.update_in(cx, |_, window, cx| {
6294            window.dispatch_action(
6295                crate::SelectPermissionGranularity {
6296                    tool_call_id: "allow-granularity-test-1".to_string(),
6297                    index: 1,
6298                }
6299                .boxed_clone(),
6300                cx,
6301            );
6302        });
6303
6304        cx.run_until_parked();
6305
6306        // Simulate clicking the Allow button by dispatching AllowOnce action
6307        // which should use the selected granularity
6308        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
6309            view.allow_once(&AllowOnce, window, cx)
6310        });
6311
6312        cx.run_until_parked();
6313
6314        // Verify tool call was authorized
6315        thread_view.read_with(cx, |thread_view, cx| {
6316            let tool_call = thread_view.pending_tool_call(cx);
6317            assert!(
6318                tool_call.is_none(),
6319                "Tool call should be authorized after Allow with pattern granularity"
6320            );
6321        });
6322    }
6323
6324    #[gpui::test]
6325    async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
6326        init_test(cx);
6327
6328        let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
6329        let tool_call =
6330            acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
6331
6332        let permission_options =
6333            ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
6334                .build_permission_options();
6335
6336        let connection =
6337            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6338                tool_call_id.clone(),
6339                permission_options.clone(),
6340            )]));
6341
6342        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6343
6344        let (conversation_view, cx) =
6345            setup_conversation_view(StubAgentServer::new(connection), cx).await;
6346        add_to_workspace(conversation_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(&conversation_view, cx);
6359        message_editor.update_in(cx, |editor, window, cx| {
6360            editor.set_text("Push changes", window, cx);
6361        });
6362
6363        active_thread(&conversation_view, cx)
6364            .update_in(cx, |view, window, cx| view.send(window, cx));
6365
6366        cx.run_until_parked();
6367
6368        // Use default granularity (last option = "Only this time")
6369        // Simulate clicking the Deny button
6370        active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
6371            view.reject_once(&RejectOnce, window, cx)
6372        });
6373
6374        cx.run_until_parked();
6375
6376        // Verify tool call was rejected (no longer waiting for confirmation)
6377        conversation_view.read_with(cx, |conversation_view, cx| {
6378            let tool_call = conversation_view.pending_tool_call(cx);
6379            assert!(
6380                tool_call.is_none(),
6381                "Tool call should be rejected after Deny"
6382            );
6383        });
6384    }
6385
6386    #[gpui::test]
6387    async fn test_option_id_transformation_for_allow() {
6388        let permission_options = ToolPermissionContext::new(
6389            TerminalTool::NAME,
6390            vec!["cargo build --release".to_string()],
6391        )
6392        .build_permission_options();
6393
6394        let PermissionOptions::Dropdown(choices) = permission_options else {
6395            panic!("Expected dropdown permission options");
6396        };
6397
6398        let allow_ids: Vec<String> = choices
6399            .iter()
6400            .map(|choice| choice.allow.option_id.0.to_string())
6401            .collect();
6402
6403        assert!(allow_ids.contains(&"allow".to_string()));
6404        assert_eq!(
6405            allow_ids
6406                .iter()
6407                .filter(|id| *id == "always_allow:terminal")
6408                .count(),
6409            2,
6410            "Expected two always_allow:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6411        );
6412    }
6413
6414    #[gpui::test]
6415    async fn test_option_id_transformation_for_deny() {
6416        let permission_options = ToolPermissionContext::new(
6417            TerminalTool::NAME,
6418            vec!["cargo build --release".to_string()],
6419        )
6420        .build_permission_options();
6421
6422        let PermissionOptions::Dropdown(choices) = permission_options else {
6423            panic!("Expected dropdown permission options");
6424        };
6425
6426        let deny_ids: Vec<String> = choices
6427            .iter()
6428            .map(|choice| choice.deny.option_id.0.to_string())
6429            .collect();
6430
6431        assert!(deny_ids.contains(&"deny".to_string()));
6432        assert_eq!(
6433            deny_ids
6434                .iter()
6435                .filter(|id| *id == "always_deny:terminal")
6436                .count(),
6437            2,
6438            "Expected two always_deny:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6439        );
6440    }
6441
6442    #[gpui::test]
6443    async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
6444        init_test(cx);
6445
6446        let (conversation_view, cx) =
6447            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6448        add_to_workspace(conversation_view.clone(), cx);
6449
6450        let active = active_thread(&conversation_view, cx);
6451        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6452        let thread = cx.read(|cx| active.read(cx).thread.clone());
6453
6454        title_editor.read_with(cx, |editor, cx| {
6455            assert!(!editor.read_only(cx));
6456        });
6457
6458        cx.focus(&conversation_view);
6459        cx.focus(&title_editor);
6460
6461        cx.dispatch_action(editor::actions::DeleteLine);
6462        cx.simulate_input("My Custom Title");
6463
6464        cx.run_until_parked();
6465
6466        title_editor.read_with(cx, |editor, cx| {
6467            assert_eq!(editor.text(cx), "My Custom Title");
6468        });
6469        thread.read_with(cx, |thread, _cx| {
6470            assert_eq!(thread.title(), Some("My Custom Title".into()));
6471        });
6472    }
6473
6474    #[gpui::test]
6475    async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
6476        init_test(cx);
6477
6478        let (conversation_view, cx) =
6479            setup_conversation_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
6480
6481        let active = active_thread(&conversation_view, cx);
6482        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6483
6484        title_editor.read_with(cx, |editor, cx| {
6485            assert!(
6486                editor.read_only(cx),
6487                "Title editor should be read-only when the connection does not support set_title"
6488            );
6489        });
6490    }
6491
6492    #[gpui::test]
6493    async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
6494        init_test(cx);
6495
6496        let connection = StubAgentConnection::new();
6497
6498        let (conversation_view, cx) =
6499            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
6500
6501        let message_editor = message_editor(&conversation_view, cx);
6502        message_editor.update_in(cx, |editor, window, cx| {
6503            editor.set_text("Some prompt", window, cx);
6504        });
6505        active_thread(&conversation_view, cx)
6506            .update_in(cx, |view, window, cx| view.send(window, cx));
6507
6508        let session_id = conversation_view.read_with(cx, |view, cx| {
6509            view.active_thread()
6510                .unwrap()
6511                .read(cx)
6512                .thread
6513                .read(cx)
6514                .session_id()
6515                .clone()
6516        });
6517
6518        cx.run_until_parked();
6519
6520        cx.update(|_, _cx| {
6521            connection.end_turn(session_id, acp::StopReason::MaxTokens);
6522        });
6523
6524        cx.run_until_parked();
6525
6526        conversation_view.read_with(cx, |conversation_view, cx| {
6527            let state = conversation_view.active_thread().unwrap();
6528            let error = &state.read(cx).thread_error;
6529            assert!(
6530                matches!(error, Some(ThreadError::MaxOutputTokens)),
6531                "Expected ThreadError::MaxOutputTokens, got: {:?}",
6532                error.is_some()
6533            );
6534        });
6535    }
6536
6537    fn create_test_acp_thread(
6538        parent_session_id: Option<acp::SessionId>,
6539        session_id: &str,
6540        connection: Rc<dyn AgentConnection>,
6541        project: Entity<Project>,
6542        cx: &mut App,
6543    ) -> Entity<AcpThread> {
6544        let action_log = cx.new(|_| ActionLog::new(project.clone()));
6545        cx.new(|cx| {
6546            AcpThread::new(
6547                parent_session_id,
6548                None,
6549                None,
6550                connection,
6551                project,
6552                action_log,
6553                acp::SessionId::new(session_id),
6554                watch::Receiver::constant(acp::PromptCapabilities::new()),
6555                cx,
6556            )
6557        })
6558    }
6559
6560    fn request_test_tool_authorization(
6561        thread: &Entity<AcpThread>,
6562        tool_call_id: &str,
6563        option_id: &str,
6564        cx: &mut TestAppContext,
6565    ) -> Task<acp_thread::RequestPermissionOutcome> {
6566        let tool_call_id = acp::ToolCallId::new(tool_call_id);
6567        let label = format!("Tool {tool_call_id}");
6568        let option_id = acp::PermissionOptionId::new(option_id);
6569        cx.update(|cx| {
6570            thread.update(cx, |thread, cx| {
6571                thread
6572                    .request_tool_call_authorization(
6573                        acp::ToolCall::new(tool_call_id, label)
6574                            .kind(acp::ToolKind::Edit)
6575                            .into(),
6576                        PermissionOptions::Flat(vec![acp::PermissionOption::new(
6577                            option_id,
6578                            "Allow",
6579                            acp::PermissionOptionKind::AllowOnce,
6580                        )]),
6581                        cx,
6582                    )
6583                    .unwrap()
6584            })
6585        })
6586    }
6587
6588    #[gpui::test]
6589    async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {
6590        init_test(cx);
6591
6592        let fs = FakeFs::new(cx.executor());
6593        let project = Project::test(fs, [], cx).await;
6594        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6595
6596        let (thread, conversation) = cx.update(|cx| {
6597            let thread =
6598                create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
6599            let conversation = cx.new(|cx| {
6600                let mut conversation = Conversation::default();
6601                conversation.register_thread(thread.clone(), cx);
6602                conversation
6603            });
6604            (thread, conversation)
6605        });
6606
6607        let _task1 = request_test_tool_authorization(&thread, "tc-1", "allow-1", cx);
6608        let _task2 = request_test_tool_authorization(&thread, "tc-2", "allow-2", cx);
6609
6610        cx.read(|cx| {
6611            let session_id = acp::SessionId::new("session-1");
6612            let (_, tool_call_id, _) = conversation
6613                .read(cx)
6614                .pending_tool_call(&session_id, cx)
6615                .expect("Expected a pending tool call");
6616            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
6617        });
6618
6619        cx.update(|cx| {
6620            conversation.update(cx, |conversation, cx| {
6621                conversation.authorize_tool_call(
6622                    acp::SessionId::new("session-1"),
6623                    acp::ToolCallId::new("tc-1"),
6624                    SelectedPermissionOutcome::new(
6625                        acp::PermissionOptionId::new("allow-1"),
6626                        acp::PermissionOptionKind::AllowOnce,
6627                    ),
6628                    cx,
6629                );
6630            });
6631        });
6632
6633        cx.run_until_parked();
6634
6635        cx.read(|cx| {
6636            let session_id = acp::SessionId::new("session-1");
6637            let (_, tool_call_id, _) = conversation
6638                .read(cx)
6639                .pending_tool_call(&session_id, cx)
6640                .expect("Expected tc-2 to be pending after tc-1 was authorized");
6641            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
6642        });
6643
6644        cx.update(|cx| {
6645            conversation.update(cx, |conversation, cx| {
6646                conversation.authorize_tool_call(
6647                    acp::SessionId::new("session-1"),
6648                    acp::ToolCallId::new("tc-2"),
6649                    SelectedPermissionOutcome::new(
6650                        acp::PermissionOptionId::new("allow-2"),
6651                        acp::PermissionOptionKind::AllowOnce,
6652                    ),
6653                    cx,
6654                );
6655            });
6656        });
6657
6658        cx.run_until_parked();
6659
6660        cx.read(|cx| {
6661            let session_id = acp::SessionId::new("session-1");
6662            assert!(
6663                conversation
6664                    .read(cx)
6665                    .pending_tool_call(&session_id, cx)
6666                    .is_none(),
6667                "Expected no pending tool calls after both were authorized"
6668            );
6669        });
6670    }
6671
6672    #[gpui::test]
6673    async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {
6674        init_test(cx);
6675
6676        let fs = FakeFs::new(cx.executor());
6677        let project = Project::test(fs, [], cx).await;
6678        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6679
6680        let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
6681            let parent_thread =
6682                create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
6683            let subagent_thread = create_test_acp_thread(
6684                Some(acp::SessionId::new("parent")),
6685                "subagent",
6686                connection.clone(),
6687                project.clone(),
6688                cx,
6689            );
6690            let conversation = cx.new(|cx| {
6691                let mut conversation = Conversation::default();
6692                conversation.register_thread(parent_thread.clone(), cx);
6693                conversation.register_thread(subagent_thread.clone(), cx);
6694                conversation
6695            });
6696            (parent_thread, subagent_thread, conversation)
6697        });
6698
6699        let _parent_task =
6700            request_test_tool_authorization(&parent_thread, "parent-tc", "allow-parent", cx);
6701        let _subagent_task =
6702            request_test_tool_authorization(&subagent_thread, "subagent-tc", "allow-subagent", cx);
6703
6704        // Querying with the subagent's session ID returns only the
6705        // subagent's own tool call (subagent path is scoped to its session)
6706        cx.read(|cx| {
6707            let subagent_id = acp::SessionId::new("subagent");
6708            let (session_id, tool_call_id, _) = conversation
6709                .read(cx)
6710                .pending_tool_call(&subagent_id, cx)
6711                .expect("Expected subagent's pending tool call");
6712            assert_eq!(session_id, acp::SessionId::new("subagent"));
6713            assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
6714        });
6715
6716        // Querying with the parent's session ID returns the first pending
6717        // request in FIFO order across all sessions
6718        cx.read(|cx| {
6719            let parent_id = acp::SessionId::new("parent");
6720            let (session_id, tool_call_id, _) = conversation
6721                .read(cx)
6722                .pending_tool_call(&parent_id, cx)
6723                .expect("Expected a pending tool call from parent query");
6724            assert_eq!(session_id, acp::SessionId::new("parent"));
6725            assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
6726        });
6727    }
6728
6729    #[gpui::test]
6730    async fn test_conversation_parent_pending_tool_call_returns_first_across_threads(
6731        cx: &mut TestAppContext,
6732    ) {
6733        init_test(cx);
6734
6735        let fs = FakeFs::new(cx.executor());
6736        let project = Project::test(fs, [], cx).await;
6737        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6738
6739        let (thread_a, thread_b, conversation) = cx.update(|cx| {
6740            let thread_a =
6741                create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
6742            let thread_b =
6743                create_test_acp_thread(None, "thread-b", connection.clone(), project.clone(), cx);
6744            let conversation = cx.new(|cx| {
6745                let mut conversation = Conversation::default();
6746                conversation.register_thread(thread_a.clone(), cx);
6747                conversation.register_thread(thread_b.clone(), cx);
6748                conversation
6749            });
6750            (thread_a, thread_b, conversation)
6751        });
6752
6753        let _task_a = request_test_tool_authorization(&thread_a, "tc-a", "allow-a", cx);
6754        let _task_b = request_test_tool_authorization(&thread_b, "tc-b", "allow-b", cx);
6755
6756        // Both threads are non-subagent, so pending_tool_call always returns
6757        // the first entry from permission_requests (FIFO across all sessions)
6758        cx.read(|cx| {
6759            let session_a = acp::SessionId::new("thread-a");
6760            let (session_id, tool_call_id, _) = conversation
6761                .read(cx)
6762                .pending_tool_call(&session_a, cx)
6763                .expect("Expected a pending tool call");
6764            assert_eq!(session_id, acp::SessionId::new("thread-a"));
6765            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6766        });
6767
6768        // Querying with thread-b also returns thread-a's tool call,
6769        // because non-subagent queries always use permission_requests.first()
6770        cx.read(|cx| {
6771            let session_b = acp::SessionId::new("thread-b");
6772            let (session_id, tool_call_id, _) = conversation
6773                .read(cx)
6774                .pending_tool_call(&session_b, cx)
6775                .expect("Expected a pending tool call from thread-b query");
6776            assert_eq!(
6777                session_id,
6778                acp::SessionId::new("thread-a"),
6779                "Non-subagent queries always return the first pending request in FIFO order"
6780            );
6781            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6782        });
6783
6784        // After authorizing thread-a's tool call, thread-b's becomes first
6785        cx.update(|cx| {
6786            conversation.update(cx, |conversation, cx| {
6787                conversation.authorize_tool_call(
6788                    acp::SessionId::new("thread-a"),
6789                    acp::ToolCallId::new("tc-a"),
6790                    SelectedPermissionOutcome::new(
6791                        acp::PermissionOptionId::new("allow-a"),
6792                        acp::PermissionOptionKind::AllowOnce,
6793                    ),
6794                    cx,
6795                );
6796            });
6797        });
6798
6799        cx.run_until_parked();
6800
6801        cx.read(|cx| {
6802            let session_b = acp::SessionId::new("thread-b");
6803            let (session_id, tool_call_id, _) = conversation
6804                .read(cx)
6805                .pending_tool_call(&session_b, cx)
6806                .expect("Expected thread-b's tool call after thread-a's was authorized");
6807            assert_eq!(session_id, acp::SessionId::new("thread-b"));
6808            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
6809        });
6810    }
6811
6812    #[gpui::test]
6813    async fn test_move_queued_message_to_empty_main_editor(cx: &mut TestAppContext) {
6814        init_test(cx);
6815
6816        let (conversation_view, cx) =
6817            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6818
6819        // Add a plain-text message to the queue directly.
6820        active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6821            thread.add_to_queue(
6822                vec![acp::ContentBlock::Text(acp::TextContent::new(
6823                    "queued message".to_string(),
6824                ))],
6825                vec![],
6826                cx,
6827            );
6828            // Main editor must be empty for this path — it is by default, but
6829            // assert to make the precondition explicit.
6830            assert!(thread.message_editor.read(cx).is_empty(cx));
6831            thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6832        });
6833
6834        cx.run_until_parked();
6835
6836        // Queue should now be empty.
6837        let queue_len = active_thread(&conversation_view, cx)
6838            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6839        assert_eq!(queue_len, 0, "Queue should be empty after move");
6840
6841        // Main editor should contain the queued message text.
6842        let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6843        assert_eq!(
6844            text, "queued message",
6845            "Main editor should contain the moved queued message"
6846        );
6847    }
6848
6849    #[gpui::test]
6850    async fn test_move_queued_message_to_non_empty_main_editor(cx: &mut TestAppContext) {
6851        init_test(cx);
6852
6853        let (conversation_view, cx) =
6854            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6855
6856        // Seed the main editor with existing content.
6857        message_editor(&conversation_view, cx).update_in(cx, |editor, window, cx| {
6858            editor.set_message(
6859                vec![acp::ContentBlock::Text(acp::TextContent::new(
6860                    "existing content".to_string(),
6861                ))],
6862                window,
6863                cx,
6864            );
6865        });
6866
6867        // Add a plain-text message to the queue.
6868        active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6869            thread.add_to_queue(
6870                vec![acp::ContentBlock::Text(acp::TextContent::new(
6871                    "queued message".to_string(),
6872                ))],
6873                vec![],
6874                cx,
6875            );
6876            thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6877        });
6878
6879        cx.run_until_parked();
6880
6881        // Queue should now be empty.
6882        let queue_len = active_thread(&conversation_view, cx)
6883            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6884        assert_eq!(queue_len, 0, "Queue should be empty after move");
6885
6886        // Main editor should contain existing content + separator + queued content.
6887        let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6888        assert_eq!(
6889            text, "existing content\n\nqueued message",
6890            "Main editor should have existing content and queued message separated by two newlines"
6891        );
6892    }
6893
6894    #[gpui::test]
6895    async fn test_close_all_sessions_skips_when_unsupported(cx: &mut TestAppContext) {
6896        init_test(cx);
6897
6898        let fs = FakeFs::new(cx.executor());
6899        let project = Project::test(fs, [], cx).await;
6900        let (multi_workspace, cx) =
6901            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6902        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
6903
6904        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
6905        let connection_store =
6906            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
6907
6908        // StubAgentConnection defaults to supports_close_session() -> false
6909        let conversation_view = cx.update(|window, cx| {
6910            cx.new(|cx| {
6911                ConversationView::new(
6912                    Rc::new(StubAgentServer::default_response()),
6913                    connection_store,
6914                    Agent::Custom { id: "Test".into() },
6915                    None,
6916                    None,
6917                    None,
6918                    None,
6919                    workspace.downgrade(),
6920                    project,
6921                    Some(thread_store),
6922                    None,
6923                    window,
6924                    cx,
6925                )
6926            })
6927        });
6928
6929        cx.run_until_parked();
6930
6931        conversation_view.read_with(cx, |view, _cx| {
6932            let connected = view.as_connected().expect("Should be connected");
6933            assert!(
6934                !connected.threads.is_empty(),
6935                "There should be at least one thread"
6936            );
6937            assert!(
6938                !connected.connection.supports_close_session(),
6939                "StubAgentConnection should not support close"
6940            );
6941        });
6942
6943        conversation_view
6944            .update(cx, |view, cx| {
6945                view.as_connected()
6946                    .expect("Should be connected")
6947                    .close_all_sessions(cx)
6948            })
6949            .await;
6950    }
6951
6952    #[gpui::test]
6953    async fn test_close_all_sessions_calls_close_when_supported(cx: &mut TestAppContext) {
6954        init_test(cx);
6955
6956        let (conversation_view, cx) =
6957            setup_conversation_view(StubAgentServer::new(CloseCapableConnection::new()), cx).await;
6958
6959        cx.run_until_parked();
6960
6961        let close_capable = conversation_view.read_with(cx, |view, _cx| {
6962            let connected = view.as_connected().expect("Should be connected");
6963            assert!(
6964                !connected.threads.is_empty(),
6965                "There should be at least one thread"
6966            );
6967            assert!(
6968                connected.connection.supports_close_session(),
6969                "CloseCapableConnection should support close"
6970            );
6971            connected
6972                .connection
6973                .clone()
6974                .into_any()
6975                .downcast::<CloseCapableConnection>()
6976                .expect("Should be CloseCapableConnection")
6977        });
6978
6979        conversation_view
6980            .update(cx, |view, cx| {
6981                view.as_connected()
6982                    .expect("Should be connected")
6983                    .close_all_sessions(cx)
6984            })
6985            .await;
6986
6987        let closed_count = close_capable.closed_sessions.lock().len();
6988        assert!(
6989            closed_count > 0,
6990            "close_session should have been called for each thread"
6991        );
6992    }
6993
6994    #[gpui::test]
6995    async fn test_close_session_returns_error_when_unsupported(cx: &mut TestAppContext) {
6996        init_test(cx);
6997
6998        let (conversation_view, cx) =
6999            setup_conversation_view(StubAgentServer::default_response(), cx).await;
7000
7001        cx.run_until_parked();
7002
7003        let result = conversation_view
7004            .update(cx, |view, cx| {
7005                let connected = view.as_connected().expect("Should be connected");
7006                assert!(
7007                    !connected.connection.supports_close_session(),
7008                    "StubAgentConnection should not support close"
7009                );
7010                let session_id = connected
7011                    .threads
7012                    .keys()
7013                    .next()
7014                    .expect("Should have at least one thread")
7015                    .clone();
7016                connected.connection.clone().close_session(&session_id, cx)
7017            })
7018            .await;
7019
7020        assert!(
7021            result.is_err(),
7022            "close_session should return an error when close is not supported"
7023        );
7024        assert!(
7025            result.unwrap_err().to_string().contains("not supported"),
7026            "Error message should indicate that closing is not supported"
7027        );
7028    }
7029
7030    #[derive(Clone)]
7031    struct CloseCapableConnection {
7032        closed_sessions: Arc<Mutex<Vec<acp::SessionId>>>,
7033    }
7034
7035    impl CloseCapableConnection {
7036        fn new() -> Self {
7037            Self {
7038                closed_sessions: Arc::new(Mutex::new(Vec::new())),
7039            }
7040        }
7041    }
7042
7043    impl AgentConnection for CloseCapableConnection {
7044        fn agent_id(&self) -> AgentId {
7045            AgentId::new("close-capable")
7046        }
7047
7048        fn telemetry_id(&self) -> SharedString {
7049            "close-capable".into()
7050        }
7051
7052        fn new_session(
7053            self: Rc<Self>,
7054            project: Entity<Project>,
7055            work_dirs: PathList,
7056            cx: &mut gpui::App,
7057        ) -> Task<gpui::Result<Entity<AcpThread>>> {
7058            let action_log = cx.new(|_| ActionLog::new(project.clone()));
7059            let thread = cx.new(|cx| {
7060                AcpThread::new(
7061                    None,
7062                    Some("CloseCapableConnection".into()),
7063                    Some(work_dirs),
7064                    self,
7065                    project,
7066                    action_log,
7067                    SessionId::new("close-capable-session"),
7068                    watch::Receiver::constant(
7069                        acp::PromptCapabilities::new()
7070                            .image(true)
7071                            .audio(true)
7072                            .embedded_context(true),
7073                    ),
7074                    cx,
7075                )
7076            });
7077            Task::ready(Ok(thread))
7078        }
7079
7080        fn supports_close_session(&self) -> bool {
7081            true
7082        }
7083
7084        fn close_session(
7085            self: Rc<Self>,
7086            session_id: &acp::SessionId,
7087            _cx: &mut App,
7088        ) -> Task<Result<()>> {
7089            self.closed_sessions.lock().push(session_id.clone());
7090            Task::ready(Ok(()))
7091        }
7092
7093        fn auth_methods(&self) -> &[acp::AuthMethod] {
7094            &[]
7095        }
7096
7097        fn authenticate(
7098            &self,
7099            _method_id: acp::AuthMethodId,
7100            _cx: &mut App,
7101        ) -> Task<gpui::Result<()>> {
7102            Task::ready(Ok(()))
7103        }
7104
7105        fn prompt(
7106            &self,
7107            _id: Option<acp_thread::UserMessageId>,
7108            _params: acp::PromptRequest,
7109            _cx: &mut App,
7110        ) -> Task<gpui::Result<acp::PromptResponse>> {
7111            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
7112        }
7113
7114        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
7115
7116        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7117            self
7118        }
7119    }
7120}