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