connection_view.rs

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