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