thread_view.rs

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