conversation_view.rs

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