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