thread_view.rs

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