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_ne!(mw.workspace(), &workspace1);
3410            })
3411            .unwrap();
3412
3413        // Window is active, agent panel is visible in workspace1, but workspace1
3414        // is in the background. The notification should show because the user
3415        // can't actually see the agent panel.
3416        active_thread(&conversation_view, cx)
3417            .update_in(cx, |view, window, cx| view.send(window, cx));
3418
3419        cx.run_until_parked();
3420
3421        assert!(
3422            cx.windows()
3423                .iter()
3424                .any(|window| window.downcast::<AgentNotification>().is_some()),
3425            "Expected notification when workspace is in background within MultiWorkspace"
3426        );
3427
3428        // Also verify: clicking "View Panel" should switch to workspace1.
3429        cx.windows()
3430            .iter()
3431            .find_map(|window| window.downcast::<AgentNotification>())
3432            .unwrap()
3433            .update(cx, |window, _, cx| window.accept(cx))
3434            .unwrap();
3435
3436        cx.run_until_parked();
3437
3438        multi_workspace_handle
3439            .read_with(cx, |mw, _cx| {
3440                assert_eq!(
3441                    mw.workspace(),
3442                    &workspace1,
3443                    "Expected workspace1 to become the active workspace after accepting notification"
3444                );
3445            })
3446            .unwrap();
3447    }
3448
3449    #[gpui::test]
3450    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
3451        init_test(cx);
3452
3453        // Set notify_when_agent_waiting to Never
3454        cx.update(|cx| {
3455            AgentSettings::override_global(
3456                AgentSettings {
3457                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
3458                    ..AgentSettings::get_global(cx).clone()
3459                },
3460                cx,
3461            );
3462        });
3463
3464        let (conversation_view, cx) =
3465            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3466
3467        let message_editor = message_editor(&conversation_view, cx);
3468        message_editor.update_in(cx, |editor, window, cx| {
3469            editor.set_text("Hello", window, cx);
3470        });
3471
3472        // Window is active
3473
3474        active_thread(&conversation_view, cx)
3475            .update_in(cx, |view, window, cx| view.send(window, cx));
3476
3477        cx.run_until_parked();
3478
3479        // Should NOT show notification because notify_when_agent_waiting is Never
3480        assert!(
3481            !cx.windows()
3482                .iter()
3483                .any(|window| window.downcast::<AgentNotification>().is_some()),
3484            "Expected no notification when notify_when_agent_waiting is Never"
3485        );
3486    }
3487
3488    #[gpui::test]
3489    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
3490        init_test(cx);
3491
3492        let (conversation_view, cx) =
3493            setup_conversation_view(StubAgentServer::default_response(), cx).await;
3494
3495        let weak_view = conversation_view.downgrade();
3496
3497        let message_editor = message_editor(&conversation_view, cx);
3498        message_editor.update_in(cx, |editor, window, cx| {
3499            editor.set_text("Hello", window, cx);
3500        });
3501
3502        cx.deactivate_window();
3503
3504        active_thread(&conversation_view, cx)
3505            .update_in(cx, |view, window, cx| view.send(window, cx));
3506
3507        cx.run_until_parked();
3508
3509        // Verify notification is shown
3510        assert!(
3511            cx.windows()
3512                .iter()
3513                .any(|window| window.downcast::<AgentNotification>().is_some()),
3514            "Expected notification to be shown"
3515        );
3516
3517        // Drop the thread view (simulating navigation to a new thread)
3518        drop(conversation_view);
3519        drop(message_editor);
3520        // Trigger an update to flush effects, which will call release_dropped_entities
3521        cx.update(|_window, _cx| {});
3522        cx.run_until_parked();
3523
3524        // Verify the entity was actually released
3525        assert!(
3526            !weak_view.is_upgradable(),
3527            "Thread view entity should be released after dropping"
3528        );
3529
3530        // The notification should be automatically closed via on_release
3531        assert!(
3532            !cx.windows()
3533                .iter()
3534                .any(|window| window.downcast::<AgentNotification>().is_some()),
3535            "Notification should be closed when thread view is dropped"
3536        );
3537    }
3538
3539    async fn setup_conversation_view(
3540        agent: impl AgentServer + 'static,
3541        cx: &mut TestAppContext,
3542    ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3543        let (conversation_view, _history, cx) =
3544            setup_conversation_view_with_history_and_initial_content(agent, None, cx).await;
3545        (conversation_view, cx)
3546    }
3547
3548    async fn setup_thread_view_with_history(
3549        agent: impl AgentServer + 'static,
3550        cx: &mut TestAppContext,
3551    ) -> (
3552        Entity<ConversationView>,
3553        Entity<ThreadHistory>,
3554        &mut VisualTestContext,
3555    ) {
3556        let (conversation_view, history, cx) =
3557            setup_conversation_view_with_history_and_initial_content(agent, None, cx).await;
3558        (conversation_view, history.expect("Missing history"), cx)
3559    }
3560
3561    async fn setup_conversation_view_with_initial_content(
3562        agent: impl AgentServer + 'static,
3563        initial_content: AgentInitialContent,
3564        cx: &mut TestAppContext,
3565    ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3566        let (conversation_view, _history, cx) =
3567            setup_conversation_view_with_history_and_initial_content(
3568                agent,
3569                Some(initial_content),
3570                cx,
3571            )
3572            .await;
3573        (conversation_view, cx)
3574    }
3575
3576    async fn setup_conversation_view_with_history_and_initial_content(
3577        agent: impl AgentServer + 'static,
3578        initial_content: Option<AgentInitialContent>,
3579        cx: &mut TestAppContext,
3580    ) -> (
3581        Entity<ConversationView>,
3582        Option<Entity<ThreadHistory>>,
3583        &mut VisualTestContext,
3584    ) {
3585        let fs = FakeFs::new(cx.executor());
3586        let project = Project::test(fs, [], cx).await;
3587        let (multi_workspace, cx) =
3588            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3589        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3590
3591        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3592        let connection_store =
3593            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3594
3595        let agent_key = Agent::Custom { id: "Test".into() };
3596
3597        let conversation_view = cx.update(|window, cx| {
3598            cx.new(|cx| {
3599                ConversationView::new(
3600                    Rc::new(agent),
3601                    connection_store.clone(),
3602                    agent_key.clone(),
3603                    None,
3604                    None,
3605                    None,
3606                    initial_content,
3607                    workspace.downgrade(),
3608                    project,
3609                    Some(thread_store),
3610                    None,
3611                    window,
3612                    cx,
3613                )
3614            })
3615        });
3616        cx.run_until_parked();
3617
3618        let history = cx.update(|_window, cx| {
3619            connection_store
3620                .read(cx)
3621                .entry(&agent_key)
3622                .and_then(|e| e.read(cx).history().cloned())
3623        });
3624
3625        (conversation_view, history, cx)
3626    }
3627
3628    fn add_to_workspace(conversation_view: Entity<ConversationView>, cx: &mut VisualTestContext) {
3629        let workspace =
3630            conversation_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3631
3632        workspace
3633            .update_in(cx, |workspace, window, cx| {
3634                workspace.add_item_to_active_pane(
3635                    Box::new(cx.new(|_| ThreadViewItem(conversation_view.clone()))),
3636                    None,
3637                    true,
3638                    window,
3639                    cx,
3640                );
3641            })
3642            .unwrap();
3643    }
3644
3645    struct ThreadViewItem(Entity<ConversationView>);
3646
3647    impl Item for ThreadViewItem {
3648        type Event = ();
3649
3650        fn include_in_nav_history() -> bool {
3651            false
3652        }
3653
3654        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3655            "Test".into()
3656        }
3657    }
3658
3659    impl EventEmitter<()> for ThreadViewItem {}
3660
3661    impl Focusable for ThreadViewItem {
3662        fn focus_handle(&self, cx: &App) -> FocusHandle {
3663            self.0.read(cx).focus_handle(cx)
3664        }
3665    }
3666
3667    impl Render for ThreadViewItem {
3668        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3669            // Render the title editor in the element tree too. In the real app
3670            // it is part of the agent panel
3671            let title_editor = self
3672                .0
3673                .read(cx)
3674                .active_thread()
3675                .map(|t| t.read(cx).title_editor.clone());
3676
3677            v_flex().children(title_editor).child(self.0.clone())
3678        }
3679    }
3680
3681    pub(crate) struct StubAgentServer<C> {
3682        connection: C,
3683    }
3684
3685    impl<C> StubAgentServer<C> {
3686        pub(crate) fn new(connection: C) -> Self {
3687            Self { connection }
3688        }
3689    }
3690
3691    impl StubAgentServer<StubAgentConnection> {
3692        pub(crate) fn default_response() -> Self {
3693            let conn = StubAgentConnection::new();
3694            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3695                acp::ContentChunk::new("Default response".into()),
3696            )]);
3697            Self::new(conn)
3698        }
3699    }
3700
3701    impl<C> AgentServer for StubAgentServer<C>
3702    where
3703        C: 'static + AgentConnection + Send + Clone,
3704    {
3705        fn logo(&self) -> ui::IconName {
3706            ui::IconName::ZedAgent
3707        }
3708
3709        fn agent_id(&self) -> AgentId {
3710            "Test".into()
3711        }
3712
3713        fn connect(
3714            &self,
3715            _delegate: AgentServerDelegate,
3716            _project: Entity<Project>,
3717            _cx: &mut App,
3718        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3719            Task::ready(Ok(Rc::new(self.connection.clone())))
3720        }
3721
3722        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3723            self
3724        }
3725    }
3726
3727    struct FailingAgentServer;
3728
3729    impl AgentServer for FailingAgentServer {
3730        fn logo(&self) -> ui::IconName {
3731            ui::IconName::AiOpenAi
3732        }
3733
3734        fn agent_id(&self) -> AgentId {
3735            AgentId::new("Codex CLI")
3736        }
3737
3738        fn connect(
3739            &self,
3740            _delegate: AgentServerDelegate,
3741            _project: Entity<Project>,
3742            _cx: &mut App,
3743        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3744            Task::ready(Err(anyhow!(
3745                "extracting downloaded asset for \
3746                 https://github.com/zed-industries/codex-acp/releases/download/v0.9.4/\
3747                 codex-acp-0.9.4-aarch64-pc-windows-msvc.zip: \
3748                 failed to iterate over archive: Invalid gzip header"
3749            )))
3750        }
3751
3752        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3753            self
3754        }
3755    }
3756
3757    #[derive(Clone)]
3758    struct StubSessionList {
3759        sessions: Vec<AgentSessionInfo>,
3760    }
3761
3762    impl StubSessionList {
3763        fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3764            Self { sessions }
3765        }
3766    }
3767
3768    impl AgentSessionList for StubSessionList {
3769        fn list_sessions(
3770            &self,
3771            _request: AgentSessionListRequest,
3772            _cx: &mut App,
3773        ) -> Task<anyhow::Result<AgentSessionListResponse>> {
3774            Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
3775        }
3776
3777        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3778            self
3779        }
3780    }
3781
3782    #[derive(Clone)]
3783    struct SessionHistoryConnection {
3784        sessions: Vec<AgentSessionInfo>,
3785    }
3786
3787    impl SessionHistoryConnection {
3788        fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3789            Self { sessions }
3790        }
3791    }
3792
3793    fn build_test_thread(
3794        connection: Rc<dyn AgentConnection>,
3795        project: Entity<Project>,
3796        name: &'static str,
3797        session_id: SessionId,
3798        cx: &mut App,
3799    ) -> Entity<AcpThread> {
3800        let action_log = cx.new(|_| ActionLog::new(project.clone()));
3801        cx.new(|cx| {
3802            AcpThread::new(
3803                None,
3804                Some(name.into()),
3805                None,
3806                connection,
3807                project,
3808                action_log,
3809                session_id,
3810                watch::Receiver::constant(
3811                    acp::PromptCapabilities::new()
3812                        .image(true)
3813                        .audio(true)
3814                        .embedded_context(true),
3815                ),
3816                cx,
3817            )
3818        })
3819    }
3820
3821    impl AgentConnection for SessionHistoryConnection {
3822        fn agent_id(&self) -> AgentId {
3823            AgentId::new("history-connection")
3824        }
3825
3826        fn telemetry_id(&self) -> SharedString {
3827            "history-connection".into()
3828        }
3829
3830        fn new_session(
3831            self: Rc<Self>,
3832            project: Entity<Project>,
3833            _work_dirs: PathList,
3834            cx: &mut App,
3835        ) -> Task<anyhow::Result<Entity<AcpThread>>> {
3836            let thread = build_test_thread(
3837                self,
3838                project,
3839                "SessionHistoryConnection",
3840                SessionId::new("history-session"),
3841                cx,
3842            );
3843            Task::ready(Ok(thread))
3844        }
3845
3846        fn supports_load_session(&self) -> bool {
3847            true
3848        }
3849
3850        fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
3851            Some(Rc::new(StubSessionList::new(self.sessions.clone())))
3852        }
3853
3854        fn auth_methods(&self) -> &[acp::AuthMethod] {
3855            &[]
3856        }
3857
3858        fn authenticate(
3859            &self,
3860            _method_id: acp::AuthMethodId,
3861            _cx: &mut App,
3862        ) -> Task<anyhow::Result<()>> {
3863            Task::ready(Ok(()))
3864        }
3865
3866        fn prompt(
3867            &self,
3868            _id: Option<acp_thread::UserMessageId>,
3869            _params: acp::PromptRequest,
3870            _cx: &mut App,
3871        ) -> Task<anyhow::Result<acp::PromptResponse>> {
3872            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3873        }
3874
3875        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3876
3877        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3878            self
3879        }
3880    }
3881
3882    #[derive(Clone)]
3883    struct ResumeOnlyAgentConnection;
3884
3885    impl AgentConnection for ResumeOnlyAgentConnection {
3886        fn agent_id(&self) -> AgentId {
3887            AgentId::new("resume-only")
3888        }
3889
3890        fn telemetry_id(&self) -> SharedString {
3891            "resume-only".into()
3892        }
3893
3894        fn new_session(
3895            self: Rc<Self>,
3896            project: Entity<Project>,
3897            _work_dirs: PathList,
3898            cx: &mut gpui::App,
3899        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3900            let thread = build_test_thread(
3901                self,
3902                project,
3903                "ResumeOnlyAgentConnection",
3904                SessionId::new("new-session"),
3905                cx,
3906            );
3907            Task::ready(Ok(thread))
3908        }
3909
3910        fn supports_resume_session(&self) -> bool {
3911            true
3912        }
3913
3914        fn resume_session(
3915            self: Rc<Self>,
3916            session_id: acp::SessionId,
3917            project: Entity<Project>,
3918            _work_dirs: PathList,
3919            _title: Option<SharedString>,
3920            cx: &mut App,
3921        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3922            let thread =
3923                build_test_thread(self, project, "ResumeOnlyAgentConnection", session_id, cx);
3924            Task::ready(Ok(thread))
3925        }
3926
3927        fn auth_methods(&self) -> &[acp::AuthMethod] {
3928            &[]
3929        }
3930
3931        fn authenticate(
3932            &self,
3933            _method_id: acp::AuthMethodId,
3934            _cx: &mut App,
3935        ) -> Task<gpui::Result<()>> {
3936            Task::ready(Ok(()))
3937        }
3938
3939        fn prompt(
3940            &self,
3941            _id: Option<acp_thread::UserMessageId>,
3942            _params: acp::PromptRequest,
3943            _cx: &mut App,
3944        ) -> Task<gpui::Result<acp::PromptResponse>> {
3945            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3946        }
3947
3948        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3949
3950        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3951            self
3952        }
3953    }
3954
3955    /// Simulates an agent that requires authentication before a session can be
3956    /// created. `new_session` returns `AuthRequired` until `authenticate` is
3957    /// called with the correct method, after which sessions are created normally.
3958    #[derive(Clone)]
3959    struct AuthGatedAgentConnection {
3960        authenticated: Arc<Mutex<bool>>,
3961        auth_method: acp::AuthMethod,
3962    }
3963
3964    impl AuthGatedAgentConnection {
3965        const AUTH_METHOD_ID: &str = "test-login";
3966
3967        fn new() -> Self {
3968            Self {
3969                authenticated: Arc::new(Mutex::new(false)),
3970                auth_method: acp::AuthMethod::Agent(acp::AuthMethodAgent::new(
3971                    Self::AUTH_METHOD_ID,
3972                    "Test Login",
3973                )),
3974            }
3975        }
3976    }
3977
3978    impl AgentConnection for AuthGatedAgentConnection {
3979        fn agent_id(&self) -> AgentId {
3980            AgentId::new("auth-gated")
3981        }
3982
3983        fn telemetry_id(&self) -> SharedString {
3984            "auth-gated".into()
3985        }
3986
3987        fn new_session(
3988            self: Rc<Self>,
3989            project: Entity<Project>,
3990            work_dirs: PathList,
3991            cx: &mut gpui::App,
3992        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3993            if !*self.authenticated.lock() {
3994                return Task::ready(Err(acp_thread::AuthRequired::new()
3995                    .with_description("Sign in to continue".to_string())
3996                    .into()));
3997            }
3998
3999            let session_id = acp::SessionId::new("auth-gated-session");
4000            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4001            Task::ready(Ok(cx.new(|cx| {
4002                AcpThread::new(
4003                    None,
4004                    None,
4005                    Some(work_dirs),
4006                    self,
4007                    project,
4008                    action_log,
4009                    session_id,
4010                    watch::Receiver::constant(
4011                        acp::PromptCapabilities::new()
4012                            .image(true)
4013                            .audio(true)
4014                            .embedded_context(true),
4015                    ),
4016                    cx,
4017                )
4018            })))
4019        }
4020
4021        fn auth_methods(&self) -> &[acp::AuthMethod] {
4022            std::slice::from_ref(&self.auth_method)
4023        }
4024
4025        fn authenticate(
4026            &self,
4027            method_id: acp::AuthMethodId,
4028            _cx: &mut App,
4029        ) -> Task<gpui::Result<()>> {
4030            if &method_id == self.auth_method.id() {
4031                *self.authenticated.lock() = true;
4032                Task::ready(Ok(()))
4033            } else {
4034                Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
4035            }
4036        }
4037
4038        fn prompt(
4039            &self,
4040            _id: Option<acp_thread::UserMessageId>,
4041            _params: acp::PromptRequest,
4042            _cx: &mut App,
4043        ) -> Task<gpui::Result<acp::PromptResponse>> {
4044            unimplemented!()
4045        }
4046
4047        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4048            unimplemented!()
4049        }
4050
4051        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4052            self
4053        }
4054    }
4055
4056    #[derive(Clone)]
4057    struct SaboteurAgentConnection;
4058
4059    impl AgentConnection for SaboteurAgentConnection {
4060        fn agent_id(&self) -> AgentId {
4061            AgentId::new("saboteur")
4062        }
4063
4064        fn telemetry_id(&self) -> SharedString {
4065            "saboteur".into()
4066        }
4067
4068        fn new_session(
4069            self: Rc<Self>,
4070            project: Entity<Project>,
4071            work_dirs: PathList,
4072            cx: &mut gpui::App,
4073        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4074            Task::ready(Ok(cx.new(|cx| {
4075                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4076                AcpThread::new(
4077                    None,
4078                    None,
4079                    Some(work_dirs),
4080                    self,
4081                    project,
4082                    action_log,
4083                    SessionId::new("test"),
4084                    watch::Receiver::constant(
4085                        acp::PromptCapabilities::new()
4086                            .image(true)
4087                            .audio(true)
4088                            .embedded_context(true),
4089                    ),
4090                    cx,
4091                )
4092            })))
4093        }
4094
4095        fn auth_methods(&self) -> &[acp::AuthMethod] {
4096            &[]
4097        }
4098
4099        fn authenticate(
4100            &self,
4101            _method_id: acp::AuthMethodId,
4102            _cx: &mut App,
4103        ) -> Task<gpui::Result<()>> {
4104            unimplemented!()
4105        }
4106
4107        fn prompt(
4108            &self,
4109            _id: Option<acp_thread::UserMessageId>,
4110            _params: acp::PromptRequest,
4111            _cx: &mut App,
4112        ) -> Task<gpui::Result<acp::PromptResponse>> {
4113            Task::ready(Err(anyhow::anyhow!("Error prompting")))
4114        }
4115
4116        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4117            unimplemented!()
4118        }
4119
4120        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4121            self
4122        }
4123    }
4124
4125    /// Simulates a model which always returns a refusal response
4126    #[derive(Clone)]
4127    struct RefusalAgentConnection;
4128
4129    impl AgentConnection for RefusalAgentConnection {
4130        fn agent_id(&self) -> AgentId {
4131            AgentId::new("refusal")
4132        }
4133
4134        fn telemetry_id(&self) -> SharedString {
4135            "refusal".into()
4136        }
4137
4138        fn new_session(
4139            self: Rc<Self>,
4140            project: Entity<Project>,
4141            work_dirs: PathList,
4142            cx: &mut gpui::App,
4143        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4144            Task::ready(Ok(cx.new(|cx| {
4145                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4146                AcpThread::new(
4147                    None,
4148                    None,
4149                    Some(work_dirs),
4150                    self,
4151                    project,
4152                    action_log,
4153                    SessionId::new("test"),
4154                    watch::Receiver::constant(
4155                        acp::PromptCapabilities::new()
4156                            .image(true)
4157                            .audio(true)
4158                            .embedded_context(true),
4159                    ),
4160                    cx,
4161                )
4162            })))
4163        }
4164
4165        fn auth_methods(&self) -> &[acp::AuthMethod] {
4166            &[]
4167        }
4168
4169        fn authenticate(
4170            &self,
4171            _method_id: acp::AuthMethodId,
4172            _cx: &mut App,
4173        ) -> Task<gpui::Result<()>> {
4174            unimplemented!()
4175        }
4176
4177        fn prompt(
4178            &self,
4179            _id: Option<acp_thread::UserMessageId>,
4180            _params: acp::PromptRequest,
4181            _cx: &mut App,
4182        ) -> Task<gpui::Result<acp::PromptResponse>> {
4183            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
4184        }
4185
4186        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4187            unimplemented!()
4188        }
4189
4190        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4191            self
4192        }
4193    }
4194
4195    #[derive(Clone)]
4196    struct CwdCapturingConnection {
4197        captured_work_dirs: Arc<Mutex<Option<PathList>>>,
4198    }
4199
4200    impl CwdCapturingConnection {
4201        fn new() -> Self {
4202            Self {
4203                captured_work_dirs: Arc::new(Mutex::new(None)),
4204            }
4205        }
4206    }
4207
4208    impl AgentConnection for CwdCapturingConnection {
4209        fn agent_id(&self) -> AgentId {
4210            AgentId::new("cwd-capturing")
4211        }
4212
4213        fn telemetry_id(&self) -> SharedString {
4214            "cwd-capturing".into()
4215        }
4216
4217        fn new_session(
4218            self: Rc<Self>,
4219            project: Entity<Project>,
4220            work_dirs: PathList,
4221            cx: &mut gpui::App,
4222        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4223            *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4224            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4225            let thread = cx.new(|cx| {
4226                AcpThread::new(
4227                    None,
4228                    None,
4229                    Some(work_dirs),
4230                    self.clone(),
4231                    project,
4232                    action_log,
4233                    SessionId::new("new-session"),
4234                    watch::Receiver::constant(
4235                        acp::PromptCapabilities::new()
4236                            .image(true)
4237                            .audio(true)
4238                            .embedded_context(true),
4239                    ),
4240                    cx,
4241                )
4242            });
4243            Task::ready(Ok(thread))
4244        }
4245
4246        fn supports_load_session(&self) -> bool {
4247            true
4248        }
4249
4250        fn load_session(
4251            self: Rc<Self>,
4252            session_id: acp::SessionId,
4253            project: Entity<Project>,
4254            work_dirs: PathList,
4255            _title: Option<SharedString>,
4256            cx: &mut App,
4257        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4258            *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4259            let action_log = cx.new(|_| ActionLog::new(project.clone()));
4260            let thread = cx.new(|cx| {
4261                AcpThread::new(
4262                    None,
4263                    None,
4264                    Some(work_dirs),
4265                    self.clone(),
4266                    project,
4267                    action_log,
4268                    session_id,
4269                    watch::Receiver::constant(
4270                        acp::PromptCapabilities::new()
4271                            .image(true)
4272                            .audio(true)
4273                            .embedded_context(true),
4274                    ),
4275                    cx,
4276                )
4277            });
4278            Task::ready(Ok(thread))
4279        }
4280
4281        fn auth_methods(&self) -> &[acp::AuthMethod] {
4282            &[]
4283        }
4284
4285        fn authenticate(
4286            &self,
4287            _method_id: acp::AuthMethodId,
4288            _cx: &mut App,
4289        ) -> Task<gpui::Result<()>> {
4290            Task::ready(Ok(()))
4291        }
4292
4293        fn prompt(
4294            &self,
4295            _id: Option<acp_thread::UserMessageId>,
4296            _params: acp::PromptRequest,
4297            _cx: &mut App,
4298        ) -> Task<gpui::Result<acp::PromptResponse>> {
4299            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4300        }
4301
4302        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4303
4304        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4305            self
4306        }
4307    }
4308
4309    pub(crate) fn init_test(cx: &mut TestAppContext) {
4310        cx.update(|cx| {
4311            let settings_store = SettingsStore::test(cx);
4312            cx.set_global(settings_store);
4313            ThreadMetadataStore::init_global(cx);
4314            theme_settings::init(theme::LoadThemes::JustBase, cx);
4315            editor::init(cx);
4316            agent_panel::init(cx);
4317            release_channel::init(semver::Version::new(0, 0, 0), cx);
4318            prompt_store::init(cx)
4319        });
4320    }
4321
4322    fn active_thread(
4323        conversation_view: &Entity<ConversationView>,
4324        cx: &TestAppContext,
4325    ) -> Entity<ThreadView> {
4326        cx.read(|cx| {
4327            conversation_view
4328                .read(cx)
4329                .active_thread()
4330                .expect("No active thread")
4331                .clone()
4332        })
4333    }
4334
4335    fn message_editor(
4336        conversation_view: &Entity<ConversationView>,
4337        cx: &TestAppContext,
4338    ) -> Entity<MessageEditor> {
4339        let thread = active_thread(conversation_view, cx);
4340        cx.read(|cx| thread.read(cx).message_editor.clone())
4341    }
4342
4343    #[gpui::test]
4344    async fn test_rewind_views(cx: &mut TestAppContext) {
4345        init_test(cx);
4346
4347        let fs = FakeFs::new(cx.executor());
4348        fs.insert_tree(
4349            "/project",
4350            json!({
4351                "test1.txt": "old content 1",
4352                "test2.txt": "old content 2"
4353            }),
4354        )
4355        .await;
4356        let project = Project::test(fs, [Path::new("/project")], cx).await;
4357        let (multi_workspace, cx) =
4358            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4359        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4360
4361        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
4362        let connection_store =
4363            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
4364
4365        let connection = Rc::new(StubAgentConnection::new());
4366        let conversation_view = cx.update(|window, cx| {
4367            cx.new(|cx| {
4368                ConversationView::new(
4369                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4370                    connection_store,
4371                    Agent::Custom { id: "Test".into() },
4372                    None,
4373                    None,
4374                    None,
4375                    None,
4376                    workspace.downgrade(),
4377                    project.clone(),
4378                    Some(thread_store.clone()),
4379                    None,
4380                    window,
4381                    cx,
4382                )
4383            })
4384        });
4385
4386        cx.run_until_parked();
4387
4388        let thread = conversation_view
4389            .read_with(cx, |view, cx| {
4390                view.active_thread().map(|r| r.read(cx).thread.clone())
4391            })
4392            .unwrap();
4393
4394        // First user message
4395        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4396            acp::ToolCall::new("tool1", "Edit file 1")
4397                .kind(acp::ToolKind::Edit)
4398                .status(acp::ToolCallStatus::Completed)
4399                .content(vec![acp::ToolCallContent::Diff(
4400                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
4401                )]),
4402        )]);
4403
4404        thread
4405            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4406            .await
4407            .unwrap();
4408        cx.run_until_parked();
4409
4410        thread.read_with(cx, |thread, _cx| {
4411            assert_eq!(thread.entries().len(), 2);
4412        });
4413
4414        conversation_view.read_with(cx, |view, cx| {
4415            let entry_view_state = view
4416                .active_thread()
4417                .map(|active| active.read(cx).entry_view_state.clone())
4418                .unwrap();
4419            entry_view_state.read_with(cx, |entry_view_state, _| {
4420                assert!(
4421                    entry_view_state
4422                        .entry(0)
4423                        .unwrap()
4424                        .message_editor()
4425                        .is_some()
4426                );
4427                assert!(entry_view_state.entry(1).unwrap().has_content());
4428            });
4429        });
4430
4431        // Second user message
4432        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4433            acp::ToolCall::new("tool2", "Edit file 2")
4434                .kind(acp::ToolKind::Edit)
4435                .status(acp::ToolCallStatus::Completed)
4436                .content(vec![acp::ToolCallContent::Diff(
4437                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4438                )]),
4439        )]);
4440
4441        thread
4442            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4443            .await
4444            .unwrap();
4445        cx.run_until_parked();
4446
4447        let second_user_message_id = thread.read_with(cx, |thread, _| {
4448            assert_eq!(thread.entries().len(), 4);
4449            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4450                panic!();
4451            };
4452            user_message.id.clone().unwrap()
4453        });
4454
4455        conversation_view.read_with(cx, |view, cx| {
4456            let entry_view_state = view
4457                .active_thread()
4458                .unwrap()
4459                .read(cx)
4460                .entry_view_state
4461                .clone();
4462            entry_view_state.read_with(cx, |entry_view_state, _| {
4463                assert!(
4464                    entry_view_state
4465                        .entry(0)
4466                        .unwrap()
4467                        .message_editor()
4468                        .is_some()
4469                );
4470                assert!(entry_view_state.entry(1).unwrap().has_content());
4471                assert!(
4472                    entry_view_state
4473                        .entry(2)
4474                        .unwrap()
4475                        .message_editor()
4476                        .is_some()
4477                );
4478                assert!(entry_view_state.entry(3).unwrap().has_content());
4479            });
4480        });
4481
4482        // Rewind to first message
4483        thread
4484            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4485            .await
4486            .unwrap();
4487
4488        cx.run_until_parked();
4489
4490        thread.read_with(cx, |thread, _| {
4491            assert_eq!(thread.entries().len(), 2);
4492        });
4493
4494        conversation_view.read_with(cx, |view, cx| {
4495            let active = view.active_thread().unwrap();
4496            active
4497                .read(cx)
4498                .entry_view_state
4499                .read_with(cx, |entry_view_state, _| {
4500                    assert!(
4501                        entry_view_state
4502                            .entry(0)
4503                            .unwrap()
4504                            .message_editor()
4505                            .is_some()
4506                    );
4507                    assert!(entry_view_state.entry(1).unwrap().has_content());
4508
4509                    // Old views should be dropped
4510                    assert!(entry_view_state.entry(2).is_none());
4511                    assert!(entry_view_state.entry(3).is_none());
4512                });
4513        });
4514    }
4515
4516    #[gpui::test]
4517    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4518        init_test(cx);
4519
4520        let connection = StubAgentConnection::new();
4521
4522        // Each user prompt will result in a user message entry plus an agent message entry.
4523        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4524            acp::ContentChunk::new("Response 1".into()),
4525        )]);
4526
4527        let (conversation_view, cx) =
4528            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4529
4530        let thread = conversation_view
4531            .read_with(cx, |view, cx| {
4532                view.active_thread().map(|r| r.read(cx).thread.clone())
4533            })
4534            .unwrap();
4535
4536        thread
4537            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4538            .await
4539            .unwrap();
4540        cx.run_until_parked();
4541
4542        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4543            acp::ContentChunk::new("Response 2".into()),
4544        )]);
4545
4546        thread
4547            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4548            .await
4549            .unwrap();
4550        cx.run_until_parked();
4551
4552        // Move somewhere else first so we're not trivially already on the last user prompt.
4553        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4554            view.scroll_to_top(cx);
4555        });
4556        cx.run_until_parked();
4557
4558        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4559            view.scroll_to_most_recent_user_prompt(cx);
4560            let scroll_top = view.list_state.logical_scroll_top();
4561            // Entries layout is: [User1, Assistant1, User2, Assistant2]
4562            assert_eq!(scroll_top.item_ix, 2);
4563        });
4564    }
4565
4566    #[gpui::test]
4567    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4568        cx: &mut TestAppContext,
4569    ) {
4570        init_test(cx);
4571
4572        let (conversation_view, cx) =
4573            setup_conversation_view(StubAgentServer::default_response(), cx).await;
4574
4575        // With no entries, scrolling should be a no-op and must not panic.
4576        active_thread(&conversation_view, cx).update(cx, |view, cx| {
4577            view.scroll_to_most_recent_user_prompt(cx);
4578            let scroll_top = view.list_state.logical_scroll_top();
4579            assert_eq!(scroll_top.item_ix, 0);
4580        });
4581    }
4582
4583    #[gpui::test]
4584    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4585        init_test(cx);
4586
4587        let connection = StubAgentConnection::new();
4588
4589        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4590            acp::ContentChunk::new("Response".into()),
4591        )]);
4592
4593        let (conversation_view, cx) =
4594            setup_conversation_view(StubAgentServer::new(connection), cx).await;
4595        add_to_workspace(conversation_view.clone(), cx);
4596
4597        let message_editor = message_editor(&conversation_view, cx);
4598        message_editor.update_in(cx, |editor, window, cx| {
4599            editor.set_text("Original message to edit", window, cx);
4600        });
4601        active_thread(&conversation_view, cx)
4602            .update_in(cx, |view, window, cx| view.send(window, cx));
4603
4604        cx.run_until_parked();
4605
4606        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4607            assert_eq!(
4608                view.active_thread()
4609                    .and_then(|active| active.read(cx).editing_message),
4610                None
4611            );
4612
4613            view.active_thread()
4614                .map(|active| &active.read(cx).entry_view_state)
4615                .as_ref()
4616                .unwrap()
4617                .read(cx)
4618                .entry(0)
4619                .unwrap()
4620                .message_editor()
4621                .unwrap()
4622                .clone()
4623        });
4624
4625        // Focus
4626        cx.focus(&user_message_editor);
4627        conversation_view.read_with(cx, |view, cx| {
4628            assert_eq!(
4629                view.active_thread()
4630                    .and_then(|active| active.read(cx).editing_message),
4631                Some(0)
4632            );
4633        });
4634
4635        // Edit
4636        user_message_editor.update_in(cx, |editor, window, cx| {
4637            editor.set_text("Edited message content", window, cx);
4638        });
4639
4640        // Cancel
4641        user_message_editor.update_in(cx, |_editor, window, cx| {
4642            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4643        });
4644
4645        conversation_view.read_with(cx, |view, cx| {
4646            assert_eq!(
4647                view.active_thread()
4648                    .and_then(|active| active.read(cx).editing_message),
4649                None
4650            );
4651        });
4652
4653        user_message_editor.read_with(cx, |editor, cx| {
4654            assert_eq!(editor.text(cx), "Original message to edit");
4655        });
4656    }
4657
4658    #[gpui::test]
4659    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4660        init_test(cx);
4661
4662        let connection = StubAgentConnection::new();
4663
4664        let (conversation_view, cx) =
4665            setup_conversation_view(StubAgentServer::new(connection), cx).await;
4666        add_to_workspace(conversation_view.clone(), cx);
4667
4668        let message_editor = message_editor(&conversation_view, cx);
4669        message_editor.update_in(cx, |editor, window, cx| {
4670            editor.set_text("", window, cx);
4671        });
4672
4673        let thread = cx.read(|cx| {
4674            conversation_view
4675                .read(cx)
4676                .active_thread()
4677                .unwrap()
4678                .read(cx)
4679                .thread
4680                .clone()
4681        });
4682        let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4683
4684        active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
4685            view.send(window, cx);
4686        });
4687        cx.run_until_parked();
4688
4689        let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4690        assert_eq!(
4691            entries_before, entries_after,
4692            "No message should be sent when editor is empty"
4693        );
4694    }
4695
4696    #[gpui::test]
4697    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4698        init_test(cx);
4699
4700        let connection = StubAgentConnection::new();
4701
4702        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4703            acp::ContentChunk::new("Response".into()),
4704        )]);
4705
4706        let (conversation_view, cx) =
4707            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4708        add_to_workspace(conversation_view.clone(), cx);
4709
4710        let message_editor = message_editor(&conversation_view, cx);
4711        message_editor.update_in(cx, |editor, window, cx| {
4712            editor.set_text("Original message to edit", window, cx);
4713        });
4714        active_thread(&conversation_view, cx)
4715            .update_in(cx, |view, window, cx| view.send(window, cx));
4716
4717        cx.run_until_parked();
4718
4719        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4720            assert_eq!(
4721                view.active_thread()
4722                    .and_then(|active| active.read(cx).editing_message),
4723                None
4724            );
4725            assert_eq!(
4726                view.active_thread()
4727                    .unwrap()
4728                    .read(cx)
4729                    .thread
4730                    .read(cx)
4731                    .entries()
4732                    .len(),
4733                2
4734            );
4735
4736            view.active_thread()
4737                .map(|active| &active.read(cx).entry_view_state)
4738                .as_ref()
4739                .unwrap()
4740                .read(cx)
4741                .entry(0)
4742                .unwrap()
4743                .message_editor()
4744                .unwrap()
4745                .clone()
4746        });
4747
4748        // Focus
4749        cx.focus(&user_message_editor);
4750
4751        // Edit
4752        user_message_editor.update_in(cx, |editor, window, cx| {
4753            editor.set_text("Edited message content", window, cx);
4754        });
4755
4756        // Send
4757        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4758            acp::ContentChunk::new("New Response".into()),
4759        )]);
4760
4761        user_message_editor.update_in(cx, |_editor, window, cx| {
4762            window.dispatch_action(Box::new(Chat), cx);
4763        });
4764
4765        cx.run_until_parked();
4766
4767        conversation_view.read_with(cx, |view, cx| {
4768            assert_eq!(
4769                view.active_thread()
4770                    .and_then(|active| active.read(cx).editing_message),
4771                None
4772            );
4773
4774            let entries = view
4775                .active_thread()
4776                .unwrap()
4777                .read(cx)
4778                .thread
4779                .read(cx)
4780                .entries();
4781            assert_eq!(entries.len(), 2);
4782            assert_eq!(
4783                entries[0].to_markdown(cx),
4784                "## User\n\nEdited message content\n\n"
4785            );
4786            assert_eq!(
4787                entries[1].to_markdown(cx),
4788                "## Assistant\n\nNew Response\n\n"
4789            );
4790
4791            let entry_view_state = view
4792                .active_thread()
4793                .map(|active| &active.read(cx).entry_view_state)
4794                .unwrap();
4795            let new_editor = entry_view_state.read_with(cx, |state, _cx| {
4796                assert!(!state.entry(1).unwrap().has_content());
4797                state.entry(0).unwrap().message_editor().unwrap().clone()
4798            });
4799
4800            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4801        })
4802    }
4803
4804    #[gpui::test]
4805    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4806        init_test(cx);
4807
4808        let connection = StubAgentConnection::new();
4809
4810        let (conversation_view, cx) =
4811            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4812        add_to_workspace(conversation_view.clone(), cx);
4813
4814        let message_editor = message_editor(&conversation_view, cx);
4815        message_editor.update_in(cx, |editor, window, cx| {
4816            editor.set_text("Original message to edit", window, cx);
4817        });
4818        active_thread(&conversation_view, cx)
4819            .update_in(cx, |view, window, cx| view.send(window, cx));
4820
4821        cx.run_until_parked();
4822
4823        let (user_message_editor, session_id) = conversation_view.read_with(cx, |view, cx| {
4824            let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
4825            assert_eq!(thread.entries().len(), 1);
4826
4827            let editor = view
4828                .active_thread()
4829                .map(|active| &active.read(cx).entry_view_state)
4830                .as_ref()
4831                .unwrap()
4832                .read(cx)
4833                .entry(0)
4834                .unwrap()
4835                .message_editor()
4836                .unwrap()
4837                .clone();
4838
4839            (editor, thread.session_id().clone())
4840        });
4841
4842        // Focus
4843        cx.focus(&user_message_editor);
4844
4845        conversation_view.read_with(cx, |view, cx| {
4846            assert_eq!(
4847                view.active_thread()
4848                    .and_then(|active| active.read(cx).editing_message),
4849                Some(0)
4850            );
4851        });
4852
4853        // Edit
4854        user_message_editor.update_in(cx, |editor, window, cx| {
4855            editor.set_text("Edited message content", window, cx);
4856        });
4857
4858        conversation_view.read_with(cx, |view, cx| {
4859            assert_eq!(
4860                view.active_thread()
4861                    .and_then(|active| active.read(cx).editing_message),
4862                Some(0)
4863            );
4864        });
4865
4866        // Finish streaming response
4867        cx.update(|_, cx| {
4868            connection.send_update(
4869                session_id.clone(),
4870                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
4871                cx,
4872            );
4873            connection.end_turn(session_id, acp::StopReason::EndTurn);
4874        });
4875
4876        conversation_view.read_with(cx, |view, cx| {
4877            assert_eq!(
4878                view.active_thread()
4879                    .and_then(|active| active.read(cx).editing_message),
4880                Some(0)
4881            );
4882        });
4883
4884        cx.run_until_parked();
4885
4886        // Should still be editing
4887        cx.update(|window, cx| {
4888            assert!(user_message_editor.focus_handle(cx).is_focused(window));
4889            assert_eq!(
4890                conversation_view
4891                    .read(cx)
4892                    .active_thread()
4893                    .and_then(|active| active.read(cx).editing_message),
4894                Some(0)
4895            );
4896            assert_eq!(
4897                user_message_editor.read(cx).text(cx),
4898                "Edited message content"
4899            );
4900        });
4901    }
4902
4903    #[gpui::test]
4904    async fn test_stale_stop_does_not_disable_follow_tail_during_regenerate(
4905        cx: &mut TestAppContext,
4906    ) {
4907        init_test(cx);
4908
4909        let connection = StubAgentConnection::new();
4910
4911        let (conversation_view, cx) =
4912            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4913        add_to_workspace(conversation_view.clone(), cx);
4914
4915        let message_editor = message_editor(&conversation_view, cx);
4916        message_editor.update_in(cx, |editor, window, cx| {
4917            editor.set_text("Original message to edit", window, cx);
4918        });
4919        active_thread(&conversation_view, cx)
4920            .update_in(cx, |view, window, cx| view.send(window, cx));
4921
4922        cx.run_until_parked();
4923
4924        let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4925            view.active_thread()
4926                .map(|active| &active.read(cx).entry_view_state)
4927                .as_ref()
4928                .unwrap()
4929                .read(cx)
4930                .entry(0)
4931                .unwrap()
4932                .message_editor()
4933                .unwrap()
4934                .clone()
4935        });
4936
4937        cx.focus(&user_message_editor);
4938        user_message_editor.update_in(cx, |editor, window, cx| {
4939            editor.set_text("Edited message content", window, cx);
4940        });
4941
4942        user_message_editor.update_in(cx, |_editor, window, cx| {
4943            window.dispatch_action(Box::new(Chat), cx);
4944        });
4945
4946        cx.run_until_parked();
4947
4948        conversation_view.read_with(cx, |view, cx| {
4949            let active = view.active_thread().unwrap();
4950            let active = active.read(cx);
4951
4952            assert_eq!(active.thread.read(cx).status(), ThreadStatus::Generating);
4953            assert!(
4954                active.list_state.is_following_tail(),
4955                "stale stop events from the cancelled turn must not disable follow-tail for the new turn"
4956            );
4957        });
4958    }
4959
4960    struct GeneratingThreadSetup {
4961        conversation_view: Entity<ConversationView>,
4962        thread: Entity<AcpThread>,
4963        message_editor: Entity<MessageEditor>,
4964    }
4965
4966    async fn setup_generating_thread(
4967        cx: &mut TestAppContext,
4968    ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
4969        let connection = StubAgentConnection::new();
4970
4971        let (conversation_view, cx) =
4972            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4973        add_to_workspace(conversation_view.clone(), cx);
4974
4975        let message_editor = message_editor(&conversation_view, cx);
4976        message_editor.update_in(cx, |editor, window, cx| {
4977            editor.set_text("Hello", window, cx);
4978        });
4979        active_thread(&conversation_view, cx)
4980            .update_in(cx, |view, window, cx| view.send(window, cx));
4981
4982        let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
4983            let thread = view
4984                .active_thread()
4985                .as_ref()
4986                .unwrap()
4987                .read(cx)
4988                .thread
4989                .clone();
4990            (thread.clone(), thread.read(cx).session_id().clone())
4991        });
4992
4993        cx.run_until_parked();
4994
4995        cx.update(|_, cx| {
4996            connection.send_update(
4997                session_id.clone(),
4998                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4999                    "Response chunk".into(),
5000                )),
5001                cx,
5002            );
5003        });
5004
5005        cx.run_until_parked();
5006
5007        thread.read_with(cx, |thread, _cx| {
5008            assert_eq!(thread.status(), ThreadStatus::Generating);
5009        });
5010
5011        (
5012            GeneratingThreadSetup {
5013                conversation_view,
5014                thread,
5015                message_editor,
5016            },
5017            cx,
5018        )
5019    }
5020
5021    #[gpui::test]
5022    async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
5023        init_test(cx);
5024
5025        let (setup, cx) = setup_generating_thread(cx).await;
5026
5027        let focus_handle = setup
5028            .conversation_view
5029            .read_with(cx, |view, cx| view.focus_handle(cx));
5030        cx.update(|window, cx| {
5031            window.focus(&focus_handle, cx);
5032        });
5033
5034        setup.conversation_view.update_in(cx, |_, window, cx| {
5035            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5036        });
5037
5038        cx.run_until_parked();
5039
5040        setup.thread.read_with(cx, |thread, _cx| {
5041            assert_eq!(thread.status(), ThreadStatus::Idle);
5042        });
5043    }
5044
5045    #[gpui::test]
5046    async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
5047        init_test(cx);
5048
5049        let (setup, cx) = setup_generating_thread(cx).await;
5050
5051        let editor_focus_handle = setup
5052            .message_editor
5053            .read_with(cx, |editor, cx| editor.focus_handle(cx));
5054        cx.update(|window, cx| {
5055            window.focus(&editor_focus_handle, cx);
5056        });
5057
5058        setup.message_editor.update_in(cx, |_, window, cx| {
5059            window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
5060        });
5061
5062        cx.run_until_parked();
5063
5064        setup.thread.read_with(cx, |thread, _cx| {
5065            assert_eq!(thread.status(), ThreadStatus::Idle);
5066        });
5067    }
5068
5069    #[gpui::test]
5070    async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
5071        init_test(cx);
5072
5073        let (conversation_view, cx) =
5074            setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
5075        add_to_workspace(conversation_view.clone(), cx);
5076
5077        let thread = conversation_view.read_with(cx, |view, cx| {
5078            view.active_thread().unwrap().read(cx).thread.clone()
5079        });
5080
5081        thread.read_with(cx, |thread, _cx| {
5082            assert_eq!(thread.status(), ThreadStatus::Idle);
5083        });
5084
5085        let focus_handle = conversation_view.read_with(cx, |view, _cx| view.focus_handle.clone());
5086        cx.update(|window, cx| {
5087            window.focus(&focus_handle, cx);
5088        });
5089
5090        conversation_view.update_in(cx, |_, window, cx| {
5091            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5092        });
5093
5094        cx.run_until_parked();
5095
5096        thread.read_with(cx, |thread, _cx| {
5097            assert_eq!(thread.status(), ThreadStatus::Idle);
5098        });
5099    }
5100
5101    #[gpui::test]
5102    async fn test_interrupt(cx: &mut TestAppContext) {
5103        init_test(cx);
5104
5105        let connection = StubAgentConnection::new();
5106
5107        let (conversation_view, cx) =
5108            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5109        add_to_workspace(conversation_view.clone(), cx);
5110
5111        let message_editor = message_editor(&conversation_view, cx);
5112        message_editor.update_in(cx, |editor, window, cx| {
5113            editor.set_text("Message 1", window, cx);
5114        });
5115        active_thread(&conversation_view, cx)
5116            .update_in(cx, |view, window, cx| view.send(window, cx));
5117
5118        let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
5119            let thread = view.active_thread().unwrap().read(cx).thread.clone();
5120
5121            (thread.clone(), thread.read(cx).session_id().clone())
5122        });
5123
5124        cx.run_until_parked();
5125
5126        cx.update(|_, cx| {
5127            connection.send_update(
5128                session_id.clone(),
5129                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5130                    "Message 1 resp".into(),
5131                )),
5132                cx,
5133            );
5134        });
5135
5136        cx.run_until_parked();
5137
5138        thread.read_with(cx, |thread, cx| {
5139            assert_eq!(
5140                thread.to_markdown(cx),
5141                indoc::indoc! {"
5142                        ## User
5143
5144                        Message 1
5145
5146                        ## Assistant
5147
5148                        Message 1 resp
5149
5150                    "}
5151            )
5152        });
5153
5154        message_editor.update_in(cx, |editor, window, cx| {
5155            editor.set_text("Message 2", window, cx);
5156        });
5157        active_thread(&conversation_view, cx)
5158            .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
5159
5160        cx.update(|_, cx| {
5161            // Simulate a response sent after beginning to cancel
5162            connection.send_update(
5163                session_id.clone(),
5164                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
5165                cx,
5166            );
5167        });
5168
5169        cx.run_until_parked();
5170
5171        // Last Message 1 response should appear before Message 2
5172        thread.read_with(cx, |thread, cx| {
5173            assert_eq!(
5174                thread.to_markdown(cx),
5175                indoc::indoc! {"
5176                        ## User
5177
5178                        Message 1
5179
5180                        ## Assistant
5181
5182                        Message 1 response
5183
5184                        ## User
5185
5186                        Message 2
5187
5188                    "}
5189            )
5190        });
5191
5192        cx.update(|_, cx| {
5193            connection.send_update(
5194                session_id.clone(),
5195                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5196                    "Message 2 response".into(),
5197                )),
5198                cx,
5199            );
5200            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5201        });
5202
5203        cx.run_until_parked();
5204
5205        thread.read_with(cx, |thread, cx| {
5206            assert_eq!(
5207                thread.to_markdown(cx),
5208                indoc::indoc! {"
5209                        ## User
5210
5211                        Message 1
5212
5213                        ## Assistant
5214
5215                        Message 1 response
5216
5217                        ## User
5218
5219                        Message 2
5220
5221                        ## Assistant
5222
5223                        Message 2 response
5224
5225                    "}
5226            )
5227        });
5228    }
5229
5230    #[gpui::test]
5231    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
5232        init_test(cx);
5233
5234        let connection = StubAgentConnection::new();
5235        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5236            acp::ContentChunk::new("Response".into()),
5237        )]);
5238
5239        let (conversation_view, cx) =
5240            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5241        add_to_workspace(conversation_view.clone(), cx);
5242
5243        let message_editor = message_editor(&conversation_view, cx);
5244        message_editor.update_in(cx, |editor, window, cx| {
5245            editor.set_text("Original message to edit", window, cx)
5246        });
5247        active_thread(&conversation_view, cx)
5248            .update_in(cx, |view, window, cx| view.send(window, cx));
5249        cx.run_until_parked();
5250
5251        let user_message_editor = conversation_view.read_with(cx, |conversation_view, cx| {
5252            conversation_view
5253                .active_thread()
5254                .map(|active| &active.read(cx).entry_view_state)
5255                .as_ref()
5256                .unwrap()
5257                .read(cx)
5258                .entry(0)
5259                .expect("Should have at least one entry")
5260                .message_editor()
5261                .expect("Should have message editor")
5262                .clone()
5263        });
5264
5265        cx.focus(&user_message_editor);
5266        conversation_view.read_with(cx, |view, cx| {
5267            assert_eq!(
5268                view.active_thread()
5269                    .and_then(|active| active.read(cx).editing_message),
5270                Some(0)
5271            );
5272        });
5273
5274        // Ensure to edit the focused message before proceeding otherwise, since
5275        // its content is not different from what was sent, focus will be lost.
5276        user_message_editor.update_in(cx, |editor, window, cx| {
5277            editor.set_text("Original message to edit with ", window, cx)
5278        });
5279
5280        // Create a simple buffer with some text so we can create a selection
5281        // that will then be added to the message being edited.
5282        let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5283            (
5284                conversation_view.workspace.clone(),
5285                conversation_view.project.clone(),
5286            )
5287        });
5288        let buffer = project.update(cx, |project, cx| {
5289            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5290        });
5291
5292        workspace
5293            .update_in(cx, |workspace, window, cx| {
5294                let editor = cx.new(|cx| {
5295                    let mut editor =
5296                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5297
5298                    editor.change_selections(Default::default(), window, cx, |selections| {
5299                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5300                    });
5301
5302                    editor
5303                });
5304                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5305            })
5306            .unwrap();
5307
5308        conversation_view.update_in(cx, |view, window, cx| {
5309            assert_eq!(
5310                view.active_thread()
5311                    .and_then(|active| active.read(cx).editing_message),
5312                Some(0)
5313            );
5314            view.insert_selections(window, cx);
5315        });
5316
5317        user_message_editor.read_with(cx, |editor, cx| {
5318            let text = editor.editor().read(cx).text(cx);
5319            let expected_text = String::from("Original message to edit with selection ");
5320
5321            assert_eq!(text, expected_text);
5322        });
5323    }
5324
5325    #[gpui::test]
5326    async fn test_insert_selections(cx: &mut TestAppContext) {
5327        init_test(cx);
5328
5329        let connection = StubAgentConnection::new();
5330        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5331            acp::ContentChunk::new("Response".into()),
5332        )]);
5333
5334        let (conversation_view, cx) =
5335            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5336        add_to_workspace(conversation_view.clone(), cx);
5337
5338        let message_editor = message_editor(&conversation_view, cx);
5339        message_editor.update_in(cx, |editor, window, cx| {
5340            editor.set_text("Can you review this snippet ", window, cx)
5341        });
5342
5343        // Create a simple buffer with some text so we can create a selection
5344        // that will then be added to the message being edited.
5345        let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5346            (
5347                conversation_view.workspace.clone(),
5348                conversation_view.project.clone(),
5349            )
5350        });
5351        let buffer = project.update(cx, |project, cx| {
5352            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5353        });
5354
5355        workspace
5356            .update_in(cx, |workspace, window, cx| {
5357                let editor = cx.new(|cx| {
5358                    let mut editor =
5359                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5360
5361                    editor.change_selections(Default::default(), window, cx, |selections| {
5362                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5363                    });
5364
5365                    editor
5366                });
5367                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5368            })
5369            .unwrap();
5370
5371        conversation_view.update_in(cx, |view, window, cx| {
5372            assert_eq!(
5373                view.active_thread()
5374                    .and_then(|active| active.read(cx).editing_message),
5375                None
5376            );
5377            view.insert_selections(window, cx);
5378        });
5379
5380        message_editor.read_with(cx, |editor, cx| {
5381            let text = editor.text(cx);
5382            let expected_txt = String::from("Can you review this snippet selection ");
5383
5384            assert_eq!(text, expected_txt);
5385        })
5386    }
5387
5388    #[gpui::test]
5389    async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
5390        init_test(cx);
5391
5392        let tool_call_id = acp::ToolCallId::new("terminal-1");
5393        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
5394            .kind(acp::ToolKind::Edit);
5395
5396        let permission_options = ToolPermissionContext::new(
5397            TerminalTool::NAME,
5398            vec!["cargo build --release".to_string()],
5399        )
5400        .build_permission_options();
5401
5402        let connection =
5403            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5404                tool_call_id.clone(),
5405                permission_options,
5406            )]));
5407
5408        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5409
5410        let (conversation_view, cx) =
5411            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5412
5413        // Disable notifications to avoid popup windows
5414        cx.update(|_window, cx| {
5415            AgentSettings::override_global(
5416                AgentSettings {
5417                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5418                    ..AgentSettings::get_global(cx).clone()
5419                },
5420                cx,
5421            );
5422        });
5423
5424        let message_editor = message_editor(&conversation_view, cx);
5425        message_editor.update_in(cx, |editor, window, cx| {
5426            editor.set_text("Run cargo build", window, cx);
5427        });
5428
5429        active_thread(&conversation_view, cx)
5430            .update_in(cx, |view, window, cx| view.send(window, cx));
5431
5432        cx.run_until_parked();
5433
5434        // Verify the tool call is in WaitingForConfirmation state with the expected options
5435        conversation_view.read_with(cx, |conversation_view, cx| {
5436            let thread = conversation_view
5437                .active_thread()
5438                .expect("Thread should exist")
5439                .read(cx)
5440                .thread
5441                .clone();
5442            let thread = thread.read(cx);
5443
5444            let tool_call = thread.entries().iter().find_map(|entry| {
5445                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5446                    Some(call)
5447                } else {
5448                    None
5449                }
5450            });
5451
5452            assert!(tool_call.is_some(), "Expected a tool call entry");
5453            let tool_call = tool_call.unwrap();
5454
5455            // Verify it's waiting for confirmation
5456            assert!(
5457                matches!(
5458                    tool_call.status,
5459                    acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
5460                ),
5461                "Expected WaitingForConfirmation status, got {:?}",
5462                tool_call.status
5463            );
5464
5465            // Verify the options count (granularity options only, no separate Deny option)
5466            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5467                &tool_call.status
5468            {
5469                let PermissionOptions::Dropdown(choices) = options else {
5470                    panic!("Expected dropdown permission options");
5471                };
5472
5473                assert_eq!(
5474                    choices.len(),
5475                    3,
5476                    "Expected 3 permission options (granularity only)"
5477                );
5478
5479                // Verify specific button labels (now using neutral names)
5480                let labels: Vec<&str> = choices
5481                    .iter()
5482                    .map(|choice| choice.allow.name.as_ref())
5483                    .collect();
5484                assert!(
5485                    labels.contains(&"Always for terminal"),
5486                    "Missing 'Always for terminal' option"
5487                );
5488                assert!(
5489                    labels.contains(&"Always for `cargo build` commands"),
5490                    "Missing pattern option"
5491                );
5492                assert!(
5493                    labels.contains(&"Only this time"),
5494                    "Missing 'Only this time' option"
5495                );
5496            }
5497        });
5498    }
5499
5500    #[gpui::test]
5501    async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5502        init_test(cx);
5503
5504        let tool_call_id = acp::ToolCallId::new("edit-file-1");
5505        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5506            .kind(acp::ToolKind::Edit);
5507
5508        let permission_options =
5509            ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5510                .build_permission_options();
5511
5512        let connection =
5513            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5514                tool_call_id.clone(),
5515                permission_options,
5516            )]));
5517
5518        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5519
5520        let (conversation_view, cx) =
5521            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5522
5523        // Disable notifications
5524        cx.update(|_window, cx| {
5525            AgentSettings::override_global(
5526                AgentSettings {
5527                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5528                    ..AgentSettings::get_global(cx).clone()
5529                },
5530                cx,
5531            );
5532        });
5533
5534        let message_editor = message_editor(&conversation_view, cx);
5535        message_editor.update_in(cx, |editor, window, cx| {
5536            editor.set_text("Edit the main file", window, cx);
5537        });
5538
5539        active_thread(&conversation_view, cx)
5540            .update_in(cx, |view, window, cx| view.send(window, cx));
5541
5542        cx.run_until_parked();
5543
5544        // Verify the options
5545        conversation_view.read_with(cx, |conversation_view, cx| {
5546            let thread = conversation_view
5547                .active_thread()
5548                .expect("Thread should exist")
5549                .read(cx)
5550                .thread
5551                .clone();
5552            let thread = thread.read(cx);
5553
5554            let tool_call = thread.entries().iter().find_map(|entry| {
5555                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5556                    Some(call)
5557                } else {
5558                    None
5559                }
5560            });
5561
5562            assert!(tool_call.is_some(), "Expected a tool call entry");
5563            let tool_call = tool_call.unwrap();
5564
5565            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5566                &tool_call.status
5567            {
5568                let PermissionOptions::Dropdown(choices) = options else {
5569                    panic!("Expected dropdown permission options");
5570                };
5571
5572                let labels: Vec<&str> = choices
5573                    .iter()
5574                    .map(|choice| choice.allow.name.as_ref())
5575                    .collect();
5576                assert!(
5577                    labels.contains(&"Always for edit file"),
5578                    "Missing 'Always for edit file' option"
5579                );
5580                assert!(
5581                    labels.contains(&"Always for `src/`"),
5582                    "Missing path pattern option"
5583                );
5584            } else {
5585                panic!("Expected WaitingForConfirmation status");
5586            }
5587        });
5588    }
5589
5590    #[gpui::test]
5591    async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5592        init_test(cx);
5593
5594        let tool_call_id = acp::ToolCallId::new("fetch-1");
5595        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5596            .kind(acp::ToolKind::Fetch);
5597
5598        let permission_options =
5599            ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5600                .build_permission_options();
5601
5602        let connection =
5603            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5604                tool_call_id.clone(),
5605                permission_options,
5606            )]));
5607
5608        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5609
5610        let (conversation_view, cx) =
5611            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5612
5613        // Disable notifications
5614        cx.update(|_window, cx| {
5615            AgentSettings::override_global(
5616                AgentSettings {
5617                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5618                    ..AgentSettings::get_global(cx).clone()
5619                },
5620                cx,
5621            );
5622        });
5623
5624        let message_editor = message_editor(&conversation_view, cx);
5625        message_editor.update_in(cx, |editor, window, cx| {
5626            editor.set_text("Fetch the docs", window, cx);
5627        });
5628
5629        active_thread(&conversation_view, cx)
5630            .update_in(cx, |view, window, cx| view.send(window, cx));
5631
5632        cx.run_until_parked();
5633
5634        // Verify the options
5635        conversation_view.read_with(cx, |conversation_view, cx| {
5636            let thread = conversation_view
5637                .active_thread()
5638                .expect("Thread should exist")
5639                .read(cx)
5640                .thread
5641                .clone();
5642            let thread = thread.read(cx);
5643
5644            let tool_call = thread.entries().iter().find_map(|entry| {
5645                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5646                    Some(call)
5647                } else {
5648                    None
5649                }
5650            });
5651
5652            assert!(tool_call.is_some(), "Expected a tool call entry");
5653            let tool_call = tool_call.unwrap();
5654
5655            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5656                &tool_call.status
5657            {
5658                let PermissionOptions::Dropdown(choices) = options else {
5659                    panic!("Expected dropdown permission options");
5660                };
5661
5662                let labels: Vec<&str> = choices
5663                    .iter()
5664                    .map(|choice| choice.allow.name.as_ref())
5665                    .collect();
5666                assert!(
5667                    labels.contains(&"Always for fetch"),
5668                    "Missing 'Always for fetch' option"
5669                );
5670                assert!(
5671                    labels.contains(&"Always for `docs.rs`"),
5672                    "Missing domain pattern option"
5673                );
5674            } else {
5675                panic!("Expected WaitingForConfirmation status");
5676            }
5677        });
5678    }
5679
5680    #[gpui::test]
5681    async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5682        init_test(cx);
5683
5684        let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5685        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5686            .kind(acp::ToolKind::Edit);
5687
5688        // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5689        let permission_options = ToolPermissionContext::new(
5690            TerminalTool::NAME,
5691            vec!["./deploy.sh --production".to_string()],
5692        )
5693        .build_permission_options();
5694
5695        let connection =
5696            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5697                tool_call_id.clone(),
5698                permission_options,
5699            )]));
5700
5701        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5702
5703        let (conversation_view, cx) =
5704            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5705
5706        // Disable notifications
5707        cx.update(|_window, cx| {
5708            AgentSettings::override_global(
5709                AgentSettings {
5710                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5711                    ..AgentSettings::get_global(cx).clone()
5712                },
5713                cx,
5714            );
5715        });
5716
5717        let message_editor = message_editor(&conversation_view, cx);
5718        message_editor.update_in(cx, |editor, window, cx| {
5719            editor.set_text("Run the deploy script", window, cx);
5720        });
5721
5722        active_thread(&conversation_view, cx)
5723            .update_in(cx, |view, window, cx| view.send(window, cx));
5724
5725        cx.run_until_parked();
5726
5727        // Verify only 2 options (no pattern button when command doesn't match pattern)
5728        conversation_view.read_with(cx, |conversation_view, cx| {
5729            let thread = conversation_view
5730                .active_thread()
5731                .expect("Thread should exist")
5732                .read(cx)
5733                .thread
5734                .clone();
5735            let thread = thread.read(cx);
5736
5737            let tool_call = thread.entries().iter().find_map(|entry| {
5738                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5739                    Some(call)
5740                } else {
5741                    None
5742                }
5743            });
5744
5745            assert!(tool_call.is_some(), "Expected a tool call entry");
5746            let tool_call = tool_call.unwrap();
5747
5748            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5749                &tool_call.status
5750            {
5751                let PermissionOptions::Dropdown(choices) = options else {
5752                    panic!("Expected dropdown permission options");
5753                };
5754
5755                assert_eq!(
5756                    choices.len(),
5757                    2,
5758                    "Expected 2 permission options (no pattern option)"
5759                );
5760
5761                let labels: Vec<&str> = choices
5762                    .iter()
5763                    .map(|choice| choice.allow.name.as_ref())
5764                    .collect();
5765                assert!(
5766                    labels.contains(&"Always for terminal"),
5767                    "Missing 'Always for terminal' option"
5768                );
5769                assert!(
5770                    labels.contains(&"Only this time"),
5771                    "Missing 'Only this time' option"
5772                );
5773                // Should NOT contain a pattern option
5774                assert!(
5775                    !labels.iter().any(|l| l.contains("commands")),
5776                    "Should not have pattern option"
5777                );
5778            } else {
5779                panic!("Expected WaitingForConfirmation status");
5780            }
5781        });
5782    }
5783
5784    #[gpui::test]
5785    async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5786        init_test(cx);
5787
5788        let tool_call_id = acp::ToolCallId::new("action-test-1");
5789        let tool_call =
5790            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5791
5792        let permission_options =
5793            ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
5794                .build_permission_options();
5795
5796        let connection =
5797            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5798                tool_call_id.clone(),
5799                permission_options,
5800            )]));
5801
5802        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5803
5804        let (conversation_view, cx) =
5805            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5806        add_to_workspace(conversation_view.clone(), cx);
5807
5808        cx.update(|_window, cx| {
5809            AgentSettings::override_global(
5810                AgentSettings {
5811                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5812                    ..AgentSettings::get_global(cx).clone()
5813                },
5814                cx,
5815            );
5816        });
5817
5818        let message_editor = message_editor(&conversation_view, cx);
5819        message_editor.update_in(cx, |editor, window, cx| {
5820            editor.set_text("Run tests", window, cx);
5821        });
5822
5823        active_thread(&conversation_view, cx)
5824            .update_in(cx, |view, window, cx| view.send(window, cx));
5825
5826        cx.run_until_parked();
5827
5828        // Verify tool call is waiting for confirmation
5829        conversation_view.read_with(cx, |conversation_view, cx| {
5830            let tool_call = conversation_view.pending_tool_call(cx);
5831            assert!(
5832                tool_call.is_some(),
5833                "Expected a tool call waiting for confirmation"
5834            );
5835        });
5836
5837        // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
5838        conversation_view.update_in(cx, |_, window, cx| {
5839            window.dispatch_action(
5840                crate::AuthorizeToolCall {
5841                    tool_call_id: "action-test-1".to_string(),
5842                    option_id: "allow".to_string(),
5843                    option_kind: "AllowOnce".to_string(),
5844                }
5845                .boxed_clone(),
5846                cx,
5847            );
5848        });
5849
5850        cx.run_until_parked();
5851
5852        // Verify tool call is no longer waiting for confirmation (was authorized)
5853        conversation_view.read_with(cx, |conversation_view, cx| {
5854            let tool_call = conversation_view.pending_tool_call(cx);
5855            assert!(
5856                tool_call.is_none(),
5857                "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
5858            );
5859        });
5860    }
5861
5862    #[gpui::test]
5863    async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
5864        init_test(cx);
5865
5866        let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
5867        let tool_call =
5868            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5869
5870        let permission_options =
5871            ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5872                .build_permission_options();
5873
5874        let connection =
5875            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5876                tool_call_id.clone(),
5877                permission_options.clone(),
5878            )]));
5879
5880        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5881
5882        let (conversation_view, cx) =
5883            setup_conversation_view(StubAgentServer::new(connection), cx).await;
5884        add_to_workspace(conversation_view.clone(), cx);
5885
5886        cx.update(|_window, cx| {
5887            AgentSettings::override_global(
5888                AgentSettings {
5889                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5890                    ..AgentSettings::get_global(cx).clone()
5891                },
5892                cx,
5893            );
5894        });
5895
5896        let message_editor = message_editor(&conversation_view, cx);
5897        message_editor.update_in(cx, |editor, window, cx| {
5898            editor.set_text("Install dependencies", window, cx);
5899        });
5900
5901        active_thread(&conversation_view, cx)
5902            .update_in(cx, |view, window, cx| view.send(window, cx));
5903
5904        cx.run_until_parked();
5905
5906        // Find the pattern option ID (the choice with non-empty sub_patterns)
5907        let pattern_option = match &permission_options {
5908            PermissionOptions::Dropdown(choices) => choices
5909                .iter()
5910                .find(|choice| !choice.sub_patterns.is_empty())
5911                .map(|choice| &choice.allow)
5912                .expect("Should have a pattern option for npm command"),
5913            _ => panic!("Expected dropdown permission options"),
5914        };
5915
5916        // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
5917        conversation_view.update_in(cx, |_, window, cx| {
5918            window.dispatch_action(
5919                crate::AuthorizeToolCall {
5920                    tool_call_id: "pattern-action-test-1".to_string(),
5921                    option_id: pattern_option.option_id.0.to_string(),
5922                    option_kind: "AllowAlways".to_string(),
5923                }
5924                .boxed_clone(),
5925                cx,
5926            );
5927        });
5928
5929        cx.run_until_parked();
5930
5931        // Verify tool call was authorized
5932        conversation_view.read_with(cx, |conversation_view, cx| {
5933            let tool_call = conversation_view.pending_tool_call(cx);
5934            assert!(
5935                tool_call.is_none(),
5936                "Tool call should be authorized after selecting pattern option"
5937            );
5938        });
5939    }
5940
5941    #[gpui::test]
5942    async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
5943        init_test(cx);
5944
5945        let tool_call_id = acp::ToolCallId::new("granularity-test-1");
5946        let tool_call =
5947            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
5948
5949        let permission_options =
5950            ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".to_string()])
5951                .build_permission_options();
5952
5953        let connection =
5954            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5955                tool_call_id.clone(),
5956                permission_options.clone(),
5957            )]));
5958
5959        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5960
5961        let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
5962        add_to_workspace(thread_view.clone(), cx);
5963
5964        cx.update(|_window, cx| {
5965            AgentSettings::override_global(
5966                AgentSettings {
5967                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5968                    ..AgentSettings::get_global(cx).clone()
5969                },
5970                cx,
5971            );
5972        });
5973
5974        let message_editor = message_editor(&thread_view, cx);
5975        message_editor.update_in(cx, |editor, window, cx| {
5976            editor.set_text("Build the project", window, cx);
5977        });
5978
5979        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5980
5981        cx.run_until_parked();
5982
5983        // Verify default granularity is the last option (index 2 = "Only this time")
5984        thread_view.read_with(cx, |thread_view, cx| {
5985            let state = thread_view.active_thread().unwrap();
5986            let selected = state.read(cx).permission_selections.get(&tool_call_id);
5987            assert!(
5988                selected.is_none(),
5989                "Should have no selection initially (defaults to last)"
5990            );
5991        });
5992
5993        // Select the first option (index 0 = "Always for terminal")
5994        thread_view.update_in(cx, |_, window, cx| {
5995            window.dispatch_action(
5996                crate::SelectPermissionGranularity {
5997                    tool_call_id: "granularity-test-1".to_string(),
5998                    index: 0,
5999                }
6000                .boxed_clone(),
6001                cx,
6002            );
6003        });
6004
6005        cx.run_until_parked();
6006
6007        // Verify the selection was updated
6008        thread_view.read_with(cx, |thread_view, cx| {
6009            let state = thread_view.active_thread().unwrap();
6010            let selected = state.read(cx).permission_selections.get(&tool_call_id);
6011            assert_eq!(
6012                selected.and_then(|s| s.choice_index()),
6013                Some(0),
6014                "Should have selected index 0"
6015            );
6016        });
6017    }
6018
6019    #[gpui::test]
6020    async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
6021        init_test(cx);
6022
6023        let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
6024        let tool_call =
6025            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
6026
6027        let permission_options =
6028            ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
6029                .build_permission_options();
6030
6031        // Verify we have the expected options
6032        let PermissionOptions::Dropdown(choices) = &permission_options else {
6033            panic!("Expected dropdown permission options");
6034        };
6035
6036        assert_eq!(choices.len(), 3);
6037        assert!(
6038            choices[0]
6039                .allow
6040                .option_id
6041                .0
6042                .contains("always_allow:terminal")
6043        );
6044        assert!(
6045            choices[1]
6046                .allow
6047                .option_id
6048                .0
6049                .contains("always_allow:terminal")
6050        );
6051        assert!(!choices[1].sub_patterns.is_empty());
6052        assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
6053
6054        let connection =
6055            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6056                tool_call_id.clone(),
6057                permission_options.clone(),
6058            )]));
6059
6060        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6061
6062        let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
6063        add_to_workspace(thread_view.clone(), cx);
6064
6065        cx.update(|_window, cx| {
6066            AgentSettings::override_global(
6067                AgentSettings {
6068                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6069                    ..AgentSettings::get_global(cx).clone()
6070                },
6071                cx,
6072            );
6073        });
6074
6075        let message_editor = message_editor(&thread_view, cx);
6076        message_editor.update_in(cx, |editor, window, cx| {
6077            editor.set_text("Install dependencies", window, cx);
6078        });
6079
6080        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6081
6082        cx.run_until_parked();
6083
6084        // Select the pattern option (index 1 = "Always for `npm` commands")
6085        thread_view.update_in(cx, |_, window, cx| {
6086            window.dispatch_action(
6087                crate::SelectPermissionGranularity {
6088                    tool_call_id: "allow-granularity-test-1".to_string(),
6089                    index: 1,
6090                }
6091                .boxed_clone(),
6092                cx,
6093            );
6094        });
6095
6096        cx.run_until_parked();
6097
6098        // Simulate clicking the Allow button by dispatching AllowOnce action
6099        // which should use the selected granularity
6100        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
6101            view.allow_once(&AllowOnce, window, cx)
6102        });
6103
6104        cx.run_until_parked();
6105
6106        // Verify tool call was authorized
6107        thread_view.read_with(cx, |thread_view, cx| {
6108            let tool_call = thread_view.pending_tool_call(cx);
6109            assert!(
6110                tool_call.is_none(),
6111                "Tool call should be authorized after Allow with pattern granularity"
6112            );
6113        });
6114    }
6115
6116    #[gpui::test]
6117    async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
6118        init_test(cx);
6119
6120        let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
6121        let tool_call =
6122            acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
6123
6124        let permission_options =
6125            ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
6126                .build_permission_options();
6127
6128        let connection =
6129            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6130                tool_call_id.clone(),
6131                permission_options.clone(),
6132            )]));
6133
6134        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6135
6136        let (conversation_view, cx) =
6137            setup_conversation_view(StubAgentServer::new(connection), cx).await;
6138        add_to_workspace(conversation_view.clone(), cx);
6139
6140        cx.update(|_window, cx| {
6141            AgentSettings::override_global(
6142                AgentSettings {
6143                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6144                    ..AgentSettings::get_global(cx).clone()
6145                },
6146                cx,
6147            );
6148        });
6149
6150        let message_editor = message_editor(&conversation_view, cx);
6151        message_editor.update_in(cx, |editor, window, cx| {
6152            editor.set_text("Push changes", window, cx);
6153        });
6154
6155        active_thread(&conversation_view, cx)
6156            .update_in(cx, |view, window, cx| view.send(window, cx));
6157
6158        cx.run_until_parked();
6159
6160        // Use default granularity (last option = "Only this time")
6161        // Simulate clicking the Deny button
6162        active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
6163            view.reject_once(&RejectOnce, window, cx)
6164        });
6165
6166        cx.run_until_parked();
6167
6168        // Verify tool call was rejected (no longer waiting for confirmation)
6169        conversation_view.read_with(cx, |conversation_view, cx| {
6170            let tool_call = conversation_view.pending_tool_call(cx);
6171            assert!(
6172                tool_call.is_none(),
6173                "Tool call should be rejected after Deny"
6174            );
6175        });
6176    }
6177
6178    #[gpui::test]
6179    async fn test_option_id_transformation_for_allow() {
6180        let permission_options = ToolPermissionContext::new(
6181            TerminalTool::NAME,
6182            vec!["cargo build --release".to_string()],
6183        )
6184        .build_permission_options();
6185
6186        let PermissionOptions::Dropdown(choices) = permission_options else {
6187            panic!("Expected dropdown permission options");
6188        };
6189
6190        let allow_ids: Vec<String> = choices
6191            .iter()
6192            .map(|choice| choice.allow.option_id.0.to_string())
6193            .collect();
6194
6195        assert!(allow_ids.contains(&"allow".to_string()));
6196        assert_eq!(
6197            allow_ids
6198                .iter()
6199                .filter(|id| *id == "always_allow:terminal")
6200                .count(),
6201            2,
6202            "Expected two always_allow:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6203        );
6204    }
6205
6206    #[gpui::test]
6207    async fn test_option_id_transformation_for_deny() {
6208        let permission_options = ToolPermissionContext::new(
6209            TerminalTool::NAME,
6210            vec!["cargo build --release".to_string()],
6211        )
6212        .build_permission_options();
6213
6214        let PermissionOptions::Dropdown(choices) = permission_options else {
6215            panic!("Expected dropdown permission options");
6216        };
6217
6218        let deny_ids: Vec<String> = choices
6219            .iter()
6220            .map(|choice| choice.deny.option_id.0.to_string())
6221            .collect();
6222
6223        assert!(deny_ids.contains(&"deny".to_string()));
6224        assert_eq!(
6225            deny_ids
6226                .iter()
6227                .filter(|id| *id == "always_deny:terminal")
6228                .count(),
6229            2,
6230            "Expected two always_deny:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6231        );
6232    }
6233
6234    #[gpui::test]
6235    async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
6236        init_test(cx);
6237
6238        let (conversation_view, cx) =
6239            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6240        add_to_workspace(conversation_view.clone(), cx);
6241
6242        let active = active_thread(&conversation_view, cx);
6243        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6244        let thread = cx.read(|cx| active.read(cx).thread.clone());
6245
6246        title_editor.read_with(cx, |editor, cx| {
6247            assert!(!editor.read_only(cx));
6248        });
6249
6250        cx.focus(&conversation_view);
6251        cx.focus(&title_editor);
6252
6253        cx.dispatch_action(editor::actions::DeleteLine);
6254        cx.simulate_input("My Custom Title");
6255
6256        cx.run_until_parked();
6257
6258        title_editor.read_with(cx, |editor, cx| {
6259            assert_eq!(editor.text(cx), "My Custom Title");
6260        });
6261        thread.read_with(cx, |thread, _cx| {
6262            assert_eq!(thread.title(), Some("My Custom Title".into()));
6263        });
6264    }
6265
6266    #[gpui::test]
6267    async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
6268        init_test(cx);
6269
6270        let (conversation_view, cx) =
6271            setup_conversation_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
6272
6273        let active = active_thread(&conversation_view, cx);
6274        let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6275
6276        title_editor.read_with(cx, |editor, cx| {
6277            assert!(
6278                editor.read_only(cx),
6279                "Title editor should be read-only when the connection does not support set_title"
6280            );
6281        });
6282    }
6283
6284    #[gpui::test]
6285    async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
6286        init_test(cx);
6287
6288        let connection = StubAgentConnection::new();
6289
6290        let (conversation_view, cx) =
6291            setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
6292
6293        let message_editor = message_editor(&conversation_view, cx);
6294        message_editor.update_in(cx, |editor, window, cx| {
6295            editor.set_text("Some prompt", window, cx);
6296        });
6297        active_thread(&conversation_view, cx)
6298            .update_in(cx, |view, window, cx| view.send(window, cx));
6299
6300        let session_id = conversation_view.read_with(cx, |view, cx| {
6301            view.active_thread()
6302                .unwrap()
6303                .read(cx)
6304                .thread
6305                .read(cx)
6306                .session_id()
6307                .clone()
6308        });
6309
6310        cx.run_until_parked();
6311
6312        cx.update(|_, _cx| {
6313            connection.end_turn(session_id, acp::StopReason::MaxTokens);
6314        });
6315
6316        cx.run_until_parked();
6317
6318        conversation_view.read_with(cx, |conversation_view, cx| {
6319            let state = conversation_view.active_thread().unwrap();
6320            let error = &state.read(cx).thread_error;
6321            match error {
6322                Some(ThreadError::Other { message, .. }) => {
6323                    assert!(
6324                        message.contains("Maximum tokens reached"),
6325                        "Expected 'Maximum tokens reached' error, got: {}",
6326                        message
6327                    );
6328                }
6329                other => panic!(
6330                    "Expected ThreadError::Other with 'Maximum tokens reached', got: {:?}",
6331                    other.is_some()
6332                ),
6333            }
6334        });
6335    }
6336
6337    fn create_test_acp_thread(
6338        parent_session_id: Option<acp::SessionId>,
6339        session_id: &str,
6340        connection: Rc<dyn AgentConnection>,
6341        project: Entity<Project>,
6342        cx: &mut App,
6343    ) -> Entity<AcpThread> {
6344        let action_log = cx.new(|_| ActionLog::new(project.clone()));
6345        cx.new(|cx| {
6346            AcpThread::new(
6347                parent_session_id,
6348                None,
6349                None,
6350                connection,
6351                project,
6352                action_log,
6353                acp::SessionId::new(session_id),
6354                watch::Receiver::constant(acp::PromptCapabilities::new()),
6355                cx,
6356            )
6357        })
6358    }
6359
6360    fn request_test_tool_authorization(
6361        thread: &Entity<AcpThread>,
6362        tool_call_id: &str,
6363        option_id: &str,
6364        cx: &mut TestAppContext,
6365    ) -> Task<acp_thread::RequestPermissionOutcome> {
6366        let tool_call_id = acp::ToolCallId::new(tool_call_id);
6367        let label = format!("Tool {tool_call_id}");
6368        let option_id = acp::PermissionOptionId::new(option_id);
6369        cx.update(|cx| {
6370            thread.update(cx, |thread, cx| {
6371                thread
6372                    .request_tool_call_authorization(
6373                        acp::ToolCall::new(tool_call_id, label)
6374                            .kind(acp::ToolKind::Edit)
6375                            .into(),
6376                        PermissionOptions::Flat(vec![acp::PermissionOption::new(
6377                            option_id,
6378                            "Allow",
6379                            acp::PermissionOptionKind::AllowOnce,
6380                        )]),
6381                        cx,
6382                    )
6383                    .unwrap()
6384            })
6385        })
6386    }
6387
6388    #[gpui::test]
6389    async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {
6390        init_test(cx);
6391
6392        let fs = FakeFs::new(cx.executor());
6393        let project = Project::test(fs, [], cx).await;
6394        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6395
6396        let (thread, conversation) = cx.update(|cx| {
6397            let thread =
6398                create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
6399            let conversation = cx.new(|cx| {
6400                let mut conversation = Conversation::default();
6401                conversation.register_thread(thread.clone(), cx);
6402                conversation
6403            });
6404            (thread, conversation)
6405        });
6406
6407        let _task1 = request_test_tool_authorization(&thread, "tc-1", "allow-1", cx);
6408        let _task2 = request_test_tool_authorization(&thread, "tc-2", "allow-2", cx);
6409
6410        cx.read(|cx| {
6411            let session_id = acp::SessionId::new("session-1");
6412            let (_, tool_call_id, _) = conversation
6413                .read(cx)
6414                .pending_tool_call(&session_id, cx)
6415                .expect("Expected a pending tool call");
6416            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
6417        });
6418
6419        cx.update(|cx| {
6420            conversation.update(cx, |conversation, cx| {
6421                conversation.authorize_tool_call(
6422                    acp::SessionId::new("session-1"),
6423                    acp::ToolCallId::new("tc-1"),
6424                    SelectedPermissionOutcome::new(
6425                        acp::PermissionOptionId::new("allow-1"),
6426                        acp::PermissionOptionKind::AllowOnce,
6427                    ),
6428                    cx,
6429                );
6430            });
6431        });
6432
6433        cx.run_until_parked();
6434
6435        cx.read(|cx| {
6436            let session_id = acp::SessionId::new("session-1");
6437            let (_, tool_call_id, _) = conversation
6438                .read(cx)
6439                .pending_tool_call(&session_id, cx)
6440                .expect("Expected tc-2 to be pending after tc-1 was authorized");
6441            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
6442        });
6443
6444        cx.update(|cx| {
6445            conversation.update(cx, |conversation, cx| {
6446                conversation.authorize_tool_call(
6447                    acp::SessionId::new("session-1"),
6448                    acp::ToolCallId::new("tc-2"),
6449                    SelectedPermissionOutcome::new(
6450                        acp::PermissionOptionId::new("allow-2"),
6451                        acp::PermissionOptionKind::AllowOnce,
6452                    ),
6453                    cx,
6454                );
6455            });
6456        });
6457
6458        cx.run_until_parked();
6459
6460        cx.read(|cx| {
6461            let session_id = acp::SessionId::new("session-1");
6462            assert!(
6463                conversation
6464                    .read(cx)
6465                    .pending_tool_call(&session_id, cx)
6466                    .is_none(),
6467                "Expected no pending tool calls after both were authorized"
6468            );
6469        });
6470    }
6471
6472    #[gpui::test]
6473    async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {
6474        init_test(cx);
6475
6476        let fs = FakeFs::new(cx.executor());
6477        let project = Project::test(fs, [], cx).await;
6478        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6479
6480        let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
6481            let parent_thread =
6482                create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
6483            let subagent_thread = create_test_acp_thread(
6484                Some(acp::SessionId::new("parent")),
6485                "subagent",
6486                connection.clone(),
6487                project.clone(),
6488                cx,
6489            );
6490            let conversation = cx.new(|cx| {
6491                let mut conversation = Conversation::default();
6492                conversation.register_thread(parent_thread.clone(), cx);
6493                conversation.register_thread(subagent_thread.clone(), cx);
6494                conversation
6495            });
6496            (parent_thread, subagent_thread, conversation)
6497        });
6498
6499        let _parent_task =
6500            request_test_tool_authorization(&parent_thread, "parent-tc", "allow-parent", cx);
6501        let _subagent_task =
6502            request_test_tool_authorization(&subagent_thread, "subagent-tc", "allow-subagent", cx);
6503
6504        // Querying with the subagent's session ID returns only the
6505        // subagent's own tool call (subagent path is scoped to its session)
6506        cx.read(|cx| {
6507            let subagent_id = acp::SessionId::new("subagent");
6508            let (session_id, tool_call_id, _) = conversation
6509                .read(cx)
6510                .pending_tool_call(&subagent_id, cx)
6511                .expect("Expected subagent's pending tool call");
6512            assert_eq!(session_id, acp::SessionId::new("subagent"));
6513            assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
6514        });
6515
6516        // Querying with the parent's session ID returns the first pending
6517        // request in FIFO order across all sessions
6518        cx.read(|cx| {
6519            let parent_id = acp::SessionId::new("parent");
6520            let (session_id, tool_call_id, _) = conversation
6521                .read(cx)
6522                .pending_tool_call(&parent_id, cx)
6523                .expect("Expected a pending tool call from parent query");
6524            assert_eq!(session_id, acp::SessionId::new("parent"));
6525            assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
6526        });
6527    }
6528
6529    #[gpui::test]
6530    async fn test_conversation_parent_pending_tool_call_returns_first_across_threads(
6531        cx: &mut TestAppContext,
6532    ) {
6533        init_test(cx);
6534
6535        let fs = FakeFs::new(cx.executor());
6536        let project = Project::test(fs, [], cx).await;
6537        let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6538
6539        let (thread_a, thread_b, conversation) = cx.update(|cx| {
6540            let thread_a =
6541                create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
6542            let thread_b =
6543                create_test_acp_thread(None, "thread-b", connection.clone(), project.clone(), cx);
6544            let conversation = cx.new(|cx| {
6545                let mut conversation = Conversation::default();
6546                conversation.register_thread(thread_a.clone(), cx);
6547                conversation.register_thread(thread_b.clone(), cx);
6548                conversation
6549            });
6550            (thread_a, thread_b, conversation)
6551        });
6552
6553        let _task_a = request_test_tool_authorization(&thread_a, "tc-a", "allow-a", cx);
6554        let _task_b = request_test_tool_authorization(&thread_b, "tc-b", "allow-b", cx);
6555
6556        // Both threads are non-subagent, so pending_tool_call always returns
6557        // the first entry from permission_requests (FIFO across all sessions)
6558        cx.read(|cx| {
6559            let session_a = acp::SessionId::new("thread-a");
6560            let (session_id, tool_call_id, _) = conversation
6561                .read(cx)
6562                .pending_tool_call(&session_a, cx)
6563                .expect("Expected a pending tool call");
6564            assert_eq!(session_id, acp::SessionId::new("thread-a"));
6565            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6566        });
6567
6568        // Querying with thread-b also returns thread-a's tool call,
6569        // because non-subagent queries always use permission_requests.first()
6570        cx.read(|cx| {
6571            let session_b = acp::SessionId::new("thread-b");
6572            let (session_id, tool_call_id, _) = conversation
6573                .read(cx)
6574                .pending_tool_call(&session_b, cx)
6575                .expect("Expected a pending tool call from thread-b query");
6576            assert_eq!(
6577                session_id,
6578                acp::SessionId::new("thread-a"),
6579                "Non-subagent queries always return the first pending request in FIFO order"
6580            );
6581            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6582        });
6583
6584        // After authorizing thread-a's tool call, thread-b's becomes first
6585        cx.update(|cx| {
6586            conversation.update(cx, |conversation, cx| {
6587                conversation.authorize_tool_call(
6588                    acp::SessionId::new("thread-a"),
6589                    acp::ToolCallId::new("tc-a"),
6590                    SelectedPermissionOutcome::new(
6591                        acp::PermissionOptionId::new("allow-a"),
6592                        acp::PermissionOptionKind::AllowOnce,
6593                    ),
6594                    cx,
6595                );
6596            });
6597        });
6598
6599        cx.run_until_parked();
6600
6601        cx.read(|cx| {
6602            let session_b = acp::SessionId::new("thread-b");
6603            let (session_id, tool_call_id, _) = conversation
6604                .read(cx)
6605                .pending_tool_call(&session_b, cx)
6606                .expect("Expected thread-b's tool call after thread-a's was authorized");
6607            assert_eq!(session_id, acp::SessionId::new("thread-b"));
6608            assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
6609        });
6610    }
6611
6612    #[gpui::test]
6613    async fn test_move_queued_message_to_empty_main_editor(cx: &mut TestAppContext) {
6614        init_test(cx);
6615
6616        let (conversation_view, cx) =
6617            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6618
6619        // Add a plain-text message to the queue directly.
6620        active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6621            thread.add_to_queue(
6622                vec![acp::ContentBlock::Text(acp::TextContent::new(
6623                    "queued message".to_string(),
6624                ))],
6625                vec![],
6626                cx,
6627            );
6628            // Main editor must be empty for this path — it is by default, but
6629            // assert to make the precondition explicit.
6630            assert!(thread.message_editor.read(cx).is_empty(cx));
6631            thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6632        });
6633
6634        cx.run_until_parked();
6635
6636        // Queue should now be empty.
6637        let queue_len = active_thread(&conversation_view, cx)
6638            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6639        assert_eq!(queue_len, 0, "Queue should be empty after move");
6640
6641        // Main editor should contain the queued message text.
6642        let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6643        assert_eq!(
6644            text, "queued message",
6645            "Main editor should contain the moved queued message"
6646        );
6647    }
6648
6649    #[gpui::test]
6650    async fn test_move_queued_message_to_non_empty_main_editor(cx: &mut TestAppContext) {
6651        init_test(cx);
6652
6653        let (conversation_view, cx) =
6654            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6655
6656        // Seed the main editor with existing content.
6657        message_editor(&conversation_view, cx).update_in(cx, |editor, window, cx| {
6658            editor.set_message(
6659                vec![acp::ContentBlock::Text(acp::TextContent::new(
6660                    "existing content".to_string(),
6661                ))],
6662                window,
6663                cx,
6664            );
6665        });
6666
6667        // Add a plain-text message to the queue.
6668        active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6669            thread.add_to_queue(
6670                vec![acp::ContentBlock::Text(acp::TextContent::new(
6671                    "queued message".to_string(),
6672                ))],
6673                vec![],
6674                cx,
6675            );
6676            thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6677        });
6678
6679        cx.run_until_parked();
6680
6681        // Queue should now be empty.
6682        let queue_len = active_thread(&conversation_view, cx)
6683            .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6684        assert_eq!(queue_len, 0, "Queue should be empty after move");
6685
6686        // Main editor should contain existing content + separator + queued content.
6687        let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6688        assert_eq!(
6689            text, "existing content\n\nqueued message",
6690            "Main editor should have existing content and queued message separated by two newlines"
6691        );
6692    }
6693
6694    #[gpui::test]
6695    async fn test_close_all_sessions_skips_when_unsupported(cx: &mut TestAppContext) {
6696        init_test(cx);
6697
6698        let fs = FakeFs::new(cx.executor());
6699        let project = Project::test(fs, [], cx).await;
6700        let (multi_workspace, cx) =
6701            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6702        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
6703
6704        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
6705        let connection_store =
6706            cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
6707
6708        // StubAgentConnection defaults to supports_close_session() -> false
6709        let conversation_view = cx.update(|window, cx| {
6710            cx.new(|cx| {
6711                ConversationView::new(
6712                    Rc::new(StubAgentServer::default_response()),
6713                    connection_store,
6714                    Agent::Custom { id: "Test".into() },
6715                    None,
6716                    None,
6717                    None,
6718                    None,
6719                    workspace.downgrade(),
6720                    project,
6721                    Some(thread_store),
6722                    None,
6723                    window,
6724                    cx,
6725                )
6726            })
6727        });
6728
6729        cx.run_until_parked();
6730
6731        conversation_view.read_with(cx, |view, _cx| {
6732            let connected = view.as_connected().expect("Should be connected");
6733            assert!(
6734                !connected.threads.is_empty(),
6735                "There should be at least one thread"
6736            );
6737            assert!(
6738                !connected.connection.supports_close_session(),
6739                "StubAgentConnection should not support close"
6740            );
6741        });
6742
6743        conversation_view
6744            .update(cx, |view, cx| {
6745                view.as_connected()
6746                    .expect("Should be connected")
6747                    .close_all_sessions(cx)
6748            })
6749            .await;
6750    }
6751
6752    #[gpui::test]
6753    async fn test_close_all_sessions_calls_close_when_supported(cx: &mut TestAppContext) {
6754        init_test(cx);
6755
6756        let (conversation_view, cx) =
6757            setup_conversation_view(StubAgentServer::new(CloseCapableConnection::new()), cx).await;
6758
6759        cx.run_until_parked();
6760
6761        let close_capable = conversation_view.read_with(cx, |view, _cx| {
6762            let connected = view.as_connected().expect("Should be connected");
6763            assert!(
6764                !connected.threads.is_empty(),
6765                "There should be at least one thread"
6766            );
6767            assert!(
6768                connected.connection.supports_close_session(),
6769                "CloseCapableConnection should support close"
6770            );
6771            connected
6772                .connection
6773                .clone()
6774                .into_any()
6775                .downcast::<CloseCapableConnection>()
6776                .expect("Should be CloseCapableConnection")
6777        });
6778
6779        conversation_view
6780            .update(cx, |view, cx| {
6781                view.as_connected()
6782                    .expect("Should be connected")
6783                    .close_all_sessions(cx)
6784            })
6785            .await;
6786
6787        let closed_count = close_capable.closed_sessions.lock().len();
6788        assert!(
6789            closed_count > 0,
6790            "close_session should have been called for each thread"
6791        );
6792    }
6793
6794    #[gpui::test]
6795    async fn test_close_session_returns_error_when_unsupported(cx: &mut TestAppContext) {
6796        init_test(cx);
6797
6798        let (conversation_view, cx) =
6799            setup_conversation_view(StubAgentServer::default_response(), cx).await;
6800
6801        cx.run_until_parked();
6802
6803        let result = conversation_view
6804            .update(cx, |view, cx| {
6805                let connected = view.as_connected().expect("Should be connected");
6806                assert!(
6807                    !connected.connection.supports_close_session(),
6808                    "StubAgentConnection should not support close"
6809                );
6810                let session_id = connected
6811                    .threads
6812                    .keys()
6813                    .next()
6814                    .expect("Should have at least one thread")
6815                    .clone();
6816                connected.connection.clone().close_session(&session_id, cx)
6817            })
6818            .await;
6819
6820        assert!(
6821            result.is_err(),
6822            "close_session should return an error when close is not supported"
6823        );
6824        assert!(
6825            result.unwrap_err().to_string().contains("not supported"),
6826            "Error message should indicate that closing is not supported"
6827        );
6828    }
6829
6830    #[derive(Clone)]
6831    struct CloseCapableConnection {
6832        closed_sessions: Arc<Mutex<Vec<acp::SessionId>>>,
6833    }
6834
6835    impl CloseCapableConnection {
6836        fn new() -> Self {
6837            Self {
6838                closed_sessions: Arc::new(Mutex::new(Vec::new())),
6839            }
6840        }
6841    }
6842
6843    impl AgentConnection for CloseCapableConnection {
6844        fn agent_id(&self) -> AgentId {
6845            AgentId::new("close-capable")
6846        }
6847
6848        fn telemetry_id(&self) -> SharedString {
6849            "close-capable".into()
6850        }
6851
6852        fn new_session(
6853            self: Rc<Self>,
6854            project: Entity<Project>,
6855            work_dirs: PathList,
6856            cx: &mut gpui::App,
6857        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6858            let action_log = cx.new(|_| ActionLog::new(project.clone()));
6859            let thread = cx.new(|cx| {
6860                AcpThread::new(
6861                    None,
6862                    Some("CloseCapableConnection".into()),
6863                    Some(work_dirs),
6864                    self,
6865                    project,
6866                    action_log,
6867                    SessionId::new("close-capable-session"),
6868                    watch::Receiver::constant(
6869                        acp::PromptCapabilities::new()
6870                            .image(true)
6871                            .audio(true)
6872                            .embedded_context(true),
6873                    ),
6874                    cx,
6875                )
6876            });
6877            Task::ready(Ok(thread))
6878        }
6879
6880        fn supports_close_session(&self) -> bool {
6881            true
6882        }
6883
6884        fn close_session(
6885            self: Rc<Self>,
6886            session_id: &acp::SessionId,
6887            _cx: &mut App,
6888        ) -> Task<Result<()>> {
6889            self.closed_sessions.lock().push(session_id.clone());
6890            Task::ready(Ok(()))
6891        }
6892
6893        fn auth_methods(&self) -> &[acp::AuthMethod] {
6894            &[]
6895        }
6896
6897        fn authenticate(
6898            &self,
6899            _method_id: acp::AuthMethodId,
6900            _cx: &mut App,
6901        ) -> Task<gpui::Result<()>> {
6902            Task::ready(Ok(()))
6903        }
6904
6905        fn prompt(
6906            &self,
6907            _id: Option<acp_thread::UserMessageId>,
6908            _params: acp::PromptRequest,
6909            _cx: &mut App,
6910        ) -> Task<gpui::Result<acp::PromptResponse>> {
6911            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
6912        }
6913
6914        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
6915
6916        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6917            self
6918        }
6919    }
6920}