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