conversation_view.rs

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