conversation_view.rs

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