thread_view.rs

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