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