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