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