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