conversation_view.rs

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