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    collapsed_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"
 339            || agent.name() == "Codex"
 340            || !available_commands.borrow().is_empty()
 341        {
 342            format!(
 343                "Message {} — @ to include context, / for commands",
 344                agent.name()
 345            )
 346        } else {
 347            format!("Message {} — @ to include context", agent.name())
 348        };
 349
 350        let message_editor = cx.new(|cx| {
 351            let mut editor = MessageEditor::new(
 352                workspace.clone(),
 353                project.clone(),
 354                history_store.clone(),
 355                prompt_store.clone(),
 356                prompt_capabilities.clone(),
 357                available_commands.clone(),
 358                agent.name(),
 359                &placeholder,
 360                editor::EditorMode::AutoHeight {
 361                    min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
 362                    max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
 363                },
 364                window,
 365                cx,
 366            );
 367            if let Some(entry) = summarize_thread {
 368                editor.insert_thread_summary(entry, window, cx);
 369            }
 370            editor
 371        });
 372
 373        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 374
 375        let entry_view_state = cx.new(|_| {
 376            EntryViewState::new(
 377                workspace.clone(),
 378                project.clone(),
 379                history_store.clone(),
 380                prompt_store.clone(),
 381                prompt_capabilities.clone(),
 382                available_commands.clone(),
 383                agent.name(),
 384            )
 385        });
 386
 387        let agent_server_store = project.read(cx).agent_server_store().clone();
 388        let subscriptions = [
 389            cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
 390            cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
 391            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 392            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 393            cx.subscribe_in(
 394                &agent_server_store,
 395                window,
 396                Self::handle_agent_servers_updated,
 397            ),
 398        ];
 399
 400        Self {
 401            agent: agent.clone(),
 402            workspace: workspace.clone(),
 403            project: project.clone(),
 404            entry_view_state,
 405            thread_state: Self::initial_state(
 406                agent.clone(),
 407                resume_thread.clone(),
 408                workspace.clone(),
 409                project.clone(),
 410                window,
 411                cx,
 412            ),
 413            login: None,
 414            message_editor,
 415            model_selector: None,
 416            profile_selector: None,
 417
 418            notifications: Vec::new(),
 419            notification_subscriptions: HashMap::default(),
 420            list_state: list_state,
 421            thread_retry_status: None,
 422            thread_error: None,
 423            thread_feedback: Default::default(),
 424            auth_task: None,
 425            collapsed_tool_calls: HashSet::default(),
 426            expanded_thinking_blocks: HashSet::default(),
 427            editing_message: None,
 428            edits_expanded: false,
 429            plan_expanded: false,
 430            prompt_capabilities,
 431            available_commands,
 432            editor_expanded: false,
 433            should_be_following: false,
 434            history_store,
 435            hovered_recent_history_item: None,
 436            is_loading_contents: false,
 437            _subscriptions: subscriptions,
 438            _cancel_task: None,
 439            focus_handle: cx.focus_handle(),
 440            new_server_version_available: None,
 441            resume_thread_metadata: resume_thread,
 442        }
 443    }
 444
 445    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 446        self.thread_state = Self::initial_state(
 447            self.agent.clone(),
 448            self.resume_thread_metadata.clone(),
 449            self.workspace.clone(),
 450            self.project.clone(),
 451            window,
 452            cx,
 453        );
 454        self.available_commands.replace(vec![]);
 455        self.new_server_version_available.take();
 456        cx.notify();
 457    }
 458
 459    fn initial_state(
 460        agent: Rc<dyn AgentServer>,
 461        resume_thread: Option<DbThreadMetadata>,
 462        workspace: WeakEntity<Workspace>,
 463        project: Entity<Project>,
 464        window: &mut Window,
 465        cx: &mut Context<Self>,
 466    ) -> ThreadState {
 467        if project.read(cx).is_via_collab()
 468            && agent.clone().downcast::<NativeAgentServer>().is_none()
 469        {
 470            return ThreadState::LoadError(LoadError::Other(
 471                "External agents are not yet supported in shared projects.".into(),
 472            ));
 473        }
 474        let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 475        // Pick the first non-single-file worktree for the root directory if there are any,
 476        // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
 477        worktrees.sort_by(|l, r| {
 478            l.read(cx)
 479                .is_single_file()
 480                .cmp(&r.read(cx).is_single_file())
 481        });
 482        let root_dir = worktrees
 483            .into_iter()
 484            .filter_map(|worktree| {
 485                if worktree.read(cx).is_single_file() {
 486                    Some(worktree.read(cx).abs_path().parent()?.into())
 487                } else {
 488                    Some(worktree.read(cx).abs_path())
 489                }
 490            })
 491            .next();
 492        let (status_tx, mut status_rx) = watch::channel("Loading…".into());
 493        let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
 494        let delegate = AgentServerDelegate::new(
 495            project.read(cx).agent_server_store().clone(),
 496            project.clone(),
 497            Some(status_tx),
 498            Some(new_version_available_tx),
 499        );
 500
 501        let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
 502        let load_task = cx.spawn_in(window, async move |this, cx| {
 503            let connection = match connect_task.await {
 504                Ok((connection, login)) => {
 505                    this.update(cx, |this, _| this.login = login).ok();
 506                    connection
 507                }
 508                Err(err) => {
 509                    this.update_in(cx, |this, window, cx| {
 510                        if err.downcast_ref::<LoadError>().is_some() {
 511                            this.handle_load_error(err, window, cx);
 512                        } else {
 513                            this.handle_thread_error(err, cx);
 514                        }
 515                        cx.notify();
 516                    })
 517                    .log_err();
 518                    return;
 519                }
 520            };
 521
 522            let result = if let Some(native_agent) = connection
 523                .clone()
 524                .downcast::<agent2::NativeAgentConnection>()
 525                && let Some(resume) = resume_thread.clone()
 526            {
 527                cx.update(|_, cx| {
 528                    native_agent
 529                        .0
 530                        .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
 531                })
 532                .log_err()
 533            } else {
 534                let root_dir = if let Some(acp_agent) = connection
 535                    .clone()
 536                    .downcast::<agent_servers::AcpConnection>()
 537                {
 538                    acp_agent.root_dir().into()
 539                } else {
 540                    root_dir.unwrap_or(paths::home_dir().as_path().into())
 541                };
 542                cx.update(|_, cx| {
 543                    connection
 544                        .clone()
 545                        .new_thread(project.clone(), &root_dir, cx)
 546                })
 547                .log_err()
 548            };
 549
 550            let Some(result) = result else {
 551                return;
 552            };
 553
 554            let result = match result.await {
 555                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 556                    Ok(err) => {
 557                        cx.update(|window, cx| {
 558                            Self::handle_auth_required(this, err, agent, connection, window, cx)
 559                        })
 560                        .log_err();
 561                        return;
 562                    }
 563                    Err(err) => Err(err),
 564                },
 565                Ok(thread) => Ok(thread),
 566            };
 567
 568            this.update_in(cx, |this, window, cx| {
 569                match result {
 570                    Ok(thread) => {
 571                        let action_log = thread.read(cx).action_log().clone();
 572
 573                        this.prompt_capabilities
 574                            .replace(thread.read(cx).prompt_capabilities());
 575
 576                        let count = thread.read(cx).entries().len();
 577                        this.entry_view_state.update(cx, |view_state, cx| {
 578                            for ix in 0..count {
 579                                view_state.sync_entry(ix, &thread, window, cx);
 580                            }
 581                            this.list_state.splice_focusable(
 582                                0..0,
 583                                (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
 584                            );
 585                        });
 586
 587                        if let Some(resume) = resume_thread {
 588                            this.history_store.update(cx, |history, cx| {
 589                                history.push_recently_opened_entry(
 590                                    HistoryEntryId::AcpThread(resume.id),
 591                                    cx,
 592                                );
 593                            });
 594                        }
 595
 596                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 597
 598                        this.model_selector = thread
 599                            .read(cx)
 600                            .connection()
 601                            .model_selector(thread.read(cx).session_id())
 602                            .map(|selector| {
 603                                cx.new(|cx| {
 604                                    AcpModelSelectorPopover::new(
 605                                        selector,
 606                                        PopoverMenuHandle::default(),
 607                                        this.focus_handle(cx),
 608                                        window,
 609                                        cx,
 610                                    )
 611                                })
 612                            });
 613
 614                        let mode_selector = thread
 615                            .read(cx)
 616                            .connection()
 617                            .session_modes(thread.read(cx).session_id(), cx)
 618                            .map(|session_modes| {
 619                                let fs = this.project.read(cx).fs().clone();
 620                                let focus_handle = this.focus_handle(cx);
 621                                cx.new(|_cx| {
 622                                    ModeSelector::new(
 623                                        session_modes,
 624                                        this.agent.clone(),
 625                                        fs,
 626                                        focus_handle,
 627                                    )
 628                                })
 629                            });
 630
 631                        let mut subscriptions = vec![
 632                            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 633                            cx.observe(&action_log, |_, _, cx| cx.notify()),
 634                        ];
 635
 636                        let title_editor =
 637                            if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
 638                                let editor = cx.new(|cx| {
 639                                    let mut editor = Editor::single_line(window, cx);
 640                                    editor.set_text(thread.read(cx).title(), window, cx);
 641                                    editor
 642                                });
 643                                subscriptions.push(cx.subscribe_in(
 644                                    &editor,
 645                                    window,
 646                                    Self::handle_title_editor_event,
 647                                ));
 648                                Some(editor)
 649                            } else {
 650                                None
 651                            };
 652
 653                        this.thread_state = ThreadState::Ready {
 654                            thread,
 655                            title_editor,
 656                            mode_selector,
 657                            _subscriptions: subscriptions,
 658                        };
 659                        this.message_editor.focus_handle(cx).focus(window);
 660
 661                        this.profile_selector = this.as_native_thread(cx).map(|thread| {
 662                            cx.new(|cx| {
 663                                ProfileSelector::new(
 664                                    <dyn Fs>::global(cx),
 665                                    Arc::new(thread.clone()),
 666                                    this.focus_handle(cx),
 667                                    cx,
 668                                )
 669                            })
 670                        });
 671
 672                        cx.notify();
 673                    }
 674                    Err(err) => {
 675                        this.handle_load_error(err, window, cx);
 676                    }
 677                };
 678            })
 679            .log_err();
 680        });
 681
 682        cx.spawn(async move |this, cx| {
 683            while let Ok(new_version) = new_version_available_rx.recv().await {
 684                if let Some(new_version) = new_version {
 685                    this.update(cx, |this, cx| {
 686                        this.new_server_version_available = Some(new_version.into());
 687                        cx.notify();
 688                    })
 689                    .log_err();
 690                }
 691            }
 692        })
 693        .detach();
 694
 695        let loading_view = cx.new(|cx| {
 696            let update_title_task = cx.spawn(async move |this, cx| {
 697                loop {
 698                    let status = status_rx.recv().await?;
 699                    this.update(cx, |this: &mut LoadingView, cx| {
 700                        this.title = status;
 701                        cx.notify();
 702                    })?;
 703                }
 704            });
 705
 706            LoadingView {
 707                title: "Loading…".into(),
 708                _load_task: load_task,
 709                _update_title_task: update_title_task,
 710            }
 711        });
 712
 713        ThreadState::Loading(loading_view)
 714    }
 715
 716    fn handle_auth_required(
 717        this: WeakEntity<Self>,
 718        err: AuthRequired,
 719        agent: Rc<dyn AgentServer>,
 720        connection: Rc<dyn AgentConnection>,
 721        window: &mut Window,
 722        cx: &mut App,
 723    ) {
 724        let agent_name = agent.name();
 725        let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
 726            let registry = LanguageModelRegistry::global(cx);
 727
 728            let sub = window.subscribe(&registry, cx, {
 729                let provider_id = provider_id.clone();
 730                let this = this.clone();
 731                move |_, ev, window, cx| {
 732                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
 733                        && &provider_id == updated_provider_id
 734                        && LanguageModelRegistry::global(cx)
 735                            .read(cx)
 736                            .provider(&provider_id)
 737                            .map_or(false, |provider| provider.is_authenticated(cx))
 738                    {
 739                        this.update(cx, |this, cx| {
 740                            this.reset(window, cx);
 741                        })
 742                        .ok();
 743                    }
 744                }
 745            });
 746
 747            let view = registry.read(cx).provider(&provider_id).map(|provider| {
 748                provider.configuration_view(
 749                    language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
 750                    window,
 751                    cx,
 752                )
 753            });
 754
 755            (view, Some(sub))
 756        } else {
 757            (None, None)
 758        };
 759
 760        this.update(cx, |this, cx| {
 761            this.thread_state = ThreadState::Unauthenticated {
 762                pending_auth_method: None,
 763                connection,
 764                configuration_view,
 765                description: err
 766                    .description
 767                    .clone()
 768                    .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
 769                _subscription: subscription,
 770            };
 771            if this.message_editor.focus_handle(cx).is_focused(window) {
 772                this.focus_handle.focus(window)
 773            }
 774            cx.notify();
 775        })
 776        .ok();
 777    }
 778
 779    fn handle_load_error(
 780        &mut self,
 781        err: anyhow::Error,
 782        window: &mut Window,
 783        cx: &mut Context<Self>,
 784    ) {
 785        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 786            self.thread_state = ThreadState::LoadError(load_err.clone());
 787        } else {
 788            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 789        }
 790        if self.message_editor.focus_handle(cx).is_focused(window) {
 791            self.focus_handle.focus(window)
 792        }
 793        cx.notify();
 794    }
 795
 796    fn handle_agent_servers_updated(
 797        &mut self,
 798        _agent_server_store: &Entity<project::AgentServerStore>,
 799        _event: &project::AgentServersUpdated,
 800        window: &mut Window,
 801        cx: &mut Context<Self>,
 802    ) {
 803        // If we're in a LoadError state OR have a thread_error set (which can happen
 804        // when agent.connect() fails during loading), retry loading the thread.
 805        // This handles the case where a thread is restored before authentication completes.
 806        let should_retry =
 807            matches!(&self.thread_state, ThreadState::LoadError(_)) || self.thread_error.is_some();
 808
 809        if should_retry {
 810            self.thread_error = None;
 811            self.reset(window, cx);
 812        }
 813    }
 814
 815    pub fn workspace(&self) -> &WeakEntity<Workspace> {
 816        &self.workspace
 817    }
 818
 819    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 820        match &self.thread_state {
 821            ThreadState::Ready { thread, .. } => Some(thread),
 822            ThreadState::Unauthenticated { .. }
 823            | ThreadState::Loading { .. }
 824            | ThreadState::LoadError { .. } => None,
 825        }
 826    }
 827
 828    pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
 829        match &self.thread_state {
 830            ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
 831            ThreadState::Unauthenticated { .. }
 832            | ThreadState::Loading { .. }
 833            | ThreadState::LoadError { .. } => None,
 834        }
 835    }
 836
 837    pub fn title(&self, cx: &App) -> SharedString {
 838        match &self.thread_state {
 839            ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
 840            ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
 841            ThreadState::LoadError(error) => match error {
 842                LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
 843                LoadError::FailedToInstall(_) => {
 844                    format!("Failed to Install {}", self.agent.name()).into()
 845                }
 846                LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
 847                LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
 848            },
 849        }
 850    }
 851
 852    pub fn title_editor(&self) -> Option<Entity<Editor>> {
 853        if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
 854            title_editor.clone()
 855        } else {
 856            None
 857        }
 858    }
 859
 860    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 861        self.thread_error.take();
 862        self.thread_retry_status.take();
 863
 864        if let Some(thread) = self.thread() {
 865            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 866        }
 867    }
 868
 869    pub fn expand_message_editor(
 870        &mut self,
 871        _: &ExpandMessageEditor,
 872        _window: &mut Window,
 873        cx: &mut Context<Self>,
 874    ) {
 875        self.set_editor_is_expanded(!self.editor_expanded, cx);
 876        cx.notify();
 877    }
 878
 879    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 880        self.editor_expanded = is_expanded;
 881        self.message_editor.update(cx, |editor, cx| {
 882            if is_expanded {
 883                editor.set_mode(
 884                    EditorMode::Full {
 885                        scale_ui_elements_with_buffer_font_size: false,
 886                        show_active_line_background: false,
 887                        sized_by_content: false,
 888                    },
 889                    cx,
 890                )
 891            } else {
 892                let agent_settings = AgentSettings::get_global(cx);
 893                editor.set_mode(
 894                    EditorMode::AutoHeight {
 895                        min_lines: agent_settings.message_editor_min_lines,
 896                        max_lines: Some(agent_settings.set_message_editor_max_lines()),
 897                    },
 898                    cx,
 899                )
 900            }
 901        });
 902        cx.notify();
 903    }
 904
 905    pub fn handle_title_editor_event(
 906        &mut self,
 907        title_editor: &Entity<Editor>,
 908        event: &EditorEvent,
 909        window: &mut Window,
 910        cx: &mut Context<Self>,
 911    ) {
 912        let Some(thread) = self.thread() else { return };
 913
 914        match event {
 915            EditorEvent::BufferEdited => {
 916                let new_title = title_editor.read(cx).text(cx);
 917                thread.update(cx, |thread, cx| {
 918                    thread
 919                        .set_title(new_title.into(), cx)
 920                        .detach_and_log_err(cx);
 921                })
 922            }
 923            EditorEvent::Blurred => {
 924                if title_editor.read(cx).text(cx).is_empty() {
 925                    title_editor.update(cx, |editor, cx| {
 926                        editor.set_text("New Thread", window, cx);
 927                    });
 928                }
 929            }
 930            _ => {}
 931        }
 932    }
 933
 934    pub fn handle_message_editor_event(
 935        &mut self,
 936        _: &Entity<MessageEditor>,
 937        event: &MessageEditorEvent,
 938        window: &mut Window,
 939        cx: &mut Context<Self>,
 940    ) {
 941        match event {
 942            MessageEditorEvent::Send => self.send(window, cx),
 943            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 944            MessageEditorEvent::Focus => {
 945                self.cancel_editing(&Default::default(), window, cx);
 946            }
 947            MessageEditorEvent::LostFocus => {}
 948        }
 949    }
 950
 951    pub fn handle_entry_view_event(
 952        &mut self,
 953        _: &Entity<EntryViewState>,
 954        event: &EntryViewEvent,
 955        window: &mut Window,
 956        cx: &mut Context<Self>,
 957    ) {
 958        match &event.view_event {
 959            ViewEvent::NewDiff(tool_call_id) => {
 960                if !AgentSettings::get_global(cx).expand_edit_card {
 961                    self.collapsed_tool_calls.insert(tool_call_id.clone());
 962                }
 963            }
 964            ViewEvent::NewTerminal(tool_call_id) => {
 965                if !AgentSettings::get_global(cx).expand_terminal_card {
 966                    self.collapsed_tool_calls.insert(tool_call_id.clone());
 967                }
 968            }
 969            ViewEvent::TerminalMovedToBackground(tool_call_id) => {
 970                self.collapsed_tool_calls.insert(tool_call_id.clone());
 971            }
 972            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 973                if let Some(thread) = self.thread()
 974                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 975                        thread.read(cx).entries().get(event.entry_index)
 976                    && user_message.id.is_some()
 977                {
 978                    self.editing_message = Some(event.entry_index);
 979                    cx.notify();
 980                }
 981            }
 982            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
 983                if let Some(thread) = self.thread()
 984                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 985                        thread.read(cx).entries().get(event.entry_index)
 986                    && user_message.id.is_some()
 987                {
 988                    if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
 989                        self.editing_message = None;
 990                        cx.notify();
 991                    }
 992                }
 993            }
 994            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 995                self.regenerate(event.entry_index, editor.clone(), window, cx);
 996            }
 997            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 998                self.cancel_editing(&Default::default(), window, cx);
 999            }
