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};
  19use editor::scroll::Autoscroll;
  20use editor::{
  21    Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
  22};
  23use feature_flags::{
  24    AgentSharingFeatureFlag, AgentV2FeatureFlag, CloudThinkingToggleFeatureFlag,
  25    FeatureFlagAppExt as _,
  26};
  27use file_icons::FileIcons;
  28use fs::Fs;
  29use futures::FutureExt as _;
  30use gpui::{
  31    Action, Animation, AnimationExt, AnyView, App, ClickEvent, ClipboardItem, CursorStyle,
  32    ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, ListOffset, ListState, ObjectFit,
  33    PlatformDisplay, ScrollHandle, SharedString, Subscription, Task, TextStyle, WeakEntity, Window,
  34    WindowHandle, div, ease_in_out, img, linear_color_stop, linear_gradient, list, point,
  35    pulsating_between,
  36};
  37use language::Buffer;
  38use language_model::LanguageModelRegistry;
  39use markdown::{Markdown, MarkdownElement, MarkdownFont, MarkdownStyle};
  40use project::{AgentServerStore, ExternalAgentServerName, Project, ProjectEntryId};
  41use prompt_store::{PromptId, PromptStore};
  42use rope::Point;
  43use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
  44use std::cell::RefCell;
  45use std::path::Path;
  46use std::sync::Arc;
  47use std::time::Instant;
  48use std::{collections::BTreeMap, rc::Rc, time::Duration};
  49use terminal_view::terminal_panel::TerminalPanel;
  50use text::{Anchor, ToPoint as _};
  51use theme::AgentFontSize;
  52use ui::{
  53    Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, CopyButton, DecoratedIcon,
  54    DiffStat, Disclosure, Divider, DividerColor, IconButtonShape, IconDecoration,
  55    IconDecorationKind, KeyBinding, PopoverMenu, PopoverMenuHandle, SpinnerLabel, TintColor,
  56    Tooltip, WithScrollbar, prelude::*, right_click_menu,
  57};
  58use util::defer;
  59use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  60use workspace::{CollaboratorId, NewTerminal, Toast, Workspace, notifications::NotificationId};
  61use zed_actions::agent::{Chat, ToggleModelSelector};
  62use zed_actions::assistant::OpenRulesLibrary;
  63
  64use super::config_options::ConfigOptionsView;
  65use super::entry_view_state::EntryViewState;
  66use super::thread_history::AcpThreadHistory;
  67use crate::acp::AcpModelSelectorPopover;
  68use crate::acp::ModeSelector;
  69use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
  70use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  71use crate::agent_diff::AgentDiff;
  72use crate::profile_selector::{ProfileProvider, ProfileSelector};
  73use crate::ui::{AgentNotification, AgentNotificationEvent};
  74use crate::{
  75    AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, AuthorizeToolCall, ClearMessageQueue,
  76    CycleFavoriteModels, CycleModeSelector, EditFirstQueuedMessage, ExpandMessageEditor,
  77    ExternalAgentInitialContent, Follow, KeepAll, NewThread, OpenAddContextMenu, OpenAgentDiff,
  78    OpenHistory, RejectAll, RejectOnce, RemoveFirstQueuedMessage, SelectPermissionGranularity,
  79    SendImmediately, SendNextQueuedMessage, ToggleProfileSelector, ToggleThinkingMode,
  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
 162pub struct AcpServerView {
 163    agent: Rc<dyn AgentServer>,
 164    agent_server_store: Entity<AgentServerStore>,
 165    workspace: WeakEntity<Workspace>,
 166    project: Entity<Project>,
 167    thread_store: Option<Entity<ThreadStore>>,
 168    prompt_store: Option<Entity<PromptStore>>,
 169    server_state: ServerState,
 170    login: Option<task::SpawnInTerminal>, // is some <=> Active | Unauthenticated
 171    history: Entity<AcpThreadHistory>,
 172    focus_handle: FocusHandle,
 173    notifications: Vec<WindowHandle<AgentNotification>>,
 174    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 175    auth_task: Option<Task<()>>,
 176    _subscriptions: Vec<Subscription>,
 177}
 178
 179impl AcpServerView {
 180    pub fn as_active_thread(&self) -> Option<Entity<AcpThreadView>> {
 181        match &self.server_state {
 182            ServerState::Connected(connected) => Some(connected.current.clone()),
 183            _ => None,
 184        }
 185    }
 186
 187    pub fn as_connected(&self) -> Option<&ConnectedServerState> {
 188        match &self.server_state {
 189            ServerState::Connected(connected) => Some(connected),
 190            _ => None,
 191        }
 192    }
 193
 194    pub fn as_connected_mut(&mut self) -> Option<&mut ConnectedServerState> {
 195        match &mut self.server_state {
 196            ServerState::Connected(connected) => Some(connected),
 197            _ => None,
 198        }
 199    }
 200}
 201
 202enum ServerState {
 203    Loading(Entity<LoadingView>),
 204    LoadError(LoadError),
 205    Connected(ConnectedServerState),
 206}
 207
 208// current -> Entity
 209// hashmap of threads, current becomes session_id
 210pub struct ConnectedServerState {
 211    auth_state: AuthState,
 212    current: Entity<AcpThreadView>,
 213    connection: Rc<dyn AgentConnection>,
 214}
 215
 216enum AuthState {
 217    Ok,
 218    Unauthenticated {
 219        description: Option<Entity<Markdown>>,
 220        configuration_view: Option<AnyView>,
 221        pending_auth_method: Option<acp::AuthMethodId>,
 222        _subscription: Option<Subscription>,
 223    },
 224}
 225
 226impl AuthState {
 227    pub fn is_ok(&self) -> bool {
 228        matches!(self, Self::Ok)
 229    }
 230}
 231
 232struct LoadingView {
 233    title: SharedString,
 234    _load_task: Task<()>,
 235    _update_title_task: Task<anyhow::Result<()>>,
 236}
 237
 238impl ConnectedServerState {
 239    pub fn has_thread_error(&self, cx: &App) -> bool {
 240        self.current.read(cx).thread_error.is_some()
 241    }
 242}
 243
 244impl AcpServerView {
 245    pub fn new(
 246        agent: Rc<dyn AgentServer>,
 247        resume_thread: Option<AgentSessionInfo>,
 248        initial_content: Option<ExternalAgentInitialContent>,
 249        workspace: WeakEntity<Workspace>,
 250        project: Entity<Project>,
 251        thread_store: Option<Entity<ThreadStore>>,
 252        prompt_store: Option<Entity<PromptStore>>,
 253        history: Entity<AcpThreadHistory>,
 254        window: &mut Window,
 255        cx: &mut Context<Self>,
 256    ) -> Self {
 257        let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
 258        let available_commands = Rc::new(RefCell::new(vec![]));
 259
 260        let agent_server_store = project.read(cx).agent_server_store().clone();
 261        let subscriptions = vec![
 262            cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
 263            cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
 264            cx.subscribe_in(
 265                &agent_server_store,
 266                window,
 267                Self::handle_agent_servers_updated,
 268            ),
 269        ];
 270
 271        cx.on_release(|this, cx| {
 272            for window in this.notifications.drain(..) {
 273                window
 274                    .update(cx, |_, window, _| {
 275                        window.remove_window();
 276                    })
 277                    .ok();
 278            }
 279        })
 280        .detach();
 281
 282        let workspace_for_state = workspace.clone();
 283        let project_for_state = project.clone();
 284
 285        Self {
 286            agent: agent.clone(),
 287            agent_server_store,
 288            workspace,
 289            project,
 290            thread_store,
 291            prompt_store,
 292            server_state: Self::initial_state(
 293                agent.clone(),
 294                resume_thread,
 295                workspace_for_state,
 296                project_for_state,
 297                prompt_capabilities,
 298                available_commands,
 299                initial_content,
 300                window,
 301                cx,
 302            ),
 303            login: None,
 304            notifications: Vec::new(),
 305            notification_subscriptions: HashMap::default(),
 306            auth_task: None,
 307            history,
 308            _subscriptions: subscriptions,
 309            focus_handle: cx.focus_handle(),
 310        }
 311    }
 312
 313    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 314        let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
 315        let available_commands = Rc::new(RefCell::new(vec![]));
 316
 317        let resume_thread_metadata = self
 318            .as_active_thread()
 319            .and_then(|thread| thread.read(cx).resume_thread_metadata.clone());
 320
 321        self.server_state = Self::initial_state(
 322            self.agent.clone(),
 323            resume_thread_metadata,
 324            self.workspace.clone(),
 325            self.project.clone(),
 326            prompt_capabilities.clone(),
 327            available_commands.clone(),
 328            None,
 329            window,
 330            cx,
 331        );
 332
 333        if let Some(connected) = self.as_connected() {
 334            connected.current.update(cx, |this, cx| {
 335                this.message_editor.update(cx, |editor, cx| {
 336                    editor.set_command_state(prompt_capabilities, available_commands, cx);
 337                });
 338            });
 339        }
 340        cx.notify();
 341    }
 342
 343    fn initial_state(
 344        agent: Rc<dyn AgentServer>,
 345        resume_thread: Option<AgentSessionInfo>,
 346        workspace: WeakEntity<Workspace>,
 347        project: Entity<Project>,
 348        prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
 349        available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
 350        initial_content: Option<ExternalAgentInitialContent>,
 351        window: &mut Window,
 352        cx: &mut Context<Self>,
 353    ) -> ServerState {
 354        if project.read(cx).is_via_collab()
 355            && agent.clone().downcast::<NativeAgentServer>().is_none()
 356        {
 357            return ServerState::LoadError(LoadError::Other(
 358                "External agents are not yet supported in shared projects.".into(),
 359            ));
 360        }
 361        let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 362        // Pick the first non-single-file worktree for the root directory if there are any,
 363        // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
 364        worktrees.sort_by(|l, r| {
 365            l.read(cx)
 366                .is_single_file()
 367                .cmp(&r.read(cx).is_single_file())
 368        });
 369        let root_dir = worktrees
 370            .into_iter()
 371            .filter_map(|worktree| {
 372                if worktree.read(cx).is_single_file() {
 373                    Some(worktree.read(cx).abs_path().parent()?.into())
 374                } else {
 375                    Some(worktree.read(cx).abs_path())
 376                }
 377            })
 378            .next();
 379        let fallback_cwd = root_dir
 380            .clone()
 381            .unwrap_or_else(|| paths::home_dir().as_path().into());
 382        let (status_tx, mut status_rx) = watch::channel("Loading…".into());
 383        let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
 384        let delegate = AgentServerDelegate::new(
 385            project.read(cx).agent_server_store().clone(),
 386            project.clone(),
 387            Some(status_tx),
 388            Some(new_version_available_tx),
 389        );
 390
 391        let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
 392        let load_task = cx.spawn_in(window, async move |this, cx| {
 393            let connection = match connect_task.await {
 394                Ok((connection, login)) => {
 395                    this.update(cx, |this, _| this.login = login).ok();
 396                    connection
 397                }
 398                Err(err) => {
 399                    this.update_in(cx, |this, window, cx| {
 400                        if err.downcast_ref::<LoadError>().is_some() {
 401                            this.handle_load_error(err, window, cx);
 402                        } else if let Some(active) = this.as_active_thread() {
 403                            active.update(cx, |active, cx| active.handle_any_thread_error(err, cx));
 404                        }
 405                        cx.notify();
 406                    })
 407                    .log_err();
 408                    return;
 409                }
 410            };
 411
 412            telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
 413
 414            let mut resumed_without_history = false;
 415            let result = if let Some(resume) = resume_thread.clone() {
 416                cx.update(|_, cx| {
 417                    let session_cwd = resume
 418                        .cwd
 419                        .clone()
 420                        .unwrap_or_else(|| fallback_cwd.as_ref().to_path_buf());
 421                    if connection.supports_load_session(cx) {
 422                        connection.clone().load_session(
 423                            resume,
 424                            project.clone(),
 425                            session_cwd.as_path(),
 426                            cx,
 427                        )
 428                    } else if connection.supports_resume_session(cx) {
 429                        resumed_without_history = true;
 430                        connection.clone().resume_session(
 431                            resume,
 432                            project.clone(),
 433                            session_cwd.as_path(),
 434                            cx,
 435                        )
 436                    } else {
 437                        Task::ready(Err(anyhow!(LoadError::Other(
 438                            "Loading or resuming sessions is not supported by this agent.".into()
 439                        ))))
 440                    }
 441                })
 442                .log_err()
 443            } else {
 444                cx.update(|_, cx| {
 445                    connection
 446                        .clone()
 447                        .new_thread(project.clone(), fallback_cwd.as_ref(), cx)
 448                })
 449                .log_err()
 450            };
 451
 452            let Some(result) = result else {
 453                return;
 454            };
 455
 456            let result = match result.await {
 457                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 458                    Ok(err) => {
 459                        cx.update(|window, cx| {
 460                            Self::handle_auth_required(this, err, agent.name(), window, cx)
 461                        })
 462                        .log_err();
 463                        return;
 464                    }
 465                    Err(err) => Err(err),
 466                },
 467                Ok(thread) => Ok(thread),
 468            };
 469
 470            this.update_in(cx, |this, window, cx| {
 471                match result {
 472                    Ok(thread) => {
 473                        let action_log = thread.read(cx).action_log().clone();
 474
 475                        prompt_capabilities.replace(thread.read(cx).prompt_capabilities());
 476
 477                        let entry_view_state = cx.new(|_| {
 478                            EntryViewState::new(
 479                                this.workspace.clone(),
 480                                this.project.downgrade(),
 481                                this.thread_store.clone(),
 482                                this.history.downgrade(),
 483                                this.prompt_store.clone(),
 484                                prompt_capabilities.clone(),
 485                                available_commands.clone(),
 486                                this.agent.name(),
 487                            )
 488                        });
 489
 490                        let count = thread.read(cx).entries().len();
 491                        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 492                        entry_view_state.update(cx, |view_state, cx| {
 493                            for ix in 0..count {
 494                                view_state.sync_entry(ix, &thread, window, cx);
 495                            }
 496                            list_state.splice_focusable(
 497                                0..0,
 498                                (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
 499                            );
 500                        });
 501
 502                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 503
 504                        let connection = thread.read(cx).connection().clone();
 505                        let session_id = thread.read(cx).session_id().clone();
 506                        let session_list = if connection.supports_session_history(cx) {
 507                            connection.session_list(cx)
 508                        } else {
 509                            None
 510                        };
 511                        this.history.update(cx, |history, cx| {
 512                            history.set_session_list(session_list, cx);
 513                        });
 514
 515                        // Check for config options first
 516                        // Config options take precedence over legacy mode/model selectors
 517                        // (feature flag gating happens at the data layer)
 518                        let config_options_provider =
 519                            connection.session_config_options(&session_id, cx);
 520
 521                        let config_options_view;
 522                        let mode_selector;
 523                        let model_selector;
 524                        if let Some(config_options) = config_options_provider {
 525                            // Use config options - don't create mode_selector or model_selector
 526                            let agent_server = this.agent.clone();
 527                            let fs = this.project.read(cx).fs().clone();
 528                            config_options_view = Some(cx.new(|cx| {
 529                                ConfigOptionsView::new(config_options, agent_server, fs, window, cx)
 530                            }));
 531                            model_selector = None;
 532                            mode_selector = None;
 533                        } else {
 534                            // Fall back to legacy mode/model selectors
 535                            config_options_view = None;
 536                            model_selector =
 537                                connection.model_selector(&session_id).map(|selector| {
 538                                    let agent_server = this.agent.clone();
 539                                    let fs = this.project.read(cx).fs().clone();
 540                                    cx.new(|cx| {
 541                                        AcpModelSelectorPopover::new(
 542                                            selector,
 543                                            agent_server,
 544                                            fs,
 545                                            PopoverMenuHandle::default(),
 546                                            this.focus_handle(cx),
 547                                            window,
 548                                            cx,
 549                                        )
 550                                    })
 551                                });
 552
 553                            mode_selector =
 554                                connection
 555                                    .session_modes(&session_id, cx)
 556                                    .map(|session_modes| {
 557                                        let fs = this.project.read(cx).fs().clone();
 558                                        let focus_handle = this.focus_handle(cx);
 559                                        cx.new(|_cx| {
 560                                            ModeSelector::new(
 561                                                session_modes,
 562                                                this.agent.clone(),
 563                                                fs,
 564                                                focus_handle,
 565                                            )
 566                                        })
 567                                    });
 568                        }
 569
 570                        let mut subscriptions = vec![
 571                            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 572                            cx.observe(&action_log, |_, _, cx| cx.notify()),
 573                            // cx.subscribe_in(
 574                            //     &entry_view_state,
 575                            //     window,
 576                            //     Self::handle_entry_view_event,
 577                            // ),
 578                        ];
 579
 580                        let title_editor =
 581                            if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
 582                                let editor = cx.new(|cx| {
 583                                    let mut editor = Editor::single_line(window, cx);
 584                                    editor.set_text(thread.read(cx).title(), window, cx);
 585                                    editor
 586                                });
 587                                subscriptions.push(cx.subscribe_in(
 588                                    &editor,
 589                                    window,
 590                                    Self::handle_title_editor_event,
 591                                ));
 592                                Some(editor)
 593                            } else {
 594                                None
 595                            };
 596
 597                        let profile_selector: Option<Rc<agent::NativeAgentConnection>> =
 598                            connection.clone().downcast();
 599                        let profile_selector = profile_selector
 600                            .and_then(|native_connection| native_connection.thread(&session_id, cx))
 601                            .map(|native_thread| {
 602                                cx.new(|cx| {
 603                                    ProfileSelector::new(
 604                                        <dyn Fs>::global(cx),
 605                                        Arc::new(native_thread),
 606                                        this.focus_handle(cx),
 607                                        cx,
 608                                    )
 609                                })
 610                            });
 611
 612                        let agent_display_name = this
 613                            .agent_server_store
 614                            .read(cx)
 615                            .agent_display_name(&ExternalAgentServerName(agent.name()))
 616                            .unwrap_or_else(|| agent.name());
 617
 618                        let weak = cx.weak_entity();
 619                        let current = cx.new(|cx| {
 620                            AcpThreadView::new(
 621                                thread,
 622                                this.login.clone(),
 623                                weak,
 624                                agent.name(),
 625                                agent_display_name,
 626                                workspace.clone(),
 627                                entry_view_state,
 628                                title_editor,
 629                                config_options_view,
 630                                mode_selector,
 631                                model_selector,
 632                                profile_selector,
 633                                list_state,
 634                                prompt_capabilities,
 635                                available_commands,
 636                                resumed_without_history,
 637                                resume_thread.clone(),
 638                                project.downgrade(),
 639                                this.thread_store.clone(),
 640                                this.history.clone(),
 641                                this.prompt_store.clone(),
 642                                initial_content,
 643                                subscriptions,
 644                                window,
 645                                cx,
 646                            )
 647                        });
 648
 649                        if this.focus_handle.contains_focused(window, cx) {
 650                            current
 651                                .read(cx)
 652                                .message_editor
 653                                .focus_handle(cx)
 654                                .focus(window, cx);
 655                        }
 656
 657                        this.server_state = ServerState::Connected(ConnectedServerState {
 658                            connection,
 659                            auth_state: AuthState::Ok,
 660                            current,
 661                        });
 662
 663                        cx.notify();
 664                    }
 665                    Err(err) => {
 666                        this.handle_load_error(err, window, cx);
 667                    }
 668                };
 669            })
 670            .log_err();
 671        });
 672
 673        cx.spawn(async move |this, cx| {
 674            while let Ok(new_version) = new_version_available_rx.recv().await {
 675                if let Some(new_version) = new_version {
 676                    this.update(cx, |this, cx| {
 677                        if let Some(thread) = this.as_active_thread() {
 678                            thread.update(cx, |thread, _cx| {
 679                                thread.new_server_version_available = Some(new_version.into());
 680                            });
 681                        }
 682                        cx.notify();
 683                    })
 684                    .ok();
 685                }
 686            }
 687        })
 688        .detach();
 689
 690        let loading_view = cx.new(|cx| {
 691            let update_title_task = cx.spawn(async move |this, cx| {
 692                loop {
 693                    let status = status_rx.recv().await?;
 694                    this.update(cx, |this: &mut LoadingView, cx| {
 695                        this.title = status;
 696                        cx.notify();
 697                    })?;
 698                }
 699            });
 700
 701            LoadingView {
 702                title: "Loading…".into(),
 703                _load_task: load_task,
 704                _update_title_task: update_title_task,
 705            }
 706        });
 707
 708        ServerState::Loading(loading_view)
 709    }
 710
 711    fn handle_auth_required(
 712        this: WeakEntity<Self>,
 713        err: AuthRequired,
 714        agent_name: SharedString,
 715        window: &mut Window,
 716        cx: &mut App,
 717    ) {
 718        let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
 719            let registry = LanguageModelRegistry::global(cx);
 720
 721            let sub = window.subscribe(&registry, cx, {
 722                let provider_id = provider_id.clone();
 723                let this = this.clone();
 724                move |_, ev, window, cx| {
 725                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
 726                        && &provider_id == updated_provider_id
 727                        && LanguageModelRegistry::global(cx)
 728                            .read(cx)
 729                            .provider(&provider_id)
 730                            .map_or(false, |provider| provider.is_authenticated(cx))
 731                    {
 732                        this.update(cx, |this, cx| {
 733                            this.reset(window, cx);
 734                        })
 735                        .ok();
 736                    }
 737                }
 738            });
 739
 740            let view = registry.read(cx).provider(&provider_id).map(|provider| {
 741                provider.configuration_view(
 742                    language_model::ConfigurationViewTargetAgent::Other(agent_name),
 743                    window,
 744                    cx,
 745                )
 746            });
 747
 748            (view, Some(sub))
 749        } else {
 750            (None, None)
 751        };
 752
 753        this.update(cx, |this, cx| {
 754            if let Some(connected) = this.as_connected_mut() {
 755                let description = err
 756                    .description
 757                    .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx)));
 758
 759                connected.auth_state = AuthState::Unauthenticated {
 760                    pending_auth_method: None,
 761                    configuration_view,
 762                    description,
 763                    _subscription: subscription,
 764                };
 765                if connected
 766                    .current
 767                    .read(cx)
 768                    .message_editor
 769                    .focus_handle(cx)
 770                    .is_focused(window)
 771                {
 772                    this.focus_handle.focus(window, cx)
 773                }
 774            }
 775            cx.notify();
 776        })
 777        .ok();
 778    }
 779
 780    fn handle_load_error(
 781        &mut self,
 782        err: anyhow::Error,
 783        window: &mut Window,
 784        cx: &mut Context<Self>,
 785    ) {
 786        match &self.server_state {
 787            ServerState::Connected(connected) => {
 788                if connected
 789                    .current
 790                    .read(cx)
 791                    .message_editor
 792                    .focus_handle(cx)
 793                    .is_focused(window)
 794                {
 795                    self.focus_handle.focus(window, cx)
 796                }
 797            }
 798            _ => {}
 799        }
 800        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 801            self.server_state = ServerState::LoadError(load_err.clone());
 802        } else {
 803            self.server_state =
 804                ServerState::LoadError(LoadError::Other(format!("{:#}", err).into()))
 805        }
 806        cx.notify();
 807    }
 808
 809    fn handle_agent_servers_updated(
 810        &mut self,
 811        _agent_server_store: &Entity<project::AgentServerStore>,
 812        _event: &project::AgentServersUpdated,
 813        window: &mut Window,
 814        cx: &mut Context<Self>,
 815    ) {
 816        // If we're in a LoadError state OR have a thread_error set (which can happen
 817        // when agent.connect() fails during loading), retry loading the thread.
 818        // This handles the case where a thread is restored before authentication completes.
 819        let should_retry = match &self.server_state {
 820            ServerState::Loading(_) => false,
 821            ServerState::LoadError(_) => true,
 822            ServerState::Connected(connected) => {
 823                connected.auth_state.is_ok() && connected.has_thread_error(cx)
 824            }
 825        };
 826
 827        if should_retry {
 828            if let Some(active) = self.as_active_thread() {
 829                active.update(cx, |active, cx| {
 830                    active.clear_thread_error(cx);
 831                });
 832            }
 833            self.reset(window, cx);
 834        }
 835    }
 836
 837    pub fn workspace(&self) -> &WeakEntity<Workspace> {
 838        &self.workspace
 839    }
 840
 841    pub fn title(&self, cx: &App) -> SharedString {
 842        match &self.server_state {
 843            ServerState::Connected(_) => "New Thread".into(),
 844            ServerState::Loading(loading_view) => loading_view.read(cx).title.clone(),
 845            ServerState::LoadError(error) => match error {
 846                LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
 847                LoadError::FailedToInstall(_) => {
 848                    format!("Failed to Install {}", self.agent.name()).into()
 849                }
 850                LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
 851                LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
 852            },
 853        }
 854    }
 855
 856    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 857        if let Some(active) = self.as_active_thread() {
 858            active.update(cx, |active, cx| {
 859                active.cancel_generation(cx);
 860            });
 861        }
 862    }
 863
 864    pub fn handle_title_editor_event(
 865        &mut self,
 866        title_editor: &Entity<Editor>,
 867        event: &EditorEvent,
 868        window: &mut Window,
 869        cx: &mut Context<Self>,
 870    ) {
 871        if let Some(active) = self.as_active_thread() {
 872            active.update(cx, |active, cx| {
 873                active.handle_title_editor_event(title_editor, event, window, cx);
 874            });
 875        }
 876    }
 877
 878    pub fn is_loading(&self) -> bool {
 879        matches!(self.server_state, ServerState::Loading { .. })
 880    }
 881
 882    fn update_turn_tokens(&mut self, cx: &mut Context<Self>) {
 883        if let Some(active) = self.as_active_thread() {
 884            active.update(cx, |active, cx| {
 885                active.update_turn_tokens(cx);
 886            });
 887        }
 888    }
 889
 890    fn send_queued_message_at_index(
 891        &mut self,
 892        index: usize,
 893        is_send_now: bool,
 894        window: &mut Window,
 895        cx: &mut Context<Self>,
 896    ) {
 897        if let Some(active) = self.as_active_thread() {
 898            active.update(cx, |active, cx| {
 899                active.send_queued_message_at_index(index, is_send_now, window, cx);
 900            });
 901        }
 902    }
 903
 904    fn handle_thread_event(
 905        &mut self,
 906        thread: &Entity<AcpThread>,
 907        event: &AcpThreadEvent,
 908        window: &mut Window,
 909        cx: &mut Context<Self>,
 910    ) {
 911        match event {
 912            AcpThreadEvent::NewEntry => {
 913                let len = thread.read(cx).entries().len();
 914                let index = len - 1;
 915                if let Some(active) = self.as_active_thread() {
 916                    let entry_view_state = active.read(cx).entry_view_state.clone();
 917                    let list_state = active.read(cx).list_state.clone();
 918                    entry_view_state.update(cx, |view_state, cx| {
 919                        view_state.sync_entry(index, thread, window, cx);
 920                        list_state.splice_focusable(
 921                            index..index,
 922                            [view_state
 923                                .entry(index)
 924                                .and_then(|entry| entry.focus_handle(cx))],
 925                        );
 926                    });
 927                }
 928            }
 929            AcpThreadEvent::EntryUpdated(index) => {
 930                if let Some(entry_view_state) = self
 931                    .as_active_thread()
 932                    .map(|active| active.read(cx).entry_view_state.clone())
 933                {
 934                    entry_view_state.update(cx, |view_state, cx| {
 935                        view_state.sync_entry(*index, thread, window, cx)
 936                    });
 937                }
 938            }
 939            AcpThreadEvent::EntriesRemoved(range) => {
 940                if let Some(active) = self.as_active_thread() {
 941                    let entry_view_state = active.read(cx).entry_view_state.clone();
 942                    let list_state = active.read(cx).list_state.clone();
 943                    entry_view_state.update(cx, |view_state, _cx| view_state.remove(range.clone()));
 944                    list_state.splice(range.clone(), 0);
 945                }
 946            }
 947            AcpThreadEvent::ToolAuthorizationRequired => {
 948                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
 949            }
 950            AcpThreadEvent::Retry(retry) => {
 951                if let Some(active) = self.as_active_thread() {
 952                    active.update(cx, |active, _cx| {
 953                        active.thread_retry_status = Some(retry.clone());
 954                    });
 955                }
 956            }
 957            AcpThreadEvent::Stopped => {
 958                if let Some(active) = self.as_active_thread() {
 959                    active.update(cx, |active, _cx| {
 960                        active.thread_retry_status.take();
 961                    });
 962                }
 963                let used_tools = thread.read(cx).used_tools_since_last_user_message();
 964                self.notify_with_sound(
 965                    if used_tools {
 966                        "Finished running tools"
 967                    } else {
 968                        "New message"
 969                    },
 970                    IconName::ZedAssistant,
 971                    window,
 972                    cx,
 973                );
 974
 975                let should_send_queued = if let Some(active) = self.as_active_thread() {
 976                    active.update(cx, |active, cx| {
 977                        if active.skip_queue_processing_count > 0 {
 978                            active.skip_queue_processing_count -= 1;
 979                            false
 980                        } else if active.user_interrupted_generation {
 981                            // Manual interruption: don't auto-process queue.
 982                            // Reset the flag so future completions can process normally.
 983                            active.user_interrupted_generation = false;
 984                            false
 985                        } else {
 986                            let has_queued = !active.local_queued_messages.is_empty();
 987                            // Don't auto-send if the first message editor is currently focused
 988                            let is_first_editor_focused = active
 989                                .queued_message_editors
 990                                .first()
 991                                .is_some_and(|editor| editor.focus_handle(cx).is_focused(window));
 992                            has_queued && !is_first_editor_focused
 993                        }
 994                    })
 995                } else {
 996                    false
 997                };
 998                if should_send_queued {
 999                    self.send_queued_message_at_index(0, false, window, cx);
1000                }
1001
1002                self.history.update(cx, |history, cx| history.refresh(cx));
1003            }
1004            AcpThreadEvent::Refusal => {
1005                let error = ThreadError::Refusal;
1006                if let Some(active) = self.as_active_thread() {
1007                    active.update(cx, |active, cx| {
1008                        active.handle_thread_error(error, cx);
1009                        active.thread_retry_status.take();
1010                    });
1011                }
1012                let model_or_agent_name = self.current_model_name(cx);
1013                let notification_message =
1014                    format!("{} refused to respond to this request", model_or_agent_name);
1015                self.notify_with_sound(&notification_message, IconName::Warning, window, cx);
1016            }
1017            AcpThreadEvent::Error => {
1018                if let Some(active) = self.as_active_thread() {
1019                    active.update(cx, |active, _cx| {
1020                        active.thread_retry_status.take();
1021                    });
1022                }
1023                self.notify_with_sound(
1024                    "Agent stopped due to an error",
1025                    IconName::Warning,
1026                    window,
1027                    cx,
1028                );
1029            }
1030            AcpThreadEvent::LoadError(error) => {
1031                match &self.server_state {
1032                    ServerState::Connected(connected) => {
1033                        if connected
1034                            .current
1035                            .read(cx)
1036                            .message_editor
1037                            .focus_handle(cx)
1038                            .is_focused(window)
1039                        {
1040                            self.focus_handle.focus(window, cx)
1041                        }
1042                    }
1043                    _ => {}
1044                }
1045                self.server_state = ServerState::LoadError(error.clone());
1046            }
1047            AcpThreadEvent::TitleUpdated => {
1048                let title = thread.read(cx).title();
1049                if let Some(title_editor) = self
1050                    .as_active_thread()
1051                    .and_then(|active| active.read(cx).title_editor.clone())
1052                {
1053                    title_editor.update(cx, |editor, cx| {
1054                        if editor.text(cx) != title {
1055                            editor.set_text(title, window, cx);
1056                        }
1057                    });
1058                }
1059                self.history.update(cx, |history, cx| history.refresh(cx));
1060            }
1061            AcpThreadEvent::PromptCapabilitiesUpdated => {
1062                if let Some(active) = self.as_active_thread() {
1063                    active.update(cx, |active, _cx| {
1064                        active
1065                            .prompt_capabilities
1066                            .replace(thread.read(_cx).prompt_capabilities());
1067                    });
1068                }
1069            }
1070            AcpThreadEvent::TokenUsageUpdated => {
1071                self.update_turn_tokens(cx);
1072            }
1073            AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1074                let mut available_commands = available_commands.clone();
1075
1076                if thread
1077                    .read(cx)
1078                    .connection()
1079                    .auth_methods()
1080                    .iter()
1081                    .any(|method| method.id.0.as_ref() == "claude-login")
1082                {
1083                    available_commands.push(acp::AvailableCommand::new("login", "Authenticate"));
1084                    available_commands.push(acp::AvailableCommand::new("logout", "Authenticate"));
1085                }
1086
1087                let has_commands = !available_commands.is_empty();
1088                if let Some(active) = self.as_active_thread() {
1089                    active.update(cx, |active, _cx| {
1090                        active.available_commands.replace(available_commands);
1091                    });
1092                }
1093
1094                let agent_display_name = self
1095                    .agent_server_store
1096                    .read(cx)
1097                    .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1098                    .unwrap_or_else(|| self.agent.name());
1099
1100                if let Some(active) = self.as_active_thread() {
1101                    let new_placeholder =
1102                        placeholder_text(agent_display_name.as_ref(), has_commands);
1103                    active.update(cx, |active, cx| {
1104                        active.message_editor.update(cx, |editor, cx| {
1105                            editor.set_placeholder_text(&new_placeholder, window, cx);
1106                        });
1107                    });
1108                }
1109            }
1110            AcpThreadEvent::ModeUpdated(_mode) => {
1111                // The connection keeps track of the mode
1112                cx.notify();
1113            }
1114            AcpThreadEvent::ConfigOptionsUpdated(_) => {
1115                // The watch task in ConfigOptionsView handles rebuilding selectors
1116                cx.notify();
1117            }
1118        }
1119        cx.notify();
1120    }
1121
1122    fn authenticate(
1123        &mut self,
1124        method: acp::AuthMethodId,
1125        window: &mut Window,
1126        cx: &mut Context<Self>,
1127    ) {
1128        let Some(connected) = self.as_connected_mut() else {
1129            return;
1130        };
1131        let connection = connected.connection.clone();
1132
1133        let AuthState::Unauthenticated {
1134            configuration_view,
1135            pending_auth_method,
1136            ..
1137        } = &mut connected.auth_state
1138        else {
1139            return;
1140        };
1141
1142        let agent_telemetry_id = connection.telemetry_id();
1143
1144        // Check for the experimental "terminal-auth" _meta field
1145        let auth_method = connection.auth_methods().iter().find(|m| m.id == method);
1146
1147        if let Some(terminal_auth) = auth_method
1148            .and_then(|a| a.meta.as_ref())
1149            .and_then(|m| m.get("terminal-auth"))
1150        {
1151            // Extract terminal auth details from meta
1152            if let (Some(command), Some(label)) = (
1153                terminal_auth.get("command").and_then(|v| v.as_str()),
1154                terminal_auth.get("label").and_then(|v| v.as_str()),
1155            ) {
1156                let args = terminal_auth
1157                    .get("args")
1158                    .and_then(|v| v.as_array())
1159                    .map(|arr| {
1160                        arr.iter()
1161                            .filter_map(|v| v.as_str().map(String::from))
1162                            .collect()
1163                    })
1164                    .unwrap_or_default();
1165
1166                let env = terminal_auth
1167                    .get("env")
1168                    .and_then(|v| v.as_object())
1169                    .map(|obj| {
1170                        obj.iter()
1171                            .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
1172                            .collect::<HashMap<String, String>>()
1173                    })
1174                    .unwrap_or_default();
1175
1176                // Run SpawnInTerminal in the same dir as the ACP server
1177                let cwd = connected
1178                    .connection
1179                    .clone()
1180                    .downcast::<agent_servers::AcpConnection>()
1181                    .map(|acp_conn| acp_conn.root_dir().to_path_buf());
1182
1183                // Build SpawnInTerminal from _meta
1184                let login = task::SpawnInTerminal {
1185                    id: task::TaskId(format!("external-agent-{}-login", label)),
1186                    full_label: label.to_string(),
1187                    label: label.to_string(),
1188                    command: Some(command.to_string()),
1189                    args,
1190                    command_label: label.to_string(),
1191                    cwd,
1192                    env,
1193                    use_new_terminal: true,
1194                    allow_concurrent_runs: true,
1195                    hide: task::HideStrategy::Always,
1196                    ..Default::default()
1197                };
1198
1199                configuration_view.take();
1200                pending_auth_method.replace(method.clone());
1201
1202                if let Some(workspace) = self.workspace.upgrade() {
1203                    let project = self.project.clone();
1204                    let authenticate = Self::spawn_external_agent_login(
1205                        login,
1206                        workspace,
1207                        project,
1208                        method.clone(),
1209                        false,
1210                        window,
1211                        cx,
1212                    );
1213                    cx.notify();
1214                    self.auth_task = Some(cx.spawn_in(window, {
1215                        async move |this, cx| {
1216                            let result = authenticate.await;
1217
1218                            match &result {
1219                                Ok(_) => telemetry::event!(
1220                                    "Authenticate Agent Succeeded",
1221                                    agent = agent_telemetry_id
1222                                ),
1223                                Err(_) => {
1224                                    telemetry::event!(
1225                                        "Authenticate Agent Failed",
1226                                        agent = agent_telemetry_id,
1227                                    )
1228                                }
1229                            }
1230
1231                            this.update_in(cx, |this, window, cx| {
1232                                if let Err(err) = result {
1233                                    if let Some(ConnectedServerState {
1234                                        auth_state:
1235                                            AuthState::Unauthenticated {
1236                                                pending_auth_method,
1237                                                ..
1238                                            },
1239                                        ..
1240                                    }) = this.as_connected_mut()
1241                                    {
1242                                        pending_auth_method.take();
1243                                    }
1244                                    if let Some(active) = this.as_active_thread() {
1245                                        active.update(cx, |active, cx| {
1246                                            active.handle_any_thread_error(err, cx);
1247                                        })
1248                                    }
1249                                } else {
1250                                    this.reset(window, cx);
1251                                }
1252                                this.auth_task.take()
1253                            })
1254                            .ok();
1255                        }
1256                    }));
1257                }
1258                return;
1259            }
1260        }
1261
1262        if method.0.as_ref() == "gemini-api-key" {
1263            let registry = LanguageModelRegistry::global(cx);
1264            let provider = registry
1265                .read(cx)
1266                .provider(&language_model::GOOGLE_PROVIDER_ID)
1267                .unwrap();
1268            if !provider.is_authenticated(cx) {
1269                let this = cx.weak_entity();
1270                let agent_name = self.agent.name();
1271                window.defer(cx, |window, cx| {
1272                    Self::handle_auth_required(
1273                        this,
1274                        AuthRequired {
1275                            description: Some("GEMINI_API_KEY must be set".to_owned()),
1276                            provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1277                        },
1278                        agent_name,
1279                        window,
1280                        cx,
1281                    );
1282                });
1283                return;
1284            }
1285        } else if method.0.as_ref() == "vertex-ai"
1286            && std::env::var("GOOGLE_API_KEY").is_err()
1287            && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1288                || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1289        {
1290            let this = cx.weak_entity();
1291            let agent_name = self.agent.name();
1292
1293            window.defer(cx, |window, cx| {
1294                    Self::handle_auth_required(
1295                        this,
1296                        AuthRequired {
1297                            description: Some(
1298                                "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1299                                    .to_owned(),
1300                            ),
1301                            provider_id: None,
1302                        },
1303                        agent_name,
1304                        window,
1305                        cx,
1306                    )
1307                });
1308            return;
1309        }
1310
1311        configuration_view.take();
1312        pending_auth_method.replace(method.clone());
1313        let authenticate = if let Some(login) = self.login.clone() {
1314            if let Some(workspace) = self.workspace.upgrade() {
1315                let project = self.project.clone();
1316                Self::spawn_external_agent_login(
1317                    login,
1318                    workspace,
1319                    project,
1320                    method.clone(),
1321                    false,
1322                    window,
1323                    cx,
1324                )
1325            } else {
1326                Task::ready(Ok(()))
1327            }
1328        } else {
1329            connection.authenticate(method, cx)
1330        };
1331        cx.notify();
1332        self.auth_task = Some(cx.spawn_in(window, {
1333            async move |this, cx| {
1334                let result = authenticate.await;
1335
1336                match &result {
1337                    Ok(_) => telemetry::event!(
1338                        "Authenticate Agent Succeeded",
1339                        agent = agent_telemetry_id
1340                    ),
1341                    Err(_) => {
1342                        telemetry::event!("Authenticate Agent Failed", agent = agent_telemetry_id,)
1343                    }
1344                }
1345
1346                this.update_in(cx, |this, window, cx| {
1347                    if let Err(err) = result {
1348                        if let Some(ConnectedServerState {
1349                            auth_state:
1350                                AuthState::Unauthenticated {
1351                                    pending_auth_method,
1352                                    ..
1353                                },
1354                            ..
1355                        }) = this.as_connected_mut()
1356                        {
1357                            pending_auth_method.take();
1358                        }
1359                        if let Some(active) = this.as_active_thread() {
1360                            active.update(cx, |active, cx| active.handle_any_thread_error(err, cx));
1361                        }
1362                    } else {
1363                        this.reset(window, cx);
1364                    }
1365                    this.auth_task.take()
1366                })
1367                .ok();
1368            }
1369        }));
1370    }
1371
1372    fn spawn_external_agent_login(
1373        login: task::SpawnInTerminal,
1374        workspace: Entity<Workspace>,
1375        project: Entity<Project>,
1376        method: acp::AuthMethodId,
1377        previous_attempt: bool,
1378        window: &mut Window,
1379        cx: &mut App,
1380    ) -> Task<Result<()>> {
1381        let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1382            return Task::ready(Ok(()));
1383        };
1384
1385        window.spawn(cx, async move |cx| {
1386            let mut task = login.clone();
1387            if let Some(cmd) = &task.command {
1388                // Have "node" command use Zed's managed Node runtime by default
1389                if cmd == "node" {
1390                    let resolved_node_runtime = project
1391                        .update(cx, |project, cx| {
1392                            let agent_server_store = project.agent_server_store().clone();
1393                            agent_server_store.update(cx, |store, cx| {
1394                                store.node_runtime().map(|node_runtime| {
1395                                    cx.background_spawn(async move {
1396                                        node_runtime.binary_path().await
1397                                    })
1398                                })
1399                            })
1400                        });
1401
1402                    if let Some(resolve_task) = resolved_node_runtime {
1403                        if let Ok(node_path) = resolve_task.await {
1404                            task.command = Some(node_path.to_string_lossy().to_string());
1405                        }
1406                    }
1407                }
1408            }
1409            task.shell = task::Shell::WithArguments {
1410                program: task.command.take().expect("login command should be set"),
1411                args: std::mem::take(&mut task.args),
1412                title_override: None
1413            };
1414            task.full_label = task.label.clone();
1415            task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1416            task.command_label = task.label.clone();
1417            task.use_new_terminal = true;
1418            task.allow_concurrent_runs = true;
1419            task.hide = task::HideStrategy::Always;
1420
1421            let terminal = terminal_panel
1422                .update_in(cx, |terminal_panel, window, cx| {
1423                    terminal_panel.spawn_task(&task, window, cx)
1424                })?
1425                .await?;
1426
1427            let success_patterns = match method.0.as_ref() {
1428                "claude-login" | "spawn-gemini-cli" => vec![
1429                    "Login successful".to_string(),
1430                    "Type your message".to_string(),
1431                ],
1432                _ => Vec::new(),
1433            };
1434            if success_patterns.is_empty() {
1435                // No success patterns specified: wait for the process to exit and check exit code
1436                let exit_status = terminal
1437                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1438                    .await;
1439
1440                match exit_status {
1441                    Some(status) if status.success() => Ok(()),
1442                    Some(status) => Err(anyhow!(
1443                        "Login command failed with exit code: {:?}",
1444                        status.code()
1445                    )),
1446                    None => Err(anyhow!("Login command terminated without exit status")),
1447                }
1448            } else {
1449                // Look for specific output patterns to detect successful login
1450                let mut exit_status = terminal
1451                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1452                    .fuse();
1453
1454                let logged_in = cx
1455                    .spawn({
1456                        let terminal = terminal.clone();
1457                        async move |cx| {
1458                            loop {
1459                                cx.background_executor().timer(Duration::from_secs(1)).await;
1460                                let content =
1461                                    terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1462                                if success_patterns.iter().any(|pattern| content.contains(pattern))
1463                                {
1464                                    return anyhow::Ok(());
1465                                }
1466                            }
1467                        }
1468                    })
1469                    .fuse();
1470                futures::pin_mut!(logged_in);
1471                futures::select_biased! {
1472                    result = logged_in => {
1473                        if let Err(e) = result {
1474                            log::error!("{e}");
1475                            return Err(anyhow!("exited before logging in"));
1476                        }
1477                    }
1478                    _ = exit_status => {
1479                        if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server()) && login.label.contains("gemini") {
1480                            return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, project.clone(), method, true, window, cx))?.await
1481                        }
1482                        return Err(anyhow!("exited before logging in"));
1483                    }
1484                }
1485                terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1486                Ok(())
1487            }
1488        })
1489    }
1490
1491    pub fn has_user_submitted_prompt(&self, cx: &App) -> bool {
1492        self.as_active_thread().is_some_and(|active| {
1493            active
1494                .read(cx)
1495                .thread
1496                .read(cx)
1497                .entries()
1498                .iter()
1499                .any(|entry| {
1500                    matches!(
1501                        entry,
1502                        AgentThreadEntry::UserMessage(user_message) if user_message.id.is_some()
1503                    )
1504                })
1505        })
1506    }
1507
1508    fn render_auth_required_state(
1509        &self,
1510        connection: &Rc<dyn AgentConnection>,
1511        description: Option<&Entity<Markdown>>,
1512        configuration_view: Option<&AnyView>,
1513        pending_auth_method: Option<&acp::AuthMethodId>,
1514        window: &mut Window,
1515        cx: &Context<Self>,
1516    ) -> impl IntoElement {
1517        let auth_methods = connection.auth_methods();
1518
1519        let agent_display_name = self
1520            .agent_server_store
1521            .read(cx)
1522            .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1523            .unwrap_or_else(|| self.agent.name());
1524
1525        let show_fallback_description = auth_methods.len() > 1
1526            && configuration_view.is_none()
1527            && description.is_none()
1528            && pending_auth_method.is_none();
1529
1530        let auth_buttons = || {
1531            h_flex().justify_end().flex_wrap().gap_1().children(
1532                connection
1533                    .auth_methods()
1534                    .iter()
1535                    .enumerate()
1536                    .rev()
1537                    .map(|(ix, method)| {
1538                        let (method_id, name) = if self.project.read(cx).is_via_remote_server()
1539                            && method.id.0.as_ref() == "oauth-personal"
1540                            && method.name == "Log in with Google"
1541                        {
1542                            ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
1543                        } else {
1544                            (method.id.0.clone(), method.name.clone())
1545                        };
1546
1547                        let agent_telemetry_id = connection.telemetry_id();
1548
1549                        Button::new(method_id.clone(), name)
1550                            .label_size(LabelSize::Small)
1551                            .map(|this| {
1552                                if ix == 0 {
1553                                    this.style(ButtonStyle::Tinted(TintColor::Accent))
1554                                } else {
1555                                    this.style(ButtonStyle::Outlined)
1556                                }
1557                            })
1558                            .when_some(method.description.clone(), |this, description| {
1559                                this.tooltip(Tooltip::text(description))
1560                            })
1561                            .on_click({
1562                                cx.listener(move |this, _, window, cx| {
1563                                    telemetry::event!(
1564                                        "Authenticate Agent Started",
1565                                        agent = agent_telemetry_id,
1566                                        method = method_id
1567                                    );
1568
1569                                    this.authenticate(
1570                                        acp::AuthMethodId::new(method_id.clone()),
1571                                        window,
1572                                        cx,
1573                                    )
1574                                })
1575                            })
1576                    }),
1577            )
1578        };
1579
1580        if pending_auth_method.is_some() {
1581            return Callout::new()
1582                .icon(IconName::Info)
1583                .title(format!("Authenticating to {}", agent_display_name))
1584                .actions_slot(
1585                    Icon::new(IconName::ArrowCircle)
1586                        .size(IconSize::Small)
1587                        .color(Color::Muted)
1588                        .with_rotate_animation(2)
1589                        .into_any_element(),
1590                )
1591                .into_any_element();
1592        }
1593
1594        Callout::new()
1595            .icon(IconName::Info)
1596            .title(format!("Authenticate to {}", agent_display_name))
1597            .when(auth_methods.len() == 1, |this| {
1598                this.actions_slot(auth_buttons())
1599            })
1600            .description_slot(
1601                v_flex()
1602                    .text_ui(cx)
1603                    .map(|this| {
1604                        if show_fallback_description {
1605                            this.child(
1606                                Label::new("Choose one of the following authentication options:")
1607                                    .size(LabelSize::Small)
1608                                    .color(Color::Muted),
1609                            )
1610                        } else {
1611                            this.children(
1612                                configuration_view
1613                                    .cloned()
1614                                    .map(|view| div().w_full().child(view)),
1615                            )
1616                            .children(description.map(|desc| {
1617                                self.render_markdown(
1618                                    desc.clone(),
1619                                    MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
1620                                )
1621                            }))
1622                        }
1623                    })
1624                    .when(auth_methods.len() > 1, |this| {
1625                        this.gap_1().child(auth_buttons())
1626                    }),
1627            )
1628            .into_any_element()
1629    }
1630
1631    fn render_load_error(
1632        &self,
1633        e: &LoadError,
1634        window: &mut Window,
1635        cx: &mut Context<Self>,
1636    ) -> AnyElement {
1637        let (title, message, action_slot): (_, SharedString, _) = match e {
1638            LoadError::Unsupported {
1639                command: path,
1640                current_version,
1641                minimum_version,
1642            } => {
1643                return self.render_unsupported(path, current_version, minimum_version, window, cx);
1644            }
1645            LoadError::FailedToInstall(msg) => (
1646                "Failed to Install",
1647                msg.into(),
1648                Some(self.create_copy_button(msg.to_string()).into_any_element()),
1649            ),
1650            LoadError::Exited { status } => (
1651                "Failed to Launch",
1652                format!("Server exited with status {status}").into(),
1653                None,
1654            ),
1655            LoadError::Other(msg) => (
1656                "Failed to Launch",
1657                msg.into(),
1658                Some(self.create_copy_button(msg.to_string()).into_any_element()),
1659            ),
1660        };
1661
1662        Callout::new()
1663            .severity(Severity::Error)
1664            .icon(IconName::XCircleFilled)
1665            .title(title)
1666            .description(message)
1667            .actions_slot(div().children(action_slot))
1668            .into_any_element()
1669    }
1670
1671    fn render_unsupported(
1672        &self,
1673        path: &SharedString,
1674        version: &SharedString,
1675        minimum_version: &SharedString,
1676        _window: &mut Window,
1677        cx: &mut Context<Self>,
1678    ) -> AnyElement {
1679        let (heading_label, description_label) = (
1680            format!("Upgrade {} to work with Zed", self.agent.name()),
1681            if version.is_empty() {
1682                format!(
1683                    "Currently using {}, which does not report a valid --version",
1684                    path,
1685                )
1686            } else {
1687                format!(
1688                    "Currently using {}, which is only version {} (need at least {minimum_version})",
1689                    path, version
1690                )
1691            },
1692        );
1693
1694        v_flex()
1695            .w_full()
1696            .p_3p5()
1697            .gap_2p5()
1698            .border_t_1()
1699            .border_color(cx.theme().colors().border)
1700            .bg(linear_gradient(
1701                180.,
1702                linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
1703                linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
1704            ))
1705            .child(
1706                v_flex().gap_0p5().child(Label::new(heading_label)).child(
1707                    Label::new(description_label)
1708                        .size(LabelSize::Small)
1709                        .color(Color::Muted),
1710                ),
1711            )
1712            .into_any_element()
1713    }
1714
1715    pub(crate) fn as_native_connection(
1716        &self,
1717        cx: &App,
1718    ) -> Option<Rc<agent::NativeAgentConnection>> {
1719        let acp_thread = self.as_active_thread()?.read(cx).thread.read(cx);
1720        acp_thread.connection().clone().downcast()
1721    }
1722
1723    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
1724        let acp_thread = self.as_active_thread()?.read(cx).thread.read(cx);
1725        self.as_native_connection(cx)?
1726            .thread(acp_thread.session_id(), cx)
1727    }
1728
1729    fn queued_messages_len(&self, cx: &App) -> usize {
1730        self.as_active_thread()
1731            .map(|thread| thread.read(cx).local_queued_messages.len())
1732            .unwrap_or_default()
1733    }
1734
1735    fn update_queued_message(
1736        &mut self,
1737        index: usize,
1738        content: Vec<acp::ContentBlock>,
1739        tracked_buffers: Vec<Entity<Buffer>>,
1740        cx: &mut Context<Self>,
1741    ) -> bool {
1742        match self.as_active_thread() {
1743            Some(thread) => thread.update(cx, |thread, _cx| {
1744                if index < thread.local_queued_messages.len() {
1745                    thread.local_queued_messages[index] = QueuedMessage {
1746                        content,
1747                        tracked_buffers,
1748                    };
1749                    true
1750                } else {
1751                    false
1752                }
1753            }),
1754            None => false,
1755        }
1756    }
1757
1758    fn queued_message_contents(&self, cx: &App) -> Vec<Vec<acp::ContentBlock>> {
1759        match self.as_active_thread() {
1760            None => Vec::new(),
1761            Some(thread) => thread
1762                .read(cx)
1763                .local_queued_messages
1764                .iter()
1765                .map(|q| q.content.clone())
1766                .collect(),
1767        }
1768    }
1769
1770    fn save_queued_message_at_index(&mut self, index: usize, cx: &mut Context<Self>) {
1771        let editor = match self.as_active_thread() {
1772            Some(thread) => thread.read(cx).queued_message_editors.get(index).cloned(),
1773            None => None,
1774        };
1775        let Some(editor) = editor else {
1776            return;
1777        };
1778
1779        let contents_task = editor.update(cx, |editor, cx| editor.contents(false, cx));
1780
1781        cx.spawn(async move |this, cx| {
1782            let Ok((content, tracked_buffers)) = contents_task.await else {
1783                return Ok::<(), anyhow::Error>(());
1784            };
1785
1786            this.update(cx, |this, cx| {
1787                this.update_queued_message(index, content, tracked_buffers, cx);
1788                cx.notify();
1789            })?;
1790
1791            Ok(())
1792        })
1793        .detach_and_log_err(cx);
1794    }
1795
1796    fn sync_queued_message_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1797        let needed_count = self.queued_messages_len(cx);
1798        let queued_messages = self.queued_message_contents(cx);
1799
1800        let agent_name = self.agent.name();
1801        let workspace = self.workspace.clone();
1802        let project = self.project.downgrade();
1803        let history = self.history.downgrade();
1804
1805        let Some(thread) = self.as_active_thread() else {
1806            return;
1807        };
1808        let prompt_capabilities = thread.read(cx).prompt_capabilities.clone();
1809        let available_commands = thread.read(cx).available_commands.clone();
1810
1811        let current_count = thread.read(cx).queued_message_editors.len();
1812        let last_synced = thread.read(cx).last_synced_queue_length;
1813
1814        if current_count == needed_count && needed_count == last_synced {
1815            return;
1816        }
1817
1818        if current_count > needed_count {
1819            thread.update(cx, |thread, _cx| {
1820                thread.queued_message_editors.truncate(needed_count);
1821                thread
1822                    .queued_message_editor_subscriptions
1823                    .truncate(needed_count);
1824            });
1825
1826            let editors = thread.read(cx).queued_message_editors.clone();
1827            for (index, editor) in editors.into_iter().enumerate() {
1828                if let Some(content) = queued_messages.get(index) {
1829                    editor.update(cx, |editor, cx| {
1830                        editor.set_message(content.clone(), window, cx);
1831                    });
1832                }
1833            }
1834        }
1835
1836        while thread.read(cx).queued_message_editors.len() < needed_count {
1837            let index = thread.read(cx).queued_message_editors.len();
1838            let content = queued_messages.get(index).cloned().unwrap_or_default();
1839
1840            let editor = cx.new(|cx| {
1841                let mut editor = MessageEditor::new(
1842                    workspace.clone(),
1843                    project.clone(),
1844                    None,
1845                    history.clone(),
1846                    None,
1847                    prompt_capabilities.clone(),
1848                    available_commands.clone(),
1849                    agent_name.clone(),
1850                    "",
1851                    EditorMode::AutoHeight {
1852                        min_lines: 1,
1853                        max_lines: Some(10),
1854                    },
1855                    window,
1856                    cx,
1857                );
1858                editor.set_message(content, window, cx);
1859                editor
1860            });
1861
1862            let subscription = cx.subscribe_in(
1863                &editor,
1864                window,
1865                move |this, _editor, event, window, cx| match event {
1866                    MessageEditorEvent::LostFocus => {
1867                        this.save_queued_message_at_index(index, cx);
1868                    }
1869                    MessageEditorEvent::Cancel => {
1870                        window.focus(&this.focus_handle(cx), cx);
1871                    }
1872                    MessageEditorEvent::Send => {
1873                        window.focus(&this.focus_handle(cx), cx);
1874                    }
1875                    MessageEditorEvent::SendImmediately => {
1876                        this.send_queued_message_at_index(index, true, window, cx);
1877                    }
1878                    _ => {}
1879                },
1880            );
1881
1882            thread.update(cx, |thread, _cx| {
1883                thread.queued_message_editors.push(editor);
1884                thread
1885                    .queued_message_editor_subscriptions
1886                    .push(subscription);
1887            });
1888        }
1889
1890        if let Some(active) = self.as_active_thread() {
1891            active.update(cx, |active, _cx| {
1892                active.last_synced_queue_length = needed_count;
1893            });
1894        }
1895    }
1896
1897    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
1898        let workspace = self.workspace.clone();
1899        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
1900            crate::acp::thread_view::active_thread::open_link(text, &workspace, window, cx);
1901        })
1902    }
1903
1904    fn notify_with_sound(
1905        &mut self,
1906        caption: impl Into<SharedString>,
1907        icon: IconName,
1908        window: &mut Window,
1909        cx: &mut Context<Self>,
1910    ) {
1911        self.play_notification_sound(window, cx);
1912        self.show_notification(caption, icon, window, cx);
1913    }
1914
1915    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
1916        let settings = AgentSettings::get_global(cx);
1917        if settings.play_sound_when_agent_done && !window.is_window_active() {
1918            Audio::play_sound(Sound::AgentDone, cx);
1919        }
1920    }
1921
1922    fn show_notification(
1923        &mut self,
1924        caption: impl Into<SharedString>,
1925        icon: IconName,
1926        window: &mut Window,
1927        cx: &mut Context<Self>,
1928    ) {
1929        if !self.notifications.is_empty() {
1930            return;
1931        }
1932
1933        let settings = AgentSettings::get_global(cx);
1934
1935        let window_is_inactive = !window.is_window_active();
1936        let panel_is_hidden = self
1937            .workspace
1938            .upgrade()
1939            .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
1940            .unwrap_or(true);
1941
1942        let should_notify = window_is_inactive || panel_is_hidden;
1943
1944        if !should_notify {
1945            return;
1946        }
1947
1948        // TODO: Change this once we have title summarization for external agents.
1949        let title = self.agent.name();
1950
1951        match settings.notify_when_agent_waiting {
1952            NotifyWhenAgentWaiting::PrimaryScreen => {
1953                if let Some(primary) = cx.primary_display() {
1954                    self.pop_up(icon, caption.into(), title, window, primary, cx);
1955                }
1956            }
1957            NotifyWhenAgentWaiting::AllScreens => {
1958                let caption = caption.into();
1959                for screen in cx.displays() {
1960                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
1961                }
1962            }
1963            NotifyWhenAgentWaiting::Never => {
1964                // Don't show anything
1965            }
1966        }
1967    }
1968
1969    fn pop_up(
1970        &mut self,
1971        icon: IconName,
1972        caption: SharedString,
1973        title: SharedString,
1974        window: &mut Window,
1975        screen: Rc<dyn PlatformDisplay>,
1976        cx: &mut Context<Self>,
1977    ) {
1978        let options = AgentNotification::window_options(screen, cx);
1979
1980        let project_name = self.workspace.upgrade().and_then(|workspace| {
1981            workspace
1982                .read(cx)
1983                .project()
1984                .read(cx)
1985                .visible_worktrees(cx)
1986                .next()
1987                .map(|worktree| worktree.read(cx).root_name_str().to_string())
1988        });
1989
1990        if let Some(screen_window) = cx
1991            .open_window(options, |_window, cx| {
1992                cx.new(|_cx| {
1993                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
1994                })
1995            })
1996            .log_err()
1997            && let Some(pop_up) = screen_window.entity(cx).log_err()
1998        {
1999            self.notification_subscriptions
2000                .entry(screen_window)
2001                .or_insert_with(Vec::new)
2002                .push(cx.subscribe_in(&pop_up, window, {
2003                    |this, _, event, window, cx| match event {
2004                        AgentNotificationEvent::Accepted => {
2005                            let handle = window.window_handle();
2006                            cx.activate(true);
2007
2008                            let workspace_handle = this.workspace.clone();
2009
2010                            // If there are multiple Zed windows, activate the correct one.
2011                            cx.defer(move |cx| {
2012                                handle
2013                                    .update(cx, |_view, window, _cx| {
2014                                        window.activate_window();
2015
2016                                        if let Some(workspace) = workspace_handle.upgrade() {
2017                                            workspace.update(_cx, |workspace, cx| {
2018                                                workspace.focus_panel::<AgentPanel>(window, cx);
2019                                            });
2020                                        }
2021                                    })
2022                                    .log_err();
2023                            });
2024
2025                            this.dismiss_notifications(cx);
2026                        }
2027                        AgentNotificationEvent::Dismissed => {
2028                            this.dismiss_notifications(cx);
2029                        }
2030                    }
2031                }));
2032
2033            self.notifications.push(screen_window);
2034
2035            // If the user manually refocuses the original window, dismiss the popup.
2036            self.notification_subscriptions
2037                .entry(screen_window)
2038                .or_insert_with(Vec::new)
2039                .push({
2040                    let pop_up_weak = pop_up.downgrade();
2041
2042                    cx.observe_window_activation(window, move |_, window, cx| {
2043                        if window.is_window_active()
2044                            && let Some(pop_up) = pop_up_weak.upgrade()
2045                        {
2046                            pop_up.update(cx, |_, cx| {
2047                                cx.emit(AgentNotificationEvent::Dismissed);
2048                            });
2049                        }
2050                    })
2051                });
2052        }
2053    }
2054
2055    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2056        for window in self.notifications.drain(..) {
2057            window
2058                .update(cx, |_, window, _| {
2059                    window.remove_window();
2060                })
2061                .ok();
2062
2063            self.notification_subscriptions.remove(&window);
2064        }
2065    }
2066
2067    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2068        if let Some(entry_view_state) = self
2069            .as_active_thread()
2070            .map(|active| active.read(cx).entry_view_state.clone())
2071        {
2072            entry_view_state.update(cx, |entry_view_state, cx| {
2073                entry_view_state.agent_ui_font_size_changed(cx);
2074            });
2075        }
2076    }
2077
2078    pub(crate) fn insert_dragged_files(
2079        &self,
2080        paths: Vec<project::ProjectPath>,
2081        added_worktrees: Vec<Entity<project::Worktree>>,
2082        window: &mut Window,
2083        cx: &mut Context<Self>,
2084    ) {
2085        if let Some(active_thread) = self.as_active_thread() {
2086            active_thread.update(cx, |thread, cx| {
2087                thread.message_editor.update(cx, |editor, cx| {
2088                    editor.insert_dragged_files(paths, added_worktrees, window, cx);
2089                })
2090            });
2091        }
2092    }
2093
2094    /// Inserts the selected text into the message editor or the message being
2095    /// edited, if any.
2096    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
2097        if let Some(active_thread) = self.as_active_thread() {
2098            active_thread.update(cx, |thread, cx| {
2099                thread.active_editor(cx).update(cx, |editor, cx| {
2100                    editor.insert_selections(window, cx);
2101                })
2102            });
2103        }
2104    }
2105
2106    /// Inserts terminal text as a crease into the message editor.
2107    pub(crate) fn insert_terminal_text(
2108        &self,
2109        text: String,
2110        window: &mut Window,
2111        cx: &mut Context<Self>,
2112    ) {
2113        if let Some(active_thread) = self.as_active_thread() {
2114            active_thread.update(cx, |thread, cx| {
2115                thread.message_editor.update(cx, |editor, cx| {
2116                    editor.insert_terminal_crease(text, window, cx);
2117                })
2118            });
2119        }
2120    }
2121
2122    fn current_model_name(&self, cx: &App) -> SharedString {
2123        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
2124        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
2125        // This provides better clarity about what refused the request
2126        if self.as_native_connection(cx).is_some() {
2127            self.as_active_thread()
2128                .and_then(|active| active.read(cx).model_selector.clone())
2129                .and_then(|selector| selector.read(cx).active_model(cx))
2130                .map(|model| model.name.clone())
2131                .unwrap_or_else(|| SharedString::from("The model"))
2132        } else {
2133            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
2134            self.agent.name()
2135        }
2136    }
2137
2138    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2139        let message = message.into();
2140
2141        CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
2142    }
2143
2144    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2145        let agent_name = self.agent.name();
2146        if let Some(active) = self.as_active_thread() {
2147            active.update(cx, |active, cx| active.clear_thread_error(cx));
2148        }
2149        let this = cx.weak_entity();
2150        window.defer(cx, |window, cx| {
2151            Self::handle_auth_required(this, AuthRequired::new(), agent_name, window, cx);
2152        })
2153    }
2154
2155    pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
2156        let task = self.history.update(cx, |history, cx| {
2157            history.delete_session(&entry.session_id, cx)
2158        });
2159        task.detach_and_log_err(cx);
2160    }
2161}
2162
2163fn loading_contents_spinner(size: IconSize) -> AnyElement {
2164    Icon::new(IconName::LoadCircle)
2165        .size(size)
2166        .color(Color::Accent)
2167        .with_rotate_animation(3)
2168        .into_any_element()
2169}
2170
2171fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
2172    if agent_name == "Zed Agent" {
2173        format!("Message the {} — @ to include context", agent_name)
2174    } else if has_commands {
2175        format!(
2176            "Message {} — @ to include context, / for commands",
2177            agent_name
2178        )
2179    } else {
2180        format!("Message {} — @ to include context", agent_name)
2181    }
2182}
2183
2184impl Focusable for AcpServerView {
2185    fn focus_handle(&self, cx: &App) -> FocusHandle {
2186        match self.as_active_thread() {
2187            Some(thread) => thread.read(cx).focus_handle(cx),
2188            None => self.focus_handle.clone(),
2189        }
2190    }
2191}
2192
2193#[cfg(any(test, feature = "test-support"))]
2194impl AcpServerView {
2195    /// Expands a tool call so its content is visible.
2196    /// This is primarily useful for visual testing.
2197    pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
2198        if let Some(active) = self.as_active_thread() {
2199            active.update(cx, |active, _cx| {
2200                active.expanded_tool_calls.insert(tool_call_id);
2201            });
2202            cx.notify();
2203        }
2204    }
2205
2206    /// Expands a subagent card so its content is visible.
2207    /// This is primarily useful for visual testing.
2208    pub fn expand_subagent(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
2209        if let Some(active) = self.as_active_thread() {
2210            active.update(cx, |active, _cx| {
2211                active.expanded_subagents.insert(session_id);
2212            });
2213            cx.notify();
2214        }
2215    }
2216}
2217
2218impl Render for AcpServerView {
2219    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2220        self.sync_queued_message_editors(window, cx);
2221
2222        v_flex()
2223            .size_full()
2224            .track_focus(&self.focus_handle)
2225            .bg(cx.theme().colors().panel_background)
2226            .child(match &self.server_state {
2227                ServerState::Loading { .. } => v_flex()
2228                    .flex_1()
2229                    // .child(self.render_recent_history(cx))
2230                    .into_any(),
2231                ServerState::LoadError(e) => v_flex()
2232                    .flex_1()
2233                    .size_full()
2234                    .items_center()
2235                    .justify_end()
2236                    .child(self.render_load_error(e, window, cx))
2237                    .into_any(),
2238                ServerState::Connected(ConnectedServerState {
2239                    connection,
2240                    auth_state:
2241                        AuthState::Unauthenticated {
2242                            description,
2243                            configuration_view,
2244                            pending_auth_method,
2245                            _subscription,
2246                        },
2247                    ..
2248                }) => v_flex()
2249                    .flex_1()
2250                    .size_full()
2251                    .justify_end()
2252                    .child(self.render_auth_required_state(
2253                        connection,
2254                        description.as_ref(),
2255                        configuration_view.as_ref(),
2256                        pending_auth_method.as_ref(),
2257                        window,
2258                        cx,
2259                    ))
2260                    .into_any_element(),
2261                ServerState::Connected(connected) => connected.current.clone().into_any_element(),
2262            })
2263    }
2264}
2265
2266fn plan_label_markdown_style(
2267    status: &acp::PlanEntryStatus,
2268    window: &Window,
2269    cx: &App,
2270) -> MarkdownStyle {
2271    let default_md_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
2272
2273    MarkdownStyle {
2274        base_text_style: TextStyle {
2275            color: cx.theme().colors().text_muted,
2276            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2277                Some(gpui::StrikethroughStyle {
2278                    thickness: px(1.),
2279                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2280                })
2281            } else {
2282                None
2283            },
2284            ..default_md_style.base_text_style
2285        },
2286        ..default_md_style
2287    }
2288}
2289
2290#[cfg(test)]
2291pub(crate) mod tests {
2292    use acp_thread::{
2293        AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
2294    };
2295    use action_log::ActionLog;
2296    use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
2297    use agent_client_protocol::SessionId;
2298    use editor::MultiBufferOffset;
2299    use fs::FakeFs;
2300    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
2301    use project::Project;
2302    use serde_json::json;
2303    use settings::SettingsStore;
2304    use std::any::Any;
2305    use std::path::Path;
2306    use std::rc::Rc;
2307    use workspace::Item;
2308
2309    use super::*;
2310
2311    #[gpui::test]
2312    async fn test_drop(cx: &mut TestAppContext) {
2313        init_test(cx);
2314
2315        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2316        let weak_view = thread_view.downgrade();
2317        drop(thread_view);
2318        assert!(!weak_view.is_upgradable());
2319    }
2320
2321    #[gpui::test]
2322    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2323        init_test(cx);
2324
2325        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2326
2327        let message_editor = message_editor(&thread_view, cx);
2328        message_editor.update_in(cx, |editor, window, cx| {
2329            editor.set_text("Hello", window, cx);
2330        });
2331
2332        cx.deactivate_window();
2333
2334        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2335
2336        cx.run_until_parked();
2337
2338        assert!(
2339            cx.windows()
2340                .iter()
2341                .any(|window| window.downcast::<AgentNotification>().is_some())
2342        );
2343    }
2344
2345    #[gpui::test]
2346    async fn test_notification_for_error(cx: &mut TestAppContext) {
2347        init_test(cx);
2348
2349        let (thread_view, cx) =
2350            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2351
2352        let message_editor = message_editor(&thread_view, cx);
2353        message_editor.update_in(cx, |editor, window, cx| {
2354            editor.set_text("Hello", window, cx);
2355        });
2356
2357        cx.deactivate_window();
2358
2359        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2360
2361        cx.run_until_parked();
2362
2363        assert!(
2364            cx.windows()
2365                .iter()
2366                .any(|window| window.downcast::<AgentNotification>().is_some())
2367        );
2368    }
2369
2370    #[gpui::test]
2371    async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
2372        init_test(cx);
2373
2374        let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
2375        let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
2376
2377        let fs = FakeFs::new(cx.executor());
2378        let project = Project::test(fs, [], cx).await;
2379        let (workspace, cx) =
2380            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2381
2382        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2383        // Create history without an initial session list - it will be set after connection
2384        let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2385
2386        let thread_view = cx.update(|window, cx| {
2387            cx.new(|cx| {
2388                AcpServerView::new(
2389                    Rc::new(StubAgentServer::default_response()),
2390                    None,
2391                    None,
2392                    workspace.downgrade(),
2393                    project,
2394                    Some(thread_store),
2395                    None,
2396                    history.clone(),
2397                    window,
2398                    cx,
2399                )
2400            })
2401        });
2402
2403        // Wait for connection to establish
2404        cx.run_until_parked();
2405
2406        // Initially empty because StubAgentConnection.session_list() returns None
2407        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2408            assert_eq!(view.recent_history_entries.len(), 0);
2409        });
2410
2411        // Now set the session list - this simulates external agents providing their history
2412        let list_a: Rc<dyn AgentSessionList> =
2413            Rc::new(StubSessionList::new(vec![session_a.clone()]));
2414        history.update(cx, |history, cx| {
2415            history.set_session_list(Some(list_a), cx);
2416        });
2417        cx.run_until_parked();
2418
2419        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2420            assert_eq!(view.recent_history_entries.len(), 1);
2421            assert_eq!(
2422                view.recent_history_entries[0].session_id,
2423                session_a.session_id
2424            );
2425        });
2426
2427        // Update to a different session list
2428        let list_b: Rc<dyn AgentSessionList> =
2429            Rc::new(StubSessionList::new(vec![session_b.clone()]));
2430        history.update(cx, |history, cx| {
2431            history.set_session_list(Some(list_b), cx);
2432        });
2433        cx.run_until_parked();
2434
2435        active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2436            assert_eq!(view.recent_history_entries.len(), 1);
2437            assert_eq!(
2438                view.recent_history_entries[0].session_id,
2439                session_b.session_id
2440            );
2441        });
2442    }
2443
2444    #[gpui::test]
2445    async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
2446        init_test(cx);
2447
2448        let session = AgentSessionInfo::new(SessionId::new("resume-session"));
2449        let fs = FakeFs::new(cx.executor());
2450        let project = Project::test(fs, [], cx).await;
2451        let (workspace, cx) =
2452            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2453
2454        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2455        let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2456
2457        let thread_view = cx.update(|window, cx| {
2458            cx.new(|cx| {
2459                AcpServerView::new(
2460                    Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
2461                    Some(session),
2462                    None,
2463                    workspace.downgrade(),
2464                    project,
2465                    Some(thread_store),
2466                    None,
2467                    history,
2468                    window,
2469                    cx,
2470                )
2471            })
2472        });
2473
2474        cx.run_until_parked();
2475
2476        thread_view.read_with(cx, |view, cx| {
2477            let state = view.as_active_thread().unwrap();
2478            assert!(state.read(cx).resumed_without_history);
2479            assert_eq!(state.read(cx).list_state.item_count(), 0);
2480        });
2481    }
2482
2483    #[gpui::test]
2484    async fn test_refusal_handling(cx: &mut TestAppContext) {
2485        init_test(cx);
2486
2487        let (thread_view, cx) =
2488            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
2489
2490        let message_editor = message_editor(&thread_view, cx);
2491        message_editor.update_in(cx, |editor, window, cx| {
2492            editor.set_text("Do something harmful", window, cx);
2493        });
2494
2495        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2496
2497        cx.run_until_parked();
2498
2499        // Check that the refusal error is set
2500        thread_view.read_with(cx, |thread_view, cx| {
2501            let state = thread_view.as_active_thread().unwrap();
2502            assert!(
2503                matches!(state.read(cx).thread_error, Some(ThreadError::Refusal)),
2504                "Expected refusal error to be set"
2505            );
2506        });
2507    }
2508
2509    #[gpui::test]
2510    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
2511        init_test(cx);
2512
2513        let tool_call_id = acp::ToolCallId::new("1");
2514        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
2515            .kind(acp::ToolKind::Edit)
2516            .content(vec!["hi".into()]);
2517        let connection =
2518            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
2519                tool_call_id,
2520                PermissionOptions::Flat(vec![acp::PermissionOption::new(
2521                    "1",
2522                    "Allow",
2523                    acp::PermissionOptionKind::AllowOnce,
2524                )]),
2525            )]));
2526
2527        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
2528
2529        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
2530
2531        let message_editor = message_editor(&thread_view, cx);
2532        message_editor.update_in(cx, |editor, window, cx| {
2533            editor.set_text("Hello", window, cx);
2534        });
2535
2536        cx.deactivate_window();
2537
2538        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2539
2540        cx.run_until_parked();
2541
2542        assert!(
2543            cx.windows()
2544                .iter()
2545                .any(|window| window.downcast::<AgentNotification>().is_some())
2546        );
2547    }
2548
2549    #[gpui::test]
2550    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
2551        init_test(cx);
2552
2553        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2554
2555        add_to_workspace(thread_view.clone(), cx);
2556
2557        let message_editor = message_editor(&thread_view, cx);
2558
2559        message_editor.update_in(cx, |editor, window, cx| {
2560            editor.set_text("Hello", window, cx);
2561        });
2562
2563        // Window is active (don't deactivate), but panel will be hidden
2564        // Note: In the test environment, the panel is not actually added to the dock,
2565        // so is_agent_panel_hidden will return true
2566
2567        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2568
2569        cx.run_until_parked();
2570
2571        // Should show notification because window is active but panel is hidden
2572        assert!(
2573            cx.windows()
2574                .iter()
2575                .any(|window| window.downcast::<AgentNotification>().is_some()),
2576            "Expected notification when panel is hidden"
2577        );
2578    }
2579
2580    #[gpui::test]
2581    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
2582        init_test(cx);
2583
2584        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2585
2586        let message_editor = message_editor(&thread_view, cx);
2587        message_editor.update_in(cx, |editor, window, cx| {
2588            editor.set_text("Hello", window, cx);
2589        });
2590
2591        // Deactivate window - should show notification regardless of setting
2592        cx.deactivate_window();
2593
2594        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2595
2596        cx.run_until_parked();
2597
2598        // Should still show notification when window is inactive (existing behavior)
2599        assert!(
2600            cx.windows()
2601                .iter()
2602                .any(|window| window.downcast::<AgentNotification>().is_some()),
2603            "Expected notification when window is inactive"
2604        );
2605    }
2606
2607    #[gpui::test]
2608    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
2609        init_test(cx);
2610
2611        // Set notify_when_agent_waiting to Never
2612        cx.update(|cx| {
2613            AgentSettings::override_global(
2614                AgentSettings {
2615                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
2616                    ..AgentSettings::get_global(cx).clone()
2617                },
2618                cx,
2619            );
2620        });
2621
2622        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2623
2624        let message_editor = message_editor(&thread_view, cx);
2625        message_editor.update_in(cx, |editor, window, cx| {
2626            editor.set_text("Hello", window, cx);
2627        });
2628
2629        // Window is active
2630
2631        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2632
2633        cx.run_until_parked();
2634
2635        // Should NOT show notification because notify_when_agent_waiting is Never
2636        assert!(
2637            !cx.windows()
2638                .iter()
2639                .any(|window| window.downcast::<AgentNotification>().is_some()),
2640            "Expected no notification when notify_when_agent_waiting is Never"
2641        );
2642    }
2643
2644    #[gpui::test]
2645    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
2646        init_test(cx);
2647
2648        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2649
2650        let weak_view = thread_view.downgrade();
2651
2652        let message_editor = message_editor(&thread_view, cx);
2653        message_editor.update_in(cx, |editor, window, cx| {
2654            editor.set_text("Hello", window, cx);
2655        });
2656
2657        cx.deactivate_window();
2658
2659        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2660
2661        cx.run_until_parked();
2662
2663        // Verify notification is shown
2664        assert!(
2665            cx.windows()
2666                .iter()
2667                .any(|window| window.downcast::<AgentNotification>().is_some()),
2668            "Expected notification to be shown"
2669        );
2670
2671        // Drop the thread view (simulating navigation to a new thread)
2672        drop(thread_view);
2673        drop(message_editor);
2674        // Trigger an update to flush effects, which will call release_dropped_entities
2675        cx.update(|_window, _cx| {});
2676        cx.run_until_parked();
2677
2678        // Verify the entity was actually released
2679        assert!(
2680            !weak_view.is_upgradable(),
2681            "Thread view entity should be released after dropping"
2682        );
2683
2684        // The notification should be automatically closed via on_release
2685        assert!(
2686            !cx.windows()
2687                .iter()
2688                .any(|window| window.downcast::<AgentNotification>().is_some()),
2689            "Notification should be closed when thread view is dropped"
2690        );
2691    }
2692
2693    async fn setup_thread_view(
2694        agent: impl AgentServer + 'static,
2695        cx: &mut TestAppContext,
2696    ) -> (Entity<AcpServerView>, &mut VisualTestContext) {
2697        let fs = FakeFs::new(cx.executor());
2698        let project = Project::test(fs, [], cx).await;
2699        let (workspace, cx) =
2700            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2701
2702        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2703        let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2704
2705        let thread_view = cx.update(|window, cx| {
2706            cx.new(|cx| {
2707                AcpServerView::new(
2708                    Rc::new(agent),
2709                    None,
2710                    None,
2711                    workspace.downgrade(),
2712                    project,
2713                    Some(thread_store),
2714                    None,
2715                    history,
2716                    window,
2717                    cx,
2718                )
2719            })
2720        });
2721        cx.run_until_parked();
2722        (thread_view, cx)
2723    }
2724
2725    fn add_to_workspace(thread_view: Entity<AcpServerView>, cx: &mut VisualTestContext) {
2726        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
2727
2728        workspace
2729            .update_in(cx, |workspace, window, cx| {
2730                workspace.add_item_to_active_pane(
2731                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
2732                    None,
2733                    true,
2734                    window,
2735                    cx,
2736                );
2737            })
2738            .unwrap();
2739    }
2740
2741    struct ThreadViewItem(Entity<AcpServerView>);
2742
2743    impl Item for ThreadViewItem {
2744        type Event = ();
2745
2746        fn include_in_nav_history() -> bool {
2747            false
2748        }
2749
2750        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
2751            "Test".into()
2752        }
2753    }
2754
2755    impl EventEmitter<()> for ThreadViewItem {}
2756
2757    impl Focusable for ThreadViewItem {
2758        fn focus_handle(&self, cx: &App) -> FocusHandle {
2759            self.0.read(cx).focus_handle(cx)
2760        }
2761    }
2762
2763    impl Render for ThreadViewItem {
2764        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2765            self.0.clone().into_any_element()
2766        }
2767    }
2768
2769    struct StubAgentServer<C> {
2770        connection: C,
2771    }
2772
2773    impl<C> StubAgentServer<C> {
2774        fn new(connection: C) -> Self {
2775            Self { connection }
2776        }
2777    }
2778
2779    impl StubAgentServer<StubAgentConnection> {
2780        fn default_response() -> Self {
2781            let conn = StubAgentConnection::new();
2782            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
2783                acp::ContentChunk::new("Default response".into()),
2784            )]);
2785            Self::new(conn)
2786        }
2787    }
2788
2789    impl<C> AgentServer for StubAgentServer<C>
2790    where
2791        C: 'static + AgentConnection + Send + Clone,
2792    {
2793        fn logo(&self) -> ui::IconName {
2794            ui::IconName::Ai
2795        }
2796
2797        fn name(&self) -> SharedString {
2798            "Test".into()
2799        }
2800
2801        fn connect(
2802            &self,
2803            _root_dir: Option<&Path>,
2804            _delegate: AgentServerDelegate,
2805            _cx: &mut App,
2806        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
2807            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
2808        }
2809
2810        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2811            self
2812        }
2813    }
2814
2815    #[derive(Clone)]
2816    struct StubSessionList {
2817        sessions: Vec<AgentSessionInfo>,
2818    }
2819
2820    impl StubSessionList {
2821        fn new(sessions: Vec<AgentSessionInfo>) -> Self {
2822            Self { sessions }
2823        }
2824    }
2825
2826    impl AgentSessionList for StubSessionList {
2827        fn list_sessions(
2828            &self,
2829            _request: AgentSessionListRequest,
2830            _cx: &mut App,
2831        ) -> Task<anyhow::Result<AgentSessionListResponse>> {
2832            Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
2833        }
2834        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2835            self
2836        }
2837    }
2838
2839    #[derive(Clone)]
2840    struct ResumeOnlyAgentConnection;
2841
2842    impl AgentConnection for ResumeOnlyAgentConnection {
2843        fn telemetry_id(&self) -> SharedString {
2844            "resume-only".into()
2845        }
2846
2847        fn new_thread(
2848            self: Rc<Self>,
2849            project: Entity<Project>,
2850            _cwd: &Path,
2851            cx: &mut gpui::App,
2852        ) -> Task<gpui::Result<Entity<AcpThread>>> {
2853            let action_log = cx.new(|_| ActionLog::new(project.clone()));
2854            let thread = cx.new(|cx| {
2855                AcpThread::new(
2856                    "ResumeOnlyAgentConnection",
2857                    self.clone(),
2858                    project,
2859                    action_log,
2860                    SessionId::new("new-session"),
2861                    watch::Receiver::constant(
2862                        acp::PromptCapabilities::new()
2863                            .image(true)
2864                            .audio(true)
2865                            .embedded_context(true),
2866                    ),
2867                    cx,
2868                )
2869            });
2870            Task::ready(Ok(thread))
2871        }
2872
2873        fn supports_resume_session(&self, _cx: &App) -> bool {
2874            true
2875        }
2876
2877        fn resume_session(
2878            self: Rc<Self>,
2879            session: AgentSessionInfo,
2880            project: Entity<Project>,
2881            _cwd: &Path,
2882            cx: &mut App,
2883        ) -> Task<gpui::Result<Entity<AcpThread>>> {
2884            let action_log = cx.new(|_| ActionLog::new(project.clone()));
2885            let thread = cx.new(|cx| {
2886                AcpThread::new(
2887                    "ResumeOnlyAgentConnection",
2888                    self.clone(),
2889                    project,
2890                    action_log,
2891                    session.session_id,
2892                    watch::Receiver::constant(
2893                        acp::PromptCapabilities::new()
2894                            .image(true)
2895                            .audio(true)
2896                            .embedded_context(true),
2897                    ),
2898                    cx,
2899                )
2900            });
2901            Task::ready(Ok(thread))
2902        }
2903
2904        fn auth_methods(&self) -> &[acp::AuthMethod] {
2905            &[]
2906        }
2907
2908        fn authenticate(
2909            &self,
2910            _method_id: acp::AuthMethodId,
2911            _cx: &mut App,
2912        ) -> Task<gpui::Result<()>> {
2913            Task::ready(Ok(()))
2914        }
2915
2916        fn prompt(
2917            &self,
2918            _id: Option<acp_thread::UserMessageId>,
2919            _params: acp::PromptRequest,
2920            _cx: &mut App,
2921        ) -> Task<gpui::Result<acp::PromptResponse>> {
2922            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
2923        }
2924
2925        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
2926
2927        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2928            self
2929        }
2930    }
2931
2932    #[derive(Clone)]
2933    struct SaboteurAgentConnection;
2934
2935    impl AgentConnection for SaboteurAgentConnection {
2936        fn telemetry_id(&self) -> SharedString {
2937            "saboteur".into()
2938        }
2939
2940        fn new_thread(
2941            self: Rc<Self>,
2942            project: Entity<Project>,
2943            _cwd: &Path,
2944            cx: &mut gpui::App,
2945        ) -> Task<gpui::Result<Entity<AcpThread>>> {
2946            Task::ready(Ok(cx.new(|cx| {
2947                let action_log = cx.new(|_| ActionLog::new(project.clone()));
2948                AcpThread::new(
2949                    "SaboteurAgentConnection",
2950                    self,
2951                    project,
2952                    action_log,
2953                    SessionId::new("test"),
2954                    watch::Receiver::constant(
2955                        acp::PromptCapabilities::new()
2956                            .image(true)
2957                            .audio(true)
2958                            .embedded_context(true),
2959                    ),
2960                    cx,
2961                )
2962            })))
2963        }
2964
2965        fn auth_methods(&self) -> &[acp::AuthMethod] {
2966            &[]
2967        }
2968
2969        fn authenticate(
2970            &self,
2971            _method_id: acp::AuthMethodId,
2972            _cx: &mut App,
2973        ) -> Task<gpui::Result<()>> {
2974            unimplemented!()
2975        }
2976
2977        fn prompt(
2978            &self,
2979            _id: Option<acp_thread::UserMessageId>,
2980            _params: acp::PromptRequest,
2981            _cx: &mut App,
2982        ) -> Task<gpui::Result<acp::PromptResponse>> {
2983            Task::ready(Err(anyhow::anyhow!("Error prompting")))
2984        }
2985
2986        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
2987            unimplemented!()
2988        }
2989
2990        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
2991            self
2992        }
2993    }
2994
2995    /// Simulates a model which always returns a refusal response
2996    #[derive(Clone)]
2997    struct RefusalAgentConnection;
2998
2999    impl AgentConnection for RefusalAgentConnection {
3000        fn telemetry_id(&self) -> SharedString {
3001            "refusal".into()
3002        }
3003
3004        fn new_thread(
3005            self: Rc<Self>,
3006            project: Entity<Project>,
3007            _cwd: &Path,
3008            cx: &mut gpui::App,
3009        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3010            Task::ready(Ok(cx.new(|cx| {
3011                let action_log = cx.new(|_| ActionLog::new(project.clone()));
3012                AcpThread::new(
3013                    "RefusalAgentConnection",
3014                    self,
3015                    project,
3016                    action_log,
3017                    SessionId::new("test"),
3018                    watch::Receiver::constant(
3019                        acp::PromptCapabilities::new()
3020                            .image(true)
3021                            .audio(true)
3022                            .embedded_context(true),
3023                    ),
3024                    cx,
3025                )
3026            })))
3027        }
3028
3029        fn auth_methods(&self) -> &[acp::AuthMethod] {
3030            &[]
3031        }
3032
3033        fn authenticate(
3034            &self,
3035            _method_id: acp::AuthMethodId,
3036            _cx: &mut App,
3037        ) -> Task<gpui::Result<()>> {
3038            unimplemented!()
3039        }
3040
3041        fn prompt(
3042            &self,
3043            _id: Option<acp_thread::UserMessageId>,
3044            _params: acp::PromptRequest,
3045            _cx: &mut App,
3046        ) -> Task<gpui::Result<acp::PromptResponse>> {
3047            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
3048        }
3049
3050        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3051            unimplemented!()
3052        }
3053
3054        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3055            self
3056        }
3057    }
3058
3059    pub(crate) fn init_test(cx: &mut TestAppContext) {
3060        cx.update(|cx| {
3061            let settings_store = SettingsStore::test(cx);
3062            cx.set_global(settings_store);
3063            theme::init(theme::LoadThemes::JustBase, cx);
3064            editor::init(cx);
3065            release_channel::init(semver::Version::new(0, 0, 0), cx);
3066            prompt_store::init(cx)
3067        });
3068    }
3069
3070    fn active_thread(
3071        thread_view: &Entity<AcpServerView>,
3072        cx: &TestAppContext,
3073    ) -> Entity<AcpThreadView> {
3074        cx.read(|cx| thread_view.read(cx).as_connected().unwrap().current.clone())
3075    }
3076
3077    fn message_editor(
3078        thread_view: &Entity<AcpServerView>,
3079        cx: &TestAppContext,
3080    ) -> Entity<MessageEditor> {
3081        let thread = active_thread(thread_view, cx);
3082        cx.read(|cx| thread.read(cx).message_editor.clone())
3083    }
3084
3085    #[gpui::test]
3086    async fn test_rewind_views(cx: &mut TestAppContext) {
3087        init_test(cx);
3088
3089        let fs = FakeFs::new(cx.executor());
3090        fs.insert_tree(
3091            "/project",
3092            json!({
3093                "test1.txt": "old content 1",
3094                "test2.txt": "old content 2"
3095            }),
3096        )
3097        .await;
3098        let project = Project::test(fs, [Path::new("/project")], cx).await;
3099        let (workspace, cx) =
3100            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3101
3102        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3103        let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
3104
3105        let connection = Rc::new(StubAgentConnection::new());
3106        let thread_view = cx.update(|window, cx| {
3107            cx.new(|cx| {
3108                AcpServerView::new(
3109                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
3110                    None,
3111                    None,
3112                    workspace.downgrade(),
3113                    project.clone(),
3114                    Some(thread_store.clone()),
3115                    None,
3116                    history,
3117                    window,
3118                    cx,
3119                )
3120            })
3121        });
3122
3123        cx.run_until_parked();
3124
3125        let thread = thread_view
3126            .read_with(cx, |view, cx| {
3127                view.as_active_thread().map(|r| r.read(cx).thread.clone())
3128            })
3129            .unwrap();
3130
3131        // First user message
3132        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
3133            acp::ToolCall::new("tool1", "Edit file 1")
3134                .kind(acp::ToolKind::Edit)
3135                .status(acp::ToolCallStatus::Completed)
3136                .content(vec![acp::ToolCallContent::Diff(
3137                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
3138                )]),
3139        )]);
3140
3141        thread
3142            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
3143            .await
3144            .unwrap();
3145        cx.run_until_parked();
3146
3147        thread.read_with(cx, |thread, _cx| {
3148            assert_eq!(thread.entries().len(), 2);
3149        });
3150
3151        thread_view.read_with(cx, |view, cx| {
3152            let entry_view_state = view
3153                .as_active_thread()
3154                .map(|active| active.read(cx).entry_view_state.clone())
3155                .unwrap();
3156            entry_view_state.read_with(cx, |entry_view_state, _| {
3157                assert!(
3158                    entry_view_state
3159                        .entry(0)
3160                        .unwrap()
3161                        .message_editor()
3162                        .is_some()
3163                );
3164                assert!(entry_view_state.entry(1).unwrap().has_content());
3165            });
3166        });
3167
3168        // Second user message
3169        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
3170            acp::ToolCall::new("tool2", "Edit file 2")
3171                .kind(acp::ToolKind::Edit)
3172                .status(acp::ToolCallStatus::Completed)
3173                .content(vec![acp::ToolCallContent::Diff(
3174                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
3175                )]),
3176        )]);
3177
3178        thread
3179            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
3180            .await
3181            .unwrap();
3182        cx.run_until_parked();
3183
3184        let second_user_message_id = thread.read_with(cx, |thread, _| {
3185            assert_eq!(thread.entries().len(), 4);
3186            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
3187                panic!();
3188            };
3189            user_message.id.clone().unwrap()
3190        });
3191
3192        thread_view.read_with(cx, |view, cx| {
3193            let entry_view_state = view
3194                .as_active_thread()
3195                .unwrap()
3196                .read(cx)
3197                .entry_view_state
3198                .clone();
3199            entry_view_state.read_with(cx, |entry_view_state, _| {
3200                assert!(
3201                    entry_view_state
3202                        .entry(0)
3203                        .unwrap()
3204                        .message_editor()
3205                        .is_some()
3206                );
3207                assert!(entry_view_state.entry(1).unwrap().has_content());
3208                assert!(
3209                    entry_view_state
3210                        .entry(2)
3211                        .unwrap()
3212                        .message_editor()
3213                        .is_some()
3214                );
3215                assert!(entry_view_state.entry(3).unwrap().has_content());
3216            });
3217        });
3218
3219        // Rewind to first message
3220        thread
3221            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
3222            .await
3223            .unwrap();
3224
3225        cx.run_until_parked();
3226
3227        thread.read_with(cx, |thread, _| {
3228            assert_eq!(thread.entries().len(), 2);
3229        });
3230
3231        thread_view.read_with(cx, |view, cx| {
3232            let active = view.as_active_thread().unwrap();
3233            active
3234                .read(cx)
3235                .entry_view_state
3236                .read_with(cx, |entry_view_state, _| {
3237                    assert!(
3238                        entry_view_state
3239                            .entry(0)
3240                            .unwrap()
3241                            .message_editor()
3242                            .is_some()
3243                    );
3244                    assert!(entry_view_state.entry(1).unwrap().has_content());
3245
3246                    // Old views should be dropped
3247                    assert!(entry_view_state.entry(2).is_none());
3248                    assert!(entry_view_state.entry(3).is_none());
3249                });
3250        });
3251    }
3252
3253    #[gpui::test]
3254    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
3255        init_test(cx);
3256
3257        let connection = StubAgentConnection::new();
3258
3259        // Each user prompt will result in a user message entry plus an agent message entry.
3260        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3261            acp::ContentChunk::new("Response 1".into()),
3262        )]);
3263
3264        let (thread_view, cx) =
3265            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
3266
3267        let thread = thread_view
3268            .read_with(cx, |view, cx| {
3269                view.as_active_thread().map(|r| r.read(cx).thread.clone())
3270            })
3271            .unwrap();
3272
3273        thread
3274            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
3275            .await
3276            .unwrap();
3277        cx.run_until_parked();
3278
3279        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3280            acp::ContentChunk::new("Response 2".into()),
3281        )]);
3282
3283        thread
3284            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
3285            .await
3286            .unwrap();
3287        cx.run_until_parked();
3288
3289        // Move somewhere else first so we're not trivially already on the last user prompt.
3290        active_thread(&thread_view, cx).update(cx, |view, cx| {
3291            view.scroll_to_top(cx);
3292        });
3293        cx.run_until_parked();
3294
3295        active_thread(&thread_view, cx).update(cx, |view, cx| {
3296            view.scroll_to_most_recent_user_prompt(cx);
3297            let scroll_top = view.list_state.logical_scroll_top();
3298            // Entries layout is: [User1, Assistant1, User2, Assistant2]
3299            assert_eq!(scroll_top.item_ix, 2);
3300        });
3301    }
3302
3303    #[gpui::test]
3304    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
3305        cx: &mut TestAppContext,
3306    ) {
3307        init_test(cx);
3308
3309        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3310
3311        // With no entries, scrolling should be a no-op and must not panic.
3312        active_thread(&thread_view, cx).update(cx, |view, cx| {
3313            view.scroll_to_most_recent_user_prompt(cx);
3314            let scroll_top = view.list_state.logical_scroll_top();
3315            assert_eq!(scroll_top.item_ix, 0);
3316        });
3317    }
3318
3319    #[gpui::test]
3320    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
3321        init_test(cx);
3322
3323        let connection = StubAgentConnection::new();
3324
3325        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3326            acp::ContentChunk::new("Response".into()),
3327        )]);
3328
3329        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3330        add_to_workspace(thread_view.clone(), cx);
3331
3332        let message_editor = message_editor(&thread_view, cx);
3333        message_editor.update_in(cx, |editor, window, cx| {
3334            editor.set_text("Original message to edit", window, cx);
3335        });
3336        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3337
3338        cx.run_until_parked();
3339
3340        let user_message_editor = thread_view.read_with(cx, |view, cx| {
3341            assert_eq!(
3342                view.as_active_thread()
3343                    .and_then(|active| active.read(cx).editing_message),
3344                None
3345            );
3346
3347            view.as_active_thread()
3348                .map(|active| &active.read(cx).entry_view_state)
3349                .as_ref()
3350                .unwrap()
3351                .read(cx)
3352                .entry(0)
3353                .unwrap()
3354                .message_editor()
3355                .unwrap()
3356                .clone()
3357        });
3358
3359        // Focus
3360        cx.focus(&user_message_editor);
3361        thread_view.read_with(cx, |view, cx| {
3362            assert_eq!(
3363                view.as_active_thread()
3364                    .and_then(|active| active.read(cx).editing_message),
3365                Some(0)
3366            );
3367        });
3368
3369        // Edit
3370        user_message_editor.update_in(cx, |editor, window, cx| {
3371            editor.set_text("Edited message content", window, cx);
3372        });
3373
3374        // Cancel
3375        user_message_editor.update_in(cx, |_editor, window, cx| {
3376            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
3377        });
3378
3379        thread_view.read_with(cx, |view, cx| {
3380            assert_eq!(
3381                view.as_active_thread()
3382                    .and_then(|active| active.read(cx).editing_message),
3383                None
3384            );
3385        });
3386
3387        user_message_editor.read_with(cx, |editor, cx| {
3388            assert_eq!(editor.text(cx), "Original message to edit");
3389        });
3390    }
3391
3392    #[gpui::test]
3393    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
3394        init_test(cx);
3395
3396        let connection = StubAgentConnection::new();
3397
3398        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3399        add_to_workspace(thread_view.clone(), cx);
3400
3401        let message_editor = message_editor(&thread_view, cx);
3402        message_editor.update_in(cx, |editor, window, cx| {
3403            editor.set_text("", window, cx);
3404        });
3405
3406        let thread = cx.read(|cx| {
3407            thread_view
3408                .read(cx)
3409                .as_active_thread()
3410                .unwrap()
3411                .read(cx)
3412                .thread
3413                .clone()
3414        });
3415        let entries_before = cx.read(|cx| thread.read(cx).entries().len());
3416
3417        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
3418            view.send(window, cx);
3419        });
3420        cx.run_until_parked();
3421
3422        let entries_after = cx.read(|cx| thread.read(cx).entries().len());
3423        assert_eq!(
3424            entries_before, entries_after,
3425            "No message should be sent when editor is empty"
3426        );
3427    }
3428
3429    #[gpui::test]
3430    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
3431        init_test(cx);
3432
3433        let connection = StubAgentConnection::new();
3434
3435        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3436            acp::ContentChunk::new("Response".into()),
3437        )]);
3438
3439        let (thread_view, cx) =
3440            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
3441        add_to_workspace(thread_view.clone(), cx);
3442
3443        let message_editor = message_editor(&thread_view, cx);
3444        message_editor.update_in(cx, |editor, window, cx| {
3445            editor.set_text("Original message to edit", window, cx);
3446        });
3447        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3448
3449        cx.run_until_parked();
3450
3451        let user_message_editor = thread_view.read_with(cx, |view, cx| {
3452            assert_eq!(
3453                view.as_active_thread()
3454                    .and_then(|active| active.read(cx).editing_message),
3455                None
3456            );
3457            assert_eq!(
3458                view.as_active_thread()
3459                    .unwrap()
3460                    .read(cx)
3461                    .thread
3462                    .read(cx)
3463                    .entries()
3464                    .len(),
3465                2
3466            );
3467
3468            view.as_active_thread()
3469                .map(|active| &active.read(cx).entry_view_state)
3470                .as_ref()
3471                .unwrap()
3472                .read(cx)
3473                .entry(0)
3474                .unwrap()
3475                .message_editor()
3476                .unwrap()
3477                .clone()
3478        });
3479
3480        // Focus
3481        cx.focus(&user_message_editor);
3482
3483        // Edit
3484        user_message_editor.update_in(cx, |editor, window, cx| {
3485            editor.set_text("Edited message content", window, cx);
3486        });
3487
3488        // Send
3489        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3490            acp::ContentChunk::new("New Response".into()),
3491        )]);
3492
3493        user_message_editor.update_in(cx, |_editor, window, cx| {
3494            window.dispatch_action(Box::new(Chat), cx);
3495        });
3496
3497        cx.run_until_parked();
3498
3499        thread_view.read_with(cx, |view, cx| {
3500            assert_eq!(
3501                view.as_active_thread()
3502                    .and_then(|active| active.read(cx).editing_message),
3503                None
3504            );
3505
3506            let entries = view
3507                .as_active_thread()
3508                .unwrap()
3509                .read(cx)
3510                .thread
3511                .read(cx)
3512                .entries();
3513            assert_eq!(entries.len(), 2);
3514            assert_eq!(
3515                entries[0].to_markdown(cx),
3516                "## User\n\nEdited message content\n\n"
3517            );
3518            assert_eq!(
3519                entries[1].to_markdown(cx),
3520                "## Assistant\n\nNew Response\n\n"
3521            );
3522
3523            let entry_view_state = view
3524                .as_active_thread()
3525                .map(|active| &active.read(cx).entry_view_state)
3526                .unwrap();
3527            let new_editor = entry_view_state.read_with(cx, |state, _cx| {
3528                assert!(!state.entry(1).unwrap().has_content());
3529                state.entry(0).unwrap().message_editor().unwrap().clone()
3530            });
3531
3532            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
3533        })
3534    }
3535
3536    #[gpui::test]
3537    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
3538        init_test(cx);
3539
3540        let connection = StubAgentConnection::new();
3541
3542        let (thread_view, cx) =
3543            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
3544        add_to_workspace(thread_view.clone(), cx);
3545
3546        let message_editor = message_editor(&thread_view, cx);
3547        message_editor.update_in(cx, |editor, window, cx| {
3548            editor.set_text("Original message to edit", window, cx);
3549        });
3550        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3551
3552        cx.run_until_parked();
3553
3554        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
3555            let thread = view.as_active_thread().unwrap().read(cx).thread.read(cx);
3556            assert_eq!(thread.entries().len(), 1);
3557
3558            let editor = view
3559                .as_active_thread()
3560                .map(|active| &active.read(cx).entry_view_state)
3561                .as_ref()
3562                .unwrap()
3563                .read(cx)
3564                .entry(0)
3565                .unwrap()
3566                .message_editor()
3567                .unwrap()
3568                .clone();
3569
3570            (editor, thread.session_id().clone())
3571        });
3572
3573        // Focus
3574        cx.focus(&user_message_editor);
3575
3576        thread_view.read_with(cx, |view, cx| {
3577            assert_eq!(
3578                view.as_active_thread()
3579                    .and_then(|active| active.read(cx).editing_message),
3580                Some(0)
3581            );
3582        });
3583
3584        // Edit
3585        user_message_editor.update_in(cx, |editor, window, cx| {
3586            editor.set_text("Edited message content", window, cx);
3587        });
3588
3589        thread_view.read_with(cx, |view, cx| {
3590            assert_eq!(
3591                view.as_active_thread()
3592                    .and_then(|active| active.read(cx).editing_message),
3593                Some(0)
3594            );
3595        });
3596
3597        // Finish streaming response
3598        cx.update(|_, cx| {
3599            connection.send_update(
3600                session_id.clone(),
3601                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
3602                cx,
3603            );
3604            connection.end_turn(session_id, acp::StopReason::EndTurn);
3605        });
3606
3607        thread_view.read_with(cx, |view, cx| {
3608            assert_eq!(
3609                view.as_active_thread()
3610                    .and_then(|active| active.read(cx).editing_message),
3611                Some(0)
3612            );
3613        });
3614
3615        cx.run_until_parked();
3616
3617        // Should still be editing
3618        cx.update(|window, cx| {
3619            assert!(user_message_editor.focus_handle(cx).is_focused(window));
3620            assert_eq!(
3621                thread_view
3622                    .read(cx)
3623                    .as_active_thread()
3624                    .and_then(|active| active.read(cx).editing_message),
3625                Some(0)
3626            );
3627            assert_eq!(
3628                user_message_editor.read(cx).text(cx),
3629                "Edited message content"
3630            );
3631        });
3632    }
3633
3634    struct GeneratingThreadSetup {
3635        thread_view: Entity<AcpServerView>,
3636        thread: Entity<AcpThread>,
3637        message_editor: Entity<MessageEditor>,
3638    }
3639
3640    async fn setup_generating_thread(
3641        cx: &mut TestAppContext,
3642    ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
3643        let connection = StubAgentConnection::new();
3644
3645        let (thread_view, cx) =
3646            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
3647        add_to_workspace(thread_view.clone(), cx);
3648
3649        let message_editor = message_editor(&thread_view, cx);
3650        message_editor.update_in(cx, |editor, window, cx| {
3651            editor.set_text("Hello", window, cx);
3652        });
3653        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3654
3655        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
3656            let thread = view
3657                .as_active_thread()
3658                .as_ref()
3659                .unwrap()
3660                .read(cx)
3661                .thread
3662                .clone();
3663            (thread.clone(), thread.read(cx).session_id().clone())
3664        });
3665
3666        cx.run_until_parked();
3667
3668        cx.update(|_, cx| {
3669            connection.send_update(
3670                session_id.clone(),
3671                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3672                    "Response chunk".into(),
3673                )),
3674                cx,
3675            );
3676        });
3677
3678        cx.run_until_parked();
3679
3680        thread.read_with(cx, |thread, _cx| {
3681            assert_eq!(thread.status(), ThreadStatus::Generating);
3682        });
3683
3684        (
3685            GeneratingThreadSetup {
3686                thread_view,
3687                thread,
3688                message_editor,
3689            },
3690            cx,
3691        )
3692    }
3693
3694    #[gpui::test]
3695    async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
3696        init_test(cx);
3697
3698        let (setup, cx) = setup_generating_thread(cx).await;
3699
3700        let focus_handle = setup
3701            .thread_view
3702            .read_with(cx, |view, cx| view.focus_handle(cx));
3703        cx.update(|window, cx| {
3704            window.focus(&focus_handle, cx);
3705        });
3706
3707        setup.thread_view.update_in(cx, |_, window, cx| {
3708            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
3709        });
3710
3711        cx.run_until_parked();
3712
3713        setup.thread.read_with(cx, |thread, _cx| {
3714            assert_eq!(thread.status(), ThreadStatus::Idle);
3715        });
3716    }
3717
3718    #[gpui::test]
3719    async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
3720        init_test(cx);
3721
3722        let (setup, cx) = setup_generating_thread(cx).await;
3723
3724        let editor_focus_handle = setup
3725            .message_editor
3726            .read_with(cx, |editor, cx| editor.focus_handle(cx));
3727        cx.update(|window, cx| {
3728            window.focus(&editor_focus_handle, cx);
3729        });
3730
3731        setup.message_editor.update_in(cx, |_, window, cx| {
3732            window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
3733        });
3734
3735        cx.run_until_parked();
3736
3737        setup.thread.read_with(cx, |thread, _cx| {
3738            assert_eq!(thread.status(), ThreadStatus::Idle);
3739        });
3740    }
3741
3742    #[gpui::test]
3743    async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
3744        init_test(cx);
3745
3746        let (thread_view, cx) =
3747            setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
3748        add_to_workspace(thread_view.clone(), cx);
3749
3750        let thread = thread_view.read_with(cx, |view, cx| {
3751            view.as_active_thread().unwrap().read(cx).thread.clone()
3752        });
3753
3754        thread.read_with(cx, |thread, _cx| {
3755            assert_eq!(thread.status(), ThreadStatus::Idle);
3756        });
3757
3758        let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
3759        cx.update(|window, cx| {
3760            window.focus(&focus_handle, cx);
3761        });
3762
3763        thread_view.update_in(cx, |_, window, cx| {
3764            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
3765        });
3766
3767        cx.run_until_parked();
3768
3769        thread.read_with(cx, |thread, _cx| {
3770            assert_eq!(thread.status(), ThreadStatus::Idle);
3771        });
3772    }
3773
3774    #[gpui::test]
3775    async fn test_interrupt(cx: &mut TestAppContext) {
3776        init_test(cx);
3777
3778        let connection = StubAgentConnection::new();
3779
3780        let (thread_view, cx) =
3781            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
3782        add_to_workspace(thread_view.clone(), cx);
3783
3784        let message_editor = message_editor(&thread_view, cx);
3785        message_editor.update_in(cx, |editor, window, cx| {
3786            editor.set_text("Message 1", window, cx);
3787        });
3788        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3789
3790        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
3791            let thread = view.as_active_thread().unwrap().read(cx).thread.clone();
3792
3793            (thread.clone(), thread.read(cx).session_id().clone())
3794        });
3795
3796        cx.run_until_parked();
3797
3798        cx.update(|_, cx| {
3799            connection.send_update(
3800                session_id.clone(),
3801                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3802                    "Message 1 resp".into(),
3803                )),
3804                cx,
3805            );
3806        });
3807
3808        cx.run_until_parked();
3809
3810        thread.read_with(cx, |thread, cx| {
3811            assert_eq!(
3812                thread.to_markdown(cx),
3813                indoc::indoc! {"
3814                        ## User
3815
3816                        Message 1
3817
3818                        ## Assistant
3819
3820                        Message 1 resp
3821
3822                    "}
3823            )
3824        });
3825
3826        message_editor.update_in(cx, |editor, window, cx| {
3827            editor.set_text("Message 2", window, cx);
3828        });
3829        active_thread(&thread_view, cx)
3830            .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
3831
3832        cx.update(|_, cx| {
3833            // Simulate a response sent after beginning to cancel
3834            connection.send_update(
3835                session_id.clone(),
3836                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
3837                cx,
3838            );
3839        });
3840
3841        cx.run_until_parked();
3842
3843        // Last Message 1 response should appear before Message 2
3844        thread.read_with(cx, |thread, cx| {
3845            assert_eq!(
3846                thread.to_markdown(cx),
3847                indoc::indoc! {"
3848                        ## User
3849
3850                        Message 1
3851
3852                        ## Assistant
3853
3854                        Message 1 response
3855
3856                        ## User
3857
3858                        Message 2
3859
3860                    "}
3861            )
3862        });
3863
3864        cx.update(|_, cx| {
3865            connection.send_update(
3866                session_id.clone(),
3867                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3868                    "Message 2 response".into(),
3869                )),
3870                cx,
3871            );
3872            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
3873        });
3874
3875        cx.run_until_parked();
3876
3877        thread.read_with(cx, |thread, cx| {
3878            assert_eq!(
3879                thread.to_markdown(cx),
3880                indoc::indoc! {"
3881                        ## User
3882
3883                        Message 1
3884
3885                        ## Assistant
3886
3887                        Message 1 response
3888
3889                        ## User
3890
3891                        Message 2
3892
3893                        ## Assistant
3894
3895                        Message 2 response
3896
3897                    "}
3898            )
3899        });
3900    }
3901
3902    #[gpui::test]
3903    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
3904        init_test(cx);
3905
3906        let connection = StubAgentConnection::new();
3907        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3908            acp::ContentChunk::new("Response".into()),
3909        )]);
3910
3911        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3912        add_to_workspace(thread_view.clone(), cx);
3913
3914        let message_editor = message_editor(&thread_view, cx);
3915        message_editor.update_in(cx, |editor, window, cx| {
3916            editor.set_text("Original message to edit", window, cx)
3917        });
3918        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3919        cx.run_until_parked();
3920
3921        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
3922            thread_view
3923                .as_active_thread()
3924                .map(|active| &active.read(cx).entry_view_state)
3925                .as_ref()
3926                .unwrap()
3927                .read(cx)
3928                .entry(0)
3929                .expect("Should have at least one entry")
3930                .message_editor()
3931                .expect("Should have message editor")
3932                .clone()
3933        });
3934
3935        cx.focus(&user_message_editor);
3936        thread_view.read_with(cx, |view, cx| {
3937            assert_eq!(
3938                view.as_active_thread()
3939                    .and_then(|active| active.read(cx).editing_message),
3940                Some(0)
3941            );
3942        });
3943
3944        // Ensure to edit the focused message before proceeding otherwise, since
3945        // its content is not different from what was sent, focus will be lost.
3946        user_message_editor.update_in(cx, |editor, window, cx| {
3947            editor.set_text("Original message to edit with ", window, cx)
3948        });
3949
3950        // Create a simple buffer with some text so we can create a selection
3951        // that will then be added to the message being edited.
3952        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
3953            (thread_view.workspace.clone(), thread_view.project.clone())
3954        });
3955        let buffer = project.update(cx, |project, cx| {
3956            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
3957        });
3958
3959        workspace
3960            .update_in(cx, |workspace, window, cx| {
3961                let editor = cx.new(|cx| {
3962                    let mut editor =
3963                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
3964
3965                    editor.change_selections(Default::default(), window, cx, |selections| {
3966                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
3967                    });
3968
3969                    editor
3970                });
3971                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
3972            })
3973            .unwrap();
3974
3975        thread_view.update_in(cx, |view, window, cx| {
3976            assert_eq!(
3977                view.as_active_thread()
3978                    .and_then(|active| active.read(cx).editing_message),
3979                Some(0)
3980            );
3981            view.insert_selections(window, cx);
3982        });
3983
3984        user_message_editor.read_with(cx, |editor, cx| {
3985            let text = editor.editor().read(cx).text(cx);
3986            let expected_text = String::from("Original message to edit with selection ");
3987
3988            assert_eq!(text, expected_text);
3989        });
3990    }
3991
3992    #[gpui::test]
3993    async fn test_insert_selections(cx: &mut TestAppContext) {
3994        init_test(cx);
3995
3996        let connection = StubAgentConnection::new();
3997        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3998            acp::ContentChunk::new("Response".into()),
3999        )]);
4000
4001        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4002        add_to_workspace(thread_view.clone(), cx);
4003
4004        let message_editor = message_editor(&thread_view, cx);
4005        message_editor.update_in(cx, |editor, window, cx| {
4006            editor.set_text("Can you review this snippet ", window, cx)
4007        });
4008
4009        // Create a simple buffer with some text so we can create a selection
4010        // that will then be added to the message being edited.
4011        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
4012            (thread_view.workspace.clone(), thread_view.project.clone())
4013        });
4014        let buffer = project.update(cx, |project, cx| {
4015            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
4016        });
4017
4018        workspace
4019            .update_in(cx, |workspace, window, cx| {
4020                let editor = cx.new(|cx| {
4021                    let mut editor =
4022                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
4023
4024                    editor.change_selections(Default::default(), window, cx, |selections| {
4025                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
4026                    });
4027
4028                    editor
4029                });
4030                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
4031            })
4032            .unwrap();
4033
4034        thread_view.update_in(cx, |view, window, cx| {
4035            assert_eq!(
4036                view.as_active_thread()
4037                    .and_then(|active| active.read(cx).editing_message),
4038                None
4039            );
4040            view.insert_selections(window, cx);
4041        });
4042
4043        message_editor.read_with(cx, |editor, cx| {
4044            let text = editor.text(cx);
4045            let expected_txt = String::from("Can you review this snippet selection ");
4046
4047            assert_eq!(text, expected_txt);
4048        })
4049    }
4050
4051    #[gpui::test]
4052    async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
4053        init_test(cx);
4054
4055        let tool_call_id = acp::ToolCallId::new("terminal-1");
4056        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
4057            .kind(acp::ToolKind::Edit);
4058
4059        let permission_options =
4060            ToolPermissionContext::new(TerminalTool::NAME, "cargo build --release")
4061                .build_permission_options();
4062
4063        let connection =
4064            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4065                tool_call_id.clone(),
4066                permission_options,
4067            )]));
4068
4069        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4070
4071        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4072
4073        // Disable notifications to avoid popup windows
4074        cx.update(|_window, cx| {
4075            AgentSettings::override_global(
4076                AgentSettings {
4077                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4078                    ..AgentSettings::get_global(cx).clone()
4079                },
4080                cx,
4081            );
4082        });
4083
4084        let message_editor = message_editor(&thread_view, cx);
4085        message_editor.update_in(cx, |editor, window, cx| {
4086            editor.set_text("Run cargo build", window, cx);
4087        });
4088
4089        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4090
4091        cx.run_until_parked();
4092
4093        // Verify the tool call is in WaitingForConfirmation state with the expected options
4094        thread_view.read_with(cx, |thread_view, cx| {
4095            let thread = thread_view
4096                .as_active_thread()
4097                .expect("Thread should exist")
4098                .read(cx)
4099                .thread
4100                .clone();
4101            let thread = thread.read(cx);
4102
4103            let tool_call = thread.entries().iter().find_map(|entry| {
4104                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
4105                    Some(call)
4106                } else {
4107                    None
4108                }
4109            });
4110
4111            assert!(tool_call.is_some(), "Expected a tool call entry");
4112            let tool_call = tool_call.unwrap();
4113
4114            // Verify it's waiting for confirmation
4115            assert!(
4116                matches!(
4117                    tool_call.status,
4118                    acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
4119                ),
4120                "Expected WaitingForConfirmation status, got {:?}",
4121                tool_call.status
4122            );
4123
4124            // Verify the options count (granularity options only, no separate Deny option)
4125            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
4126                &tool_call.status
4127            {
4128                let PermissionOptions::Dropdown(choices) = options else {
4129                    panic!("Expected dropdown permission options");
4130                };
4131
4132                assert_eq!(
4133                    choices.len(),
4134                    3,
4135                    "Expected 3 permission options (granularity only)"
4136                );
4137
4138                // Verify specific button labels (now using neutral names)
4139                let labels: Vec<&str> = choices
4140                    .iter()
4141                    .map(|choice| choice.allow.name.as_ref())
4142                    .collect();
4143                assert!(
4144                    labels.contains(&"Always for terminal"),
4145                    "Missing 'Always for terminal' option"
4146                );
4147                assert!(
4148                    labels.contains(&"Always for `cargo` commands"),
4149                    "Missing pattern option"
4150                );
4151                assert!(
4152                    labels.contains(&"Only this time"),
4153                    "Missing 'Only this time' option"
4154                );
4155            }
4156        });
4157    }
4158
4159    #[gpui::test]
4160    async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
4161        init_test(cx);
4162
4163        let tool_call_id = acp::ToolCallId::new("edit-file-1");
4164        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
4165            .kind(acp::ToolKind::Edit);
4166
4167        let permission_options = ToolPermissionContext::new(EditFileTool::NAME, "src/main.rs")
4168            .build_permission_options();
4169
4170        let connection =
4171            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4172                tool_call_id.clone(),
4173                permission_options,
4174            )]));
4175
4176        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4177
4178        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4179
4180        // Disable notifications
4181        cx.update(|_window, cx| {
4182            AgentSettings::override_global(
4183                AgentSettings {
4184                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4185                    ..AgentSettings::get_global(cx).clone()
4186                },
4187                cx,
4188            );
4189        });
4190
4191        let message_editor = message_editor(&thread_view, cx);
4192        message_editor.update_in(cx, |editor, window, cx| {
4193            editor.set_text("Edit the main file", window, cx);
4194        });
4195
4196        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4197
4198        cx.run_until_parked();
4199
4200        // Verify the options
4201        thread_view.read_with(cx, |thread_view, cx| {
4202            let thread = thread_view
4203                .as_active_thread()
4204                .expect("Thread should exist")
4205                .read(cx)
4206                .thread
4207                .clone();
4208            let thread = thread.read(cx);
4209
4210            let tool_call = thread.entries().iter().find_map(|entry| {
4211                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
4212                    Some(call)
4213                } else {
4214                    None
4215                }
4216            });
4217
4218            assert!(tool_call.is_some(), "Expected a tool call entry");
4219            let tool_call = tool_call.unwrap();
4220
4221            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
4222                &tool_call.status
4223            {
4224                let PermissionOptions::Dropdown(choices) = options else {
4225                    panic!("Expected dropdown permission options");
4226                };
4227
4228                let labels: Vec<&str> = choices
4229                    .iter()
4230                    .map(|choice| choice.allow.name.as_ref())
4231                    .collect();
4232                assert!(
4233                    labels.contains(&"Always for edit file"),
4234                    "Missing 'Always for edit file' option"
4235                );
4236                assert!(
4237                    labels.contains(&"Always for `src/`"),
4238                    "Missing path pattern option"
4239                );
4240            } else {
4241                panic!("Expected WaitingForConfirmation status");
4242            }
4243        });
4244    }
4245
4246    #[gpui::test]
4247    async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
4248        init_test(cx);
4249
4250        let tool_call_id = acp::ToolCallId::new("fetch-1");
4251        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
4252            .kind(acp::ToolKind::Fetch);
4253
4254        let permission_options =
4255            ToolPermissionContext::new(FetchTool::NAME, "https://docs.rs/gpui")
4256                .build_permission_options();
4257
4258        let connection =
4259            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4260                tool_call_id.clone(),
4261                permission_options,
4262            )]));
4263
4264        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4265
4266        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4267
4268        // Disable notifications
4269        cx.update(|_window, cx| {
4270            AgentSettings::override_global(
4271                AgentSettings {
4272                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4273                    ..AgentSettings::get_global(cx).clone()
4274                },
4275                cx,
4276            );
4277        });
4278
4279        let message_editor = message_editor(&thread_view, cx);
4280        message_editor.update_in(cx, |editor, window, cx| {
4281            editor.set_text("Fetch the docs", window, cx);
4282        });
4283
4284        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4285
4286        cx.run_until_parked();
4287
4288        // Verify the options
4289        thread_view.read_with(cx, |thread_view, cx| {
4290            let thread = thread_view
4291                .as_active_thread()
4292                .expect("Thread should exist")
4293                .read(cx)
4294                .thread
4295                .clone();
4296            let thread = thread.read(cx);
4297
4298            let tool_call = thread.entries().iter().find_map(|entry| {
4299                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
4300                    Some(call)
4301                } else {
4302                    None
4303                }
4304            });
4305
4306            assert!(tool_call.is_some(), "Expected a tool call entry");
4307            let tool_call = tool_call.unwrap();
4308
4309            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
4310                &tool_call.status
4311            {
4312                let PermissionOptions::Dropdown(choices) = options else {
4313                    panic!("Expected dropdown permission options");
4314                };
4315
4316                let labels: Vec<&str> = choices
4317                    .iter()
4318                    .map(|choice| choice.allow.name.as_ref())
4319                    .collect();
4320                assert!(
4321                    labels.contains(&"Always for fetch"),
4322                    "Missing 'Always for fetch' option"
4323                );
4324                assert!(
4325                    labels.contains(&"Always for `docs.rs`"),
4326                    "Missing domain pattern option"
4327                );
4328            } else {
4329                panic!("Expected WaitingForConfirmation status");
4330            }
4331        });
4332    }
4333
4334    #[gpui::test]
4335    async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
4336        init_test(cx);
4337
4338        let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
4339        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
4340            .kind(acp::ToolKind::Edit);
4341
4342        // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
4343        let permission_options =
4344            ToolPermissionContext::new(TerminalTool::NAME, "./deploy.sh --production")
4345                .build_permission_options();
4346
4347        let connection =
4348            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4349                tool_call_id.clone(),
4350                permission_options,
4351            )]));
4352
4353        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4354
4355        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4356
4357        // Disable notifications
4358        cx.update(|_window, cx| {
4359            AgentSettings::override_global(
4360                AgentSettings {
4361                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4362                    ..AgentSettings::get_global(cx).clone()
4363                },
4364                cx,
4365            );
4366        });
4367
4368        let message_editor = message_editor(&thread_view, cx);
4369        message_editor.update_in(cx, |editor, window, cx| {
4370            editor.set_text("Run the deploy script", window, cx);
4371        });
4372
4373        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4374
4375        cx.run_until_parked();
4376
4377        // Verify only 2 options (no pattern button when command doesn't match pattern)
4378        thread_view.read_with(cx, |thread_view, cx| {
4379            let thread = thread_view
4380                .as_active_thread()
4381                .expect("Thread should exist")
4382                .read(cx)
4383                .thread
4384                .clone();
4385            let thread = thread.read(cx);
4386
4387            let tool_call = thread.entries().iter().find_map(|entry| {
4388                if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
4389                    Some(call)
4390                } else {
4391                    None
4392                }
4393            });
4394
4395            assert!(tool_call.is_some(), "Expected a tool call entry");
4396            let tool_call = tool_call.unwrap();
4397
4398            if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
4399                &tool_call.status
4400            {
4401                let PermissionOptions::Dropdown(choices) = options else {
4402                    panic!("Expected dropdown permission options");
4403                };
4404
4405                assert_eq!(
4406                    choices.len(),
4407                    2,
4408                    "Expected 2 permission options (no pattern option)"
4409                );
4410
4411                let labels: Vec<&str> = choices
4412                    .iter()
4413                    .map(|choice| choice.allow.name.as_ref())
4414                    .collect();
4415                assert!(
4416                    labels.contains(&"Always for terminal"),
4417                    "Missing 'Always for terminal' option"
4418                );
4419                assert!(
4420                    labels.contains(&"Only this time"),
4421                    "Missing 'Only this time' option"
4422                );
4423                // Should NOT contain a pattern option
4424                assert!(
4425                    !labels.iter().any(|l| l.contains("commands")),
4426                    "Should not have pattern option"
4427                );
4428            } else {
4429                panic!("Expected WaitingForConfirmation status");
4430            }
4431        });
4432    }
4433
4434    #[gpui::test]
4435    async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
4436        init_test(cx);
4437
4438        let tool_call_id = acp::ToolCallId::new("action-test-1");
4439        let tool_call =
4440            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
4441
4442        let permission_options =
4443            ToolPermissionContext::new(TerminalTool::NAME, "cargo test").build_permission_options();
4444
4445        let connection =
4446            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4447                tool_call_id.clone(),
4448                permission_options,
4449            )]));
4450
4451        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4452
4453        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4454        add_to_workspace(thread_view.clone(), cx);
4455
4456        cx.update(|_window, cx| {
4457            AgentSettings::override_global(
4458                AgentSettings {
4459                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4460                    ..AgentSettings::get_global(cx).clone()
4461                },
4462                cx,
4463            );
4464        });
4465
4466        let message_editor = message_editor(&thread_view, cx);
4467        message_editor.update_in(cx, |editor, window, cx| {
4468            editor.set_text("Run tests", window, cx);
4469        });
4470
4471        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4472
4473        cx.run_until_parked();
4474
4475        // Verify tool call is waiting for confirmation
4476        thread_view.read_with(cx, |thread_view, cx| {
4477            let thread = thread_view
4478                .as_active_thread()
4479                .expect("Thread should exist")
4480                .read(cx)
4481                .thread
4482                .clone();
4483            let thread = thread.read(cx);
4484            let tool_call = thread.first_tool_awaiting_confirmation();
4485            assert!(
4486                tool_call.is_some(),
4487                "Expected a tool call waiting for confirmation"
4488            );
4489        });
4490
4491        // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
4492        thread_view.update_in(cx, |_, window, cx| {
4493            window.dispatch_action(
4494                crate::AuthorizeToolCall {
4495                    tool_call_id: "action-test-1".to_string(),
4496                    option_id: "allow".to_string(),
4497                    option_kind: "AllowOnce".to_string(),
4498                }
4499                .boxed_clone(),
4500                cx,
4501            );
4502        });
4503
4504        cx.run_until_parked();
4505
4506        // Verify tool call is no longer waiting for confirmation (was authorized)
4507        thread_view.read_with(cx, |thread_view, cx| {
4508                let thread = thread_view.as_active_thread().expect("Thread should exist").read(cx).thread.clone();
4509                let thread = thread.read(cx);
4510                let tool_call = thread.first_tool_awaiting_confirmation();
4511                assert!(
4512                    tool_call.is_none(),
4513                    "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
4514                );
4515            });
4516    }
4517
4518    #[gpui::test]
4519    async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
4520        init_test(cx);
4521
4522        let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
4523        let tool_call =
4524            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
4525
4526        let permission_options = ToolPermissionContext::new(TerminalTool::NAME, "npm install")
4527            .build_permission_options();
4528
4529        let connection =
4530            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4531                tool_call_id.clone(),
4532                permission_options.clone(),
4533            )]));
4534
4535        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4536
4537        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4538        add_to_workspace(thread_view.clone(), cx);
4539
4540        cx.update(|_window, cx| {
4541            AgentSettings::override_global(
4542                AgentSettings {
4543                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4544                    ..AgentSettings::get_global(cx).clone()
4545                },
4546                cx,
4547            );
4548        });
4549
4550        let message_editor = message_editor(&thread_view, cx);
4551        message_editor.update_in(cx, |editor, window, cx| {
4552            editor.set_text("Install dependencies", window, cx);
4553        });
4554
4555        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4556
4557        cx.run_until_parked();
4558
4559        // Find the pattern option ID
4560        let pattern_option = match &permission_options {
4561            PermissionOptions::Dropdown(choices) => choices
4562                .iter()
4563                .find(|choice| {
4564                    choice
4565                        .allow
4566                        .option_id
4567                        .0
4568                        .starts_with("always_allow_pattern:")
4569                })
4570                .map(|choice| &choice.allow)
4571                .expect("Should have a pattern option for npm command"),
4572            _ => panic!("Expected dropdown permission options"),
4573        };
4574
4575        // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
4576        thread_view.update_in(cx, |_, window, cx| {
4577            window.dispatch_action(
4578                crate::AuthorizeToolCall {
4579                    tool_call_id: "pattern-action-test-1".to_string(),
4580                    option_id: pattern_option.option_id.0.to_string(),
4581                    option_kind: "AllowAlways".to_string(),
4582                }
4583                .boxed_clone(),
4584                cx,
4585            );
4586        });
4587
4588        cx.run_until_parked();
4589
4590        // Verify tool call was authorized
4591        thread_view.read_with(cx, |thread_view, cx| {
4592            let thread = thread_view
4593                .as_active_thread()
4594                .expect("Thread should exist")
4595                .read(cx)
4596                .thread
4597                .clone();
4598            let thread = thread.read(cx);
4599            let tool_call = thread.first_tool_awaiting_confirmation();
4600            assert!(
4601                tool_call.is_none(),
4602                "Tool call should be authorized after selecting pattern option"
4603            );
4604        });
4605    }
4606
4607    #[gpui::test]
4608    async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
4609        init_test(cx);
4610
4611        let tool_call_id = acp::ToolCallId::new("granularity-test-1");
4612        let tool_call =
4613            acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
4614
4615        let permission_options = ToolPermissionContext::new(TerminalTool::NAME, "cargo build")
4616            .build_permission_options();
4617
4618        let connection =
4619            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4620                tool_call_id.clone(),
4621                permission_options.clone(),
4622            )]));
4623
4624        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4625
4626        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4627        add_to_workspace(thread_view.clone(), cx);
4628
4629        cx.update(|_window, cx| {
4630            AgentSettings::override_global(
4631                AgentSettings {
4632                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4633                    ..AgentSettings::get_global(cx).clone()
4634                },
4635                cx,
4636            );
4637        });
4638
4639        let message_editor = message_editor(&thread_view, cx);
4640        message_editor.update_in(cx, |editor, window, cx| {
4641            editor.set_text("Build the project", window, cx);
4642        });
4643
4644        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4645
4646        cx.run_until_parked();
4647
4648        // Verify default granularity is the last option (index 2 = "Only this time")
4649        thread_view.read_with(cx, |thread_view, cx| {
4650            let state = thread_view.as_active_thread().unwrap();
4651            let selected = state
4652                .read(cx)
4653                .selected_permission_granularity
4654                .get(&tool_call_id);
4655            assert!(
4656                selected.is_none(),
4657                "Should have no selection initially (defaults to last)"
4658            );
4659        });
4660
4661        // Select the first option (index 0 = "Always for terminal")
4662        thread_view.update_in(cx, |_, window, cx| {
4663            window.dispatch_action(
4664                crate::SelectPermissionGranularity {
4665                    tool_call_id: "granularity-test-1".to_string(),
4666                    index: 0,
4667                }
4668                .boxed_clone(),
4669                cx,
4670            );
4671        });
4672
4673        cx.run_until_parked();
4674
4675        // Verify the selection was updated
4676        thread_view.read_with(cx, |thread_view, cx| {
4677            let state = thread_view.as_active_thread().unwrap();
4678            let selected = state
4679                .read(cx)
4680                .selected_permission_granularity
4681                .get(&tool_call_id);
4682            assert_eq!(selected, Some(&0), "Should have selected index 0");
4683        });
4684    }
4685
4686    #[gpui::test]
4687    async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
4688        init_test(cx);
4689
4690        let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
4691        let tool_call =
4692            acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
4693
4694        let permission_options = ToolPermissionContext::new(TerminalTool::NAME, "npm install")
4695            .build_permission_options();
4696
4697        // Verify we have the expected options
4698        let PermissionOptions::Dropdown(choices) = &permission_options else {
4699            panic!("Expected dropdown permission options");
4700        };
4701
4702        assert_eq!(choices.len(), 3);
4703        assert!(
4704            choices[0]
4705                .allow
4706                .option_id
4707                .0
4708                .contains("always_allow:terminal")
4709        );
4710        assert!(
4711            choices[1]
4712                .allow
4713                .option_id
4714                .0
4715                .contains("always_allow_pattern:terminal")
4716        );
4717        assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
4718
4719        let connection =
4720            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4721                tool_call_id.clone(),
4722                permission_options.clone(),
4723            )]));
4724
4725        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4726
4727        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4728        add_to_workspace(thread_view.clone(), cx);
4729
4730        cx.update(|_window, cx| {
4731            AgentSettings::override_global(
4732                AgentSettings {
4733                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4734                    ..AgentSettings::get_global(cx).clone()
4735                },
4736                cx,
4737            );
4738        });
4739
4740        let message_editor = message_editor(&thread_view, cx);
4741        message_editor.update_in(cx, |editor, window, cx| {
4742            editor.set_text("Install dependencies", window, cx);
4743        });
4744
4745        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4746
4747        cx.run_until_parked();
4748
4749        // Select the pattern option (index 1 = "Always for `npm` commands")
4750        thread_view.update_in(cx, |_, window, cx| {
4751            window.dispatch_action(
4752                crate::SelectPermissionGranularity {
4753                    tool_call_id: "allow-granularity-test-1".to_string(),
4754                    index: 1,
4755                }
4756                .boxed_clone(),
4757                cx,
4758            );
4759        });
4760
4761        cx.run_until_parked();
4762
4763        // Simulate clicking the Allow button by dispatching AllowOnce action
4764        // which should use the selected granularity
4765        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
4766            view.allow_once(&AllowOnce, window, cx)
4767        });
4768
4769        cx.run_until_parked();
4770
4771        // Verify tool call was authorized
4772        thread_view.read_with(cx, |thread_view, cx| {
4773            let thread = thread_view
4774                .as_active_thread()
4775                .expect("Thread should exist")
4776                .read(cx)
4777                .thread
4778                .clone();
4779            let thread = thread.read(cx);
4780            let tool_call = thread.first_tool_awaiting_confirmation();
4781            assert!(
4782                tool_call.is_none(),
4783                "Tool call should be authorized after Allow with pattern granularity"
4784            );
4785        });
4786    }
4787
4788    #[gpui::test]
4789    async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
4790        init_test(cx);
4791
4792        let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
4793        let tool_call =
4794            acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
4795
4796        let permission_options =
4797            ToolPermissionContext::new(TerminalTool::NAME, "git push").build_permission_options();
4798
4799        let connection =
4800            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4801                tool_call_id.clone(),
4802                permission_options.clone(),
4803            )]));
4804
4805        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4806
4807        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4808        add_to_workspace(thread_view.clone(), cx);
4809
4810        cx.update(|_window, cx| {
4811            AgentSettings::override_global(
4812                AgentSettings {
4813                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4814                    ..AgentSettings::get_global(cx).clone()
4815                },
4816                cx,
4817            );
4818        });
4819
4820        let message_editor = message_editor(&thread_view, cx);
4821        message_editor.update_in(cx, |editor, window, cx| {
4822            editor.set_text("Push changes", window, cx);
4823        });
4824
4825        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4826
4827        cx.run_until_parked();
4828
4829        // Use default granularity (last option = "Only this time")
4830        // Simulate clicking the Deny button
4831        active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
4832            view.reject_once(&RejectOnce, window, cx)
4833        });
4834
4835        cx.run_until_parked();
4836
4837        // Verify tool call was rejected (no longer waiting for confirmation)
4838        thread_view.read_with(cx, |thread_view, cx| {
4839            let thread = thread_view
4840                .as_active_thread()
4841                .expect("Thread should exist")
4842                .read(cx)
4843                .thread
4844                .clone();
4845            let thread = thread.read(cx);
4846            let tool_call = thread.first_tool_awaiting_confirmation();
4847            assert!(
4848                tool_call.is_none(),
4849                "Tool call should be rejected after Deny"
4850            );
4851        });
4852    }
4853
4854    #[gpui::test]
4855    async fn test_option_id_transformation_for_allow() {
4856        let permission_options =
4857            ToolPermissionContext::new(TerminalTool::NAME, "cargo build --release")
4858                .build_permission_options();
4859
4860        let PermissionOptions::Dropdown(choices) = permission_options else {
4861            panic!("Expected dropdown permission options");
4862        };
4863
4864        let allow_ids: Vec<String> = choices
4865            .iter()
4866            .map(|choice| choice.allow.option_id.0.to_string())
4867            .collect();
4868
4869        assert!(allow_ids.contains(&"always_allow:terminal".to_string()));
4870        assert!(allow_ids.contains(&"allow".to_string()));
4871        assert!(
4872            allow_ids
4873                .iter()
4874                .any(|id| id.starts_with("always_allow_pattern:terminal:")),
4875            "Missing allow pattern option"
4876        );
4877    }
4878
4879    #[gpui::test]
4880    async fn test_option_id_transformation_for_deny() {
4881        let permission_options =
4882            ToolPermissionContext::new(TerminalTool::NAME, "cargo build --release")
4883                .build_permission_options();
4884
4885        let PermissionOptions::Dropdown(choices) = permission_options else {
4886            panic!("Expected dropdown permission options");
4887        };
4888
4889        let deny_ids: Vec<String> = choices
4890            .iter()
4891            .map(|choice| choice.deny.option_id.0.to_string())
4892            .collect();
4893
4894        assert!(deny_ids.contains(&"always_deny:terminal".to_string()));
4895        assert!(deny_ids.contains(&"deny".to_string()));
4896        assert!(
4897            deny_ids
4898                .iter()
4899                .any(|id| id.starts_with("always_deny_pattern:terminal:")),
4900            "Missing deny pattern option"
4901        );
4902    }
4903}