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!(
3743                                "{separator}{}{separator}",
3744                                parent.display(path_style)
3745                            ))
3746                            .color(Color::Muted)
3747                            .size(LabelSize::XSmall)
3748                            .buffer_font(cx),
3749                        )
3750                    }
3751                });
3752
3753                let file_name = path.file_name().map(|name| {
3754                    Label::new(name.to_string())
3755                        .size(LabelSize::XSmall)
3756                        .buffer_font(cx)
3757                });
3758
3759                let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
3760                    .map(Icon::from_path)
3761                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3762                    .unwrap_or_else(|| {
3763                        Icon::new(IconName::File)
3764                            .color(Color::Muted)
3765                            .size(IconSize::Small)
3766                    });
3767
3768                let overlay_gradient = linear_gradient(
3769                    90.,
3770                    linear_color_stop(editor_bg_color, 1.),
3771                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3772                );
3773
3774                let element = h_flex()
3775                    .group("edited-code")
3776                    .id(("file-container", index))
3777                    .py_1()
3778                    .pl_2()
3779                    .pr_1()
3780                    .gap_2()
3781                    .justify_between()
3782                    .bg(editor_bg_color)
3783                    .when(index < changed_buffers.len() - 1, |parent| {
3784                        parent.border_color(cx.theme().colors().border).border_b_1()
3785                    })
3786                    .child(
3787                        h_flex()
3788                            .relative()
3789                            .id(("file-name", index))
3790                            .pr_8()
3791                            .gap_1p5()
3792                            .max_w_full()
3793                            .overflow_x_scroll()
3794                            .child(file_icon)
3795                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3796                            .child(
3797                                div()
3798                                    .absolute()
3799                                    .h_full()
3800                                    .w_12()
3801                                    .top_0()
3802                                    .bottom_0()
3803                                    .right_0()
3804                                    .bg(overlay_gradient),
3805                            )
3806                            .on_click({
3807                                let buffer = buffer.clone();
3808                                cx.listener(move |this, _, window, cx| {
3809                                    this.open_edited_buffer(&buffer, window, cx);
3810                                })
3811                            }),
3812                    )
3813                    .child(
3814                        h_flex()
3815                            .gap_1()
3816                            .visible_on_hover("edited-code")
3817                            .child(
3818                                Button::new("review", "Review")
3819                                    .label_size(LabelSize::Small)
3820                                    .on_click({
3821                                        let buffer = buffer.clone();
3822                                        cx.listener(move |this, _, window, cx| {
3823                                            this.open_edited_buffer(&buffer, window, cx);
3824                                        })
3825                                    }),
3826                            )
3827                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3828                            .child(
3829                                Button::new("reject-file", "Reject")
3830                                    .label_size(LabelSize::Small)
3831                                    .disabled(pending_edits)
3832                                    .on_click({
3833                                        let buffer = buffer.clone();
3834                                        let action_log = action_log.clone();
3835                                        move |_, _, cx| {
3836                                            action_log.update(cx, |action_log, cx| {
3837                                                action_log
3838                                                    .reject_edits_in_ranges(
3839                                                        buffer.clone(),
3840                                                        vec![Anchor::MIN..Anchor::MAX],
3841                                                        cx,
3842                                                    )
3843                                                    .detach_and_log_err(cx);
3844                                            })
3845                                        }
3846                                    }),
3847                            )
3848                            .child(
3849                                Button::new("keep-file", "Keep")
3850                                    .label_size(LabelSize::Small)
3851                                    .disabled(pending_edits)
3852                                    .on_click({
3853                                        let buffer = buffer.clone();
3854                                        let action_log = action_log.clone();
3855                                        move |_, _, cx| {
3856                                            action_log.update(cx, |action_log, cx| {
3857                                                action_log.keep_edits_in_range(
3858                                                    buffer.clone(),
3859                                                    Anchor::MIN..Anchor::MAX,
3860                                                    cx,
3861                                                );
3862                                            })
3863                                        }
3864                                    }),
3865                            ),
3866                    );
3867
3868                Some(element)
3869            },
3870        ))
3871    }
3872
3873    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3874        let focus_handle = self.message_editor.focus_handle(cx);
3875        let editor_bg_color = cx.theme().colors().editor_background;
3876        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3877            (IconName::Minimize, "Minimize Message Editor")
3878        } else {
3879            (IconName::Maximize, "Expand Message Editor")
3880        };
3881
3882        let backdrop = div()
3883            .size_full()
3884            .absolute()
3885            .inset_0()
3886            .bg(cx.theme().colors().panel_background)
3887            .opacity(0.8)
3888            .block_mouse_except_scroll();
3889
3890        let enable_editor = match self.thread_state {
3891            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3892            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3893        };
3894
3895        v_flex()
3896            .on_action(cx.listener(Self::expand_message_editor))
3897            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3898                if let Some(profile_selector) = this.profile_selector.as_ref() {
3899                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3900                } else if let Some(mode_selector) = this.mode_selector() {
3901                    mode_selector.read(cx).menu_handle().toggle(window, cx);
3902                }
3903            }))
3904            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
3905                if let Some(mode_selector) = this.mode_selector() {
3906                    mode_selector.update(cx, |mode_selector, cx| {
3907                        mode_selector.cycle_mode(window, cx);
3908                    });
3909                }
3910            }))
3911            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3912                if let Some(model_selector) = this.model_selector.as_ref() {
3913                    model_selector
3914                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3915                }
3916            }))
3917            .p_2()
3918            .gap_2()
3919            .border_t_1()
3920            .border_color(cx.theme().colors().border)
3921            .bg(editor_bg_color)
3922            .when(self.editor_expanded, |this| {
3923                this.h(vh(0.8, window)).size_full().justify_between()
3924            })
3925            .child(
3926                v_flex()
3927                    .relative()
3928                    .size_full()
3929                    .pt_1()
3930                    .pr_2p5()
3931                    .child(self.message_editor.clone())
3932                    .child(
3933                        h_flex()
3934                            .absolute()
3935                            .top_0()
3936                            .right_0()
3937                            .opacity(0.5)
3938                            .hover(|this| this.opacity(1.0))
3939                            .child(
3940                                IconButton::new("toggle-height", expand_icon)
3941                                    .icon_size(IconSize::Small)
3942                                    .icon_color(Color::Muted)
3943                                    .tooltip({
3944                                        move |window, cx| {
3945                                            Tooltip::for_action_in(
3946                                                expand_tooltip,
3947                                                &ExpandMessageEditor,
3948                                                &focus_handle,
3949                                                window,
3950                                                cx,
3951                                            )
3952                                        }
3953                                    })
3954                                    .on_click(cx.listener(|_, _, window, cx| {
3955                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3956                                    })),
3957                            ),
3958                    ),
3959            )
3960            .child(
3961                h_flex()
3962                    .flex_none()
3963                    .flex_wrap()
3964                    .justify_between()
3965                    .child(
3966                        h_flex()
3967                            .child(self.render_follow_toggle(cx))
3968                            .children(self.render_burn_mode_toggle(cx)),
3969                    )
3970                    .child(
3971                        h_flex()
3972                            .gap_1()
3973                            .children(self.render_token_usage(cx))
3974                            .children(self.profile_selector.clone())
3975                            .children(self.mode_selector().cloned())
3976                            .children(self.model_selector.clone())
3977                            .child(self.render_send_button(cx)),
3978                    ),
3979            )
3980            .when(!enable_editor, |this| this.child(backdrop))
3981            .into_any()
3982    }
3983
3984    pub(crate) fn as_native_connection(
3985        &self,
3986        cx: &App,
3987    ) -> Option<Rc<agent2::NativeAgentConnection>> {
3988        let acp_thread = self.thread()?.read(cx);
3989        acp_thread.connection().clone().downcast()
3990    }
3991
3992    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3993        let acp_thread = self.thread()?.read(cx);
3994        self.as_native_connection(cx)?
3995            .thread(acp_thread.session_id(), cx)
3996    }
3997
3998    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3999        self.as_native_thread(cx)
4000            .and_then(|thread| thread.read(cx).model())
4001            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4002    }
4003
4004    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4005        let thread = self.thread()?.read(cx);
4006        let usage = thread.token_usage()?;
4007        let is_generating = thread.status() != ThreadStatus::Idle;
4008
4009        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4010        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4011
4012        Some(
4013            h_flex()
4014                .flex_shrink_0()
4015                .gap_0p5()
4016                .mr_1p5()
4017                .child(
4018                    Label::new(used)
4019                        .size(LabelSize::Small)
4020                        .color(Color::Muted)
4021                        .map(|label| {
4022                            if is_generating {
4023                                label
4024                                    .with_animation(
4025                                        "used-tokens-label",
4026                                        Animation::new(Duration::from_secs(2))
4027                                            .repeat()
4028                                            .with_easing(pulsating_between(0.3, 0.8)),
4029                                        |label, delta| label.alpha(delta),
4030                                    )
4031                                    .into_any()
4032                            } else {
4033                                label.into_any_element()
4034                            }
4035                        }),
4036                )
4037                .child(
4038                    Label::new("/")
4039                        .size(LabelSize::Small)
4040                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4041                )
4042                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4043        )
4044    }
4045
4046    fn toggle_burn_mode(
4047        &mut self,
4048        _: &ToggleBurnMode,
4049        _window: &mut Window,
4050        cx: &mut Context<Self>,
4051    ) {
4052        let Some(thread) = self.as_native_thread(cx) else {
4053            return;
4054        };
4055
4056        thread.update(cx, |thread, cx| {
4057            let current_mode = thread.completion_mode();
4058            thread.set_completion_mode(
4059                match current_mode {
4060                    CompletionMode::Burn => CompletionMode::Normal,
4061                    CompletionMode::Normal => CompletionMode::Burn,
4062                },
4063                cx,
4064            );
4065        });
4066    }
4067
4068    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4069        let Some(thread) = self.thread() else {
4070            return;
4071        };
4072        let action_log = thread.read(cx).action_log().clone();
4073        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
4074    }
4075
4076    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4077        let Some(thread) = self.thread() else {
4078            return;
4079        };
4080        let action_log = thread.read(cx).action_log().clone();
4081        action_log
4082            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
4083            .detach();
4084    }
4085
4086    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4087        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4088    }
4089
4090    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4091        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4092    }
4093
4094    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4095        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4096    }
4097
4098    fn authorize_pending_tool_call(
4099        &mut self,
4100        kind: acp::PermissionOptionKind,
4101        window: &mut Window,
4102        cx: &mut Context<Self>,
4103    ) -> Option<()> {
4104        let thread = self.thread()?.read(cx);
4105        let tool_call = thread.first_tool_awaiting_confirmation()?;
4106        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4107            return None;
4108        };
4109        let option = options.iter().find(|o| o.kind == kind)?;
4110
4111        self.authorize_tool_call(
4112            tool_call.id.clone(),
4113            option.id.clone(),
4114            option.kind,
4115            window,
4116            cx,
4117        );
4118
4119        Some(())
4120    }
4121
4122    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4123        let thread = self.as_native_thread(cx)?.read(cx);
4124
4125        if thread
4126            .model()
4127            .is_none_or(|model| !model.supports_burn_mode())
4128        {
4129            return None;
4130        }
4131
4132        let active_completion_mode = thread.completion_mode();
4133        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4134        let icon = if burn_mode_enabled {
4135            IconName::ZedBurnModeOn
4136        } else {
4137            IconName::ZedBurnMode
4138        };
4139
4140        Some(
4141            IconButton::new("burn-mode", icon)
4142                .icon_size(IconSize::Small)
4143                .icon_color(Color::Muted)
4144                .toggle_state(burn_mode_enabled)
4145                .selected_icon_color(Color::Error)
4146                .on_click(cx.listener(|this, _event, window, cx| {
4147                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4148                }))
4149                .tooltip(move |_window, cx| {
4150                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4151                        .into()
4152                })
4153                .into_any_element(),
4154        )
4155    }
4156
4157    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4158        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4159        let is_generating = self
4160            .thread()
4161            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4162
4163        if self.is_loading_contents {
4164            div()
4165                .id("loading-message-content")
4166                .px_1()
4167                .tooltip(Tooltip::text("Loading Added Context…"))
4168                .child(loading_contents_spinner(IconSize::default()))
4169                .into_any_element()
4170        } else if is_generating && is_editor_empty {
4171            IconButton::new("stop-generation", IconName::Stop)
4172                .icon_color(Color::Error)
4173                .style(ButtonStyle::Tinted(ui::TintColor::Error))
4174                .tooltip(move |window, cx| {
4175                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
4176                })
4177                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4178                .into_any_element()
4179        } else {
4180            let send_btn_tooltip = if is_editor_empty && !is_generating {
4181                "Type to Send"
4182            } else if is_generating {
4183                "Stop and Send Message"
4184            } else {
4185                "Send"
4186            };
4187
4188            IconButton::new("send-message", IconName::Send)
4189                .style(ButtonStyle::Filled)
4190                .map(|this| {
4191                    if is_editor_empty && !is_generating {
4192                        this.disabled(true).icon_color(Color::Muted)
4193                    } else {
4194                        this.icon_color(Color::Accent)
4195                    }
4196                })
4197                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
4198                .on_click(cx.listener(|this, _, window, cx| {
4199                    this.send(window, cx);
4200                }))
4201                .into_any_element()
4202        }
4203    }
4204
4205    fn is_following(&self, cx: &App) -> bool {
4206        match self.thread().map(|thread| thread.read(cx).status()) {
4207            Some(ThreadStatus::Generating) => self
4208                .workspace
4209                .read_with(cx, |workspace, _| {
4210                    workspace.is_being_followed(CollaboratorId::Agent)
4211                })
4212                .unwrap_or(false),
4213            _ => self.should_be_following,
4214        }
4215    }
4216
4217    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4218        let following = self.is_following(cx);
4219
4220        self.should_be_following = !following;
4221        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4222            self.workspace
4223                .update(cx, |workspace, cx| {
4224                    if following {
4225                        workspace.unfollow(CollaboratorId::Agent, window, cx);
4226                    } else {
4227                        workspace.follow(CollaboratorId::Agent, window, cx);
4228                    }
4229                })
4230                .ok();
4231        }
4232
4233        telemetry::event!("Follow Agent Selected", following = !following);
4234    }
4235
4236    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4237        let following = self.is_following(cx);
4238
4239        let tooltip_label = if following {
4240            if self.agent.name() == "Zed Agent" {
4241                format!("Stop Following the {}", self.agent.name())
4242            } else {
4243                format!("Stop Following {}", self.agent.name())
4244            }
4245        } else {
4246            if self.agent.name() == "Zed Agent" {
4247                format!("Follow the {}", self.agent.name())
4248            } else {
4249                format!("Follow {}", self.agent.name())
4250            }
4251        };
4252
4253        IconButton::new("follow-agent", IconName::Crosshair)
4254            .icon_size(IconSize::Small)
4255            .icon_color(Color::Muted)
4256            .toggle_state(following)
4257            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4258            .tooltip(move |window, cx| {
4259                if following {
4260                    Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4261                } else {
4262                    Tooltip::with_meta(
4263                        tooltip_label.clone(),
4264                        Some(&Follow),
4265                        "Track the agent's location as it reads and edits files.",
4266                        window,
4267                        cx,
4268                    )
4269                }
4270            })
4271            .on_click(cx.listener(move |this, _, window, cx| {
4272                this.toggle_following(window, cx);
4273            }))
4274    }
4275
4276    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4277        let workspace = self.workspace.clone();
4278        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4279            Self::open_link(text, &workspace, window, cx);
4280        })
4281    }
4282
4283    fn open_link(
4284        url: SharedString,
4285        workspace: &WeakEntity<Workspace>,
4286        window: &mut Window,
4287        cx: &mut App,
4288    ) {
4289        let Some(workspace) = workspace.upgrade() else {
4290            cx.open_url(&url);
4291            return;
4292        };
4293
4294        if let Some(mention) = MentionUri::parse(&url).log_err() {
4295            workspace.update(cx, |workspace, cx| match mention {
4296                MentionUri::File { abs_path } => {
4297                    let project = workspace.project();
4298                    let Some(path) =
4299                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4300                    else {
4301                        return;
4302                    };
4303
4304                    workspace
4305                        .open_path(path, None, true, window, cx)
4306                        .detach_and_log_err(cx);
4307                }
4308                MentionUri::PastedImage => {}
4309                MentionUri::Directory { abs_path } => {
4310                    let project = workspace.project();
4311                    let Some(entry_id) = project.update(cx, |project, cx| {
4312                        let path = project.find_project_path(abs_path, cx)?;
4313                        project.entry_for_path(&path, cx).map(|entry| entry.id)
4314                    }) else {
4315                        return;
4316                    };
4317
4318                    project.update(cx, |_, cx| {
4319                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
4320                    });
4321                }
4322                MentionUri::Symbol {
4323                    abs_path: path,
4324                    line_range,
4325                    ..
4326                }
4327                | MentionUri::Selection {
4328                    abs_path: Some(path),
4329                    line_range,
4330                } => {
4331                    let project = workspace.project();
4332                    let Some(path) =
4333                        project.update(cx, |project, cx| project.find_project_path(path, cx))
4334                    else {
4335                        return;
4336                    };
4337
4338                    let item = workspace.open_path(path, None, true, window, cx);
4339                    window
4340                        .spawn(cx, async move |cx| {
4341                            let Some(editor) = item.await?.downcast::<Editor>() else {
4342                                return Ok(());
4343                            };
4344                            let range = Point::new(*line_range.start(), 0)
4345                                ..Point::new(*line_range.start(), 0);
4346                            editor
4347                                .update_in(cx, |editor, window, cx| {
4348                                    editor.change_selections(
4349                                        SelectionEffects::scroll(Autoscroll::center()),
4350                                        window,
4351                                        cx,
4352                                        |s| s.select_ranges(vec![range]),
4353                                    );
4354                                })
4355                                .ok();
4356                            anyhow::Ok(())
4357                        })
4358                        .detach_and_log_err(cx);
4359                }
4360                MentionUri::Selection { abs_path: None, .. } => {}
4361                MentionUri::Thread { id, name } => {
4362                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4363                        panel.update(cx, |panel, cx| {
4364                            panel.load_agent_thread(
4365                                DbThreadMetadata {
4366                                    id,
4367                                    title: name.into(),
4368                                    updated_at: Default::default(),
4369                                },
4370                                window,
4371                                cx,
4372                            )
4373                        });
4374                    }
4375                }
4376                MentionUri::TextThread { path, .. } => {
4377                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4378                        panel.update(cx, |panel, cx| {
4379                            panel
4380                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
4381                                .detach_and_log_err(cx);
4382                        });
4383                    }
4384                }
4385                MentionUri::Rule { id, .. } => {
4386                    let PromptId::User { uuid } = id else {
4387                        return;
4388                    };
4389                    window.dispatch_action(
4390                        Box::new(OpenRulesLibrary {
4391                            prompt_to_select: Some(uuid.0),
4392                        }),
4393                        cx,
4394                    )
4395                }
4396                MentionUri::Fetch { url } => {
4397                    cx.open_url(url.as_str());
4398                }
4399            })
4400        } else {
4401            cx.open_url(&url);
4402        }
4403    }
4404
4405    fn open_tool_call_location(
4406        &self,
4407        entry_ix: usize,
4408        location_ix: usize,
4409        window: &mut Window,
4410        cx: &mut Context<Self>,
4411    ) -> Option<()> {
4412        let (tool_call_location, agent_location) = self
4413            .thread()?
4414            .read(cx)
4415            .entries()
4416            .get(entry_ix)?
4417            .location(location_ix)?;
4418
4419        let project_path = self
4420            .project
4421            .read(cx)
4422            .find_project_path(&tool_call_location.path, cx)?;
4423
4424        let open_task = self
4425            .workspace
4426            .update(cx, |workspace, cx| {
4427                workspace.open_path(project_path, None, true, window, cx)
4428            })
4429            .log_err()?;
4430        window
4431            .spawn(cx, async move |cx| {
4432                let item = open_task.await?;
4433
4434                let Some(active_editor) = item.downcast::<Editor>() else {
4435                    return anyhow::Ok(());
4436                };
4437
4438                active_editor.update_in(cx, |editor, window, cx| {
4439                    let multibuffer = editor.buffer().read(cx);
4440                    let buffer = multibuffer.as_singleton();
4441                    if agent_location.buffer.upgrade() == buffer {
4442                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4443                        let anchor = editor::Anchor::in_buffer(
4444                            excerpt_id.unwrap(),
4445                            buffer.unwrap().read(cx).remote_id(),
4446                            agent_location.position,
4447                        );
4448                        editor.change_selections(Default::default(), window, cx, |selections| {
4449                            selections.select_anchor_ranges([anchor..anchor]);
4450                        })
4451                    } else {
4452                        let row = tool_call_location.line.unwrap_or_default();
4453                        editor.change_selections(Default::default(), window, cx, |selections| {
4454                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4455                        })
4456                    }
4457                })?;
4458
4459                anyhow::Ok(())
4460            })
4461            .detach_and_log_err(cx);
4462
4463        None
4464    }
4465
4466    pub fn open_thread_as_markdown(
4467        &self,
4468        workspace: Entity<Workspace>,
4469        window: &mut Window,
4470        cx: &mut App,
4471    ) -> Task<Result<()>> {
4472        let markdown_language_task = workspace
4473            .read(cx)
4474            .app_state()
4475            .languages
4476            .language_for_name("Markdown");
4477
4478        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4479            let thread = thread.read(cx);
4480            (thread.title().to_string(), thread.to_markdown(cx))
4481        } else {
4482            return Task::ready(Ok(()));
4483        };
4484
4485        window.spawn(cx, async move |cx| {
4486            let markdown_language = markdown_language_task.await?;
4487
4488            workspace.update_in(cx, |workspace, window, cx| {
4489                let project = workspace.project().clone();
4490
4491                if !project.read(cx).is_local() {
4492                    bail!("failed to open active thread as markdown in remote project");
4493                }
4494
4495                let buffer = project.update(cx, |project, cx| {
4496                    project.create_local_buffer(&markdown, Some(markdown_language), true, cx)
4497                });
4498                let buffer = cx.new(|cx| {
4499                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4500                });
4501
4502                workspace.add_item_to_active_pane(
4503                    Box::new(cx.new(|cx| {
4504                        let mut editor =
4505                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4506                        editor.set_breadcrumb_header(thread_summary);
4507                        editor
4508                    })),
4509                    None,
4510                    true,
4511                    window,
4512                    cx,
4513                );
4514
4515                anyhow::Ok(())
4516            })??;
4517            anyhow::Ok(())
4518        })
4519    }
4520
4521    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4522        self.list_state.scroll_to(ListOffset::default());
4523        cx.notify();
4524    }
4525
4526    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4527        if let Some(thread) = self.thread() {
4528            let entry_count = thread.read(cx).entries().len();
4529            self.list_state.reset(entry_count);
4530            cx.notify();
4531        }
4532    }
4533
4534    fn notify_with_sound(
4535        &mut self,
4536        caption: impl Into<SharedString>,
4537        icon: IconName,
4538        window: &mut Window,
4539        cx: &mut Context<Self>,
4540    ) {
4541        self.play_notification_sound(window, cx);
4542        self.show_notification(caption, icon, window, cx);
4543    }
4544
4545    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4546        let settings = AgentSettings::get_global(cx);
4547        if settings.play_sound_when_agent_done && !window.is_window_active() {
4548            Audio::play_sound(Sound::AgentDone, cx);
4549        }
4550    }
4551
4552    fn show_notification(
4553        &mut self,
4554        caption: impl Into<SharedString>,
4555        icon: IconName,
4556        window: &mut Window,
4557        cx: &mut Context<Self>,
4558    ) {
4559        if window.is_window_active() || !self.notifications.is_empty() {
4560            return;
4561        }
4562
4563        // TODO: Change this once we have title summarization for external agents.
4564        let title = self.agent.name();
4565
4566        match AgentSettings::get_global(cx).notify_when_agent_waiting {
4567            NotifyWhenAgentWaiting::PrimaryScreen => {
4568                if let Some(primary) = cx.primary_display() {
4569                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4570                }
4571            }
4572            NotifyWhenAgentWaiting::AllScreens => {
4573                let caption = caption.into();
4574                for screen in cx.displays() {
4575                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4576                }
4577            }
4578            NotifyWhenAgentWaiting::Never => {
4579                // Don't show anything
4580            }
4581        }
4582    }
4583
4584    fn pop_up(
4585        &mut self,
4586        icon: IconName,
4587        caption: SharedString,
4588        title: SharedString,
4589        window: &mut Window,
4590        screen: Rc<dyn PlatformDisplay>,
4591        cx: &mut Context<Self>,
4592    ) {
4593        let options = AgentNotification::window_options(screen, cx);
4594
4595        let project_name = self.workspace.upgrade().and_then(|workspace| {
4596            workspace
4597                .read(cx)
4598                .project()
4599                .read(cx)
4600                .visible_worktrees(cx)
4601                .next()
4602                .map(|worktree| worktree.read(cx).root_name_str().to_string())
4603        });
4604
4605        if let Some(screen_window) = cx
4606            .open_window(options, |_, cx| {
4607                cx.new(|_| {
4608                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4609                })
4610            })
4611            .log_err()
4612            && let Some(pop_up) = screen_window.entity(cx).log_err()
4613        {
4614            self.notification_subscriptions
4615                .entry(screen_window)
4616                .or_insert_with(Vec::new)
4617                .push(cx.subscribe_in(&pop_up, window, {
4618                    |this, _, event, window, cx| match event {
4619                        AgentNotificationEvent::Accepted => {
4620                            let handle = window.window_handle();
4621                            cx.activate(true);
4622
4623                            let workspace_handle = this.workspace.clone();
4624
4625                            // If there are multiple Zed windows, activate the correct one.
4626                            cx.defer(move |cx| {
4627                                handle
4628                                    .update(cx, |_view, window, _cx| {
4629                                        window.activate_window();
4630
4631                                        if let Some(workspace) = workspace_handle.upgrade() {
4632                                            workspace.update(_cx, |workspace, cx| {
4633                                                workspace.focus_panel::<AgentPanel>(window, cx);
4634                                            });
4635                                        }
4636                                    })
4637                                    .log_err();
4638                            });
4639
4640                            this.dismiss_notifications(cx);
4641                        }
4642                        AgentNotificationEvent::Dismissed => {
4643                            this.dismiss_notifications(cx);
4644                        }
4645                    }
4646                }));
4647
4648            self.notifications.push(screen_window);
4649
4650            // If the user manually refocuses the original window, dismiss the popup.
4651            self.notification_subscriptions
4652                .entry(screen_window)
4653                .or_insert_with(Vec::new)
4654                .push({
4655                    let pop_up_weak = pop_up.downgrade();
4656
4657                    cx.observe_window_activation(window, move |_, window, cx| {
4658                        if window.is_window_active()
4659                            && let Some(pop_up) = pop_up_weak.upgrade()
4660                        {
4661                            pop_up.update(cx, |_, cx| {
4662                                cx.emit(AgentNotificationEvent::Dismissed);
4663                            });
4664                        }
4665                    })
4666                });
4667        }
4668    }
4669
4670    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4671        for window in self.notifications.drain(..) {
4672            window
4673                .update(cx, |_, window, _| {
4674                    window.remove_window();
4675                })
4676                .ok();
4677
4678            self.notification_subscriptions.remove(&window);
4679        }
4680    }
4681
4682    fn render_thread_controls(
4683        &self,
4684        thread: &Entity<AcpThread>,
4685        cx: &Context<Self>,
4686    ) -> impl IntoElement {
4687        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4688        if is_generating {
4689            return h_flex().id("thread-controls-container").child(
4690                div()
4691                    .py_2()
4692                    .px(rems_from_px(22.))
4693                    .child(SpinnerLabel::new().size(LabelSize::Small)),
4694            );
4695        }
4696
4697        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4698            .shape(ui::IconButtonShape::Square)
4699            .icon_size(IconSize::Small)
4700            .icon_color(Color::Ignored)
4701            .tooltip(Tooltip::text("Open Thread as Markdown"))
4702            .on_click(cx.listener(move |this, _, window, cx| {
4703                if let Some(workspace) = this.workspace.upgrade() {
4704                    this.open_thread_as_markdown(workspace, window, cx)
4705                        .detach_and_log_err(cx);
4706                }
4707            }));
4708
4709        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4710            .shape(ui::IconButtonShape::Square)
4711            .icon_size(IconSize::Small)
4712            .icon_color(Color::Ignored)
4713            .tooltip(Tooltip::text("Scroll To Top"))
4714            .on_click(cx.listener(move |this, _, _, cx| {
4715                this.scroll_to_top(cx);
4716            }));
4717
4718        let mut container = h_flex()
4719            .id("thread-controls-container")
4720            .group("thread-controls-container")
4721            .w_full()
4722            .py_2()
4723            .px_5()
4724            .gap_px()
4725            .opacity(0.6)
4726            .hover(|style| style.opacity(1.))
4727            .flex_wrap()
4728            .justify_end();
4729
4730        if AgentSettings::get_global(cx).enable_feedback
4731            && self
4732                .thread()
4733                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4734        {
4735            let feedback = self.thread_feedback.feedback;
4736
4737            container = container
4738                .child(
4739                    div().visible_on_hover("thread-controls-container").child(
4740                        Label::new(match feedback {
4741                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4742                            Some(ThreadFeedback::Negative) => {
4743                                "We appreciate your feedback and will use it to improve."
4744                            }
4745                            None => {
4746                                "Rating the thread sends all of your current conversation to the Zed team."
4747                            }
4748                        })
4749                        .color(Color::Muted)
4750                        .size(LabelSize::XSmall)
4751                        .truncate(),
4752                    ),
4753                )
4754                .child(
4755                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4756                        .shape(ui::IconButtonShape::Square)
4757                        .icon_size(IconSize::Small)
4758                        .icon_color(match feedback {
4759                            Some(ThreadFeedback::Positive) => Color::Accent,
4760                            _ => Color::Ignored,
4761                        })
4762                        .tooltip(Tooltip::text("Helpful Response"))
4763                        .on_click(cx.listener(move |this, _, window, cx| {
4764                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4765                        })),
4766                )
4767                .child(
4768                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4769                        .shape(ui::IconButtonShape::Square)
4770                        .icon_size(IconSize::Small)
4771                        .icon_color(match feedback {
4772                            Some(ThreadFeedback::Negative) => Color::Accent,
4773                            _ => Color::Ignored,
4774                        })
4775                        .tooltip(Tooltip::text("Not Helpful"))
4776                        .on_click(cx.listener(move |this, _, window, cx| {
4777                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4778                        })),
4779                );
4780        }
4781
4782        container.child(open_as_markdown).child(scroll_to_top)
4783    }
4784
4785    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4786        h_flex()
4787            .key_context("AgentFeedbackMessageEditor")
4788            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4789                this.thread_feedback.dismiss_comments();
4790                cx.notify();
4791            }))
4792            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4793                this.submit_feedback_message(cx);
4794            }))
4795            .p_2()
4796            .mb_2()
4797            .mx_5()
4798            .gap_1()
4799            .rounded_md()
4800            .border_1()
4801            .border_color(cx.theme().colors().border)
4802            .bg(cx.theme().colors().editor_background)
4803            .child(div().w_full().child(editor))
4804            .child(
4805                h_flex()
4806                    .child(
4807                        IconButton::new("dismiss-feedback-message", IconName::Close)
4808                            .icon_color(Color::Error)
4809                            .icon_size(IconSize::XSmall)
4810                            .shape(ui::IconButtonShape::Square)
4811                            .on_click(cx.listener(move |this, _, _window, cx| {
4812                                this.thread_feedback.dismiss_comments();
4813                                cx.notify();
4814                            })),
4815                    )
4816                    .child(
4817                        IconButton::new("submit-feedback-message", IconName::Return)
4818                            .icon_size(IconSize::XSmall)
4819                            .shape(ui::IconButtonShape::Square)
4820                            .on_click(cx.listener(move |this, _, _window, cx| {
4821                                this.submit_feedback_message(cx);
4822                            })),
4823                    ),
4824            )
4825    }
4826
4827    fn handle_feedback_click(
4828        &mut self,
4829        feedback: ThreadFeedback,
4830        window: &mut Window,
4831        cx: &mut Context<Self>,
4832    ) {
4833        let Some(thread) = self.thread().cloned() else {
4834            return;
4835        };
4836
4837        self.thread_feedback.submit(thread, feedback, window, cx);
4838        cx.notify();
4839    }
4840
4841    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4842        let Some(thread) = self.thread().cloned() else {
4843            return;
4844        };
4845
4846        self.thread_feedback.submit_comments(thread, cx);
4847        cx.notify();
4848    }
4849
4850    fn render_token_limit_callout(
4851        &self,
4852        line_height: Pixels,
4853        cx: &mut Context<Self>,
4854    ) -> Option<Callout> {
4855        let token_usage = self.thread()?.read(cx).token_usage()?;
4856        let ratio = token_usage.ratio();
4857
4858        let (severity, title) = match ratio {
4859            acp_thread::TokenUsageRatio::Normal => return None,
4860            acp_thread::TokenUsageRatio::Warning => {
4861                (Severity::Warning, "Thread reaching the token limit soon")
4862            }
4863            acp_thread::TokenUsageRatio::Exceeded => {
4864                (Severity::Error, "Thread reached the token limit")
4865            }
4866        };
4867
4868        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4869            thread.read(cx).completion_mode() == CompletionMode::Normal
4870                && thread
4871                    .read(cx)
4872                    .model()
4873                    .is_some_and(|model| model.supports_burn_mode())
4874        });
4875
4876        let description = if burn_mode_available {
4877            "To continue, start a new thread from a summary or turn Burn Mode on."
4878        } else {
4879            "To continue, start a new thread from a summary."
4880        };
4881
4882        Some(
4883            Callout::new()
4884                .severity(severity)
4885                .line_height(line_height)
4886                .title(title)
4887                .description(description)
4888                .actions_slot(
4889                    h_flex()
4890                        .gap_0p5()
4891                        .child(
4892                            Button::new("start-new-thread", "Start New Thread")
4893                                .label_size(LabelSize::Small)
4894                                .on_click(cx.listener(|this, _, window, cx| {
4895                                    let Some(thread) = this.thread() else {
4896                                        return;
4897                                    };
4898                                    let session_id = thread.read(cx).session_id().clone();
4899                                    window.dispatch_action(
4900                                        crate::NewNativeAgentThreadFromSummary {
4901                                            from_session_id: session_id,
4902                                        }
4903                                        .boxed_clone(),
4904                                        cx,
4905                                    );
4906                                })),
4907                        )
4908                        .when(burn_mode_available, |this| {
4909                            this.child(
4910                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4911                                    .icon_size(IconSize::XSmall)
4912                                    .on_click(cx.listener(|this, _event, window, cx| {
4913                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4914                                    })),
4915                            )
4916                        }),
4917                ),
4918        )
4919    }
4920
4921    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4922        if !self.is_using_zed_ai_models(cx) {
4923            return None;
4924        }
4925
4926        let user_store = self.project.read(cx).user_store().read(cx);
4927        if user_store.is_usage_based_billing_enabled() {
4928            return None;
4929        }
4930
4931        let plan = user_store
4932            .plan()
4933            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
4934
4935        let usage = user_store.model_request_usage()?;
4936
4937        Some(
4938            div()
4939                .child(UsageCallout::new(plan, usage))
4940                .line_height(line_height),
4941        )
4942    }
4943
4944    fn agent_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4945        self.entry_view_state.update(cx, |entry_view_state, cx| {
4946            entry_view_state.agent_font_size_changed(cx);
4947        });
4948    }
4949
4950    pub(crate) fn insert_dragged_files(
4951        &self,
4952        paths: Vec<project::ProjectPath>,
4953        added_worktrees: Vec<Entity<project::Worktree>>,
4954        window: &mut Window,
4955        cx: &mut Context<Self>,
4956    ) {
4957        self.message_editor.update(cx, |message_editor, cx| {
4958            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4959        })
4960    }
4961
4962    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4963        self.message_editor.update(cx, |message_editor, cx| {
4964            message_editor.insert_selections(window, cx);
4965        })
4966    }
4967
4968    fn render_thread_retry_status_callout(
4969        &self,
4970        _window: &mut Window,
4971        _cx: &mut Context<Self>,
4972    ) -> Option<Callout> {
4973        let state = self.thread_retry_status.as_ref()?;
4974
4975        let next_attempt_in = state
4976            .duration
4977            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4978        if next_attempt_in.is_zero() {
4979            return None;
4980        }
4981
4982        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4983
4984        let retry_message = if state.max_attempts == 1 {
4985            if next_attempt_in_secs == 1 {
4986                "Retrying. Next attempt in 1 second.".to_string()
4987            } else {
4988                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4989            }
4990        } else if next_attempt_in_secs == 1 {
4991            format!(
4992                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4993                state.attempt, state.max_attempts,
4994            )
4995        } else {
4996            format!(
4997                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4998                state.attempt, state.max_attempts,
4999            )
5000        };
5001
5002        Some(
5003            Callout::new()
5004                .severity(Severity::Warning)
5005                .title(state.last_error.clone())
5006                .description(retry_message),
5007        )
5008    }
5009
5010    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5011        let content = match self.thread_error.as_ref()? {
5012            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
5013            ThreadError::Refusal => self.render_refusal_error(cx),
5014            ThreadError::AuthenticationRequired(error) => {
5015                self.render_authentication_required_error(error.clone(), cx)
5016            }
5017            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5018            ThreadError::ModelRequestLimitReached(plan) => {
5019                self.render_model_request_limit_reached_error(*plan, cx)
5020            }
5021            ThreadError::ToolUseLimitReached => {
5022                self.render_tool_use_limit_reached_error(window, cx)?
5023            }
5024        };
5025
5026        Some(div().child(content))
5027    }
5028
5029    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5030        v_flex().w_full().justify_end().child(
5031            h_flex()
5032                .p_2()
5033                .pr_3()
5034                .w_full()
5035                .gap_1p5()
5036                .border_t_1()
5037                .border_color(cx.theme().colors().border)
5038                .bg(cx.theme().colors().element_background)
5039                .child(
5040                    h_flex()
5041                        .flex_1()
5042                        .gap_1p5()
5043                        .child(
5044                            Icon::new(IconName::Download)
5045                                .color(Color::Accent)
5046                                .size(IconSize::Small),
5047                        )
5048                        .child(Label::new("New version available").size(LabelSize::Small)),
5049                )
5050                .child(
5051                    Button::new("update-button", format!("Update to v{}", version))
5052                        .label_size(LabelSize::Small)
5053                        .style(ButtonStyle::Tinted(TintColor::Accent))
5054                        .on_click(cx.listener(|this, _, window, cx| {
5055                            this.reset(window, cx);
5056                        })),
5057                ),
5058        )
5059    }
5060
5061    fn get_current_model_name(&self, cx: &App) -> SharedString {
5062        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5063        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5064        // This provides better clarity about what refused the request
5065        if self
5066            .agent
5067            .clone()
5068            .downcast::<agent2::NativeAgentServer>()
5069            .is_some()
5070        {
5071            // Native agent - use the model name
5072            self.model_selector
5073                .as_ref()
5074                .and_then(|selector| selector.read(cx).active_model_name(cx))
5075                .unwrap_or_else(|| SharedString::from("The model"))
5076        } else {
5077            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5078            self.agent.name()
5079        }
5080    }
5081
5082    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5083        let model_or_agent_name = self.get_current_model_name(cx);
5084        let refusal_message = format!(
5085            "{} 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.",
5086            model_or_agent_name
5087        );
5088
5089        Callout::new()
5090            .severity(Severity::Error)
5091            .title("Request Refused")
5092            .icon(IconName::XCircle)
5093            .description(refusal_message.clone())
5094            .actions_slot(self.create_copy_button(&refusal_message))
5095            .dismiss_action(self.dismiss_error_button(cx))
5096    }
5097
5098    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
5099        let can_resume = self
5100            .thread()
5101            .map_or(false, |thread| thread.read(cx).can_resume(cx));
5102
5103        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5104            let thread = thread.read(cx);
5105            let supports_burn_mode = thread
5106                .model()
5107                .map_or(false, |model| model.supports_burn_mode());
5108            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5109        });
5110
5111        Callout::new()
5112            .severity(Severity::Error)
5113            .title("Error")
5114            .icon(IconName::XCircle)
5115            .description(error.clone())
5116            .actions_slot(
5117                h_flex()
5118                    .gap_0p5()
5119                    .when(can_resume && can_enable_burn_mode, |this| {
5120                        this.child(
5121                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5122                                .icon(IconName::ZedBurnMode)
5123                                .icon_position(IconPosition::Start)
5124                                .icon_size(IconSize::Small)
5125                                .label_size(LabelSize::Small)
5126                                .on_click(cx.listener(|this, _, window, cx| {
5127                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5128                                    this.resume_chat(cx);
5129                                })),
5130                        )
5131                    })
5132                    .when(can_resume, |this| {
5133                        this.child(
5134                            Button::new("retry", "Retry")
5135                                .icon(IconName::RotateCw)
5136                                .icon_position(IconPosition::Start)
5137                                .icon_size(IconSize::Small)
5138                                .label_size(LabelSize::Small)
5139                                .on_click(cx.listener(|this, _, _window, cx| {
5140                                    this.resume_chat(cx);
5141                                })),
5142                        )
5143                    })
5144                    .child(self.create_copy_button(error.to_string())),
5145            )
5146            .dismiss_action(self.dismiss_error_button(cx))
5147    }
5148
5149    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5150        const ERROR_MESSAGE: &str =
5151            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5152
5153        Callout::new()
5154            .severity(Severity::Error)
5155            .icon(IconName::XCircle)
5156            .title("Free Usage Exceeded")
5157            .description(ERROR_MESSAGE)
5158            .actions_slot(
5159                h_flex()
5160                    .gap_0p5()
5161                    .child(self.upgrade_button(cx))
5162                    .child(self.create_copy_button(ERROR_MESSAGE)),
5163            )
5164            .dismiss_action(self.dismiss_error_button(cx))
5165    }
5166
5167    fn render_authentication_required_error(
5168        &self,
5169        error: SharedString,
5170        cx: &mut Context<Self>,
5171    ) -> Callout {
5172        Callout::new()
5173            .severity(Severity::Error)
5174            .title("Authentication Required")
5175            .icon(IconName::XCircle)
5176            .description(error.clone())
5177            .actions_slot(
5178                h_flex()
5179                    .gap_0p5()
5180                    .child(self.authenticate_button(cx))
5181                    .child(self.create_copy_button(error)),
5182            )
5183            .dismiss_action(self.dismiss_error_button(cx))
5184    }
5185
5186    fn render_model_request_limit_reached_error(
5187        &self,
5188        plan: cloud_llm_client::Plan,
5189        cx: &mut Context<Self>,
5190    ) -> Callout {
5191        let error_message = match plan {
5192            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5193                "Upgrade to usage-based billing for more prompts."
5194            }
5195            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5196            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5197            cloud_llm_client::Plan::V2(_) => "",
5198        };
5199
5200        Callout::new()
5201            .severity(Severity::Error)
5202            .title("Model Prompt Limit Reached")
5203            .icon(IconName::XCircle)
5204            .description(error_message)
5205            .actions_slot(
5206                h_flex()
5207                    .gap_0p5()
5208                    .child(self.upgrade_button(cx))
5209                    .child(self.create_copy_button(error_message)),
5210            )
5211            .dismiss_action(self.dismiss_error_button(cx))
5212    }
5213
5214    fn render_tool_use_limit_reached_error(
5215        &self,
5216        window: &mut Window,
5217        cx: &mut Context<Self>,
5218    ) -> Option<Callout> {
5219        let thread = self.as_native_thread(cx)?;
5220        let supports_burn_mode = thread
5221            .read(cx)
5222            .model()
5223            .is_some_and(|model| model.supports_burn_mode());
5224
5225        let focus_handle = self.focus_handle(cx);
5226
5227        Some(
5228            Callout::new()
5229                .icon(IconName::Info)
5230                .title("Consecutive tool use limit reached.")
5231                .actions_slot(
5232                    h_flex()
5233                        .gap_0p5()
5234                        .when(supports_burn_mode, |this| {
5235                            this.child(
5236                                Button::new("continue-burn-mode", "Continue with Burn Mode")
5237                                    .style(ButtonStyle::Filled)
5238                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5239                                    .layer(ElevationIndex::ModalSurface)
5240                                    .label_size(LabelSize::Small)
5241                                    .key_binding(
5242                                        KeyBinding::for_action_in(
5243                                            &ContinueWithBurnMode,
5244                                            &focus_handle,
5245                                            window,
5246                                            cx,
5247                                        )
5248                                        .map(|kb| kb.size(rems_from_px(10.))),
5249                                    )
5250                                    .tooltip(Tooltip::text(
5251                                        "Enable Burn Mode for unlimited tool use.",
5252                                    ))
5253                                    .on_click({
5254                                        cx.listener(move |this, _, _window, cx| {
5255                                            thread.update(cx, |thread, cx| {
5256                                                thread
5257                                                    .set_completion_mode(CompletionMode::Burn, cx);
5258                                            });
5259                                            this.resume_chat(cx);
5260                                        })
5261                                    }),
5262                            )
5263                        })
5264                        .child(
5265                            Button::new("continue-conversation", "Continue")
5266                                .layer(ElevationIndex::ModalSurface)
5267                                .label_size(LabelSize::Small)
5268                                .key_binding(
5269                                    KeyBinding::for_action_in(
5270                                        &ContinueThread,
5271                                        &focus_handle,
5272                                        window,
5273                                        cx,
5274                                    )
5275                                    .map(|kb| kb.size(rems_from_px(10.))),
5276                                )
5277                                .on_click(cx.listener(|this, _, _window, cx| {
5278                                    this.resume_chat(cx);
5279                                })),
5280                        ),
5281                ),
5282        )
5283    }
5284
5285    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5286        let message = message.into();
5287
5288        IconButton::new("copy", IconName::Copy)
5289            .icon_size(IconSize::Small)
5290            .icon_color(Color::Muted)
5291            .tooltip(Tooltip::text("Copy Error Message"))
5292            .on_click(move |_, _, cx| {
5293                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5294            })
5295    }
5296
5297    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5298        IconButton::new("dismiss", IconName::Close)
5299            .icon_size(IconSize::Small)
5300            .icon_color(Color::Muted)
5301            .tooltip(Tooltip::text("Dismiss Error"))
5302            .on_click(cx.listener({
5303                move |this, _, _, cx| {
5304                    this.clear_thread_error(cx);
5305                    cx.notify();
5306                }
5307            }))
5308    }
5309
5310    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5311        Button::new("authenticate", "Authenticate")
5312            .label_size(LabelSize::Small)
5313            .style(ButtonStyle::Filled)
5314            .on_click(cx.listener({
5315                move |this, _, window, cx| {
5316                    let agent = this.agent.clone();
5317                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
5318                        return;
5319                    };
5320
5321                    let connection = thread.read(cx).connection().clone();
5322                    let err = AuthRequired {
5323                        description: None,
5324                        provider_id: None,
5325                    };
5326                    this.clear_thread_error(cx);
5327                    let this = cx.weak_entity();
5328                    window.defer(cx, |window, cx| {
5329                        Self::handle_auth_required(this, err, agent, connection, window, cx);
5330                    })
5331                }
5332            }))
5333    }
5334
5335    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5336        let agent = self.agent.clone();
5337        let ThreadState::Ready { thread, .. } = &self.thread_state else {
5338            return;
5339        };
5340
5341        let connection = thread.read(cx).connection().clone();
5342        let err = AuthRequired {
5343            description: None,
5344            provider_id: None,
5345        };
5346        self.clear_thread_error(cx);
5347        let this = cx.weak_entity();
5348        window.defer(cx, |window, cx| {
5349            Self::handle_auth_required(this, err, agent, connection, window, cx);
5350        })
5351    }
5352
5353    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5354        Button::new("upgrade", "Upgrade")
5355            .label_size(LabelSize::Small)
5356            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5357            .on_click(cx.listener({
5358                move |this, _, _, cx| {
5359                    this.clear_thread_error(cx);
5360                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5361                }
5362            }))
5363    }
5364
5365    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5366        let task = match entry {
5367            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5368                history.delete_thread(thread.id.clone(), cx)
5369            }),
5370            HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5371                history.delete_text_thread(context.path.clone(), cx)
5372            }),
5373        };
5374        task.detach_and_log_err(cx);
5375    }
5376}
5377
5378fn loading_contents_spinner(size: IconSize) -> AnyElement {
5379    Icon::new(IconName::LoadCircle)
5380        .size(size)
5381        .color(Color::Accent)
5382        .with_rotate_animation(3)
5383        .into_any_element()
5384}
5385
5386impl Focusable for AcpThreadView {
5387    fn focus_handle(&self, cx: &App) -> FocusHandle {
5388        match self.thread_state {
5389            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5390                self.message_editor.focus_handle(cx)
5391            }
5392            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5393                self.focus_handle.clone()
5394            }
5395        }
5396    }
5397}
5398
5399impl Render for AcpThreadView {
5400    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5401        let has_messages = self.list_state.item_count() > 0;
5402        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5403
5404        v_flex()
5405            .size_full()
5406            .key_context("AcpThread")
5407            .on_action(cx.listener(Self::open_agent_diff))
5408            .on_action(cx.listener(Self::toggle_burn_mode))
5409            .on_action(cx.listener(Self::keep_all))
5410            .on_action(cx.listener(Self::reject_all))
5411            .on_action(cx.listener(Self::allow_always))
5412            .on_action(cx.listener(Self::allow_once))
5413            .on_action(cx.listener(Self::reject_once))
5414            .track_focus(&self.focus_handle)
5415            .bg(cx.theme().colors().panel_background)
5416            .child(match &self.thread_state {
5417                ThreadState::Unauthenticated {
5418                    connection,
5419                    description,
5420                    configuration_view,
5421                    pending_auth_method,
5422                    ..
5423                } => self
5424                    .render_auth_required_state(
5425                        connection,
5426                        description.as_ref(),
5427                        configuration_view.as_ref(),
5428                        pending_auth_method.as_ref(),
5429                        window,
5430                        cx,
5431                    )
5432                    .into_any(),
5433                ThreadState::Loading { .. } => v_flex()
5434                    .flex_1()
5435                    .child(self.render_recent_history(window, cx))
5436                    .into_any(),
5437                ThreadState::LoadError(e) => v_flex()
5438                    .flex_1()
5439                    .size_full()
5440                    .items_center()
5441                    .justify_end()
5442                    .child(self.render_load_error(e, window, cx))
5443                    .into_any(),
5444                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5445                    if has_messages {
5446                        this.child(
5447                            list(
5448                                self.list_state.clone(),
5449                                cx.processor(|this, index: usize, window, cx| {
5450                                    let Some((entry, len)) = this.thread().and_then(|thread| {
5451                                        let entries = &thread.read(cx).entries();
5452                                        Some((entries.get(index)?, entries.len()))
5453                                    }) else {
5454                                        return Empty.into_any();
5455                                    };
5456                                    this.render_entry(index, len, entry, window, cx)
5457                                }),
5458                            )
5459                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5460                            .flex_grow()
5461                            .into_any(),
5462                        )
5463                        .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5464                        .into_any()
5465                    } else {
5466                        this.child(self.render_recent_history(window, cx))
5467                            .into_any()
5468                    }
5469                }),
5470            })
5471            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5472            // above so that the scrollbar doesn't render behind it. The current setup allows
5473            // the scrollbar to stop exactly at the activity bar start.
5474            .when(has_messages, |this| match &self.thread_state {
5475                ThreadState::Ready { thread, .. } => {
5476                    this.children(self.render_activity_bar(thread, window, cx))
5477                }
5478                _ => this,
5479            })
5480            .children(self.render_thread_retry_status_callout(window, cx))
5481            .children(self.render_thread_error(window, cx))
5482            .when_some(
5483                self.new_server_version_available.as_ref().filter(|_| {
5484                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5485                }),
5486                |this, version| this.child(self.render_new_version_callout(&version, cx)),
5487            )
5488            .children(
5489                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5490                    Some(usage_callout.into_any_element())
5491                } else {
5492                    self.render_token_limit_callout(line_height, cx)
5493                        .map(|token_limit_callout| token_limit_callout.into_any_element())
5494                },
5495            )
5496            .child(self.render_message_editor(window, cx))
5497    }
5498}
5499
5500fn default_markdown_style(
5501    buffer_font: bool,
5502    muted_text: bool,
5503    window: &Window,
5504    cx: &App,
5505) -> MarkdownStyle {
5506    let theme_settings = ThemeSettings::get_global(cx);
5507    let colors = cx.theme().colors();
5508
5509    let buffer_font_size = TextSize::Small.rems(cx);
5510
5511    let mut text_style = window.text_style();
5512    let line_height = buffer_font_size * 1.75;
5513
5514    let font_family = if buffer_font {
5515        theme_settings.buffer_font.family.clone()
5516    } else {
5517        theme_settings.ui_font.family.clone()
5518    };
5519
5520    let font_size = if buffer_font {
5521        TextSize::Small.rems(cx)
5522    } else {
5523        TextSize::Default.rems(cx)
5524    };
5525
5526    let text_color = if muted_text {
5527        colors.text_muted
5528    } else {
5529        colors.text
5530    };
5531
5532    text_style.refine(&TextStyleRefinement {
5533        font_family: Some(font_family),
5534        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5535        font_features: Some(theme_settings.ui_font.features.clone()),
5536        font_size: Some(font_size.into()),
5537        line_height: Some(line_height.into()),
5538        color: Some(text_color),
5539        ..Default::default()
5540    });
5541
5542    MarkdownStyle {
5543        base_text_style: text_style.clone(),
5544        syntax: cx.theme().syntax().clone(),
5545        selection_background_color: colors.element_selection_background,
5546        code_block_overflow_x_scroll: true,
5547        table_overflow_x_scroll: true,
5548        heading_level_styles: Some(HeadingLevelStyles {
5549            h1: Some(TextStyleRefinement {
5550                font_size: Some(rems(1.15).into()),
5551                ..Default::default()
5552            }),
5553            h2: Some(TextStyleRefinement {
5554                font_size: Some(rems(1.1).into()),
5555                ..Default::default()
5556            }),
5557            h3: Some(TextStyleRefinement {
5558                font_size: Some(rems(1.05).into()),
5559                ..Default::default()
5560            }),
5561            h4: Some(TextStyleRefinement {
5562                font_size: Some(rems(1.).into()),
5563                ..Default::default()
5564            }),
5565            h5: Some(TextStyleRefinement {
5566                font_size: Some(rems(0.95).into()),
5567                ..Default::default()
5568            }),
5569            h6: Some(TextStyleRefinement {
5570                font_size: Some(rems(0.875).into()),
5571                ..Default::default()
5572            }),
5573        }),
5574        code_block: StyleRefinement {
5575            padding: EdgesRefinement {
5576                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5577                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5578                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5579                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5580            },
5581            margin: EdgesRefinement {
5582                top: Some(Length::Definite(Pixels(8.).into())),
5583                left: Some(Length::Definite(Pixels(0.).into())),
5584                right: Some(Length::Definite(Pixels(0.).into())),
5585                bottom: Some(Length::Definite(Pixels(12.).into())),
5586            },
5587            border_style: Some(BorderStyle::Solid),
5588            border_widths: EdgesRefinement {
5589                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5590                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5591                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5592                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5593            },
5594            border_color: Some(colors.border_variant),
5595            background: Some(colors.editor_background.into()),
5596            text: Some(TextStyleRefinement {
5597                font_family: Some(theme_settings.buffer_font.family.clone()),
5598                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5599                font_features: Some(theme_settings.buffer_font.features.clone()),
5600                font_size: Some(buffer_font_size.into()),
5601                ..Default::default()
5602            }),
5603            ..Default::default()
5604        },
5605        inline_code: TextStyleRefinement {
5606            font_family: Some(theme_settings.buffer_font.family.clone()),
5607            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5608            font_features: Some(theme_settings.buffer_font.features.clone()),
5609            font_size: Some(buffer_font_size.into()),
5610            background_color: Some(colors.editor_foreground.opacity(0.08)),
5611            ..Default::default()
5612        },
5613        link: TextStyleRefinement {
5614            background_color: Some(colors.editor_foreground.opacity(0.025)),
5615            underline: Some(UnderlineStyle {
5616                color: Some(colors.text_accent.opacity(0.5)),
5617                thickness: px(1.),
5618                ..Default::default()
5619            }),
5620            ..Default::default()
5621        },
5622        ..Default::default()
5623    }
5624}
5625
5626fn plan_label_markdown_style(
5627    status: &acp::PlanEntryStatus,
5628    window: &Window,
5629    cx: &App,
5630) -> MarkdownStyle {
5631    let default_md_style = default_markdown_style(false, false, window, cx);
5632
5633    MarkdownStyle {
5634        base_text_style: TextStyle {
5635            color: cx.theme().colors().text_muted,
5636            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5637                Some(gpui::StrikethroughStyle {
5638                    thickness: px(1.),
5639                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5640                })
5641            } else {
5642                None
5643            },
5644            ..default_md_style.base_text_style
5645        },
5646        ..default_md_style
5647    }
5648}
5649
5650fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5651    let default_md_style = default_markdown_style(true, false, window, cx);
5652
5653    MarkdownStyle {
5654        base_text_style: TextStyle {
5655            ..default_md_style.base_text_style
5656        },
5657        selection_background_color: cx.theme().colors().element_selection_background,
5658        ..Default::default()
5659    }
5660}
5661
5662#[cfg(test)]
5663pub(crate) mod tests {
5664    use acp_thread::StubAgentConnection;
5665    use agent_client_protocol::SessionId;
5666    use assistant_context::ContextStore;
5667    use editor::EditorSettings;
5668    use fs::FakeFs;
5669    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5670    use project::Project;
5671    use serde_json::json;
5672    use settings::SettingsStore;
5673    use std::any::Any;
5674    use std::path::Path;
5675    use workspace::Item;
5676
5677    use super::*;
5678
5679    #[gpui::test]
5680    async fn test_drop(cx: &mut TestAppContext) {
5681        init_test(cx);
5682
5683        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5684        let weak_view = thread_view.downgrade();
5685        drop(thread_view);
5686        assert!(!weak_view.is_upgradable());
5687    }
5688
5689    #[gpui::test]
5690    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5691        init_test(cx);
5692
5693        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5694
5695        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5696        message_editor.update_in(cx, |editor, window, cx| {
5697            editor.set_text("Hello", window, cx);
5698        });
5699
5700        cx.deactivate_window();
5701
5702        thread_view.update_in(cx, |thread_view, window, cx| {
5703            thread_view.send(window, cx);
5704        });
5705
5706        cx.run_until_parked();
5707
5708        assert!(
5709            cx.windows()
5710                .iter()
5711                .any(|window| window.downcast::<AgentNotification>().is_some())
5712        );
5713    }
5714
5715    #[gpui::test]
5716    async fn test_notification_for_error(cx: &mut TestAppContext) {
5717        init_test(cx);
5718
5719        let (thread_view, cx) =
5720            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5721
5722        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5723        message_editor.update_in(cx, |editor, window, cx| {
5724            editor.set_text("Hello", window, cx);
5725        });
5726
5727        cx.deactivate_window();
5728
5729        thread_view.update_in(cx, |thread_view, window, cx| {
5730            thread_view.send(window, cx);
5731        });
5732
5733        cx.run_until_parked();
5734
5735        assert!(
5736            cx.windows()
5737                .iter()
5738                .any(|window| window.downcast::<AgentNotification>().is_some())
5739        );
5740    }
5741
5742    #[gpui::test]
5743    async fn test_refusal_handling(cx: &mut TestAppContext) {
5744        init_test(cx);
5745
5746        let (thread_view, cx) =
5747            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5748
5749        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5750        message_editor.update_in(cx, |editor, window, cx| {
5751            editor.set_text("Do something harmful", window, cx);
5752        });
5753
5754        thread_view.update_in(cx, |thread_view, window, cx| {
5755            thread_view.send(window, cx);
5756        });
5757
5758        cx.run_until_parked();
5759
5760        // Check that the refusal error is set
5761        thread_view.read_with(cx, |thread_view, _cx| {
5762            assert!(
5763                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5764                "Expected refusal error to be set"
5765            );
5766        });
5767    }
5768
5769    #[gpui::test]
5770    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5771        init_test(cx);
5772
5773        let tool_call_id = acp::ToolCallId("1".into());
5774        let tool_call = acp::ToolCall {
5775            id: tool_call_id.clone(),
5776            title: "Label".into(),
5777            kind: acp::ToolKind::Edit,
5778            status: acp::ToolCallStatus::Pending,
5779            content: vec!["hi".into()],
5780            locations: vec![],
5781            raw_input: None,
5782            raw_output: None,
5783            meta: None,
5784        };
5785        let connection =
5786            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5787                tool_call_id,
5788                vec![acp::PermissionOption {
5789                    id: acp::PermissionOptionId("1".into()),
5790                    name: "Allow".into(),
5791                    kind: acp::PermissionOptionKind::AllowOnce,
5792                    meta: None,
5793                }],
5794            )]));
5795
5796        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5797
5798        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5799
5800        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5801        message_editor.update_in(cx, |editor, window, cx| {
5802            editor.set_text("Hello", window, cx);
5803        });
5804
5805        cx.deactivate_window();
5806
5807        thread_view.update_in(cx, |thread_view, window, cx| {
5808            thread_view.send(window, cx);
5809        });
5810
5811        cx.run_until_parked();
5812
5813        assert!(
5814            cx.windows()
5815                .iter()
5816                .any(|window| window.downcast::<AgentNotification>().is_some())
5817        );
5818    }
5819
5820    async fn setup_thread_view(
5821        agent: impl AgentServer + 'static,
5822        cx: &mut TestAppContext,
5823    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5824        let fs = FakeFs::new(cx.executor());
5825        let project = Project::test(fs, [], cx).await;
5826        let (workspace, cx) =
5827            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5828
5829        let context_store =
5830            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5831        let history_store =
5832            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5833
5834        let thread_view = cx.update(|window, cx| {
5835            cx.new(|cx| {
5836                AcpThreadView::new(
5837                    Rc::new(agent),
5838                    None,
5839                    None,
5840                    workspace.downgrade(),
5841                    project,
5842                    history_store,
5843                    None,
5844                    window,
5845                    cx,
5846                )
5847            })
5848        });
5849        cx.run_until_parked();
5850        (thread_view, cx)
5851    }
5852
5853    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5854        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5855
5856        workspace
5857            .update_in(cx, |workspace, window, cx| {
5858                workspace.add_item_to_active_pane(
5859                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5860                    None,
5861                    true,
5862                    window,
5863                    cx,
5864                );
5865            })
5866            .unwrap();
5867    }
5868
5869    struct ThreadViewItem(Entity<AcpThreadView>);
5870
5871    impl Item for ThreadViewItem {
5872        type Event = ();
5873
5874        fn include_in_nav_history() -> bool {
5875            false
5876        }
5877
5878        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5879            "Test".into()
5880        }
5881    }
5882
5883    impl EventEmitter<()> for ThreadViewItem {}
5884
5885    impl Focusable for ThreadViewItem {
5886        fn focus_handle(&self, cx: &App) -> FocusHandle {
5887            self.0.read(cx).focus_handle(cx)
5888        }
5889    }
5890
5891    impl Render for ThreadViewItem {
5892        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5893            self.0.clone().into_any_element()
5894        }
5895    }
5896
5897    struct StubAgentServer<C> {
5898        connection: C,
5899    }
5900
5901    impl<C> StubAgentServer<C> {
5902        fn new(connection: C) -> Self {
5903            Self { connection }
5904        }
5905    }
5906
5907    impl StubAgentServer<StubAgentConnection> {
5908        fn default_response() -> Self {
5909            let conn = StubAgentConnection::new();
5910            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5911                content: "Default response".into(),
5912            }]);
5913            Self::new(conn)
5914        }
5915    }
5916
5917    impl<C> AgentServer for StubAgentServer<C>
5918    where
5919        C: 'static + AgentConnection + Send + Clone,
5920    {
5921        fn telemetry_id(&self) -> &'static str {
5922            "test"
5923        }
5924
5925        fn logo(&self) -> ui::IconName {
5926            ui::IconName::Ai
5927        }
5928
5929        fn name(&self) -> SharedString {
5930            "Test".into()
5931        }
5932
5933        fn connect(
5934            &self,
5935            _root_dir: Option<&Path>,
5936            _delegate: AgentServerDelegate,
5937            _cx: &mut App,
5938        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
5939            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
5940        }
5941
5942        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5943            self
5944        }
5945    }
5946
5947    #[derive(Clone)]
5948    struct SaboteurAgentConnection;
5949
5950    impl AgentConnection for SaboteurAgentConnection {
5951        fn new_thread(
5952            self: Rc<Self>,
5953            project: Entity<Project>,
5954            _cwd: &Path,
5955            cx: &mut gpui::App,
5956        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5957            Task::ready(Ok(cx.new(|cx| {
5958                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5959                AcpThread::new(
5960                    "SaboteurAgentConnection",
5961                    self,
5962                    project,
5963                    action_log,
5964                    SessionId("test".into()),
5965                    watch::Receiver::constant(acp::PromptCapabilities {
5966                        image: true,
5967                        audio: true,
5968                        embedded_context: true,
5969                        meta: None,
5970                    }),
5971                    cx,
5972                )
5973            })))
5974        }
5975
5976        fn auth_methods(&self) -> &[acp::AuthMethod] {
5977            &[]
5978        }
5979
5980        fn authenticate(
5981            &self,
5982            _method_id: acp::AuthMethodId,
5983            _cx: &mut App,
5984        ) -> Task<gpui::Result<()>> {
5985            unimplemented!()
5986        }
5987
5988        fn prompt(
5989            &self,
5990            _id: Option<acp_thread::UserMessageId>,
5991            _params: acp::PromptRequest,
5992            _cx: &mut App,
5993        ) -> Task<gpui::Result<acp::PromptResponse>> {
5994            Task::ready(Err(anyhow::anyhow!("Error prompting")))
5995        }
5996
5997        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5998            unimplemented!()
5999        }
6000
6001        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6002            self
6003        }
6004    }
6005
6006    /// Simulates a model which always returns a refusal response
6007    #[derive(Clone)]
6008    struct RefusalAgentConnection;
6009
6010    impl AgentConnection for RefusalAgentConnection {
6011        fn new_thread(
6012            self: Rc<Self>,
6013            project: Entity<Project>,
6014            _cwd: &Path,
6015            cx: &mut gpui::App,
6016        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6017            Task::ready(Ok(cx.new(|cx| {
6018                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6019                AcpThread::new(
6020                    "RefusalAgentConnection",
6021                    self,
6022                    project,
6023                    action_log,
6024                    SessionId("test".into()),
6025                    watch::Receiver::constant(acp::PromptCapabilities {
6026                        image: true,
6027                        audio: true,
6028                        embedded_context: true,
6029                        meta: None,
6030                    }),
6031                    cx,
6032                )
6033            })))
6034        }
6035
6036        fn auth_methods(&self) -> &[acp::AuthMethod] {
6037            &[]
6038        }
6039
6040        fn authenticate(
6041            &self,
6042            _method_id: acp::AuthMethodId,
6043            _cx: &mut App,
6044        ) -> Task<gpui::Result<()>> {
6045            unimplemented!()
6046        }
6047
6048        fn prompt(
6049            &self,
6050            _id: Option<acp_thread::UserMessageId>,
6051            _params: acp::PromptRequest,
6052            _cx: &mut App,
6053        ) -> Task<gpui::Result<acp::PromptResponse>> {
6054            Task::ready(Ok(acp::PromptResponse {
6055                stop_reason: acp::StopReason::Refusal,
6056                meta: None,
6057            }))
6058        }
6059
6060        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6061            unimplemented!()
6062        }
6063
6064        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6065            self
6066        }
6067    }
6068
6069    pub(crate) fn init_test(cx: &mut TestAppContext) {
6070        cx.update(|cx| {
6071            let settings_store = SettingsStore::test(cx);
6072            cx.set_global(settings_store);
6073            language::init(cx);
6074            Project::init_settings(cx);
6075            AgentSettings::register(cx);
6076            workspace::init_settings(cx);
6077            ThemeSettings::register(cx);
6078            release_channel::init(SemanticVersion::default(), cx);
6079            EditorSettings::register(cx);
6080            prompt_store::init(cx)
6081        });
6082    }
6083
6084    #[gpui::test]
6085    async fn test_rewind_views(cx: &mut TestAppContext) {
6086        init_test(cx);
6087
6088        let fs = FakeFs::new(cx.executor());
6089        fs.insert_tree(
6090            "/project",
6091            json!({
6092                "test1.txt": "old content 1",
6093                "test2.txt": "old content 2"
6094            }),
6095        )
6096        .await;
6097        let project = Project::test(fs, [Path::new("/project")], cx).await;
6098        let (workspace, cx) =
6099            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6100
6101        let context_store =
6102            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
6103        let history_store =
6104            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
6105
6106        let connection = Rc::new(StubAgentConnection::new());
6107        let thread_view = cx.update(|window, cx| {
6108            cx.new(|cx| {
6109                AcpThreadView::new(
6110                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6111                    None,
6112                    None,
6113                    workspace.downgrade(),
6114                    project.clone(),
6115                    history_store.clone(),
6116                    None,
6117                    window,
6118                    cx,
6119                )
6120            })
6121        });
6122
6123        cx.run_until_parked();
6124
6125        let thread = thread_view
6126            .read_with(cx, |view, _| view.thread().cloned())
6127            .unwrap();
6128
6129        // First user message
6130        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6131            id: acp::ToolCallId("tool1".into()),
6132            title: "Edit file 1".into(),
6133            kind: acp::ToolKind::Edit,
6134            status: acp::ToolCallStatus::Completed,
6135            content: vec![acp::ToolCallContent::Diff {
6136                diff: acp::Diff {
6137                    path: "/project/test1.txt".into(),
6138                    old_text: Some("old content 1".into()),
6139                    new_text: "new content 1".into(),
6140                    meta: None,
6141                },
6142            }],
6143            locations: vec![],
6144            raw_input: None,
6145            raw_output: None,
6146            meta: None,
6147        })]);
6148
6149        thread
6150            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6151            .await
6152            .unwrap();
6153        cx.run_until_parked();
6154
6155        thread.read_with(cx, |thread, _| {
6156            assert_eq!(thread.entries().len(), 2);
6157        });
6158
6159        thread_view.read_with(cx, |view, cx| {
6160            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6161                assert!(
6162                    entry_view_state
6163                        .entry(0)
6164                        .unwrap()
6165                        .message_editor()
6166                        .is_some()
6167                );
6168                assert!(entry_view_state.entry(1).unwrap().has_content());
6169            });
6170        });
6171
6172        // Second user message
6173        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6174            id: acp::ToolCallId("tool2".into()),
6175            title: "Edit file 2".into(),
6176            kind: acp::ToolKind::Edit,
6177            status: acp::ToolCallStatus::Completed,
6178            content: vec![acp::ToolCallContent::Diff {
6179                diff: acp::Diff {
6180                    path: "/project/test2.txt".into(),
6181                    old_text: Some("old content 2".into()),
6182                    new_text: "new content 2".into(),
6183                    meta: None,
6184                },
6185            }],
6186            locations: vec![],
6187            raw_input: None,
6188            raw_output: None,
6189            meta: None,
6190        })]);
6191
6192        thread
6193            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6194            .await
6195            .unwrap();
6196        cx.run_until_parked();
6197
6198        let second_user_message_id = thread.read_with(cx, |thread, _| {
6199            assert_eq!(thread.entries().len(), 4);
6200            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6201                panic!();
6202            };
6203            user_message.id.clone().unwrap()
6204        });
6205
6206        thread_view.read_with(cx, |view, cx| {
6207            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6208                assert!(
6209                    entry_view_state
6210                        .entry(0)
6211                        .unwrap()
6212                        .message_editor()
6213                        .is_some()
6214                );
6215                assert!(entry_view_state.entry(1).unwrap().has_content());
6216                assert!(
6217                    entry_view_state
6218                        .entry(2)
6219                        .unwrap()
6220                        .message_editor()
6221                        .is_some()
6222                );
6223                assert!(entry_view_state.entry(3).unwrap().has_content());
6224            });
6225        });
6226
6227        // Rewind to first message
6228        thread
6229            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6230            .await
6231            .unwrap();
6232
6233        cx.run_until_parked();
6234
6235        thread.read_with(cx, |thread, _| {
6236            assert_eq!(thread.entries().len(), 2);
6237        });
6238
6239        thread_view.read_with(cx, |view, cx| {
6240            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6241                assert!(
6242                    entry_view_state
6243                        .entry(0)
6244                        .unwrap()
6245                        .message_editor()
6246                        .is_some()
6247                );
6248                assert!(entry_view_state.entry(1).unwrap().has_content());
6249
6250                // Old views should be dropped
6251                assert!(entry_view_state.entry(2).is_none());
6252                assert!(entry_view_state.entry(3).is_none());
6253            });
6254        });
6255    }
6256
6257    #[gpui::test]
6258    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6259        init_test(cx);
6260
6261        let connection = StubAgentConnection::new();
6262
6263        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6264            content: acp::ContentBlock::Text(acp::TextContent {
6265                text: "Response".into(),
6266                annotations: None,
6267                meta: None,
6268            }),
6269        }]);
6270
6271        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6272        add_to_workspace(thread_view.clone(), cx);
6273
6274        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6275        message_editor.update_in(cx, |editor, window, cx| {
6276            editor.set_text("Original message to edit", window, cx);
6277        });
6278        thread_view.update_in(cx, |thread_view, window, cx| {
6279            thread_view.send(window, cx);
6280        });
6281
6282        cx.run_until_parked();
6283
6284        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6285            assert_eq!(view.editing_message, None);
6286
6287            view.entry_view_state
6288                .read(cx)
6289                .entry(0)
6290                .unwrap()
6291                .message_editor()
6292                .unwrap()
6293                .clone()
6294        });
6295
6296        // Focus
6297        cx.focus(&user_message_editor);
6298        thread_view.read_with(cx, |view, _cx| {
6299            assert_eq!(view.editing_message, Some(0));
6300        });
6301
6302        // Edit
6303        user_message_editor.update_in(cx, |editor, window, cx| {
6304            editor.set_text("Edited message content", window, cx);
6305        });
6306
6307        // Cancel
6308        user_message_editor.update_in(cx, |_editor, window, cx| {
6309            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6310        });
6311
6312        thread_view.read_with(cx, |view, _cx| {
6313            assert_eq!(view.editing_message, None);
6314        });
6315
6316        user_message_editor.read_with(cx, |editor, cx| {
6317            assert_eq!(editor.text(cx), "Original message to edit");
6318        });
6319    }
6320
6321    #[gpui::test]
6322    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6323        init_test(cx);
6324
6325        let connection = StubAgentConnection::new();
6326
6327        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6328        add_to_workspace(thread_view.clone(), cx);
6329
6330        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6331        let mut events = cx.events(&message_editor);
6332        message_editor.update_in(cx, |editor, window, cx| {
6333            editor.set_text("", window, cx);
6334        });
6335
6336        message_editor.update_in(cx, |_editor, window, cx| {
6337            window.dispatch_action(Box::new(Chat), cx);
6338        });
6339        cx.run_until_parked();
6340        // We shouldn't have received any messages
6341        assert!(matches!(
6342            events.try_next(),
6343            Err(futures::channel::mpsc::TryRecvError { .. })
6344        ));
6345    }
6346
6347    #[gpui::test]
6348    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6349        init_test(cx);
6350
6351        let connection = StubAgentConnection::new();
6352
6353        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6354            content: acp::ContentBlock::Text(acp::TextContent {
6355                text: "Response".into(),
6356                annotations: None,
6357                meta: None,
6358            }),
6359        }]);
6360
6361        let (thread_view, cx) =
6362            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6363        add_to_workspace(thread_view.clone(), cx);
6364
6365        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6366        message_editor.update_in(cx, |editor, window, cx| {
6367            editor.set_text("Original message to edit", window, cx);
6368        });
6369        thread_view.update_in(cx, |thread_view, window, cx| {
6370            thread_view.send(window, cx);
6371        });
6372
6373        cx.run_until_parked();
6374
6375        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6376            assert_eq!(view.editing_message, None);
6377            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6378
6379            view.entry_view_state
6380                .read(cx)
6381                .entry(0)
6382                .unwrap()
6383                .message_editor()
6384                .unwrap()
6385                .clone()
6386        });
6387
6388        // Focus
6389        cx.focus(&user_message_editor);
6390
6391        // Edit
6392        user_message_editor.update_in(cx, |editor, window, cx| {
6393            editor.set_text("Edited message content", window, cx);
6394        });
6395
6396        // Send
6397        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6398            content: acp::ContentBlock::Text(acp::TextContent {
6399                text: "New Response".into(),
6400                annotations: None,
6401                meta: None,
6402            }),
6403        }]);
6404
6405        user_message_editor.update_in(cx, |_editor, window, cx| {
6406            window.dispatch_action(Box::new(Chat), cx);
6407        });
6408
6409        cx.run_until_parked();
6410
6411        thread_view.read_with(cx, |view, cx| {
6412            assert_eq!(view.editing_message, None);
6413
6414            let entries = view.thread().unwrap().read(cx).entries();
6415            assert_eq!(entries.len(), 2);
6416            assert_eq!(
6417                entries[0].to_markdown(cx),
6418                "## User\n\nEdited message content\n\n"
6419            );
6420            assert_eq!(
6421                entries[1].to_markdown(cx),
6422                "## Assistant\n\nNew Response\n\n"
6423            );
6424
6425            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6426                assert!(!state.entry(1).unwrap().has_content());
6427                state.entry(0).unwrap().message_editor().unwrap().clone()
6428            });
6429
6430            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6431        })
6432    }
6433
6434    #[gpui::test]
6435    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6436        init_test(cx);
6437
6438        let connection = StubAgentConnection::new();
6439
6440        let (thread_view, cx) =
6441            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6442        add_to_workspace(thread_view.clone(), cx);
6443
6444        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6445        message_editor.update_in(cx, |editor, window, cx| {
6446            editor.set_text("Original message to edit", window, cx);
6447        });
6448        thread_view.update_in(cx, |thread_view, window, cx| {
6449            thread_view.send(window, cx);
6450        });
6451
6452        cx.run_until_parked();
6453
6454        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6455            let thread = view.thread().unwrap().read(cx);
6456            assert_eq!(thread.entries().len(), 1);
6457
6458            let editor = view
6459                .entry_view_state
6460                .read(cx)
6461                .entry(0)
6462                .unwrap()
6463                .message_editor()
6464                .unwrap()
6465                .clone();
6466
6467            (editor, thread.session_id().clone())
6468        });
6469
6470        // Focus
6471        cx.focus(&user_message_editor);
6472
6473        thread_view.read_with(cx, |view, _cx| {
6474            assert_eq!(view.editing_message, Some(0));
6475        });
6476
6477        // Edit
6478        user_message_editor.update_in(cx, |editor, window, cx| {
6479            editor.set_text("Edited message content", window, cx);
6480        });
6481
6482        thread_view.read_with(cx, |view, _cx| {
6483            assert_eq!(view.editing_message, Some(0));
6484        });
6485
6486        // Finish streaming response
6487        cx.update(|_, cx| {
6488            connection.send_update(
6489                session_id.clone(),
6490                acp::SessionUpdate::AgentMessageChunk {
6491                    content: acp::ContentBlock::Text(acp::TextContent {
6492                        text: "Response".into(),
6493                        annotations: None,
6494                        meta: None,
6495                    }),
6496                },
6497                cx,
6498            );
6499            connection.end_turn(session_id, acp::StopReason::EndTurn);
6500        });
6501
6502        thread_view.read_with(cx, |view, _cx| {
6503            assert_eq!(view.editing_message, Some(0));
6504        });
6505
6506        cx.run_until_parked();
6507
6508        // Should still be editing
6509        cx.update(|window, cx| {
6510            assert!(user_message_editor.focus_handle(cx).is_focused(window));
6511            assert_eq!(thread_view.read(cx).editing_message, Some(0));
6512            assert_eq!(
6513                user_message_editor.read(cx).text(cx),
6514                "Edited message content"
6515            );
6516        });
6517    }
6518
6519    #[gpui::test]
6520    async fn test_interrupt(cx: &mut TestAppContext) {
6521        init_test(cx);
6522
6523        let connection = StubAgentConnection::new();
6524
6525        let (thread_view, cx) =
6526            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6527        add_to_workspace(thread_view.clone(), cx);
6528
6529        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6530        message_editor.update_in(cx, |editor, window, cx| {
6531            editor.set_text("Message 1", window, cx);
6532        });
6533        thread_view.update_in(cx, |thread_view, window, cx| {
6534            thread_view.send(window, cx);
6535        });
6536
6537        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6538            let thread = view.thread().unwrap();
6539
6540            (thread.clone(), thread.read(cx).session_id().clone())
6541        });
6542
6543        cx.run_until_parked();
6544
6545        cx.update(|_, cx| {
6546            connection.send_update(
6547                session_id.clone(),
6548                acp::SessionUpdate::AgentMessageChunk {
6549                    content: "Message 1 resp".into(),
6550                },
6551                cx,
6552            );
6553        });
6554
6555        cx.run_until_parked();
6556
6557        thread.read_with(cx, |thread, cx| {
6558            assert_eq!(
6559                thread.to_markdown(cx),
6560                indoc::indoc! {"
6561                    ## User
6562
6563                    Message 1
6564
6565                    ## Assistant
6566
6567                    Message 1 resp
6568
6569                "}
6570            )
6571        });
6572
6573        message_editor.update_in(cx, |editor, window, cx| {
6574            editor.set_text("Message 2", window, cx);
6575        });
6576        thread_view.update_in(cx, |thread_view, window, cx| {
6577            thread_view.send(window, cx);
6578        });
6579
6580        cx.update(|_, cx| {
6581            // Simulate a response sent after beginning to cancel
6582            connection.send_update(
6583                session_id.clone(),
6584                acp::SessionUpdate::AgentMessageChunk {
6585                    content: "onse".into(),
6586                },
6587                cx,
6588            );
6589        });
6590
6591        cx.run_until_parked();
6592
6593        // Last Message 1 response should appear before Message 2
6594        thread.read_with(cx, |thread, cx| {
6595            assert_eq!(
6596                thread.to_markdown(cx),
6597                indoc::indoc! {"
6598                    ## User
6599
6600                    Message 1
6601
6602                    ## Assistant
6603
6604                    Message 1 response
6605
6606                    ## User
6607
6608                    Message 2
6609
6610                "}
6611            )
6612        });
6613
6614        cx.update(|_, cx| {
6615            connection.send_update(
6616                session_id.clone(),
6617                acp::SessionUpdate::AgentMessageChunk {
6618                    content: "Message 2 response".into(),
6619                },
6620                cx,
6621            );
6622            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6623        });
6624
6625        cx.run_until_parked();
6626
6627        thread.read_with(cx, |thread, cx| {
6628            assert_eq!(
6629                thread.to_markdown(cx),
6630                indoc::indoc! {"
6631                    ## User
6632
6633                    Message 1
6634
6635                    ## Assistant
6636
6637                    Message 1 response
6638
6639                    ## User
6640
6641                    Message 2
6642
6643                    ## Assistant
6644
6645                    Message 2 response
6646
6647                "}
6648            )
6649        });
6650    }
6651}