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