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