thread_view.rs

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