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