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