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