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