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