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