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