1000        }
1001    }
1002
1003    fn resume_chat(&mut self, cx: &mut Context<Self>) {
1004        self.thread_error.take();
1005        let Some(thread) = self.thread() else {
1006            return;
1007        };
1008        if !thread.read(cx).can_resume(cx) {
1009            return;
1010        }
1011
1012        let task = thread.update(cx, |thread, cx| thread.resume(cx));
1013        cx.spawn(async move |this, cx| {
1014            let result = task.await;
1015
1016            this.update(cx, |this, cx| {
1017                if let Err(err) = result {
1018                    this.handle_thread_error(err, cx);
1019                }
1020            })
1021        })
1022        .detach();
1023    }
1024
1025    fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1026        let Some(thread) = self.thread() else { return };
1027
1028        if self.is_loading_contents {
1029            return;
1030        }
1031
1032        self.history_store.update(cx, |history, cx| {
1033            history.push_recently_opened_entry(
1034                HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
1035                cx,
1036            );
1037        });
1038
1039        if thread.read(cx).status() != ThreadStatus::Idle {
1040            self.stop_current_and_send_new_message(window, cx);
1041            return;
1042        }
1043
1044        let text = self.message_editor.read(cx).text(cx);
1045        let text = text.trim();
1046        if text == "/login" || text == "/logout" {
1047            let ThreadState::Ready { thread, .. } = &self.thread_state else {
1048                return;
1049            };
1050
1051            let connection = thread.read(cx).connection().clone();
1052            let can_login = !connection.auth_methods().is_empty() || self.login.is_some();
1053            // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
1054            let logout_supported = text == "/logout"
1055                && self
1056                    .available_commands
1057                    .borrow()
1058                    .iter()
1059                    .any(|command| command.name == "logout");
1060            if can_login && !logout_supported {
1061                self.message_editor
1062                    .update(cx, |editor, cx| editor.clear(window, cx));
1063
1064                let this = cx.weak_entity();
1065                let agent = self.agent.clone();
1066                window.defer(cx, |window, cx| {
1067                    Self::handle_auth_required(
1068                        this,
1069                        AuthRequired {
1070                            description: None,
1071                            provider_id: None,
1072                        },
1073                        agent,
1074                        connection,
1075                        window,
1076                        cx,
1077                    );
1078                });
1079                cx.notify();
1080                return;
1081            }
1082        }
1083
1084        self.send_impl(self.message_editor.clone(), window, cx)
1085    }
1086
1087    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1088        let Some(thread) = self.thread().cloned() else {
1089            return;
1090        };
1091
1092        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1093
1094        cx.spawn_in(window, async move |this, cx| {
1095            cancelled.await;
1096
1097            this.update_in(cx, |this, window, cx| {
1098                this.send_impl(this.message_editor.clone(), window, cx);
1099            })
1100            .ok();
1101        })
1102        .detach();
1103    }
1104
1105    fn send_impl(
1106        &mut self,
1107        message_editor: Entity<MessageEditor>,
1108        window: &mut Window,
1109        cx: &mut Context<Self>,
1110    ) {
1111        let full_mention_content = self.as_native_thread(cx).is_some_and(|thread| {
1112            // Include full contents when using minimal profile
1113            let thread = thread.read(cx);
1114            AgentSettings::get_global(cx)
1115                .profiles
1116                .get(thread.profile())
1117                .is_some_and(|profile| profile.tools.is_empty())
1118        });
1119
1120        let contents = message_editor.update(cx, |message_editor, cx| {
1121            message_editor.contents(full_mention_content, cx)
1122        });
1123
1124        let agent_telemetry_id = self.agent.telemetry_id();
1125
1126        self.thread_error.take();
1127        self.editing_message.take();
1128        self.thread_feedback.clear();
1129
1130        let Some(thread) = self.thread() else {
1131            return;
1132        };
1133        let thread = thread.downgrade();
1134        if self.should_be_following {
1135            self.workspace
1136                .update(cx, |workspace, cx| {
1137                    workspace.follow(CollaboratorId::Agent, window, cx);
1138                })
1139                .ok();
1140        }
1141
1142        self.is_loading_contents = true;
1143        let guard = cx.new(|_| ());
1144        cx.observe_release(&guard, |this, _guard, cx| {
1145            this.is_loading_contents = false;
1146            cx.notify();
1147        })
1148        .detach();
1149
1150        let task = cx.spawn_in(window, async move |this, cx| {
1151            let (contents, tracked_buffers) = contents.await?;
1152
1153            if contents.is_empty() {
1154                return Ok(());
1155            }
1156
1157            this.update_in(cx, |this, window, cx| {
1158                this.set_editor_is_expanded(false, cx);
1159                this.scroll_to_bottom(cx);
1160                this.message_editor.update(cx, |message_editor, cx| {
1161                    message_editor.clear(window, cx);
1162                });
1163            })?;
1164            let send = thread.update(cx, |thread, cx| {
1165                thread.action_log().update(cx, |action_log, cx| {
1166                    for buffer in tracked_buffers {
1167                        action_log.buffer_read(buffer, cx)
1168                    }
1169                });
1170                drop(guard);
1171
1172                telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1173
1174                thread.send(contents, cx)
1175            })?;
1176            send.await
1177        });
1178
1179        cx.spawn(async move |this, cx| {
1180            if let Err(err) = task.await {
1181                this.update(cx, |this, cx| {
1182                    this.handle_thread_error(err, cx);
1183                })
1184                .ok();
1185            } else {
1186                this.update(cx, |this, cx| {
1187                    this.should_be_following = this
1188                        .workspace
1189                        .update(cx, |workspace, _| {
1190                            workspace.is_being_followed(CollaboratorId::Agent)
1191                        })
1192                        .unwrap_or_default();
1193                })
1194                .ok();
1195            }
1196        })
1197        .detach();
1198    }
1199
1200    fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1201        let Some(thread) = self.thread().cloned() else {
1202            return;
1203        };
1204
1205        if let Some(index) = self.editing_message.take()
1206            && let Some(editor) = self
1207                .entry_view_state
1208                .read(cx)
1209                .entry(index)
1210                .and_then(|e| e.message_editor())
1211                .cloned()
1212        {
1213            editor.update(cx, |editor, cx| {
1214                if let Some(user_message) = thread
1215                    .read(cx)
1216                    .entries()
1217                    .get(index)
1218                    .and_then(|e| e.user_message())
1219                {
1220                    editor.set_message(user_message.chunks.clone(), window, cx);
1221                }
1222            })
1223        };
1224        self.focus_handle(cx).focus(window);
1225        cx.notify();
1226    }
1227
1228    fn regenerate(
1229        &mut self,
1230        entry_ix: usize,
1231        message_editor: Entity<MessageEditor>,
1232        window: &mut Window,
1233        cx: &mut Context<Self>,
1234    ) {
1235        let Some(thread) = self.thread().cloned() else {
1236            return;
1237        };
1238        if self.is_loading_contents {
1239            return;
1240        }
1241
1242        let Some(user_message_id) = thread.update(cx, |thread, _| {
1243            thread.entries().get(entry_ix)?.user_message()?.id.clone()
1244        }) else {
1245            return;
1246        };
1247
1248        cx.spawn_in(window, async move |this, cx| {
1249            thread
1250                .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1251                .await?;
1252            this.update_in(cx, |this, window, cx| {
1253                this.send_impl(message_editor, window, cx);
1254            })?;
1255            anyhow::Ok(())
1256        })
1257        .detach();
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.collapsed_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.collapsed_tool_calls.insert(id.clone());
2276                                                        } else {
2277                                                            this.collapsed_tool_calls.remove(&id);
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.collapsed_tool_calls.insert(tool_call_id.clone());
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.collapsed_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.collapsed_tool_calls.insert(id.clone());
2893                        } else {
2894                            this.collapsed_tool_calls.remove(&id);
2895                        }
2896                    }
2897                })),
2898            );
2899
2900        let terminal_view = self
2901            .entry_view_state
2902            .read(cx)
2903            .entry(entry_ix)
2904            .and_then(|entry| entry.terminal(terminal));
2905        let show_output = is_expanded && terminal_view.is_some();
2906
2907        v_flex()
2908            .my_1p5()
2909            .mx_5()
2910            .border_1()
2911            .when(tool_failed || command_failed, |card| card.border_dashed())
2912            .border_color(border_color)
2913            .rounded_md()
2914            .overflow_hidden()
2915            .child(
2916                v_flex()
2917                    .group(&header_group)
2918                    .py_1p5()
2919                    .pr_1p5()
2920                    .pl_2()
2921                    .gap_0p5()
2922                    .bg(header_bg)
2923                    .text_xs()
2924                    .child(header)
2925                    .child(
2926                        MarkdownElement::new(
2927                            command.clone(),
2928                            terminal_command_markdown_style(window, cx),
2929                        )
2930                        .code_block_renderer(
2931                            markdown::CodeBlockRenderer::Default {
2932                                copy_button: false,
2933                                copy_button_on_hover: true,
2934                                border: false,
2935                            },
2936                        ),
2937                    ),
2938            )
2939            .when(show_output, |this| {
2940                this.child(
2941                    div()
2942                        .pt_2()
2943                        .border_t_1()
2944                        .when(tool_failed || command_failed, |card| card.border_dashed())
2945                        .border_color(border_color)
2946                        .bg(cx.theme().colors().editor_background)
2947                        .rounded_b_md()
2948                        .text_ui_sm(cx)
2949                        .h_full()
2950                        .children(terminal_view.map(|terminal_view| {
2951                            if terminal_view
2952                                .read(cx)
2953                                .content_mode(window, cx)
2954                                .is_scrollable()
2955                            {
2956                                div().h_72().child(terminal_view).into_any_element()
2957                            } else {
2958                                terminal_view.into_any_element()
2959                            }
2960                        })),
2961                )
2962            })
2963            .into_any()
2964    }
2965
2966    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2967        let project_context = self
2968            .as_native_thread(cx)?
2969            .read(cx)
2970            .project_context()
2971            .read(cx);
2972
2973        let user_rules_text = if project_context.user_rules.is_empty() {
2974            None
2975        } else if project_context.user_rules.len() == 1 {
2976            let user_rules = &project_context.user_rules[0];
2977
2978            match user_rules.title.as_ref() {
2979                Some(title) => Some(format!("Using \"{title}\" user rule")),
2980                None => Some("Using user rule".into()),
2981            }
2982        } else {
2983            Some(format!(
2984                "Using {} user rules",
2985                project_context.user_rules.len()
2986            ))
2987        };
2988
2989        let first_user_rules_id = project_context
2990            .user_rules
2991            .first()
2992            .map(|user_rules| user_rules.uuid.0);
2993
2994        let rules_files = project_context
2995            .worktrees
2996            .iter()
2997            .filter_map(|worktree| worktree.rules_file.as_ref())
2998            .collect::<Vec<_>>();
2999
3000        let rules_file_text = match rules_files.as_slice() {
3001            &[] => None,
3002            &[rules_file] => Some(format!(
3003                "Using project {:?} file",
3004                rules_file.path_in_worktree
3005            )),
3006            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3007        };
3008
3009        if user_rules_text.is_none() && rules_file_text.is_none() {
3010            return None;
3011        }
3012
3013        let has_both = user_rules_text.is_some() && rules_file_text.is_some();
3014
3015        Some(
3016            h_flex()
3017                .px_2p5()
3018                .child(
3019                    Icon::new(IconName::Attach)
3020                        .size(IconSize::XSmall)
3021                        .color(Color::Disabled),
3022                )
3023                .when_some(user_rules_text, |parent, user_rules_text| {
3024                    parent.child(
3025                        h_flex()
3026                            .id("user-rules")
3027                            .ml_1()
3028                            .mr_1p5()
3029                            .child(
3030                                Label::new(user_rules_text)
3031                                    .size(LabelSize::XSmall)
3032                                    .color(Color::Muted)
3033                                    .truncate(),
3034                            )
3035                            .hover(|s| s.bg(cx.theme().colors().element_hover))
3036                            .tooltip(Tooltip::text("View User Rules"))
3037                            .on_click(move |_event, window, cx| {
3038                                window.dispatch_action(
3039                                    Box::new(OpenRulesLibrary {
3040                                        prompt_to_select: first_user_rules_id,
3041                                    }),
3042                                    cx,
3043                                )
3044                            }),
3045                    )
3046                })
3047                .when(has_both, |this| {
3048                    this.child(
3049                        Label::new("")
3050                            .size(LabelSize::XSmall)
3051                            .color(Color::Disabled),
3052                    )
3053                })
3054                .when_some(rules_file_text, |parent, rules_file_text| {
3055                    parent.child(
3056                        h_flex()
3057                            .id("project-rules")
3058                            .ml_1p5()
3059                            .child(
3060                                Label::new(rules_file_text)
3061                                    .size(LabelSize::XSmall)
3062                                    .color(Color::Muted),
3063                            )
3064                            .hover(|s| s.bg(cx.theme().colors().element_hover))
3065                            .tooltip(Tooltip::text("View Project Rules"))
3066                            .on_click(cx.listener(Self::handle_open_rules)),
3067                    )
3068                })
3069                .into_any(),
3070        )
3071    }
3072
3073    fn render_empty_state_section_header(
3074        &self,
3075        label: impl Into<SharedString>,
3076        action_slot: Option<AnyElement>,
3077        cx: &mut Context<Self>,
3078    ) -> impl IntoElement {
3079        div().pl_1().pr_1p5().child(
3080            h_flex()
3081                .mt_2()
3082                .pl_1p5()
3083                .pb_1()
3084                .w_full()
3085                .justify_between()
3086                .border_b_1()
3087                .border_color(cx.theme().colors().border_variant)
3088                .child(
3089                    Label::new(label.into())
3090                        .size(LabelSize::Small)
3091                        .color(Color::Muted),
3092                )
3093                .children(action_slot),
3094        )
3095    }
3096
3097    fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3098        let render_history = self
3099            .agent
3100            .clone()
3101            .downcast::<agent2::NativeAgentServer>()
3102            .is_some()
3103            && self
3104                .history_store
3105                .update(cx, |history_store, cx| !history_store.is_empty(cx));
3106
3107        v_flex()
3108            .size_full()
3109            .when(render_history, |this| {
3110                let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
3111                    history_store.entries().take(3).collect()
3112                });
3113                this.justify_end().child(
3114                    v_flex()
3115                        .child(
3116                            self.render_empty_state_section_header(
3117                                "Recent",
3118                                Some(
3119                                    Button::new("view-history", "View All")
3120                                        .style(ButtonStyle::Subtle)
3121                                        .label_size(LabelSize::Small)
3122                                        .key_binding(
3123                                            KeyBinding::for_action_in(
3124                                                &OpenHistory,
3125                                                &self.focus_handle(cx),
3126                                                window,
3127                                                cx,
3128                                            )
3129                                            .map(|kb| kb.size(rems_from_px(12.))),
3130                                        )
3131                                        .on_click(move |_event, window, cx| {
3132                                            window.dispatch_action(OpenHistory.boxed_clone(), cx);
3133                                        })
3134                                        .into_any_element(),
3135                                ),
3136                                cx,
3137                            ),
3138                        )
3139                        .child(
3140                            v_flex().p_1().pr_1p5().gap_1().children(
3141                                recent_history
3142                                    .into_iter()
3143                                    .enumerate()
3144                                    .map(|(index, entry)| {
3145                                        // TODO: Add keyboard navigation.
3146                                        let is_hovered =
3147                                            self.hovered_recent_history_item == Some(index);
3148                                        crate::acp::thread_history::AcpHistoryEntryElement::new(
3149                                            entry,
3150                                            cx.entity().downgrade(),
3151                                        )
3152                                        .hovered(is_hovered)
3153                                        .on_hover(cx.listener(
3154                                            move |this, is_hovered, _window, cx| {
3155                                                if *is_hovered {
3156                                                    this.hovered_recent_history_item = Some(index);
3157                                                } else if this.hovered_recent_history_item
3158                                                    == Some(index)
3159                                                {
3160                                                    this.hovered_recent_history_item = None;
3161                                                }
3162                                                cx.notify();
3163                                            },
3164                                        ))
3165                                        .into_any_element()
3166                                    }),
3167                            ),
3168                        ),
3169                )
3170            })
3171            .into_any()
3172    }
3173
3174    fn render_auth_required_state(
3175        &self,
3176        connection: &Rc<dyn AgentConnection>,
3177        description: Option<&Entity<Markdown>>,
3178        configuration_view: Option<&AnyView>,
3179        pending_auth_method: Option<&acp::AuthMethodId>,
3180        window: &mut Window,
3181        cx: &Context<Self>,
3182    ) -> Div {
3183        let show_description =
3184            configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3185
3186        let auth_methods = connection.auth_methods();
3187
3188        v_flex().flex_1().size_full().justify_end().child(
3189            v_flex()
3190                .p_2()
3191                .pr_3()
3192                .w_full()
3193                .gap_1()
3194                .border_t_1()
3195                .border_color(cx.theme().colors().border)
3196                .bg(cx.theme().status().warning.opacity(0.04))
3197                .child(
3198                    h_flex()
3199                        .gap_1p5()
3200                        .child(
3201                            Icon::new(IconName::Warning)
3202                                .color(Color::Warning)
3203                                .size(IconSize::Small),
3204                        )
3205                        .child(Label::new("Authentication Required").size(LabelSize::Small)),
3206                )
3207                .children(description.map(|desc| {
3208                    div().text_ui(cx).child(self.render_markdown(
3209                        desc.clone(),
3210                        default_markdown_style(false, false, window, cx),
3211                    ))
3212                }))
3213                .children(
3214                    configuration_view
3215                        .cloned()
3216                        .map(|view| div().w_full().child(view)),
3217                )
3218                .when(show_description, |el| {
3219                    el.child(
3220                        Label::new(format!(
3221                            "You are not currently authenticated with {}.{}",
3222                            self.agent.name(),
3223                            if auth_methods.len() > 1 {
3224                                " Please choose one of the following options:"
3225                            } else {
3226                                ""
3227                            }
3228                        ))
3229                        .size(LabelSize::Small)
3230                        .color(Color::Muted)
3231                        .mb_1()
3232                        .ml_5(),
3233                    )
3234                })
3235                .when_some(pending_auth_method, |el, _| {
3236                    el.child(
3237                        h_flex()
3238                            .py_4()
3239                            .w_full()
3240                            .justify_center()
3241                            .gap_1()
3242                            .child(
3243                                Icon::new(IconName::ArrowCircle)
3244                                    .size(IconSize::Small)
3245                                    .color(Color::Muted)
3246                                    .with_rotate_animation(2),
3247                            )
3248                            .child(Label::new("Authenticating…").size(LabelSize::Small)),
3249                    )
3250                })
3251                .when(!auth_methods.is_empty(), |this| {
3252                    this.child(
3253                        h_flex()
3254                            .justify_end()
3255                            .flex_wrap()
3256                            .gap_1()
3257                            .when(!show_description, |this| {
3258                                this.border_t_1()
3259                                    .mt_1()
3260                                    .pt_2()
3261                                    .border_color(cx.theme().colors().border.opacity(0.8))
3262                            })
3263                            .children(connection.auth_methods().iter().enumerate().rev().map(
3264                                |(ix, method)| {
3265                                    let (method_id, name) = if self
3266                                        .project
3267                                        .read(cx)
3268                                        .is_via_remote_server()
3269                                        && method.id.0.as_ref() == "oauth-personal"
3270                                        && method.name == "Log in with Google"
3271                                    {
3272                                        ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
3273                                    } else {
3274                                        (method.id.0.clone(), method.name.clone())
3275                                    };
3276
3277                                    Button::new(SharedString::from(method_id.clone()), name)
3278                                        .label_size(LabelSize::Small)
3279                                        .map(|this| {
3280                                            if ix == 0 {
3281                                                this.style(ButtonStyle::Tinted(TintColor::Warning))
3282                                            } else {
3283                                                this.style(ButtonStyle::Outlined)
3284                                            }
3285                                        })
3286                                        .when_some(
3287                                            method.description.clone(),
3288                                            |this, description| {
3289                                                this.tooltip(Tooltip::text(description))
3290                                            },
3291                                        )
3292                                        .on_click({
3293                                            cx.listener(move |this, _, window, cx| {
3294                                                telemetry::event!(
3295                                                    "Authenticate Agent Started",
3296                                                    agent = this.agent.telemetry_id(),
3297                                                    method = method_id
3298                                                );
3299
3300                                                this.authenticate(
3301                                                    acp::AuthMethodId(method_id.clone()),
3302                                                    window,
3303                                                    cx,
3304                                                )
3305                                            })
3306                                        })
3307                                },
3308                            )),
3309                    )
3310                }),
3311        )
3312    }
3313
3314    fn render_load_error(
3315        &self,
3316        e: &LoadError,
3317        window: &mut Window,
3318        cx: &mut Context<Self>,
3319    ) -> AnyElement {
3320        let (title, message, action_slot): (_, SharedString, _) = match e {
3321            LoadError::Unsupported {
3322                command: path,
3323                current_version,
3324                minimum_version,
3325            } => {
3326                return self.render_unsupported(path, current_version, minimum_version, window, cx);
3327            }
3328            LoadError::FailedToInstall(msg) => (
3329                "Failed to Install",
3330                msg.into(),
3331                Some(self.create_copy_button(msg.to_string()).into_any_element()),
3332            ),
3333            LoadError::Exited { status } => (
3334                "Failed to Launch",
3335                format!("Server exited with status {status}").into(),
3336                None,
3337            ),
3338            LoadError::Other(msg) => (
3339                "Failed to Launch",
3340                msg.into(),
3341                Some(self.create_copy_button(msg.to_string()).into_any_element()),
3342            ),
3343        };
3344
3345        Callout::new()
3346            .severity(Severity::Error)
3347            .icon(IconName::XCircleFilled)
3348            .title(title)
3349            .description(message)
3350            .actions_slot(div().children(action_slot))
3351            .into_any_element()
3352    }
3353
3354    fn render_unsupported(
3355        &self,
3356        path: &SharedString,
3357        version: &SharedString,
3358        minimum_version: &SharedString,
3359        _window: &mut Window,
3360        cx: &mut Context<Self>,
3361    ) -> AnyElement {
3362        let (heading_label, description_label) = (
3363            format!("Upgrade {} to work with Zed", self.agent.name()),
3364            if version.is_empty() {
3365                format!(
3366                    "Currently using {}, which does not report a valid --version",
3367                    path,
3368                )
3369            } else {
3370                format!(
3371                    "Currently using {}, which is only version {} (need at least {minimum_version})",
3372                    path, version
3373                )
3374            },
3375        );
3376
3377        v_flex()
3378            .w_full()
3379            .p_3p5()
3380            .gap_2p5()
3381            .border_t_1()
3382            .border_color(cx.theme().colors().border)
3383            .bg(linear_gradient(
3384                180.,
3385                linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3386                linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3387            ))
3388            .child(
3389                v_flex().gap_0p5().child(Label::new(heading_label)).child(
3390                    Label::new(description_label)
3391                        .size(LabelSize::Small)
3392                        .color(Color::Muted),
3393                ),
3394            )
3395            .into_any_element()
3396    }
3397
3398    fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
3399        let editor_bg_color = cx.theme().colors().editor_background;
3400        let active_color = cx.theme().colors().element_selected;
3401        editor_bg_color.blend(active_color.opacity(0.3))
3402    }
3403
3404    fn render_activity_bar(
3405        &self,
3406        thread_entity: &Entity<AcpThread>,
3407        window: &mut Window,
3408        cx: &Context<Self>,
3409    ) -> Option<AnyElement> {
3410        let thread = thread_entity.read(cx);
3411        let action_log = thread.action_log();
3412        let changed_buffers = action_log.read(cx).changed_buffers(cx);
3413        let plan = thread.plan();
3414
3415        if changed_buffers.is_empty() && plan.is_empty() {
3416            return None;
3417        }
3418
3419        // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3420        // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3421        // be, which blocks you from being able to accept or reject edits. This switches the
3422        // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3423        // block you from using the panel.
3424        let pending_edits = false;
3425
3426        v_flex()
3427            .mt_1()
3428            .mx_2()
3429            .bg(self.activity_bar_bg(cx))
3430            .border_1()
3431            .border_b_0()
3432            .border_color(cx.theme().colors().border)
3433            .rounded_t_md()
3434            .shadow(vec![gpui::BoxShadow {
3435                color: gpui::black().opacity(0.15),
3436                offset: point(px(1.), px(-1.)),
3437                blur_radius: px(3.),
3438                spread_radius: px(0.),
3439            }])
3440            .when(!plan.is_empty(), |this| {
3441                this.child(self.render_plan_summary(plan, window, cx))
3442                    .when(self.plan_expanded, |parent| {
3443                        parent.child(self.render_plan_entries(plan, window, cx))
3444                    })
3445            })
3446            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3447                this.child(Divider::horizontal().color(DividerColor::Border))
3448            })
3449            .when(!changed_buffers.is_empty(), |this| {
3450                this.child(self.render_edits_summary(
3451                    &changed_buffers,
3452                    self.edits_expanded,
3453                    pending_edits,
3454                    window,
3455                    cx,
3456                ))
3457                .when(self.edits_expanded, |parent| {
3458                    parent.child(self.render_edited_files(
3459                        action_log,
3460                        &changed_buffers,
3461                        pending_edits,
3462                        cx,
3463                    ))
3464                })
3465            })
3466            .into_any()
3467            .into()
3468    }
3469
3470    fn render_plan_summary(
3471        &self,
3472        plan: &Plan,
3473        window: &mut Window,
3474        cx: &Context<Self>,
3475    ) -> impl IntoElement {
3476        let stats = plan.stats();
3477
3478        let title = if let Some(entry) = stats.in_progress_entry
3479            && !self.plan_expanded
3480        {
3481            h_flex()
3482                .cursor_default()
3483                .relative()
3484                .w_full()
3485                .gap_1()
3486                .truncate()
3487                .child(
3488                    Label::new("Current:")
3489                        .size(LabelSize::Small)
3490                        .color(Color::Muted),
3491                )
3492                .child(
3493                    div()
3494                        .text_xs()
3495                        .text_color(cx.theme().colors().text_muted)
3496                        .line_clamp(1)
3497                        .child(MarkdownElement::new(
3498                            entry.content.clone(),
3499                            plan_label_markdown_style(&entry.status, window, cx),
3500                        )),
3501                )
3502                .when(stats.pending > 0, |this| {
3503                    this.child(
3504                        h_flex()
3505                            .absolute()
3506                            .top_0()
3507                            .right_0()
3508                            .h_full()
3509                            .child(div().min_w_8().h_full().bg(linear_gradient(
3510                                90.,
3511                                linear_color_stop(self.activity_bar_bg(cx), 1.),
3512                                linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
3513                            )))
3514                            .child(
3515                                div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
3516                                    Label::new(format!("{} left", stats.pending))
3517                                        .size(LabelSize::Small)
3518                                        .color(Color::Muted),
3519                                ),
3520                            ),
3521                    )
3522                })
3523        } else {
3524            let status_label = if stats.pending == 0 {
3525                "All Done".to_string()
3526            } else if stats.completed == 0 {
3527                format!("{} Tasks", plan.entries.len())
3528            } else {
3529                format!("{}/{}", stats.completed, plan.entries.len())
3530            };
3531
3532            h_flex()
3533                .w_full()
3534                .gap_1()
3535                .justify_between()
3536                .child(
3537                    Label::new("Plan")
3538                        .size(LabelSize::Small)
3539                        .color(Color::Muted),
3540                )
3541                .child(
3542                    Label::new(status_label)
3543                        .size(LabelSize::Small)
3544                        .color(Color::Muted)
3545                        .mr_1(),
3546                )
3547        };
3548
3549        h_flex()
3550            .id("plan_summary")
3551            .p_1()
3552            .w_full()
3553            .gap_1()
3554            .when(self.plan_expanded, |this| {
3555                this.border_b_1().border_color(cx.theme().colors().border)
3556            })
3557            .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3558            .child(title)
3559            .on_click(cx.listener(|this, _, _, cx| {
3560                this.plan_expanded = !this.plan_expanded;
3561                cx.notify();
3562            }))
3563    }
3564
3565    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3566        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3567            let element = h_flex()
3568                .py_1()
3569                .px_2()
3570                .gap_2()
3571                .justify_between()
3572                .bg(cx.theme().colors().editor_background)
3573                .when(index < plan.entries.len() - 1, |parent| {
3574                    parent.border_color(cx.theme().colors().border).border_b_1()
3575                })
3576                .child(
3577                    h_flex()
3578                        .id(("plan_entry", index))
3579                        .gap_1p5()
3580                        .max_w_full()
3581                        .overflow_x_scroll()
3582                        .text_xs()
3583                        .text_color(cx.theme().colors().text_muted)
3584                        .child(match entry.status {
3585                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3586                                .size(IconSize::Small)
3587                                .color(Color::Muted)
3588                                .into_any_element(),
3589                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3590                                .size(IconSize::Small)
3591                                .color(Color::Accent)
3592                                .with_rotate_animation(2)
3593                                .into_any_element(),
3594                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3595                                .size(IconSize::Small)
3596                                .color(Color::Success)
3597                                .into_any_element(),
3598                        })
3599                        .child(MarkdownElement::new(
3600                            entry.content.clone(),
3601                            plan_label_markdown_style(&entry.status, window, cx),
3602                        )),
3603                );
3604
3605            Some(element)
3606        }))
3607    }
3608
3609    fn render_edits_summary(
3610        &self,
3611        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3612        expanded: bool,
3613        pending_edits: bool,
3614        window: &mut Window,
3615        cx: &Context<Self>,
3616    ) -> Div {
3617        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3618
3619        let focus_handle = self.focus_handle(cx);
3620
3621        h_flex()
3622            .p_1()
3623            .justify_between()
3624            .flex_wrap()
3625            .when(expanded, |this| {
3626                this.border_b_1().border_color(cx.theme().colors().border)
3627            })
3628            .child(
3629                h_flex()
3630                    .id("edits-container")
3631                    .gap_1()
3632                    .child(Disclosure::new("edits-disclosure", expanded))
3633                    .map(|this| {
3634                        if pending_edits {
3635                            this.child(
3636                                Label::new(format!(
3637                                    "Editing {} {}",
3638                                    changed_buffers.len(),
3639                                    if changed_buffers.len() == 1 {
3640                                        "file"
3641                                    } else {
3642                                        "files"
3643                                    }
3644                                ))
3645                                .color(Color::Muted)
3646                                .size(LabelSize::Small)
3647                                .with_animation(
3648                                    "edit-label",
3649                                    Animation::new(Duration::from_secs(2))
3650                                        .repeat()
3651                                        .with_easing(pulsating_between(0.3, 0.7)),
3652                                    |label, delta| label.alpha(delta),
3653                                ),
3654                            )
3655                        } else {
3656                            this.child(
3657                                Label::new("Edits")
3658                                    .size(LabelSize::Small)
3659                                    .color(Color::Muted),
3660                            )
3661                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
3662                            .child(
3663                                Label::new(format!(
3664                                    "{} {}",
3665                                    changed_buffers.len(),
3666                                    if changed_buffers.len() == 1 {
3667                                        "file"
3668                                    } else {
3669                                        "files"
3670                                    }
3671                                ))
3672                                .size(LabelSize::Small)
3673                                .color(Color::Muted),
3674                            )
3675                        }
3676                    })
3677                    .on_click(cx.listener(|this, _, _, cx| {
3678                        this.edits_expanded = !this.edits_expanded;
3679                        cx.notify();
3680                    })),
3681            )
3682            .child(
3683                h_flex()
3684                    .gap_1()
3685                    .child(
3686                        IconButton::new("review-changes", IconName::ListTodo)
3687                            .icon_size(IconSize::Small)
3688                            .tooltip({
3689                                let focus_handle = focus_handle.clone();
3690                                move |window, cx| {
3691                                    Tooltip::for_action_in(
3692                                        "Review Changes",
3693                                        &OpenAgentDiff,
3694                                        &focus_handle,
3695                                        window,
3696                                        cx,
3697                                    )
3698                                }
3699                            })
3700                            .on_click(cx.listener(|_, _, window, cx| {
3701                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3702                            })),
3703                    )
3704                    .child(Divider::vertical().color(DividerColor::Border))
3705                    .child(
3706                        Button::new("reject-all-changes", "Reject All")
3707                            .label_size(LabelSize::Small)
3708                            .disabled(pending_edits)
3709                            .when(pending_edits, |this| {
3710                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3711                            })
3712                            .key_binding(
3713                                KeyBinding::for_action_in(
3714                                    &RejectAll,
3715                                    &focus_handle.clone(),
3716                                    window,
3717                                    cx,
3718                                )
3719                                .map(|kb| kb.size(rems_from_px(10.))),
3720                            )
3721                            .on_click(cx.listener(move |this, _, window, cx| {
3722                                this.reject_all(&RejectAll, window, cx);
3723                            })),
3724                    )
3725                    .child(
3726                        Button::new("keep-all-changes", "Keep All")
3727                            .label_size(LabelSize::Small)
3728                            .disabled(pending_edits)
3729                            .when(pending_edits, |this| {
3730                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3731                            })
3732                            .key_binding(
3733                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3734                                    .map(|kb| kb.size(rems_from_px(10.))),
3735                            )
3736                            .on_click(cx.listener(move |this, _, window, cx| {
3737                                this.keep_all(&KeepAll, window, cx);
3738                            })),
3739                    ),
3740            )
3741    }
3742
3743    fn render_edited_files(
3744        &self,
3745        action_log: &Entity<ActionLog>,
3746        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3747        pending_edits: bool,
3748        cx: &Context<Self>,
3749    ) -> Div {
3750        let editor_bg_color = cx.theme().colors().editor_background;
3751
3752        v_flex().children(changed_buffers.iter().enumerate().flat_map(
3753            |(index, (buffer, _diff))| {
3754                let file = buffer.read(cx).file()?;
3755                let path = file.path();
3756                let path_style = file.path_style(cx);
3757                let separator = file.path_style(cx).separator();
3758
3759                let file_path = path.parent().and_then(|parent| {
3760                    if parent.is_empty() {
3761                        None
3762                    } else {
3763                        Some(
3764                            Label::new(format!("{}{separator}", parent.display(path_style)))
3765                                .color(Color::Muted)
3766                                .size(LabelSize::XSmall)
3767                                .buffer_font(cx),
3768                        )
3769                    }
3770                });
3771
3772                let file_name = path.file_name().map(|name| {
3773                    Label::new(name.to_string())
3774                        .size(LabelSize::XSmall)
3775                        .buffer_font(cx)
3776                });
3777
3778                let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
3779                    .map(Icon::from_path)
3780                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3781                    .unwrap_or_else(|| {
3782                        Icon::new(IconName::File)
3783                            .color(Color::Muted)
3784                            .size(IconSize::Small)
3785                    });
3786
3787                let overlay_gradient = linear_gradient(
3788                    90.,
3789                    linear_color_stop(editor_bg_color, 1.),
3790                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3791                );
3792
3793                let element = h_flex()
3794                    .group("edited-code")
3795                    .id(("file-container", index))
3796                    .py_1()
3797                    .pl_2()
3798                    .pr_1()
3799                    .gap_2()
3800                    .justify_between()
3801                    .bg(editor_bg_color)
3802                    .when(index < changed_buffers.len() - 1, |parent| {
3803                        parent.border_color(cx.theme().colors().border).border_b_1()
3804                    })
3805                    .child(
3806                        h_flex()
3807                            .relative()
3808                            .id(("file-name", index))
3809                            .pr_8()
3810                            .gap_1p5()
3811                            .w_full()
3812                            .overflow_x_scroll()
3813                            .child(file_icon)
3814                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3815                            .child(
3816                                div()
3817                                    .absolute()
3818                                    .h_full()
3819                                    .w_12()
3820                                    .top_0()
3821                                    .bottom_0()
3822                                    .right_0()
3823                                    .bg(overlay_gradient),
3824                            )
3825                            .on_click({
3826                                let buffer = buffer.clone();
3827                                cx.listener(move |this, _, window, cx| {
3828                                    this.open_edited_buffer(&buffer, window, cx);
3829                                })
3830                            }),
3831                    )
3832                    .child(
3833                        h_flex()
3834                            .gap_1()
3835                            .visible_on_hover("edited-code")
3836                            .child(
3837                                Button::new("review", "Review")
3838                                    .label_size(LabelSize::Small)
3839                                    .on_click({
3840                                        let buffer = buffer.clone();
3841                                        cx.listener(move |this, _, window, cx| {
3842                                            this.open_edited_buffer(&buffer, window, cx);
3843                                        })
3844                                    }),
3845                            )
3846                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3847                            .child(
3848                                Button::new("reject-file", "Reject")
3849                                    .label_size(LabelSize::Small)
3850                                    .disabled(pending_edits)
3851                                    .on_click({
3852                                        let buffer = buffer.clone();
3853                                        let action_log = action_log.clone();
3854                                        move |_, _, cx| {
3855                                            action_log.update(cx, |action_log, cx| {
3856                                                action_log
3857                                                    .reject_edits_in_ranges(
3858                                                        buffer.clone(),
3859                                                        vec![Anchor::MIN..Anchor::MAX],
3860                                                        cx,
3861                                                    )
3862                                                    .detach_and_log_err(cx);
3863                                            })
3864                                        }
3865                                    }),
3866                            )
3867                            .child(
3868                                Button::new("keep-file", "Keep")
3869                                    .label_size(LabelSize::Small)
3870                                    .disabled(pending_edits)
3871                                    .on_click({
3872                                        let buffer = buffer.clone();
3873                                        let action_log = action_log.clone();
3874                                        move |_, _, cx| {
3875                                            action_log.update(cx, |action_log, cx| {
3876                                                action_log.keep_edits_in_range(
3877                                                    buffer.clone(),
3878                                                    Anchor::MIN..Anchor::MAX,
3879                                                    cx,
3880                                                );
3881                                            })
3882                                        }
3883                                    }),
3884                            ),
3885                    );
3886
3887                Some(element)
3888            },
3889        ))
3890    }
3891
3892    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3893        let focus_handle = self.message_editor.focus_handle(cx);
3894        let editor_bg_color = cx.theme().colors().editor_background;
3895        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3896            (IconName::Minimize, "Minimize Message Editor")
3897        } else {
3898            (IconName::Maximize, "Expand Message Editor")
3899        };
3900
3901        let backdrop = div()
3902            .size_full()
3903            .absolute()
3904            .inset_0()
3905            .bg(cx.theme().colors().panel_background)
3906            .opacity(0.8)
3907            .block_mouse_except_scroll();
3908
3909        let enable_editor = match self.thread_state {
3910            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3911            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3912        };
3913
3914        v_flex()
3915            .on_action(cx.listener(Self::expand_message_editor))
3916            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3917                if let Some(profile_selector) = this.profile_selector.as_ref() {
3918                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3919                } else if let Some(mode_selector) = this.mode_selector() {
3920                    mode_selector.read(cx).menu_handle().toggle(window, cx);
3921                }
3922            }))
3923            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
3924                if let Some(mode_selector) = this.mode_selector() {
3925                    mode_selector.update(cx, |mode_selector, cx| {
3926                        mode_selector.cycle_mode(window, cx);
3927                    });
3928                }
3929            }))
3930            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3931                if let Some(model_selector) = this.model_selector.as_ref() {
3932                    model_selector
3933                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3934                }
3935            }))
3936            .p_2()
3937            .gap_2()
3938            .border_t_1()
3939            .border_color(cx.theme().colors().border)
3940            .bg(editor_bg_color)
3941            .when(self.editor_expanded, |this| {
3942                this.h(vh(0.8, window)).size_full().justify_between()
3943            })
3944            .child(
3945                v_flex()
3946                    .relative()
3947                    .size_full()
3948                    .pt_1()
3949                    .pr_2p5()
3950                    .child(self.message_editor.clone())
3951                    .child(
3952                        h_flex()
3953                            .absolute()
3954                            .top_0()
3955                            .right_0()
3956                            .opacity(0.5)
3957                            .hover(|this| this.opacity(1.0))
3958                            .child(
3959                                IconButton::new("toggle-height", expand_icon)
3960                                    .icon_size(IconSize::Small)
3961                                    .icon_color(Color::Muted)
3962                                    .tooltip({
3963                                        move |window, cx| {
3964                                            Tooltip::for_action_in(
3965                                                expand_tooltip,
3966                                                &ExpandMessageEditor,
3967                                                &focus_handle,
3968                                                window,
3969                                                cx,
3970                                            )
3971                                        }
3972                                    })
3973                                    .on_click(cx.listener(|_, _, window, cx| {
3974                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3975                                    })),
3976                            ),
3977                    ),
3978            )
3979            .child(
3980                h_flex()
3981                    .flex_none()
3982                    .flex_wrap()
3983                    .justify_between()
3984                    .child(
3985                        h_flex()
3986                            .child(self.render_follow_toggle(cx))
3987                            .children(self.render_burn_mode_toggle(cx)),
3988                    )
3989                    .child(
3990                        h_flex()
3991                            .gap_1()
3992                            .children(self.render_token_usage(cx))
3993                            .children(self.profile_selector.clone())
3994                            .children(self.mode_selector().cloned())
3995                            .children(self.model_selector.clone())
3996                            .child(self.render_send_button(cx)),
3997                    ),
3998            )
3999            .when(!enable_editor, |this| this.child(backdrop))
4000            .into_any()
4001    }
4002
4003    pub(crate) fn as_native_connection(
4004        &self,
4005        cx: &App,
4006    ) -> Option<Rc<agent2::NativeAgentConnection>> {
4007        let acp_thread = self.thread()?.read(cx);
4008        acp_thread.connection().clone().downcast()
4009    }
4010
4011    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
4012        let acp_thread = self.thread()?.read(cx);
4013        self.as_native_connection(cx)?
4014            .thread(acp_thread.session_id(), cx)
4015    }
4016
4017    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4018        self.as_native_thread(cx)
4019            .and_then(|thread| thread.read(cx).model())
4020            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4021    }
4022
4023    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4024        let thread = self.thread()?.read(cx);
4025        let usage = thread.token_usage()?;
4026        let is_generating = thread.status() != ThreadStatus::Idle;
4027
4028        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4029        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4030
4031        Some(
4032            h_flex()
4033                .flex_shrink_0()
4034                .gap_0p5()
4035                .mr_1p5()
4036                .child(
4037                    Label::new(used)
4038                        .size(LabelSize::Small)
4039                        .color(Color::Muted)
4040                        .map(|label| {
4041                            if is_generating {
4042                                label
4043                                    .with_animation(
4044                                        "used-tokens-label",
4045                                        Animation::new(Duration::from_secs(2))
4046                                            .repeat()
4047                                            .with_easing(pulsating_between(0.3, 0.8)),
4048                                        |label, delta| label.alpha(delta),
4049                                    )
4050                                    .into_any()
4051                            } else {
4052                                label.into_any_element()
4053                            }
4054                        }),
4055                )
4056                .child(
4057                    Label::new("/")
4058                        .size(LabelSize::Small)
4059                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4060                )
4061                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4062        )
4063    }
4064
4065    fn toggle_burn_mode(
4066        &mut self,
4067        _: &ToggleBurnMode,
4068        _window: &mut Window,
4069        cx: &mut Context<Self>,
4070    ) {
4071        let Some(thread) = self.as_native_thread(cx) else {
4072            return;
4073        };
4074
4075        thread.update(cx, |thread, cx| {
4076            let current_mode = thread.completion_mode();
4077            thread.set_completion_mode(
4078                match current_mode {
4079                    CompletionMode::Burn => CompletionMode::Normal,
4080                    CompletionMode::Normal => CompletionMode::Burn,
4081                },
4082                cx,
4083            );
4084        });
4085    }
4086
4087    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4088        let Some(thread) = self.thread() else {
4089            return;
4090        };
4091        let action_log = thread.read(cx).action_log().clone();
4092        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
4093    }
4094
4095    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4096        let Some(thread) = self.thread() else {
4097            return;
4098        };
4099        let action_log = thread.read(cx).action_log().clone();
4100        action_log
4101            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
4102            .detach();
4103    }
4104
4105    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4106        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4107    }
4108
4109    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4110        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4111    }
4112
4113    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4114        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4115    }
4116
4117    fn authorize_pending_tool_call(
4118        &mut self,
4119        kind: acp::PermissionOptionKind,
4120        window: &mut Window,
4121        cx: &mut Context<Self>,
4122    ) -> Option<()> {
4123        let thread = self.thread()?.read(cx);
4124        let tool_call = thread.first_tool_awaiting_confirmation()?;
4125        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4126            return None;
4127        };
4128        let option = options.iter().find(|o| o.kind == kind)?;
4129
4130        self.authorize_tool_call(
4131            tool_call.id.clone(),
4132            option.id.clone(),
4133            option.kind,
4134            window,
4135            cx,
4136        );
4137
4138        Some(())
4139    }
4140
4141    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4142        let thread = self.as_native_thread(cx)?.read(cx);
4143
4144        if thread
4145            .model()
4146            .is_none_or(|model| !model.supports_burn_mode())
4147        {
4148            return None;
4149        }
4150
4151        let active_completion_mode = thread.completion_mode();
4152        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4153        let icon = if burn_mode_enabled {
4154            IconName::ZedBurnModeOn
4155        } else {
4156            IconName::ZedBurnMode
4157        };
4158
4159        Some(
4160            IconButton::new("burn-mode", icon)
4161                .icon_size(IconSize::Small)
4162                .icon_color(Color::Muted)
4163                .toggle_state(burn_mode_enabled)
4164                .selected_icon_color(Color::Error)
4165                .on_click(cx.listener(|this, _event, window, cx| {
4166                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4167                }))
4168                .tooltip(move |_window, cx| {
4169                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4170                        .into()
4171                })
4172                .into_any_element(),
4173        )
4174    }
4175
4176    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4177        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4178        let is_generating = self
4179            .thread()
4180            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4181
4182        if self.is_loading_contents {
4183            div()
4184                .id("loading-message-content")
4185                .px_1()
4186                .tooltip(Tooltip::text("Loading Added Context…"))
4187                .child(loading_contents_spinner(IconSize::default()))
4188                .into_any_element()
4189        } else if is_generating && is_editor_empty {
4190            IconButton::new("stop-generation", IconName::Stop)
4191                .icon_color(Color::Error)
4192                .style(ButtonStyle::Tinted(ui::TintColor::Error))
4193                .tooltip(move |window, cx| {
4194                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
4195                })
4196                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4197                .into_any_element()
4198        } else {
4199            let send_btn_tooltip = if is_editor_empty && !is_generating {
4200                "Type to Send"
4201            } else if is_generating {
4202                "Stop and Send Message"
4203            } else {
4204                "Send"
4205            };
4206
4207            IconButton::new("send-message", IconName::Send)
4208                .style(ButtonStyle::Filled)
4209                .map(|this| {
4210                    if is_editor_empty && !is_generating {
4211                        this.disabled(true).icon_color(Color::Muted)
4212                    } else {
4213                        this.icon_color(Color::Accent)
4214                    }
4215                })
4216                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
4217                .on_click(cx.listener(|this, _, window, cx| {
4218                    this.send(window, cx);
4219                }))
4220                .into_any_element()
4221        }
4222    }
4223
4224    fn is_following(&self, cx: &App) -> bool {
4225        match self.thread().map(|thread| thread.read(cx).status()) {
4226            Some(ThreadStatus::Generating) => self
4227                .workspace
4228                .read_with(cx, |workspace, _| {
4229                    workspace.is_being_followed(CollaboratorId::Agent)
4230                })
4231                .unwrap_or(false),
4232            _ => self.should_be_following,
4233        }
4234    }
4235
4236    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4237        let following = self.is_following(cx);
4238
4239        self.should_be_following = !following;
4240        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4241            self.workspace
4242                .update(cx, |workspace, cx| {
4243                    if following {
4244                        workspace.unfollow(CollaboratorId::Agent, window, cx);
4245                    } else {
4246                        workspace.follow(CollaboratorId::Agent, window, cx);
4247                    }
4248                })
4249                .ok();
4250        }
4251
4252        telemetry::event!("Follow Agent Selected", following = !following);
4253    }
4254
4255    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4256        let following = self.is_following(cx);
4257
4258        let tooltip_label = if following {
4259            if self.agent.name() == "Zed Agent" {
4260                format!("Stop Following the {}", self.agent.name())
4261            } else {
4262                format!("Stop Following {}", self.agent.name())
4263            }
4264        } else {
4265            if self.agent.name() == "Zed Agent" {
4266                format!("Follow the {}", self.agent.name())
4267            } else {
4268                format!("Follow {}", self.agent.name())
4269            }
4270        };
4271
4272        IconButton::new("follow-agent", IconName::Crosshair)
4273            .icon_size(IconSize::Small)
4274            .icon_color(Color::Muted)
4275            .toggle_state(following)
4276            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4277            .tooltip(move |window, cx| {
4278                if following {
4279                    Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4280                } else {
4281                    Tooltip::with_meta(
4282                        tooltip_label.clone(),
4283                        Some(&Follow),
4284                        "Track the agent's location as it reads and edits files.",
4285                        window,
4286                        cx,
4287                    )
4288                }
4289            })
4290            .on_click(cx.listener(move |this, _, window, cx| {
4291                this.toggle_following(window, cx);
4292            }))
4293    }
4294
4295    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4296        let workspace = self.workspace.clone();
4297        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4298            Self::open_link(text, &workspace, window, cx);
4299        })
4300    }
4301
4302    fn open_link(
4303        url: SharedString,
4304        workspace: &WeakEntity<Workspace>,
4305        window: &mut Window,
4306        cx: &mut App,
4307    ) {
4308        let Some(workspace) = workspace.upgrade() else {
4309            cx.open_url(&url);
4310            return;
4311        };
4312
4313        if let Some(mention) = MentionUri::parse(&url).log_err() {
4314            workspace.update(cx, |workspace, cx| match mention {
4315                MentionUri::File { abs_path } => {
4316                    let project = workspace.project();
4317                    let Some(path) =
4318                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4319                    else {
4320                        return;
4321                    };
4322
4323                    workspace
4324                        .open_path(path, None, true, window, cx)
4325                        .detach_and_log_err(cx);
4326                }
4327                MentionUri::PastedImage => {}
4328                MentionUri::Directory { abs_path } => {
4329                    let project = workspace.project();
4330                    let Some(entry_id) = project.update(cx, |project, cx| {
4331                        let path = project.find_project_path(abs_path, cx)?;
4332                        project.entry_for_path(&path, cx).map(|entry| entry.id)
4333                    }) else {
4334                        return;
4335                    };
4336
4337                    project.update(cx, |_, cx| {
4338                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
4339                    });
4340                }
4341                MentionUri::Symbol {
4342                    abs_path: path,
4343                    line_range,
4344                    ..
4345                }
4346                | MentionUri::Selection {
4347                    abs_path: Some(path),
4348                    line_range,
4349                } => {
4350                    let project = workspace.project();
4351                    let Some(path) =
4352                        project.update(cx, |project, cx| project.find_project_path(path, cx))
4353                    else {
4354                        return;
4355                    };
4356
4357                    let item = workspace.open_path(path, None, true, window, cx);
4358                    window
4359                        .spawn(cx, async move |cx| {
4360                            let Some(editor) = item.await?.downcast::<Editor>() else {
4361                                return Ok(());
4362                            };
4363                            let range = Point::new(*line_range.start(), 0)
4364                                ..Point::new(*line_range.start(), 0);
4365                            editor
4366                                .update_in(cx, |editor, window, cx| {
4367                                    editor.change_selections(
4368                                        SelectionEffects::scroll(Autoscroll::center()),
4369                                        window,
4370                                        cx,
4371                                        |s| s.select_ranges(vec![range]),
4372                                    );
4373                                })
4374                                .ok();
4375                            anyhow::Ok(())
4376                        })
4377                        .detach_and_log_err(cx);
4378                }
4379                MentionUri::Selection { abs_path: None, .. } => {}
4380                MentionUri::Thread { id, name } => {
4381                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4382                        panel.update(cx, |panel, cx| {
4383                            panel.load_agent_thread(
4384                                DbThreadMetadata {
4385                                    id,
4386                                    title: name.into(),
4387                                    updated_at: Default::default(),
4388                                },
4389                                window,
4390                                cx,
4391                            )
4392                        });
4393                    }
4394                }
4395                MentionUri::TextThread { path, .. } => {
4396                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4397                        panel.update(cx, |panel, cx| {
4398                            panel
4399                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
4400                                .detach_and_log_err(cx);
4401                        });
4402                    }
4403                }
4404                MentionUri::Rule { id, .. } => {
4405                    let PromptId::User { uuid } = id else {
4406                        return;
4407                    };
4408                    window.dispatch_action(
4409                        Box::new(OpenRulesLibrary {
4410                            prompt_to_select: Some(uuid.0),
4411                        }),
4412                        cx,
4413                    )
4414                }
4415                MentionUri::Fetch { url } => {
4416                    cx.open_url(url.as_str());
4417                }
4418            })
4419        } else {
4420            cx.open_url(&url);
4421        }
4422    }
4423
4424    fn open_tool_call_location(
4425        &self,
4426        entry_ix: usize,
4427        location_ix: usize,
4428        window: &mut Window,
4429        cx: &mut Context<Self>,
4430    ) -> Option<()> {
4431        let (tool_call_location, agent_location) = self
4432            .thread()?
4433            .read(cx)
4434            .entries()
4435            .get(entry_ix)?
4436            .location(location_ix)?;
4437
4438        let project_path = self
4439            .project
4440            .read(cx)
4441            .find_project_path(&tool_call_location.path, cx)?;
4442
4443        let open_task = self
4444            .workspace
4445            .update(cx, |workspace, cx| {
4446                workspace.open_path(project_path, None, true, window, cx)
4447            })
4448            .log_err()?;
4449        window
4450            .spawn(cx, async move |cx| {
4451                let item = open_task.await?;
4452
4453                let Some(active_editor) = item.downcast::<Editor>() else {
4454                    return anyhow::Ok(());
4455                };
4456
4457                active_editor.update_in(cx, |editor, window, cx| {
4458                    let multibuffer = editor.buffer().read(cx);
4459                    let buffer = multibuffer.as_singleton();
4460                    if agent_location.buffer.upgrade() == buffer {
4461                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4462                        let anchor = editor::Anchor::in_buffer(
4463                            excerpt_id.unwrap(),
4464                            buffer.unwrap().read(cx).remote_id(),
4465                            agent_location.position,
4466                        );
4467                        editor.change_selections(Default::default(), window, cx, |selections| {
4468                            selections.select_anchor_ranges([anchor..anchor]);
4469                        })
4470                    } else {
4471                        let row = tool_call_location.line.unwrap_or_default();
4472                        editor.change_selections(Default::default(), window, cx, |selections| {
4473                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4474                        })
4475                    }
4476                })?;
4477
4478                anyhow::Ok(())
4479            })
4480            .detach_and_log_err(cx);
4481
4482        None
4483    }
4484
4485    pub fn open_thread_as_markdown(
4486        &self,
4487        workspace: Entity<Workspace>,
4488        window: &mut Window,
4489        cx: &mut App,
4490    ) -> Task<Result<()>> {
4491        let markdown_language_task = workspace
4492            .read(cx)
4493            .app_state()
4494            .languages
4495            .language_for_name("Markdown");
4496
4497        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4498            let thread = thread.read(cx);
4499            (thread.title().to_string(), thread.to_markdown(cx))
4500        } else {
4501            return Task::ready(Ok(()));
4502        };
4503
4504        window.spawn(cx, async move |cx| {
4505            let markdown_language = markdown_language_task.await?;
4506
4507            workspace.update_in(cx, |workspace, window, cx| {
4508                let project = workspace.project().clone();
4509
4510                if !project.read(cx).is_local() {
4511                    bail!("failed to open active thread as markdown in remote project");
4512                }
4513
4514                let buffer = project.update(cx, |project, cx| {
4515                    project.create_local_buffer(&markdown, Some(markdown_language), true, cx)
4516                });
4517                let buffer = cx.new(|cx| {
4518                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4519                });
4520
4521                workspace.add_item_to_active_pane(
4522                    Box::new(cx.new(|cx| {
4523                        let mut editor =
4524                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4525                        editor.set_breadcrumb_header(thread_summary);
4526                        editor
4527                    })),
4528                    None,
4529                    true,
4530                    window,
4531                    cx,
4532                );
4533
4534                anyhow::Ok(())
4535            })??;
4536            anyhow::Ok(())
4537        })
4538    }
4539
4540    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4541        self.list_state.scroll_to(ListOffset::default());
4542        cx.notify();
4543    }
4544
4545    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4546        if let Some(thread) = self.thread() {
4547            let entry_count = thread.read(cx).entries().len();
4548            self.list_state.reset(entry_count);
4549            cx.notify();
4550        }
4551    }
4552
4553    fn notify_with_sound(
4554        &mut self,
4555        caption: impl Into<SharedString>,
4556        icon: IconName,
4557        window: &mut Window,
4558        cx: &mut Context<Self>,
4559    ) {
4560        self.play_notification_sound(window, cx);
4561        self.show_notification(caption, icon, window, cx);
4562    }
4563
4564    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4565        let settings = AgentSettings::get_global(cx);
4566        if settings.play_sound_when_agent_done && !window.is_window_active() {
4567            Audio::play_sound(Sound::AgentDone, cx);
4568        }
4569    }
4570
4571    fn show_notification(
4572        &mut self,
4573        caption: impl Into<SharedString>,
4574        icon: IconName,
4575        window: &mut Window,
4576        cx: &mut Context<Self>,
4577    ) {
4578        if window.is_window_active() || !self.notifications.is_empty() {
4579            return;
4580        }
4581
4582        // TODO: Change this once we have title summarization for external agents.
4583        let title = self.agent.name();
4584
4585        match AgentSettings::get_global(cx).notify_when_agent_waiting {
4586            NotifyWhenAgentWaiting::PrimaryScreen => {
4587                if let Some(primary) = cx.primary_display() {
4588                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4589                }
4590            }
4591            NotifyWhenAgentWaiting::AllScreens => {
4592                let caption = caption.into();
4593                for screen in cx.displays() {
4594                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4595                }
4596            }
4597            NotifyWhenAgentWaiting::Never => {
4598                // Don't show anything
4599            }
4600        }
4601    }
4602
4603    fn pop_up(
4604        &mut self,
4605        icon: IconName,
4606        caption: SharedString,
4607        title: SharedString,
4608        window: &mut Window,
4609        screen: Rc<dyn PlatformDisplay>,
4610        cx: &mut Context<Self>,
4611    ) {
4612        let options = AgentNotification::window_options(screen, cx);
4613
4614        let project_name = self.workspace.upgrade().and_then(|workspace| {
4615            workspace
4616                .read(cx)
4617                .project()
4618                .read(cx)
4619                .visible_worktrees(cx)
4620                .next()
4621                .map(|worktree| worktree.read(cx).root_name_str().to_string())
4622        });
4623
4624        if let Some(screen_window) = cx
4625            .open_window(options, |_, cx| {
4626                cx.new(|_| {
4627                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4628                })
4629            })
4630            .log_err()
4631            && let Some(pop_up) = screen_window.entity(cx).log_err()
4632        {
4633            self.notification_subscriptions
4634                .entry(screen_window)
4635                .or_insert_with(Vec::new)
4636                .push(cx.subscribe_in(&pop_up, window, {
4637                    |this, _, event, window, cx| match event {
4638                        AgentNotificationEvent::Accepted => {
4639                            let handle = window.window_handle();
4640                            cx.activate(true);
4641
4642                            let workspace_handle = this.workspace.clone();
4643
4644                            // If there are multiple Zed windows, activate the correct one.
4645                            cx.defer(move |cx| {
4646                                handle
4647                                    .update(cx, |_view, window, _cx| {
4648                                        window.activate_window();
4649
4650                                        if let Some(workspace) = workspace_handle.upgrade() {
4651                                            workspace.update(_cx, |workspace, cx| {
4652                                                workspace.focus_panel::<AgentPanel>(window, cx);
4653                                            });
4654                                        }
4655                                    })
4656                                    .log_err();
4657                            });
4658
4659                            this.dismiss_notifications(cx);
4660                        }
4661                        AgentNotificationEvent::Dismissed => {
4662                            this.dismiss_notifications(cx);
4663                        }
4664                    }
4665                }));
4666
4667            self.notifications.push(screen_window);
4668
4669            // If the user manually refocuses the original window, dismiss the popup.
4670            self.notification_subscriptions
4671                .entry(screen_window)
4672                .or_insert_with(Vec::new)
4673                .push({
4674                    let pop_up_weak = pop_up.downgrade();
4675
4676                    cx.observe_window_activation(window, move |_, window, cx| {
4677                        if window.is_window_active()
4678                            && let Some(pop_up) = pop_up_weak.upgrade()
4679                        {
4680                            pop_up.update(cx, |_, cx| {
4681                                cx.emit(AgentNotificationEvent::Dismissed);
4682                            });
4683                        }
4684                    })
4685                });
4686        }
4687    }
4688
4689    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4690        for window in self.notifications.drain(..) {
4691            window
4692                .update(cx, |_, window, _| {
4693                    window.remove_window();
4694                })
4695                .ok();
4696
4697            self.notification_subscriptions.remove(&window);
4698        }
4699    }
4700
4701    fn render_thread_controls(
4702        &self,
4703        thread: &Entity<AcpThread>,
4704        cx: &Context<Self>,
4705    ) -> impl IntoElement {
4706        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4707        if is_generating {
4708            return h_flex().id("thread-controls-container").child(
4709                div()
4710                    .py_2()
4711                    .px(rems_from_px(22.))
4712                    .child(SpinnerLabel::new().size(LabelSize::Small)),
4713            );
4714        }
4715
4716        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4717            .shape(ui::IconButtonShape::Square)
4718            .icon_size(IconSize::Small)
4719            .icon_color(Color::Ignored)
4720            .tooltip(Tooltip::text("Open Thread as Markdown"))
4721            .on_click(cx.listener(move |this, _, window, cx| {
4722                if let Some(workspace) = this.workspace.upgrade() {
4723                    this.open_thread_as_markdown(workspace, window, cx)
4724                        .detach_and_log_err(cx);
4725                }
4726            }));
4727
4728        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4729            .shape(ui::IconButtonShape::Square)
4730            .icon_size(IconSize::Small)
4731            .icon_color(Color::Ignored)
4732            .tooltip(Tooltip::text("Scroll To Top"))
4733            .on_click(cx.listener(move |this, _, _, cx| {
4734                this.scroll_to_top(cx);
4735            }));
4736
4737        let mut container = h_flex()
4738            .id("thread-controls-container")
4739            .group("thread-controls-container")
4740            .w_full()
4741            .py_2()
4742            .px_5()
4743            .gap_px()
4744            .opacity(0.6)
4745            .hover(|style| style.opacity(1.))
4746            .flex_wrap()
4747            .justify_end();
4748
4749        if AgentSettings::get_global(cx).enable_feedback
4750            && self
4751                .thread()
4752                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4753        {
4754            let feedback = self.thread_feedback.feedback;
4755
4756            container = container
4757                .child(
4758                    div().visible_on_hover("thread-controls-container").child(
4759                        Label::new(match feedback {
4760                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4761                            Some(ThreadFeedback::Negative) => {
4762                                "We appreciate your feedback and will use it to improve."
4763                            }
4764                            None => {
4765                                "Rating the thread sends all of your current conversation to the Zed team."
4766                            }
4767                        })
4768                        .color(Color::Muted)
4769                        .size(LabelSize::XSmall)
4770                        .truncate(),
4771                    ),
4772                )
4773                .child(
4774                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4775                        .shape(ui::IconButtonShape::Square)
4776                        .icon_size(IconSize::Small)
4777                        .icon_color(match feedback {
4778                            Some(ThreadFeedback::Positive) => Color::Accent,
4779                            _ => Color::Ignored,
4780                        })
4781                        .tooltip(Tooltip::text("Helpful Response"))
4782                        .on_click(cx.listener(move |this, _, window, cx| {
4783                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4784                        })),
4785                )
4786                .child(
4787                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4788                        .shape(ui::IconButtonShape::Square)
4789                        .icon_size(IconSize::Small)
4790                        .icon_color(match feedback {
4791                            Some(ThreadFeedback::Negative) => Color::Accent,
4792                            _ => Color::Ignored,
4793                        })
4794                        .tooltip(Tooltip::text("Not Helpful"))
4795                        .on_click(cx.listener(move |this, _, window, cx| {
4796                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4797                        })),
4798                );
4799        }
4800
4801        container.child(open_as_markdown).child(scroll_to_top)
4802    }
4803
4804    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4805        h_flex()
4806            .key_context("AgentFeedbackMessageEditor")
4807            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4808                this.thread_feedback.dismiss_comments();
4809                cx.notify();
4810            }))
4811            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4812                this.submit_feedback_message(cx);
4813            }))
4814            .p_2()
4815            .mb_2()
4816            .mx_5()
4817            .gap_1()
4818            .rounded_md()
4819            .border_1()
4820            .border_color(cx.theme().colors().border)
4821            .bg(cx.theme().colors().editor_background)
4822            .child(div().w_full().child(editor))
4823            .child(
4824                h_flex()
4825                    .child(
4826                        IconButton::new("dismiss-feedback-message", IconName::Close)
4827                            .icon_color(Color::Error)
4828                            .icon_size(IconSize::XSmall)
4829                            .shape(ui::IconButtonShape::Square)
4830                            .on_click(cx.listener(move |this, _, _window, cx| {
4831                                this.thread_feedback.dismiss_comments();
4832                                cx.notify();
4833                            })),
4834                    )
4835                    .child(
4836                        IconButton::new("submit-feedback-message", IconName::Return)
4837                            .icon_size(IconSize::XSmall)
4838                            .shape(ui::IconButtonShape::Square)
4839                            .on_click(cx.listener(move |this, _, _window, cx| {
4840                                this.submit_feedback_message(cx);
4841                            })),
4842                    ),
4843            )
4844    }
4845
4846    fn handle_feedback_click(
4847        &mut self,
4848        feedback: ThreadFeedback,
4849        window: &mut Window,
4850        cx: &mut Context<Self>,
4851    ) {
4852        let Some(thread) = self.thread().cloned() else {
4853            return;
4854        };
4855
4856        self.thread_feedback.submit(thread, feedback, window, cx);
4857        cx.notify();
4858    }
4859
4860    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4861        let Some(thread) = self.thread().cloned() else {
4862            return;
4863        };
4864
4865        self.thread_feedback.submit_comments(thread, cx);
4866        cx.notify();
4867    }
4868
4869    fn render_token_limit_callout(
4870        &self,
4871        line_height: Pixels,
4872        cx: &mut Context<Self>,
4873    ) -> Option<Callout> {
4874        let token_usage = self.thread()?.read(cx).token_usage()?;
4875        let ratio = token_usage.ratio();
4876
4877        let (severity, title) = match ratio {
4878            acp_thread::TokenUsageRatio::Normal => return None,
4879            acp_thread::TokenUsageRatio::Warning => {
4880                (Severity::Warning, "Thread reaching the token limit soon")
4881            }
4882            acp_thread::TokenUsageRatio::Exceeded => {
4883                (Severity::Error, "Thread reached the token limit")
4884            }
4885        };
4886
4887        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4888            thread.read(cx).completion_mode() == CompletionMode::Normal
4889                && thread
4890                    .read(cx)
4891                    .model()
4892                    .is_some_and(|model| model.supports_burn_mode())
4893        });
4894
4895        let description = if burn_mode_available {
4896            "To continue, start a new thread from a summary or turn Burn Mode on."
4897        } else {
4898            "To continue, start a new thread from a summary."
4899        };
4900
4901        Some(
4902            Callout::new()
4903                .severity(severity)
4904                .line_height(line_height)
4905                .title(title)
4906                .description(description)
4907                .actions_slot(
4908                    h_flex()
4909                        .gap_0p5()
4910                        .child(
4911                            Button::new("start-new-thread", "Start New Thread")
4912                                .label_size(LabelSize::Small)
4913                                .on_click(cx.listener(|this, _, window, cx| {
4914                                    let Some(thread) = this.thread() else {
4915                                        return;
4916                                    };
4917                                    let session_id = thread.read(cx).session_id().clone();
4918                                    window.dispatch_action(
4919                                        crate::NewNativeAgentThreadFromSummary {
4920                                            from_session_id: session_id,
4921                                        }
4922                                        .boxed_clone(),
4923                                        cx,
4924                                    );
4925                                })),
4926                        )
4927                        .when(burn_mode_available, |this| {
4928                            this.child(
4929                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4930                                    .icon_size(IconSize::XSmall)
4931                                    .on_click(cx.listener(|this, _event, window, cx| {
4932                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4933                                    })),
4934                            )
4935                        }),
4936                ),
4937        )
4938    }
4939
4940    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4941        if !self.is_using_zed_ai_models(cx) {
4942            return None;
4943        }
4944
4945        let user_store = self.project.read(cx).user_store().read(cx);
4946        if user_store.is_usage_based_billing_enabled() {
4947            return None;
4948        }
4949
4950        let plan = user_store
4951            .plan()
4952            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
4953
4954        let usage = user_store.model_request_usage()?;
4955
4956        Some(
4957            div()
4958                .child(UsageCallout::new(plan, usage))
4959                .line_height(line_height),
4960        )
4961    }
4962
4963    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4964        self.entry_view_state.update(cx, |entry_view_state, cx| {
4965            entry_view_state.agent_ui_font_size_changed(cx);
4966        });
4967    }
4968
4969    pub(crate) fn insert_dragged_files(
4970        &self,
4971        paths: Vec<project::ProjectPath>,
4972        added_worktrees: Vec<Entity<project::Worktree>>,
4973        window: &mut Window,
4974        cx: &mut Context<Self>,
4975    ) {
4976        self.message_editor.update(cx, |message_editor, cx| {
4977            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4978        })
4979    }
4980
4981    /// Inserts the selected text into the message editor or the message being
4982    /// edited, if any.
4983    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4984        self.active_editor(cx).update(cx, |editor, cx| {
4985            editor.insert_selections(window, cx);
4986        });
4987    }
4988
4989    fn render_thread_retry_status_callout(
4990        &self,
4991        _window: &mut Window,
4992        _cx: &mut Context<Self>,
4993    ) -> Option<Callout> {
4994        let state = self.thread_retry_status.as_ref()?;
4995
4996        let next_attempt_in = state
4997            .duration
4998            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4999        if next_attempt_in.is_zero() {
5000            return None;
5001        }
5002
5003        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5004
5005        let retry_message = if state.max_attempts == 1 {
5006            if next_attempt_in_secs == 1 {
5007                "Retrying. Next attempt in 1 second.".to_string()
5008            } else {
5009                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5010            }
5011        } else if next_attempt_in_secs == 1 {
5012            format!(
5013                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5014                state.attempt, state.max_attempts,
5015            )
5016        } else {
5017            format!(
5018                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5019                state.attempt, state.max_attempts,
5020            )
5021        };
5022
5023        Some(
5024            Callout::new()
5025                .severity(Severity::Warning)
5026                .title(state.last_error.clone())
5027                .description(retry_message),
5028        )
5029    }
5030
5031    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5032        let content = match self.thread_error.as_ref()? {
5033            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
5034            ThreadError::Refusal => self.render_refusal_error(cx),
5035            ThreadError::AuthenticationRequired(error) => {
5036                self.render_authentication_required_error(error.clone(), cx)
5037            }
5038            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5039            ThreadError::ModelRequestLimitReached(plan) => {
5040                self.render_model_request_limit_reached_error(*plan, cx)
5041            }
5042            ThreadError::ToolUseLimitReached => {
5043                self.render_tool_use_limit_reached_error(window, cx)?
5044            }
5045        };
5046
5047        Some(div().child(content))
5048    }
5049
5050    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5051        v_flex().w_full().justify_end().child(
5052            h_flex()
5053                .p_2()
5054                .pr_3()
5055                .w_full()
5056                .gap_1p5()
5057                .border_t_1()
5058                .border_color(cx.theme().colors().border)
5059                .bg(cx.theme().colors().element_background)
5060                .child(
5061                    h_flex()
5062                        .flex_1()
5063                        .gap_1p5()
5064                        .child(
5065                            Icon::new(IconName::Download)
5066                                .color(Color::Accent)
5067                                .size(IconSize::Small),
5068                        )
5069                        .child(Label::new("New version available").size(LabelSize::Small)),
5070                )
5071                .child(
5072                    Button::new("update-button", format!("Update to v{}", version))
5073                        .label_size(LabelSize::Small)
5074                        .style(ButtonStyle::Tinted(TintColor::Accent))
5075                        .on_click(cx.listener(|this, _, window, cx| {
5076                            this.reset(window, cx);
5077                        })),
5078                ),
5079        )
5080    }
5081
5082    fn get_current_model_name(&self, cx: &App) -> SharedString {
5083        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5084        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5085        // This provides better clarity about what refused the request
5086        if self
5087            .agent
5088            .clone()
5089            .downcast::<agent2::NativeAgentServer>()
5090            .is_some()
5091        {
5092            // Native agent - use the model name
5093            self.model_selector
5094                .as_ref()
5095                .and_then(|selector| selector.read(cx).active_model_name(cx))
5096                .unwrap_or_else(|| SharedString::from("The model"))
5097        } else {
5098            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5099            self.agent.name()
5100        }
5101    }
5102
5103    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5104        let model_or_agent_name = self.get_current_model_name(cx);
5105        let refusal_message = format!(
5106            "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
5107            model_or_agent_name
5108        );
5109
5110        Callout::new()
5111            .severity(Severity::Error)
5112            .title("Request Refused")
5113            .icon(IconName::XCircle)
5114            .description(refusal_message.clone())
5115            .actions_slot(self.create_copy_button(&refusal_message))
5116            .dismiss_action(self.dismiss_error_button(cx))
5117    }
5118
5119    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
5120        let can_resume = self
5121            .thread()
5122            .map_or(false, |thread| thread.read(cx).can_resume(cx));
5123
5124        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5125            let thread = thread.read(cx);
5126            let supports_burn_mode = thread
5127                .model()
5128                .map_or(false, |model| model.supports_burn_mode());
5129            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5130        });
5131
5132        Callout::new()
5133            .severity(Severity::Error)
5134            .title("Error")
5135            .icon(IconName::XCircle)
5136            .description(error.clone())
5137            .actions_slot(
5138                h_flex()
5139                    .gap_0p5()
5140                    .when(can_resume && can_enable_burn_mode, |this| {
5141                        this.child(
5142                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5143                                .icon(IconName::ZedBurnMode)
5144                                .icon_position(IconPosition::Start)
5145                                .icon_size(IconSize::Small)
5146                                .label_size(LabelSize::Small)
5147                                .on_click(cx.listener(|this, _, window, cx| {
5148                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5149                                    this.resume_chat(cx);
5150                                })),
5151                        )
5152                    })
5153                    .when(can_resume, |this| {
5154                        this.child(
5155                            Button::new("retry", "Retry")
5156                                .icon(IconName::RotateCw)
5157                                .icon_position(IconPosition::Start)
5158                                .icon_size(IconSize::Small)
5159                                .label_size(LabelSize::Small)
5160                                .on_click(cx.listener(|this, _, _window, cx| {
5161                                    this.resume_chat(cx);
5162                                })),
5163                        )
5164                    })
5165                    .child(self.create_copy_button(error.to_string())),
5166            )
5167            .dismiss_action(self.dismiss_error_button(cx))
5168    }
5169
5170    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5171        const ERROR_MESSAGE: &str =
5172            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5173
5174        Callout::new()
5175            .severity(Severity::Error)
5176            .icon(IconName::XCircle)
5177            .title("Free Usage Exceeded")
5178            .description(ERROR_MESSAGE)
5179            .actions_slot(
5180                h_flex()
5181                    .gap_0p5()
5182                    .child(self.upgrade_button(cx))
5183                    .child(self.create_copy_button(ERROR_MESSAGE)),
5184            )
5185            .dismiss_action(self.dismiss_error_button(cx))
5186    }
5187
5188    fn render_authentication_required_error(
5189        &self,
5190        error: SharedString,
5191        cx: &mut Context<Self>,
5192    ) -> Callout {
5193        Callout::new()
5194            .severity(Severity::Error)
5195            .title("Authentication Required")
5196            .icon(IconName::XCircle)
5197            .description(error.clone())
5198            .actions_slot(
5199                h_flex()
5200                    .gap_0p5()
5201                    .child(self.authenticate_button(cx))
5202                    .child(self.create_copy_button(error)),
5203            )
5204            .dismiss_action(self.dismiss_error_button(cx))
5205    }
5206
5207    fn render_model_request_limit_reached_error(
5208        &self,
5209        plan: cloud_llm_client::Plan,
5210        cx: &mut Context<Self>,
5211    ) -> Callout {
5212        let error_message = match plan {
5213            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5214                "Upgrade to usage-based billing for more prompts."
5215            }
5216            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5217            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5218            cloud_llm_client::Plan::V2(_) => "",
5219        };
5220
5221        Callout::new()
5222            .severity(Severity::Error)
5223            .title("Model Prompt Limit Reached")
5224            .icon(IconName::XCircle)
5225            .description(error_message)
5226            .actions_slot(
5227                h_flex()
5228                    .gap_0p5()
5229                    .child(self.upgrade_button(cx))
5230                    .child(self.create_copy_button(error_message)),
5231            )
5232            .dismiss_action(self.dismiss_error_button(cx))
5233    }
5234
5235    fn render_tool_use_limit_reached_error(
5236        &self,
5237        window: &mut Window,
5238        cx: &mut Context<Self>,
5239    ) -> Option<Callout> {
5240        let thread = self.as_native_thread(cx)?;
5241        let supports_burn_mode = thread
5242            .read(cx)
5243            .model()
5244            .is_some_and(|model| model.supports_burn_mode());
5245
5246        let focus_handle = self.focus_handle(cx);
5247
5248        Some(
5249            Callout::new()
5250                .icon(IconName::Info)
5251                .title("Consecutive tool use limit reached.")
5252                .actions_slot(
5253                    h_flex()
5254                        .gap_0p5()
5255                        .when(supports_burn_mode, |this| {
5256                            this.child(
5257                                Button::new("continue-burn-mode", "Continue with Burn Mode")
5258                                    .style(ButtonStyle::Filled)
5259                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5260                                    .layer(ElevationIndex::ModalSurface)
5261                                    .label_size(LabelSize::Small)
5262                                    .key_binding(
5263                                        KeyBinding::for_action_in(
5264                                            &ContinueWithBurnMode,
5265                                            &focus_handle,
5266                                            window,
5267                                            cx,
5268                                        )
5269                                        .map(|kb| kb.size(rems_from_px(10.))),
5270                                    )
5271                                    .tooltip(Tooltip::text(
5272                                        "Enable Burn Mode for unlimited tool use.",
5273                                    ))
5274                                    .on_click({
5275                                        cx.listener(move |this, _, _window, cx| {
5276                                            thread.update(cx, |thread, cx| {
5277                                                thread
5278                                                    .set_completion_mode(CompletionMode::Burn, cx);
5279                                            });
5280                                            this.resume_chat(cx);
5281                                        })
5282                                    }),
5283                            )
5284                        })
5285                        .child(
5286                            Button::new("continue-conversation", "Continue")
5287                                .layer(ElevationIndex::ModalSurface)
5288                                .label_size(LabelSize::Small)
5289                                .key_binding(
5290                                    KeyBinding::for_action_in(
5291                                        &ContinueThread,
5292                                        &focus_handle,
5293                                        window,
5294                                        cx,
5295                                    )
5296                                    .map(|kb| kb.size(rems_from_px(10.))),
5297                                )
5298                                .on_click(cx.listener(|this, _, _window, cx| {
5299                                    this.resume_chat(cx);
5300                                })),
5301                        ),
5302                ),
5303        )
5304    }
5305
5306    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5307        let message = message.into();
5308
5309        IconButton::new("copy", IconName::Copy)
5310            .icon_size(IconSize::Small)
5311            .icon_color(Color::Muted)
5312            .tooltip(Tooltip::text("Copy Error Message"))
5313            .on_click(move |_, _, cx| {
5314                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5315            })
5316    }
5317
5318    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5319        IconButton::new("dismiss", IconName::Close)
5320            .icon_size(IconSize::Small)
5321            .icon_color(Color::Muted)
5322            .tooltip(Tooltip::text("Dismiss Error"))
5323            .on_click(cx.listener({
5324                move |this, _, _, cx| {
5325                    this.clear_thread_error(cx);
5326                    cx.notify();
5327                }
5328            }))
5329    }
5330
5331    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5332        Button::new("authenticate", "Authenticate")
5333            .label_size(LabelSize::Small)
5334            .style(ButtonStyle::Filled)
5335            .on_click(cx.listener({
5336                move |this, _, window, cx| {
5337                    let agent = this.agent.clone();
5338                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
5339                        return;
5340                    };
5341
5342                    let connection = thread.read(cx).connection().clone();
5343                    let err = AuthRequired {
5344                        description: None,
5345                        provider_id: None,
5346                    };
5347                    this.clear_thread_error(cx);
5348                    let this = cx.weak_entity();
5349                    window.defer(cx, |window, cx| {
5350                        Self::handle_auth_required(this, err, agent, connection, window, cx);
5351                    })
5352                }
5353            }))
5354    }
5355
5356    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5357        let agent = self.agent.clone();
5358        let ThreadState::Ready { thread, .. } = &self.thread_state else {
5359            return;
5360        };
5361
5362        let connection = thread.read(cx).connection().clone();
5363        let err = AuthRequired {
5364            description: None,
5365            provider_id: None,
5366        };
5367        self.clear_thread_error(cx);
5368        let this = cx.weak_entity();
5369        window.defer(cx, |window, cx| {
5370            Self::handle_auth_required(this, err, agent, connection, window, cx);
5371        })
5372    }
5373
5374    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5375        Button::new("upgrade", "Upgrade")
5376            .label_size(LabelSize::Small)
5377            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5378            .on_click(cx.listener({
5379                move |this, _, _, cx| {
5380                    this.clear_thread_error(cx);
5381                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5382                }
5383            }))
5384    }
5385
5386    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5387        let task = match entry {
5388            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5389                history.delete_thread(thread.id.clone(), cx)
5390            }),
5391            HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5392                history.delete_text_thread(context.path.clone(), cx)
5393            }),
5394        };
5395        task.detach_and_log_err(cx);
5396    }
5397
5398    /// Returns the currently active editor, either for a message that is being
5399    /// edited or the editor for a new message.
5400    fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5401        if let Some(index) = self.editing_message
5402            && let Some(editor) = self
5403                .entry_view_state
5404                .read(cx)
5405                .entry(index)
5406                .and_then(|e| e.message_editor())
5407                .cloned()
5408        {
5409            editor
5410        } else {
5411            self.message_editor.clone()
5412        }
5413    }
5414}
5415
5416fn loading_contents_spinner(size: IconSize) -> AnyElement {
5417    Icon::new(IconName::LoadCircle)
5418        .size(size)
5419        .color(Color::Accent)
5420        .with_rotate_animation(3)
5421        .into_any_element()
5422}
5423
5424impl Focusable for AcpThreadView {
5425    fn focus_handle(&self, cx: &App) -> FocusHandle {
5426        match self.thread_state {
5427            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5428                self.active_editor(cx).focus_handle(cx)
5429            }
5430            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5431                self.focus_handle.clone()
5432            }
5433        }
5434    }
5435}
5436
5437impl Render for AcpThreadView {
5438    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5439        let has_messages = self.list_state.item_count() > 0;
5440        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5441
5442        v_flex()
5443            .size_full()
5444            .key_context("AcpThread")
5445            .on_action(cx.listener(Self::toggle_burn_mode))
5446            .on_action(cx.listener(Self::keep_all))
5447            .on_action(cx.listener(Self::reject_all))
5448            .on_action(cx.listener(Self::allow_always))
5449            .on_action(cx.listener(Self::allow_once))
5450            .on_action(cx.listener(Self::reject_once))
5451            .track_focus(&self.focus_handle)
5452            .bg(cx.theme().colors().panel_background)
5453            .child(match &self.thread_state {
5454                ThreadState::Unauthenticated {
5455                    connection,
5456                    description,
5457                    configuration_view,
5458                    pending_auth_method,
5459                    ..
5460                } => self
5461                    .render_auth_required_state(
5462                        connection,
5463                        description.as_ref(),
5464                        configuration_view.as_ref(),
5465                        pending_auth_method.as_ref(),
5466                        window,
5467                        cx,
5468                    )
5469                    .into_any(),
5470                ThreadState::Loading { .. } => v_flex()
5471                    .flex_1()
5472                    .child(self.render_recent_history(window, cx))
5473                    .into_any(),
5474                ThreadState::LoadError(e) => v_flex()
5475                    .flex_1()
5476                    .size_full()
5477                    .items_center()
5478                    .justify_end()
5479                    .child(self.render_load_error(e, window, cx))
5480                    .into_any(),
5481                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5482                    if has_messages {
5483                        this.child(
5484                            list(
5485                                self.list_state.clone(),
5486                                cx.processor(|this, index: usize, window, cx| {
5487                                    let Some((entry, len)) = this.thread().and_then(|thread| {
5488                                        let entries = &thread.read(cx).entries();
5489                                        Some((entries.get(index)?, entries.len()))
5490                                    }) else {
5491                                        return Empty.into_any();
5492                                    };
5493                                    this.render_entry(index, len, entry, window, cx)
5494                                }),
5495                            )
5496                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5497                            .flex_grow()
5498                            .into_any(),
5499                        )
5500                        .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5501                        .into_any()
5502                    } else {
5503                        this.child(self.render_recent_history(window, cx))
5504                            .into_any()
5505                    }
5506                }),
5507            })
5508            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5509            // above so that the scrollbar doesn't render behind it. The current setup allows
5510            // the scrollbar to stop exactly at the activity bar start.
5511            .when(has_messages, |this| match &self.thread_state {
5512                ThreadState::Ready { thread, .. } => {
5513                    this.children(self.render_activity_bar(thread, window, cx))
5514                }
5515                _ => this,
5516            })
5517            .children(self.render_thread_retry_status_callout(window, cx))
5518            .children(self.render_thread_error(window, cx))
5519            .when_some(
5520                self.new_server_version_available.as_ref().filter(|_| {
5521                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5522                }),
5523                |this, version| this.child(self.render_new_version_callout(&version, cx)),
5524            )
5525            .children(
5526                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5527                    Some(usage_callout.into_any_element())
5528                } else {
5529                    self.render_token_limit_callout(line_height, cx)
5530                        .map(|token_limit_callout| token_limit_callout.into_any_element())
5531                },
5532            )
5533            .child(self.render_message_editor(window, cx))
5534    }
5535}
5536
5537fn default_markdown_style(
5538    buffer_font: bool,
5539    muted_text: bool,
5540    window: &Window,
5541    cx: &App,
5542) -> MarkdownStyle {
5543    let theme_settings = ThemeSettings::get_global(cx);
5544    let colors = cx.theme().colors();
5545
5546    let buffer_font_size = TextSize::Small.rems(cx);
5547
5548    let mut text_style = window.text_style();
5549    let line_height = buffer_font_size * 1.75;
5550
5551    let font_family = if buffer_font {
5552        theme_settings.buffer_font.family.clone()
5553    } else {
5554        theme_settings.ui_font.family.clone()
5555    };
5556
5557    let font_size = if buffer_font {
5558        TextSize::Small.rems(cx)
5559    } else {
5560        TextSize::Default.rems(cx)
5561    };
5562
5563    let text_color = if muted_text {
5564        colors.text_muted
5565    } else {
5566        colors.text
5567    };
5568
5569    text_style.refine(&TextStyleRefinement {
5570        font_family: Some(font_family),
5571        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5572        font_features: Some(theme_settings.ui_font.features.clone()),
5573        font_size: Some(font_size.into()),
5574        line_height: Some(line_height.into()),
5575        color: Some(text_color),
5576        ..Default::default()
5577    });
5578
5579    MarkdownStyle {
5580        base_text_style: text_style.clone(),
5581        syntax: cx.theme().syntax().clone(),
5582        selection_background_color: colors.element_selection_background,
5583        code_block_overflow_x_scroll: true,
5584        table_overflow_x_scroll: true,
5585        heading_level_styles: Some(HeadingLevelStyles {
5586            h1: Some(TextStyleRefinement {
5587                font_size: Some(rems(1.15).into()),
5588                ..Default::default()
5589            }),
5590            h2: Some(TextStyleRefinement {
5591                font_size: Some(rems(1.1).into()),
5592                ..Default::default()
5593            }),
5594            h3: Some(TextStyleRefinement {
5595                font_size: Some(rems(1.05).into()),
5596                ..Default::default()
5597            }),
5598            h4: Some(TextStyleRefinement {
5599                font_size: Some(rems(1.).into()),
5600                ..Default::default()
5601            }),
5602            h5: Some(TextStyleRefinement {
5603                font_size: Some(rems(0.95).into()),
5604                ..Default::default()
5605            }),
5606            h6: Some(TextStyleRefinement {
5607                font_size: Some(rems(0.875).into()),
5608                ..Default::default()
5609            }),
5610        }),
5611        code_block: StyleRefinement {
5612            padding: EdgesRefinement {
5613                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5614                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5615                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5616                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5617            },
5618            margin: EdgesRefinement {
5619                top: Some(Length::Definite(px(8.).into())),
5620                left: Some(Length::Definite(px(0.).into())),
5621                right: Some(Length::Definite(px(0.).into())),
5622                bottom: Some(Length::Definite(px(12.).into())),
5623            },
5624            border_style: Some(BorderStyle::Solid),
5625            border_widths: EdgesRefinement {
5626                top: Some(AbsoluteLength::Pixels(px(1.))),
5627                left: Some(AbsoluteLength::Pixels(px(1.))),
5628                right: Some(AbsoluteLength::Pixels(px(1.))),
5629                bottom: Some(AbsoluteLength::Pixels(px(1.))),
5630            },
5631            border_color: Some(colors.border_variant),
5632            background: Some(colors.editor_background.into()),
5633            text: Some(TextStyleRefinement {
5634                font_family: Some(theme_settings.buffer_font.family.clone()),
5635                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5636                font_features: Some(theme_settings.buffer_font.features.clone()),
5637                font_size: Some(buffer_font_size.into()),
5638                ..Default::default()
5639            }),
5640            ..Default::default()
5641        },
5642        inline_code: TextStyleRefinement {
5643            font_family: Some(theme_settings.buffer_font.family.clone()),
5644            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5645            font_features: Some(theme_settings.buffer_font.features.clone()),
5646            font_size: Some(buffer_font_size.into()),
5647            background_color: Some(colors.editor_foreground.opacity(0.08)),
5648            ..Default::default()
5649        },
5650        link: TextStyleRefinement {
5651            background_color: Some(colors.editor_foreground.opacity(0.025)),
5652            underline: Some(UnderlineStyle {
5653                color: Some(colors.text_accent.opacity(0.5)),
5654                thickness: px(1.),
5655                ..Default::default()
5656            }),
5657            ..Default::default()
5658        },
5659        ..Default::default()
5660    }
5661}
5662
5663fn plan_label_markdown_style(
5664    status: &acp::PlanEntryStatus,
5665    window: &Window,
5666    cx: &App,
5667) -> MarkdownStyle {
5668    let default_md_style = default_markdown_style(false, false, window, cx);
5669
5670    MarkdownStyle {
5671        base_text_style: TextStyle {
5672            color: cx.theme().colors().text_muted,
5673            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5674                Some(gpui::StrikethroughStyle {
5675                    thickness: px(1.),
5676                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5677                })
5678            } else {
5679                None
5680            },
5681            ..default_md_style.base_text_style
5682        },
5683        ..default_md_style
5684    }
5685}
5686
5687fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5688    let default_md_style = default_markdown_style(true, false, window, cx);
5689
5690    MarkdownStyle {
5691        base_text_style: TextStyle {
5692            ..default_md_style.base_text_style
5693        },
5694        selection_background_color: cx.theme().colors().element_selection_background,
5695        ..Default::default()
5696    }
5697}
5698
5699#[cfg(test)]
5700pub(crate) mod tests {
5701    use acp_thread::StubAgentConnection;
5702    use agent_client_protocol::SessionId;
5703    use assistant_context::ContextStore;
5704    use editor::EditorSettings;
5705    use fs::FakeFs;
5706    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5707    use project::Project;
5708    use serde_json::json;
5709    use settings::SettingsStore;
5710    use std::any::Any;
5711    use std::path::Path;
5712    use workspace::Item;
5713
5714    use super::*;
5715
5716    #[gpui::test]
5717    async fn test_drop(cx: &mut TestAppContext) {
5718        init_test(cx);
5719
5720        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5721        let weak_view = thread_view.downgrade();
5722        drop(thread_view);
5723        assert!(!weak_view.is_upgradable());
5724    }
5725
5726    #[gpui::test]
5727    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5728        init_test(cx);
5729
5730        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5731
5732        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5733        message_editor.update_in(cx, |editor, window, cx| {
5734            editor.set_text("Hello", window, cx);
5735        });
5736
5737        cx.deactivate_window();
5738
5739        thread_view.update_in(cx, |thread_view, window, cx| {
5740            thread_view.send(window, cx);
5741        });
5742
5743        cx.run_until_parked();
5744
5745        assert!(
5746            cx.windows()
5747                .iter()
5748                .any(|window| window.downcast::<AgentNotification>().is_some())
5749        );
5750    }
5751
5752    #[gpui::test]
5753    async fn test_notification_for_error(cx: &mut TestAppContext) {
5754        init_test(cx);
5755
5756        let (thread_view, cx) =
5757            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5758
5759        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5760        message_editor.update_in(cx, |editor, window, cx| {
5761            editor.set_text("Hello", window, cx);
5762        });
5763
5764        cx.deactivate_window();
5765
5766        thread_view.update_in(cx, |thread_view, window, cx| {
5767            thread_view.send(window, cx);
5768        });
5769
5770        cx.run_until_parked();
5771
5772        assert!(
5773            cx.windows()
5774                .iter()
5775                .any(|window| window.downcast::<AgentNotification>().is_some())
5776        );
5777    }
5778
5779    #[gpui::test]
5780    async fn test_refusal_handling(cx: &mut TestAppContext) {
5781        init_test(cx);
5782
5783        let (thread_view, cx) =
5784            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5785
5786        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5787        message_editor.update_in(cx, |editor, window, cx| {
5788            editor.set_text("Do something harmful", window, cx);
5789        });
5790
5791        thread_view.update_in(cx, |thread_view, window, cx| {
5792            thread_view.send(window, cx);
5793        });
5794
5795        cx.run_until_parked();
5796
5797        // Check that the refusal error is set
5798        thread_view.read_with(cx, |thread_view, _cx| {
5799            assert!(
5800                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5801                "Expected refusal error to be set"
5802            );
5803        });
5804    }
5805
5806    #[gpui::test]
5807    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5808        init_test(cx);
5809
5810        let tool_call_id = acp::ToolCallId("1".into());
5811        let tool_call = acp::ToolCall {
5812            id: tool_call_id.clone(),
5813            title: "Label".into(),
5814            kind: acp::ToolKind::Edit,
5815            status: acp::ToolCallStatus::Pending,
5816            content: vec!["hi".into()],
5817            locations: vec![],
5818            raw_input: None,
5819            raw_output: None,
5820            meta: None,
5821        };
5822        let connection =
5823            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5824                tool_call_id,
5825                vec![acp::PermissionOption {
5826                    id: acp::PermissionOptionId("1".into()),
5827                    name: "Allow".into(),
5828                    kind: acp::PermissionOptionKind::AllowOnce,
5829                    meta: None,
5830                }],
5831            )]));
5832
5833        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5834
5835        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5836
5837        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5838        message_editor.update_in(cx, |editor, window, cx| {
5839            editor.set_text("Hello", window, cx);
5840        });
5841
5842        cx.deactivate_window();
5843
5844        thread_view.update_in(cx, |thread_view, window, cx| {
5845            thread_view.send(window, cx);
5846        });
5847
5848        cx.run_until_parked();
5849
5850        assert!(
5851            cx.windows()
5852                .iter()
5853                .any(|window| window.downcast::<AgentNotification>().is_some())
5854        );
5855    }
5856
5857    async fn setup_thread_view(
5858        agent: impl AgentServer + 'static,
5859        cx: &mut TestAppContext,
5860    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5861        let fs = FakeFs::new(cx.executor());
5862        let project = Project::test(fs, [], cx).await;
5863        let (workspace, cx) =
5864            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5865
5866        let context_store =
5867            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5868        let history_store =
5869            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5870
5871        let thread_view = cx.update(|window, cx| {
5872            cx.new(|cx| {
5873                AcpThreadView::new(
5874                    Rc::new(agent),
5875                    None,
5876                    None,
5877                    workspace.downgrade(),
5878                    project,
5879                    history_store,
5880                    None,
5881                    window,
5882                    cx,
5883                )
5884            })
5885        });
5886        cx.run_until_parked();
5887        (thread_view, cx)
5888    }
5889
5890    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5891        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5892
5893        workspace
5894            .update_in(cx, |workspace, window, cx| {
5895                workspace.add_item_to_active_pane(
5896                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5897                    None,
5898                    true,
5899                    window,
5900                    cx,
5901                );
5902            })
5903            .unwrap();
5904    }
5905
5906    struct ThreadViewItem(Entity<AcpThreadView>);
5907
5908    impl Item for ThreadViewItem {
5909        type Event = ();
5910
5911        fn include_in_nav_history() -> bool {
5912            false
5913        }
5914
5915        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5916            "Test".into()
5917        }
5918    }
5919
5920    impl EventEmitter<()> for ThreadViewItem {}
5921
5922    impl Focusable for ThreadViewItem {
5923        fn focus_handle(&self, cx: &App) -> FocusHandle {
5924            self.0.read(cx).focus_handle(cx)
5925        }
5926    }
5927
5928    impl Render for ThreadViewItem {
5929        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5930            self.0.clone().into_any_element()
5931        }
5932    }
5933
5934    struct StubAgentServer<C> {
5935        connection: C,
5936    }
5937
5938    impl<C> StubAgentServer<C> {
5939        fn new(connection: C) -> Self {
5940            Self { connection }
5941        }
5942    }
5943
5944    impl StubAgentServer<StubAgentConnection> {
5945        fn default_response() -> Self {
5946            let conn = StubAgentConnection::new();
5947            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5948                content: "Default response".into(),
5949            }]);
5950            Self::new(conn)
5951        }
5952    }
5953
5954    impl<C> AgentServer for StubAgentServer<C>
5955    where
5956        C: 'static + AgentConnection + Send + Clone,
5957    {
5958        fn telemetry_id(&self) -> &'static str {
5959            "test"
5960        }
5961
5962        fn logo(&self) -> ui::IconName {
5963            ui::IconName::Ai
5964        }
5965
5966        fn name(&self) -> SharedString {
5967            "Test".into()
5968        }
5969
5970        fn connect(
5971            &self,
5972            _root_dir: Option<&Path>,
5973            _delegate: AgentServerDelegate,
5974            _cx: &mut App,
5975        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
5976            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
5977        }
5978
5979        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5980            self
5981        }
5982    }
5983
5984    #[derive(Clone)]
5985    struct SaboteurAgentConnection;
5986
5987    impl AgentConnection for SaboteurAgentConnection {
5988        fn new_thread(
5989            self: Rc<Self>,
5990            project: Entity<Project>,
5991            _cwd: &Path,
5992            cx: &mut gpui::App,
5993        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5994            Task::ready(Ok(cx.new(|cx| {
5995                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5996                AcpThread::new(
5997                    "SaboteurAgentConnection",
5998                    self,
5999                    project,
6000                    action_log,
6001                    SessionId("test".into()),
6002                    watch::Receiver::constant(acp::PromptCapabilities {
6003                        image: true,
6004                        audio: true,
6005                        embedded_context: true,
6006                        meta: None,
6007                    }),
6008                    cx,
6009                )
6010            })))
6011        }
6012
6013        fn auth_methods(&self) -> &[acp::AuthMethod] {
6014            &[]
6015        }
6016
6017        fn authenticate(
6018            &self,
6019            _method_id: acp::AuthMethodId,
6020            _cx: &mut App,
6021        ) -> Task<gpui::Result<()>> {
6022            unimplemented!()
6023        }
6024
6025        fn prompt(
6026            &self,
6027            _id: Option<acp_thread::UserMessageId>,
6028            _params: acp::PromptRequest,
6029            _cx: &mut App,
6030        ) -> Task<gpui::Result<acp::PromptResponse>> {
6031            Task::ready(Err(anyhow::anyhow!("Error prompting")))
6032        }
6033
6034        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6035            unimplemented!()
6036        }
6037
6038        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6039            self
6040        }
6041    }
6042
6043    /// Simulates a model which always returns a refusal response
6044    #[derive(Clone)]
6045    struct RefusalAgentConnection;
6046
6047    impl AgentConnection for RefusalAgentConnection {
6048        fn new_thread(
6049            self: Rc<Self>,
6050            project: Entity<Project>,
6051            _cwd: &Path,
6052            cx: &mut gpui::App,
6053        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6054            Task::ready(Ok(cx.new(|cx| {
6055                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6056                AcpThread::new(
6057                    "RefusalAgentConnection",
6058                    self,
6059                    project,
6060                    action_log,
6061                    SessionId("test".into()),
6062                    watch::Receiver::constant(acp::PromptCapabilities {
6063                        image: true,
6064                        audio: true,
6065                        embedded_context: true,
6066                        meta: None,
6067                    }),
6068                    cx,
6069                )
6070            })))
6071        }
6072
6073        fn auth_methods(&self) -> &[acp::AuthMethod] {
6074            &[]
6075        }
6076
6077        fn authenticate(
6078            &self,
6079            _method_id: acp::AuthMethodId,
6080            _cx: &mut App,
6081        ) -> Task<gpui::Result<()>> {
6082            unimplemented!()
6083        }
6084
6085        fn prompt(
6086            &self,
6087            _id: Option<acp_thread::UserMessageId>,
6088            _params: acp::PromptRequest,
6089            _cx: &mut App,
6090        ) -> Task<gpui::Result<acp::PromptResponse>> {
6091            Task::ready(Ok(acp::PromptResponse {
6092                stop_reason: acp::StopReason::Refusal,
6093                meta: None,
6094            }))
6095        }
6096
6097        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6098            unimplemented!()
6099        }
6100
6101        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6102            self
6103        }
6104    }
6105
6106    pub(crate) fn init_test(cx: &mut TestAppContext) {
6107        cx.update(|cx| {
6108            let settings_store = SettingsStore::test(cx);
6109            cx.set_global(settings_store);
6110            language::init(cx);
6111            Project::init_settings(cx);
6112            AgentSettings::register(cx);
6113            workspace::init_settings(cx);
6114            theme::init(theme::LoadThemes::JustBase, cx);
6115            release_channel::init(SemanticVersion::default(), cx);
6116            EditorSettings::register(cx);
6117            prompt_store::init(cx)
6118        });
6119    }
6120
6121    #[gpui::test]
6122    async fn test_rewind_views(cx: &mut TestAppContext) {
6123        init_test(cx);
6124
6125        let fs = FakeFs::new(cx.executor());
6126        fs.insert_tree(
6127            "/project",
6128            json!({
6129                "test1.txt": "old content 1",
6130                "test2.txt": "old content 2"
6131            }),
6132        )
6133        .await;
6134        let project = Project::test(fs, [Path::new("/project")], cx).await;
6135        let (workspace, cx) =
6136            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6137
6138        let context_store =
6139            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
6140        let history_store =
6141            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
6142
6143        let connection = Rc::new(StubAgentConnection::new());
6144        let thread_view = cx.update(|window, cx| {
6145            cx.new(|cx| {
6146                AcpThreadView::new(
6147                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6148                    None,
6149                    None,
6150                    workspace.downgrade(),
6151                    project.clone(),
6152                    history_store.clone(),
6153                    None,
6154                    window,
6155                    cx,
6156                )
6157            })
6158        });
6159
6160        cx.run_until_parked();
6161
6162        let thread = thread_view
6163            .read_with(cx, |view, _| view.thread().cloned())
6164            .unwrap();
6165
6166        // First user message
6167        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6168            id: acp::ToolCallId("tool1".into()),
6169            title: "Edit file 1".into(),
6170            kind: acp::ToolKind::Edit,
6171            status: acp::ToolCallStatus::Completed,
6172            content: vec![acp::ToolCallContent::Diff {
6173                diff: acp::Diff {
6174                    path: "/project/test1.txt".into(),
6175                    old_text: Some("old content 1".into()),
6176                    new_text: "new content 1".into(),
6177                    meta: None,
6178                },
6179            }],
6180            locations: vec![],
6181            raw_input: None,
6182            raw_output: None,
6183            meta: None,
6184        })]);
6185
6186        thread
6187            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6188            .await
6189            .unwrap();
6190        cx.run_until_parked();
6191
6192        thread.read_with(cx, |thread, _| {
6193            assert_eq!(thread.entries().len(), 2);
6194        });
6195
6196        thread_view.read_with(cx, |view, cx| {
6197            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6198                assert!(
6199                    entry_view_state
6200                        .entry(0)
6201                        .unwrap()
6202                        .message_editor()
6203                        .is_some()
6204                );
6205                assert!(entry_view_state.entry(1).unwrap().has_content());
6206            });
6207        });
6208
6209        // Second user message
6210        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6211            id: acp::ToolCallId("tool2".into()),
6212            title: "Edit file 2".into(),
6213            kind: acp::ToolKind::Edit,
6214            status: acp::ToolCallStatus::Completed,
6215            content: vec![acp::ToolCallContent::Diff {
6216                diff: acp::Diff {
6217                    path: "/project/test2.txt".into(),
6218                    old_text: Some("old content 2".into()),
6219                    new_text: "new content 2".into(),
6220                    meta: None,
6221                },
6222            }],
6223            locations: vec![],
6224            raw_input: None,
6225            raw_output: None,
6226            meta: None,
6227        })]);
6228
6229        thread
6230            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6231            .await
6232            .unwrap();
6233        cx.run_until_parked();
6234
6235        let second_user_message_id = thread.read_with(cx, |thread, _| {
6236            assert_eq!(thread.entries().len(), 4);
6237            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6238                panic!();
6239            };
6240            user_message.id.clone().unwrap()
6241        });
6242
6243        thread_view.read_with(cx, |view, cx| {
6244            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6245                assert!(
6246                    entry_view_state
6247                        .entry(0)
6248                        .unwrap()
6249                        .message_editor()
6250                        .is_some()
6251                );
6252                assert!(entry_view_state.entry(1).unwrap().has_content());
6253                assert!(
6254                    entry_view_state
6255                        .entry(2)
6256                        .unwrap()
6257                        .message_editor()
6258                        .is_some()
6259                );
6260                assert!(entry_view_state.entry(3).unwrap().has_content());
6261            });
6262        });
6263
6264        // Rewind to first message
6265        thread
6266            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6267            .await
6268            .unwrap();
6269
6270        cx.run_until_parked();
6271
6272        thread.read_with(cx, |thread, _| {
6273            assert_eq!(thread.entries().len(), 2);
6274        });
6275
6276        thread_view.read_with(cx, |view, cx| {
6277            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6278                assert!(
6279                    entry_view_state
6280                        .entry(0)
6281                        .unwrap()
6282                        .message_editor()
6283                        .is_some()
6284                );
6285                assert!(entry_view_state.entry(1).unwrap().has_content());
6286
6287                // Old views should be dropped
6288                assert!(entry_view_state.entry(2).is_none());
6289                assert!(entry_view_state.entry(3).is_none());
6290            });
6291        });
6292    }
6293
6294    #[gpui::test]
6295    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6296        init_test(cx);
6297
6298        let connection = StubAgentConnection::new();
6299
6300        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6301            content: acp::ContentBlock::Text(acp::TextContent {
6302                text: "Response".into(),
6303                annotations: None,
6304                meta: None,
6305            }),
6306        }]);
6307
6308        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6309        add_to_workspace(thread_view.clone(), cx);
6310
6311        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6312        message_editor.update_in(cx, |editor, window, cx| {
6313            editor.set_text("Original message to edit", window, cx);
6314        });
6315        thread_view.update_in(cx, |thread_view, window, cx| {
6316            thread_view.send(window, cx);
6317        });
6318
6319        cx.run_until_parked();
6320
6321        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6322            assert_eq!(view.editing_message, None);
6323
6324            view.entry_view_state
6325                .read(cx)
6326                .entry(0)
6327                .unwrap()
6328                .message_editor()
6329                .unwrap()
6330                .clone()
6331        });
6332
6333        // Focus
6334        cx.focus(&user_message_editor);
6335        thread_view.read_with(cx, |view, _cx| {
6336            assert_eq!(view.editing_message, Some(0));
6337        });
6338
6339        // Edit
6340        user_message_editor.update_in(cx, |editor, window, cx| {
6341            editor.set_text("Edited message content", window, cx);
6342        });
6343
6344        // Cancel
6345        user_message_editor.update_in(cx, |_editor, window, cx| {
6346            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6347        });
6348
6349        thread_view.read_with(cx, |view, _cx| {
6350            assert_eq!(view.editing_message, None);
6351        });
6352
6353        user_message_editor.read_with(cx, |editor, cx| {
6354            assert_eq!(editor.text(cx), "Original message to edit");
6355        });
6356    }
6357
6358    #[gpui::test]
6359    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6360        init_test(cx);
6361
6362        let connection = StubAgentConnection::new();
6363
6364        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6365        add_to_workspace(thread_view.clone(), cx);
6366
6367        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6368        let mut events = cx.events(&message_editor);
6369        message_editor.update_in(cx, |editor, window, cx| {
6370            editor.set_text("", window, cx);
6371        });
6372
6373        message_editor.update_in(cx, |_editor, window, cx| {
6374            window.dispatch_action(Box::new(Chat), cx);
6375        });
6376        cx.run_until_parked();
6377        // We shouldn't have received any messages
6378        assert!(matches!(
6379            events.try_next(),
6380            Err(futures::channel::mpsc::TryRecvError { .. })
6381        ));
6382    }
6383
6384    #[gpui::test]
6385    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6386        init_test(cx);
6387
6388        let connection = StubAgentConnection::new();
6389
6390        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6391            content: acp::ContentBlock::Text(acp::TextContent {
6392                text: "Response".into(),
6393                annotations: None,
6394                meta: None,
6395            }),
6396        }]);
6397
6398        let (thread_view, cx) =
6399            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6400        add_to_workspace(thread_view.clone(), cx);
6401
6402        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6403        message_editor.update_in(cx, |editor, window, cx| {
6404            editor.set_text("Original message to edit", window, cx);
6405        });
6406        thread_view.update_in(cx, |thread_view, window, cx| {
6407            thread_view.send(window, cx);
6408        });
6409
6410        cx.run_until_parked();
6411
6412        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6413            assert_eq!(view.editing_message, None);
6414            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6415
6416            view.entry_view_state
6417                .read(cx)
6418                .entry(0)
6419                .unwrap()
6420                .message_editor()
6421                .unwrap()
6422                .clone()
6423        });
6424
6425        // Focus
6426        cx.focus(&user_message_editor);
6427
6428        // Edit
6429        user_message_editor.update_in(cx, |editor, window, cx| {
6430            editor.set_text("Edited message content", window, cx);
6431        });
6432
6433        // Send
6434        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6435            content: acp::ContentBlock::Text(acp::TextContent {
6436                text: "New Response".into(),
6437                annotations: None,
6438                meta: None,
6439            }),
6440        }]);
6441
6442        user_message_editor.update_in(cx, |_editor, window, cx| {
6443            window.dispatch_action(Box::new(Chat), cx);
6444        });
6445
6446        cx.run_until_parked();
6447
6448        thread_view.read_with(cx, |view, cx| {
6449            assert_eq!(view.editing_message, None);
6450
6451            let entries = view.thread().unwrap().read(cx).entries();
6452            assert_eq!(entries.len(), 2);
6453            assert_eq!(
6454                entries[0].to_markdown(cx),
6455                "## User\n\nEdited message content\n\n"
6456            );
6457            assert_eq!(
6458                entries[1].to_markdown(cx),
6459                "## Assistant\n\nNew Response\n\n"
6460            );
6461
6462            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6463                assert!(!state.entry(1).unwrap().has_content());
6464                state.entry(0).unwrap().message_editor().unwrap().clone()
6465            });
6466
6467            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6468        })
6469    }
6470
6471    #[gpui::test]
6472    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6473        init_test(cx);
6474
6475        let connection = StubAgentConnection::new();
6476
6477        let (thread_view, cx) =
6478            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6479        add_to_workspace(thread_view.clone(), cx);
6480
6481        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6482        message_editor.update_in(cx, |editor, window, cx| {
6483            editor.set_text("Original message to edit", window, cx);
6484        });
6485        thread_view.update_in(cx, |thread_view, window, cx| {
6486            thread_view.send(window, cx);
6487        });
6488
6489        cx.run_until_parked();
6490
6491        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6492            let thread = view.thread().unwrap().read(cx);
6493            assert_eq!(thread.entries().len(), 1);
6494
6495            let editor = view
6496                .entry_view_state
6497                .read(cx)
6498                .entry(0)
6499                .unwrap()
6500                .message_editor()
6501                .unwrap()
6502                .clone();
6503
6504            (editor, thread.session_id().clone())
6505        });
6506
6507        // Focus
6508        cx.focus(&user_message_editor);
6509
6510        thread_view.read_with(cx, |view, _cx| {
6511            assert_eq!(view.editing_message, Some(0));
6512        });
6513
6514        // Edit
6515        user_message_editor.update_in(cx, |editor, window, cx| {
6516            editor.set_text("Edited message content", window, cx);
6517        });
6518
6519        thread_view.read_with(cx, |view, _cx| {
6520            assert_eq!(view.editing_message, Some(0));
6521        });
6522
6523        // Finish streaming response
6524        cx.update(|_, cx| {
6525            connection.send_update(
6526                session_id.clone(),
6527                acp::SessionUpdate::AgentMessageChunk {
6528                    content: acp::ContentBlock::Text(acp::TextContent {
6529                        text: "Response".into(),
6530                        annotations: None,
6531                        meta: None,
6532                    }),
6533                },
6534                cx,
6535            );
6536            connection.end_turn(session_id, acp::StopReason::EndTurn);
6537        });
6538
6539        thread_view.read_with(cx, |view, _cx| {
6540            assert_eq!(view.editing_message, Some(0));
6541        });
6542
6543        cx.run_until_parked();
6544
6545        // Should still be editing
6546        cx.update(|window, cx| {
6547            assert!(user_message_editor.focus_handle(cx).is_focused(window));
6548            assert_eq!(thread_view.read(cx).editing_message, Some(0));
6549            assert_eq!(
6550                user_message_editor.read(cx).text(cx),
6551                "Edited message content"
6552            );
6553        });
6554    }
6555
6556    #[gpui::test]
6557    async fn test_interrupt(cx: &mut TestAppContext) {
6558        init_test(cx);
6559
6560        let connection = StubAgentConnection::new();
6561
6562        let (thread_view, cx) =
6563            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6564        add_to_workspace(thread_view.clone(), cx);
6565
6566        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6567        message_editor.update_in(cx, |editor, window, cx| {
6568            editor.set_text("Message 1", window, cx);
6569        });
6570        thread_view.update_in(cx, |thread_view, window, cx| {
6571            thread_view.send(window, cx);
6572        });
6573
6574        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6575            let thread = view.thread().unwrap();
6576
6577            (thread.clone(), thread.read(cx).session_id().clone())
6578        });
6579
6580        cx.run_until_parked();
6581
6582        cx.update(|_, cx| {
6583            connection.send_update(
6584                session_id.clone(),
6585                acp::SessionUpdate::AgentMessageChunk {
6586                    content: "Message 1 resp".into(),
6587                },
6588                cx,
6589            );
6590        });
6591
6592        cx.run_until_parked();
6593
6594        thread.read_with(cx, |thread, cx| {
6595            assert_eq!(
6596                thread.to_markdown(cx),
6597                indoc::indoc! {"
6598                    ## User
6599
6600                    Message 1
6601
6602                    ## Assistant
6603
6604                    Message 1 resp
6605
6606                "}
6607            )
6608        });
6609
6610        message_editor.update_in(cx, |editor, window, cx| {
6611            editor.set_text("Message 2", window, cx);
6612        });
6613        thread_view.update_in(cx, |thread_view, window, cx| {
6614            thread_view.send(window, cx);
6615        });
6616
6617        cx.update(|_, cx| {
6618            // Simulate a response sent after beginning to cancel
6619            connection.send_update(
6620                session_id.clone(),
6621                acp::SessionUpdate::AgentMessageChunk {
6622                    content: "onse".into(),
6623                },
6624                cx,
6625            );
6626        });
6627
6628        cx.run_until_parked();
6629
6630        // Last Message 1 response should appear before Message 2
6631        thread.read_with(cx, |thread, cx| {
6632            assert_eq!(
6633                thread.to_markdown(cx),
6634                indoc::indoc! {"
6635                    ## User
6636
6637                    Message 1
6638
6639                    ## Assistant
6640
6641                    Message 1 response
6642
6643                    ## User
6644
6645                    Message 2
6646
6647                "}
6648            )
6649        });
6650
6651        cx.update(|_, cx| {
6652            connection.send_update(
6653                session_id.clone(),
6654                acp::SessionUpdate::AgentMessageChunk {
6655                    content: "Message 2 response".into(),
6656                },
6657                cx,
6658            );
6659            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6660        });
6661
6662        cx.run_until_parked();
6663
6664        thread.read_with(cx, |thread, cx| {
6665            assert_eq!(
6666                thread.to_markdown(cx),
6667                indoc::indoc! {"
6668                    ## User
6669
6670                    Message 1
6671
6672                    ## Assistant
6673
6674                    Message 1 response
6675
6676                    ## User
6677
6678                    Message 2
6679
6680                    ## Assistant
6681
6682                    Message 2 response
6683
6684                "}
6685            )
6686        });
6687    }
6688
6689    #[gpui::test]
6690    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
6691        init_test(cx);
6692
6693        let connection = StubAgentConnection::new();
6694        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6695            content: acp::ContentBlock::Text(acp::TextContent {
6696                text: "Response".into(),
6697                annotations: None,
6698                meta: None,
6699            }),
6700        }]);
6701
6702        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6703        add_to_workspace(thread_view.clone(), cx);
6704
6705        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6706        message_editor.update_in(cx, |editor, window, cx| {
6707            editor.set_text("Original message to edit", window, cx)
6708        });
6709        thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
6710        cx.run_until_parked();
6711
6712        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
6713            thread_view
6714                .entry_view_state
6715                .read(cx)
6716                .entry(0)
6717                .expect("Should have at least one entry")
6718                .message_editor()
6719                .expect("Should have message editor")
6720                .clone()
6721        });
6722
6723        cx.focus(&user_message_editor);
6724        thread_view.read_with(cx, |thread_view, _cx| {
6725            assert_eq!(thread_view.editing_message, Some(0));
6726        });
6727
6728        // Ensure to edit the focused message before proceeding otherwise, since
6729        // its content is not different from what was sent, focus will be lost.
6730        user_message_editor.update_in(cx, |editor, window, cx| {
6731            editor.set_text("Original message to edit with ", window, cx)
6732        });
6733
6734        // Create a simple buffer with some text so we can create a selection
6735        // that will then be added to the message being edited.
6736        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
6737            (thread_view.workspace.clone(), thread_view.project.clone())
6738        });
6739        let buffer = project.update(cx, |project, cx| {
6740            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
6741        });
6742
6743        workspace
6744            .update_in(cx, |workspace, window, cx| {
6745                let editor = cx.new(|cx| {
6746                    let mut editor =
6747                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
6748
6749                    editor.change_selections(Default::default(), window, cx, |selections| {
6750                        selections.select_ranges([8..15]);
6751                    });
6752
6753                    editor
6754                });
6755                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
6756            })
6757            .unwrap();
6758
6759        thread_view.update_in(cx, |thread_view, window, cx| {
6760            assert_eq!(thread_view.editing_message, Some(0));
6761            thread_view.insert_selections(window, cx);
6762        });
6763
6764        user_message_editor.read_with(cx, |editor, cx| {
6765            let text = editor.editor().read(cx).text(cx);
6766            let expected_text = String::from("Original message to edit with selection ");
6767
6768            assert_eq!(text, expected_text);
6769        });
6770    }
6771
6772    #[gpui::test]
6773    async fn test_insert_selections(cx: &mut TestAppContext) {
6774        init_test(cx);
6775
6776        let connection = StubAgentConnection::new();
6777        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6778            content: acp::ContentBlock::Text(acp::TextContent {
6779                text: "Response".into(),
6780                annotations: None,
6781                meta: None,
6782            }),
6783        }]);
6784
6785        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6786        add_to_workspace(thread_view.clone(), cx);
6787
6788        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6789        message_editor.update_in(cx, |editor, window, cx| {
6790            editor.set_text("Can you review this snippet ", window, cx)
6791        });
6792
6793        // Create a simple buffer with some text so we can create a selection
6794        // that will then be added to the message being edited.
6795        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
6796            (thread_view.workspace.clone(), thread_view.project.clone())
6797        });
6798        let buffer = project.update(cx, |project, cx| {
6799            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
6800        });
6801
6802        workspace
6803            .update_in(cx, |workspace, window, cx| {
6804                let editor = cx.new(|cx| {
6805                    let mut editor =
6806                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
6807
6808                    editor.change_selections(Default::default(), window, cx, |selections| {
6809                        selections.select_ranges([8..15]);
6810                    });
6811
6812                    editor
6813                });
6814                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
6815            })
6816            .unwrap();
6817
6818        thread_view.update_in(cx, |thread_view, window, cx| {
6819            assert_eq!(thread_view.editing_message, None);
6820            thread_view.insert_selections(window, cx);
6821        });
6822
6823        thread_view.read_with(cx, |thread_view, cx| {
6824            let text = thread_view.message_editor.read(cx).text(cx);
6825            let expected_txt = String::from("Can you review this snippet selection ");
6826
6827            assert_eq!(text, expected_txt);
6828        })
6829    }
6830}