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