conversation_view.rs

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