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_max_range_for_buffer(
4083                                                            buffer.read(cx).remote_id(),
4084                                                        )],
4085                                                        Some(telemetry.clone()),
4086                                                        cx,
4087                                                    )
4088                                                    .detach_and_log_err(cx);
4089                                            })
4090                                        }
4091                                    }),
4092                            )
4093                            .child(
4094                                Button::new("keep-file", "Keep")
4095                                    .label_size(LabelSize::Small)
4096                                    .disabled(pending_edits)
4097                                    .on_click({
4098                                        let buffer = buffer.clone();
4099                                        let action_log = action_log.clone();
4100                                        let telemetry = telemetry.clone();
4101                                        move |_, _, cx| {
4102                                            action_log.update(cx, |action_log, cx| {
4103                                                action_log.keep_edits_in_range(
4104                                                    buffer.clone(),
4105                                                    Anchor::min_max_range_for_buffer(
4106                                                        buffer.read(cx).remote_id(),
4107                                                    ),
4108                                                    Some(telemetry.clone()),
4109                                                    cx,
4110                                                );
4111                                            })
4112                                        }
4113                                    }),
4114                            ),
4115                    );
4116
4117                Some(element)
4118            },
4119        ))
4120    }
4121
4122    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
4123        let focus_handle = self.message_editor.focus_handle(cx);
4124        let editor_bg_color = cx.theme().colors().editor_background;
4125        let (expand_icon, expand_tooltip) = if self.editor_expanded {
4126            (IconName::Minimize, "Minimize Message Editor")
4127        } else {
4128            (IconName::Maximize, "Expand Message Editor")
4129        };
4130
4131        let backdrop = div()
4132            .size_full()
4133            .absolute()
4134            .inset_0()
4135            .bg(cx.theme().colors().panel_background)
4136            .opacity(0.8)
4137            .block_mouse_except_scroll();
4138
4139        let enable_editor = match self.thread_state {
4140            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
4141            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
4142        };
4143
4144        v_flex()
4145            .on_action(cx.listener(Self::expand_message_editor))
4146            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
4147                if let Some(profile_selector) = this.profile_selector.as_ref() {
4148                    profile_selector.read(cx).menu_handle().toggle(window, cx);
4149                } else if let Some(mode_selector) = this.mode_selector() {
4150                    mode_selector.read(cx).menu_handle().toggle(window, cx);
4151                }
4152            }))
4153            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
4154                if let Some(mode_selector) = this.mode_selector() {
4155                    mode_selector.update(cx, |mode_selector, cx| {
4156                        mode_selector.cycle_mode(window, cx);
4157                    });
4158                }
4159            }))
4160            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
4161                if let Some(model_selector) = this.model_selector.as_ref() {
4162                    model_selector
4163                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
4164                }
4165            }))
4166            .p_2()
4167            .gap_2()
4168            .border_t_1()
4169            .border_color(cx.theme().colors().border)
4170            .bg(editor_bg_color)
4171            .when(self.editor_expanded, |this| {
4172                this.h(vh(0.8, window)).size_full().justify_between()
4173            })
4174            .child(
4175                v_flex()
4176                    .relative()
4177                    .size_full()
4178                    .pt_1()
4179                    .pr_2p5()
4180                    .child(self.message_editor.clone())
4181                    .child(
4182                        h_flex()
4183                            .absolute()
4184                            .top_0()
4185                            .right_0()
4186                            .opacity(0.5)
4187                            .hover(|this| this.opacity(1.0))
4188                            .child(
4189                                IconButton::new("toggle-height", expand_icon)
4190                                    .icon_size(IconSize::Small)
4191                                    .icon_color(Color::Muted)
4192                                    .tooltip({
4193                                        move |_window, cx| {
4194                                            Tooltip::for_action_in(
4195                                                expand_tooltip,
4196                                                &ExpandMessageEditor,
4197                                                &focus_handle,
4198                                                cx,
4199                                            )
4200                                        }
4201                                    })
4202                                    .on_click(cx.listener(|this, _, window, cx| {
4203                                        this.expand_message_editor(
4204                                            &ExpandMessageEditor,
4205                                            window,
4206                                            cx,
4207                                        );
4208                                    })),
4209                            ),
4210                    ),
4211            )
4212            .child(
4213                h_flex()
4214                    .flex_none()
4215                    .flex_wrap()
4216                    .justify_between()
4217                    .child(
4218                        h_flex()
4219                            .gap_0p5()
4220                            .child(self.render_add_context_button(cx))
4221                            .child(self.render_follow_toggle(cx))
4222                            .children(self.render_burn_mode_toggle(cx)),
4223                    )
4224                    .child(
4225                        h_flex()
4226                            .gap_1()
4227                            .children(self.render_token_usage(cx))
4228                            .children(self.profile_selector.clone())
4229                            .children(self.mode_selector().cloned())
4230                            .children(self.model_selector.clone())
4231                            .child(self.render_send_button(cx)),
4232                    ),
4233            )
4234            .when(!enable_editor, |this| this.child(backdrop))
4235            .into_any()
4236    }
4237
4238    pub(crate) fn as_native_connection(
4239        &self,
4240        cx: &App,
4241    ) -> Option<Rc<agent::NativeAgentConnection>> {
4242        let acp_thread = self.thread()?.read(cx);
4243        acp_thread.connection().clone().downcast()
4244    }
4245
4246    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4247        let acp_thread = self.thread()?.read(cx);
4248        self.as_native_connection(cx)?
4249            .thread(acp_thread.session_id(), cx)
4250    }
4251
4252    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4253        self.as_native_thread(cx)
4254            .and_then(|thread| thread.read(cx).model())
4255            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4256    }
4257
4258    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4259        let thread = self.thread()?.read(cx);
4260        let usage = thread.token_usage()?;
4261        let is_generating = thread.status() != ThreadStatus::Idle;
4262
4263        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4264        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4265
4266        Some(
4267            h_flex()
4268                .flex_shrink_0()
4269                .gap_0p5()
4270                .mr_1p5()
4271                .child(
4272                    Label::new(used)
4273                        .size(LabelSize::Small)
4274                        .color(Color::Muted)
4275                        .map(|label| {
4276                            if is_generating {
4277                                label
4278                                    .with_animation(
4279                                        "used-tokens-label",
4280                                        Animation::new(Duration::from_secs(2))
4281                                            .repeat()
4282                                            .with_easing(pulsating_between(0.3, 0.8)),
4283                                        |label, delta| label.alpha(delta),
4284                                    )
4285                                    .into_any()
4286                            } else {
4287                                label.into_any_element()
4288                            }
4289                        }),
4290                )
4291                .child(
4292                    Label::new("/")
4293                        .size(LabelSize::Small)
4294                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4295                )
4296                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4297        )
4298    }
4299
4300    fn toggle_burn_mode(
4301        &mut self,
4302        _: &ToggleBurnMode,
4303        _window: &mut Window,
4304        cx: &mut Context<Self>,
4305    ) {
4306        let Some(thread) = self.as_native_thread(cx) else {
4307            return;
4308        };
4309
4310        thread.update(cx, |thread, cx| {
4311            let current_mode = thread.completion_mode();
4312            thread.set_completion_mode(
4313                match current_mode {
4314                    CompletionMode::Burn => CompletionMode::Normal,
4315                    CompletionMode::Normal => CompletionMode::Burn,
4316                },
4317                cx,
4318            );
4319        });
4320    }
4321
4322    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4323        let Some(thread) = self.thread() else {
4324            return;
4325        };
4326        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4327        let action_log = thread.read(cx).action_log().clone();
4328        action_log.update(cx, |action_log, cx| {
4329            action_log.keep_all_edits(Some(telemetry), cx)
4330        });
4331    }
4332
4333    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4334        let Some(thread) = self.thread() else {
4335            return;
4336        };
4337        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4338        let action_log = thread.read(cx).action_log().clone();
4339        action_log
4340            .update(cx, |action_log, cx| {
4341                action_log.reject_all_edits(Some(telemetry), cx)
4342            })
4343            .detach();
4344    }
4345
4346    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4347        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4348    }
4349
4350    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4351        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4352    }
4353
4354    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4355        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4356    }
4357
4358    fn authorize_pending_tool_call(
4359        &mut self,
4360        kind: acp::PermissionOptionKind,
4361        window: &mut Window,
4362        cx: &mut Context<Self>,
4363    ) -> Option<()> {
4364        let thread = self.thread()?.read(cx);
4365        let tool_call = thread.first_tool_awaiting_confirmation()?;
4366        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4367            return None;
4368        };
4369        let option = options.iter().find(|o| o.kind == kind)?;
4370
4371        self.authorize_tool_call(
4372            tool_call.id.clone(),
4373            option.id.clone(),
4374            option.kind,
4375            window,
4376            cx,
4377        );
4378
4379        Some(())
4380    }
4381
4382    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4383        let thread = self.as_native_thread(cx)?.read(cx);
4384
4385        if thread
4386            .model()
4387            .is_none_or(|model| !model.supports_burn_mode())
4388        {
4389            return None;
4390        }
4391
4392        let active_completion_mode = thread.completion_mode();
4393        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4394        let icon = if burn_mode_enabled {
4395            IconName::ZedBurnModeOn
4396        } else {
4397            IconName::ZedBurnMode
4398        };
4399
4400        Some(
4401            IconButton::new("burn-mode", icon)
4402                .icon_size(IconSize::Small)
4403                .icon_color(Color::Muted)
4404                .toggle_state(burn_mode_enabled)
4405                .selected_icon_color(Color::Error)
4406                .on_click(cx.listener(|this, _event, window, cx| {
4407                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4408                }))
4409                .tooltip(move |_window, cx| {
4410                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4411                        .into()
4412                })
4413                .into_any_element(),
4414        )
4415    }
4416
4417    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4418        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4419        let is_generating = self
4420            .thread()
4421            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4422
4423        if self.is_loading_contents {
4424            div()
4425                .id("loading-message-content")
4426                .px_1()
4427                .tooltip(Tooltip::text("Loading Added Context…"))
4428                .child(loading_contents_spinner(IconSize::default()))
4429                .into_any_element()
4430        } else if is_generating && is_editor_empty {
4431            IconButton::new("stop-generation", IconName::Stop)
4432                .icon_color(Color::Error)
4433                .style(ButtonStyle::Tinted(ui::TintColor::Error))
4434                .tooltip(move |_window, cx| {
4435                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
4436                })
4437                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4438                .into_any_element()
4439        } else {
4440            let send_btn_tooltip = if is_editor_empty && !is_generating {
4441                "Type to Send"
4442            } else if is_generating {
4443                "Stop and Send Message"
4444            } else {
4445                "Send"
4446            };
4447
4448            IconButton::new("send-message", IconName::Send)
4449                .style(ButtonStyle::Filled)
4450                .map(|this| {
4451                    if is_editor_empty && !is_generating {
4452                        this.disabled(true).icon_color(Color::Muted)
4453                    } else {
4454                        this.icon_color(Color::Accent)
4455                    }
4456                })
4457                .tooltip(move |_window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, cx))
4458                .on_click(cx.listener(|this, _, window, cx| {
4459                    this.send(window, cx);
4460                }))
4461                .into_any_element()
4462        }
4463    }
4464
4465    fn is_following(&self, cx: &App) -> bool {
4466        match self.thread().map(|thread| thread.read(cx).status()) {
4467            Some(ThreadStatus::Generating) => self
4468                .workspace
4469                .read_with(cx, |workspace, _| {
4470                    workspace.is_being_followed(CollaboratorId::Agent)
4471                })
4472                .unwrap_or(false),
4473            _ => self.should_be_following,
4474        }
4475    }
4476
4477    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4478        let following = self.is_following(cx);
4479
4480        self.should_be_following = !following;
4481        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4482            self.workspace
4483                .update(cx, |workspace, cx| {
4484                    if following {
4485                        workspace.unfollow(CollaboratorId::Agent, window, cx);
4486                    } else {
4487                        workspace.follow(CollaboratorId::Agent, window, cx);
4488                    }
4489                })
4490                .ok();
4491        }
4492
4493        telemetry::event!("Follow Agent Selected", following = !following);
4494    }
4495
4496    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4497        let following = self.is_following(cx);
4498
4499        let tooltip_label = if following {
4500            if self.agent.name() == "Zed Agent" {
4501                format!("Stop Following the {}", self.agent.name())
4502            } else {
4503                format!("Stop Following {}", self.agent.name())
4504            }
4505        } else {
4506            if self.agent.name() == "Zed Agent" {
4507                format!("Follow the {}", self.agent.name())
4508            } else {
4509                format!("Follow {}", self.agent.name())
4510            }
4511        };
4512
4513        IconButton::new("follow-agent", IconName::Crosshair)
4514            .icon_size(IconSize::Small)
4515            .icon_color(Color::Muted)
4516            .toggle_state(following)
4517            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4518            .tooltip(move |_window, cx| {
4519                if following {
4520                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4521                } else {
4522                    Tooltip::with_meta(
4523                        tooltip_label.clone(),
4524                        Some(&Follow),
4525                        "Track the agent's location as it reads and edits files.",
4526                        cx,
4527                    )
4528                }
4529            })
4530            .on_click(cx.listener(move |this, _, window, cx| {
4531                this.toggle_following(window, cx);
4532            }))
4533    }
4534
4535    fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4536        let message_editor = self.message_editor.clone();
4537        let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
4538
4539        IconButton::new("add-context", IconName::AtSign)
4540            .icon_size(IconSize::Small)
4541            .icon_color(Color::Muted)
4542            .when(!menu_visible, |this| {
4543                this.tooltip(move |_window, cx| {
4544                    Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
4545                })
4546            })
4547            .on_click(cx.listener(move |_this, _, window, cx| {
4548                let message_editor_clone = message_editor.clone();
4549
4550                window.defer(cx, move |window, cx| {
4551                    message_editor_clone.update(cx, |message_editor, cx| {
4552                        message_editor.trigger_completion_menu(window, cx);
4553                    });
4554                });
4555            }))
4556    }
4557
4558    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4559        let workspace = self.workspace.clone();
4560        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4561            Self::open_link(text, &workspace, window, cx);
4562        })
4563    }
4564
4565    fn open_link(
4566        url: SharedString,
4567        workspace: &WeakEntity<Workspace>,
4568        window: &mut Window,
4569        cx: &mut App,
4570    ) {
4571        let Some(workspace) = workspace.upgrade() else {
4572            cx.open_url(&url);
4573            return;
4574        };
4575
4576        if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
4577        {
4578            workspace.update(cx, |workspace, cx| match mention {
4579                MentionUri::File { abs_path } => {
4580                    let project = workspace.project();
4581                    let Some(path) =
4582                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4583                    else {
4584                        return;
4585                    };
4586
4587                    workspace
4588                        .open_path(path, None, true, window, cx)
4589                        .detach_and_log_err(cx);
4590                }
4591                MentionUri::PastedImage => {}
4592                MentionUri::Directory { abs_path } => {
4593                    let project = workspace.project();
4594                    let Some(entry_id) = project.update(cx, |project, cx| {
4595                        let path = project.find_project_path(abs_path, cx)?;
4596                        project.entry_for_path(&path, cx).map(|entry| entry.id)
4597                    }) else {
4598                        return;
4599                    };
4600
4601                    project.update(cx, |_, cx| {
4602                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
4603                    });
4604                }
4605                MentionUri::Symbol {
4606                    abs_path: path,
4607                    line_range,
4608                    ..
4609                }
4610                | MentionUri::Selection {
4611                    abs_path: Some(path),
4612                    line_range,
4613                } => {
4614                    let project = workspace.project();
4615                    let Some(path) =
4616                        project.update(cx, |project, cx| project.find_project_path(path, cx))
4617                    else {
4618                        return;
4619                    };
4620
4621                    let item = workspace.open_path(path, None, true, window, cx);
4622                    window
4623                        .spawn(cx, async move |cx| {
4624                            let Some(editor) = item.await?.downcast::<Editor>() else {
4625                                return Ok(());
4626                            };
4627                            let range = Point::new(*line_range.start(), 0)
4628                                ..Point::new(*line_range.start(), 0);
4629                            editor
4630                                .update_in(cx, |editor, window, cx| {
4631                                    editor.change_selections(
4632                                        SelectionEffects::scroll(Autoscroll::center()),
4633                                        window,
4634                                        cx,
4635                                        |s| s.select_ranges(vec![range]),
4636                                    );
4637                                })
4638                                .ok();
4639                            anyhow::Ok(())
4640                        })
4641                        .detach_and_log_err(cx);
4642                }
4643                MentionUri::Selection { abs_path: None, .. } => {}
4644                MentionUri::Thread { id, name } => {
4645                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4646                        panel.update(cx, |panel, cx| {
4647                            panel.load_agent_thread(
4648                                DbThreadMetadata {
4649                                    id,
4650                                    title: name.into(),
4651                                    updated_at: Default::default(),
4652                                },
4653                                window,
4654                                cx,
4655                            )
4656                        });
4657                    }
4658                }
4659                MentionUri::TextThread { path, .. } => {
4660                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4661                        panel.update(cx, |panel, cx| {
4662                            panel
4663                                .open_saved_text_thread(path.as_path().into(), window, cx)
4664                                .detach_and_log_err(cx);
4665                        });
4666                    }
4667                }
4668                MentionUri::Rule { id, .. } => {
4669                    let PromptId::User { uuid } = id else {
4670                        return;
4671                    };
4672                    window.dispatch_action(
4673                        Box::new(OpenRulesLibrary {
4674                            prompt_to_select: Some(uuid.0),
4675                        }),
4676                        cx,
4677                    )
4678                }
4679                MentionUri::Fetch { url } => {
4680                    cx.open_url(url.as_str());
4681                }
4682            })
4683        } else {
4684            cx.open_url(&url);
4685        }
4686    }
4687
4688    fn open_tool_call_location(
4689        &self,
4690        entry_ix: usize,
4691        location_ix: usize,
4692        window: &mut Window,
4693        cx: &mut Context<Self>,
4694    ) -> Option<()> {
4695        let (tool_call_location, agent_location) = self
4696            .thread()?
4697            .read(cx)
4698            .entries()
4699            .get(entry_ix)?
4700            .location(location_ix)?;
4701
4702        let project_path = self
4703            .project
4704            .read(cx)
4705            .find_project_path(&tool_call_location.path, cx)?;
4706
4707        let open_task = self
4708            .workspace
4709            .update(cx, |workspace, cx| {
4710                workspace.open_path(project_path, None, true, window, cx)
4711            })
4712            .log_err()?;
4713        window
4714            .spawn(cx, async move |cx| {
4715                let item = open_task.await?;
4716
4717                let Some(active_editor) = item.downcast::<Editor>() else {
4718                    return anyhow::Ok(());
4719                };
4720
4721                active_editor.update_in(cx, |editor, window, cx| {
4722                    let multibuffer = editor.buffer().read(cx);
4723                    let buffer = multibuffer.as_singleton();
4724                    if agent_location.buffer.upgrade() == buffer {
4725                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4726                        let anchor =
4727                            editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
4728                        editor.change_selections(Default::default(), window, cx, |selections| {
4729                            selections.select_anchor_ranges([anchor..anchor]);
4730                        })
4731                    } else {
4732                        let row = tool_call_location.line.unwrap_or_default();
4733                        editor.change_selections(Default::default(), window, cx, |selections| {
4734                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4735                        })
4736                    }
4737                })?;
4738
4739                anyhow::Ok(())
4740            })
4741            .detach_and_log_err(cx);
4742
4743        None
4744    }
4745
4746    pub fn open_thread_as_markdown(
4747        &self,
4748        workspace: Entity<Workspace>,
4749        window: &mut Window,
4750        cx: &mut App,
4751    ) -> Task<Result<()>> {
4752        let markdown_language_task = workspace
4753            .read(cx)
4754            .app_state()
4755            .languages
4756            .language_for_name("Markdown");
4757
4758        let (thread_title, markdown) = if let Some(thread) = self.thread() {
4759            let thread = thread.read(cx);
4760            (thread.title().to_string(), thread.to_markdown(cx))
4761        } else {
4762            return Task::ready(Ok(()));
4763        };
4764
4765        let project = workspace.read(cx).project().clone();
4766        window.spawn(cx, async move |cx| {
4767            let markdown_language = markdown_language_task.await?;
4768
4769            let buffer = project
4770                .update(cx, |project, cx| project.create_buffer(false, cx))?
4771                .await?;
4772
4773            buffer.update(cx, |buffer, cx| {
4774                buffer.set_text(markdown, cx);
4775                buffer.set_language(Some(markdown_language), cx);
4776                buffer.set_capability(language::Capability::ReadOnly, cx);
4777            })?;
4778
4779            workspace.update_in(cx, |workspace, window, cx| {
4780                let buffer = cx
4781                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4782
4783                workspace.add_item_to_active_pane(
4784                    Box::new(cx.new(|cx| {
4785                        let mut editor =
4786                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4787                        editor.set_breadcrumb_header(thread_title);
4788                        editor
4789                    })),
4790                    None,
4791                    true,
4792                    window,
4793                    cx,
4794                );
4795            })?;
4796            anyhow::Ok(())
4797        })
4798    }
4799
4800    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4801        self.list_state.scroll_to(ListOffset::default());
4802        cx.notify();
4803    }
4804
4805    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4806        if let Some(thread) = self.thread() {
4807            let entry_count = thread.read(cx).entries().len();
4808            self.list_state.reset(entry_count);
4809            cx.notify();
4810        }
4811    }
4812
4813    fn notify_with_sound(
4814        &mut self,
4815        caption: impl Into<SharedString>,
4816        icon: IconName,
4817        window: &mut Window,
4818        cx: &mut Context<Self>,
4819    ) {
4820        self.play_notification_sound(window, cx);
4821        self.show_notification(caption, icon, window, cx);
4822    }
4823
4824    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4825        let settings = AgentSettings::get_global(cx);
4826        if settings.play_sound_when_agent_done && !window.is_window_active() {
4827            Audio::play_sound(Sound::AgentDone, cx);
4828        }
4829    }
4830
4831    fn show_notification(
4832        &mut self,
4833        caption: impl Into<SharedString>,
4834        icon: IconName,
4835        window: &mut Window,
4836        cx: &mut Context<Self>,
4837    ) {
4838        if !self.notifications.is_empty() {
4839            return;
4840        }
4841
4842        let settings = AgentSettings::get_global(cx);
4843
4844        let window_is_inactive = !window.is_window_active();
4845        let panel_is_hidden = self
4846            .workspace
4847            .upgrade()
4848            .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
4849            .unwrap_or(true);
4850
4851        let should_notify = window_is_inactive || panel_is_hidden;
4852
4853        if !should_notify {
4854            return;
4855        }
4856
4857        // TODO: Change this once we have title summarization for external agents.
4858        let title = self.agent.name();
4859
4860        match settings.notify_when_agent_waiting {
4861            NotifyWhenAgentWaiting::PrimaryScreen => {
4862                if let Some(primary) = cx.primary_display() {
4863                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4864                }
4865            }
4866            NotifyWhenAgentWaiting::AllScreens => {
4867                let caption = caption.into();
4868                for screen in cx.displays() {
4869                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4870                }
4871            }
4872            NotifyWhenAgentWaiting::Never => {
4873                // Don't show anything
4874            }
4875        }
4876    }
4877
4878    fn pop_up(
4879        &mut self,
4880        icon: IconName,
4881        caption: SharedString,
4882        title: SharedString,
4883        window: &mut Window,
4884        screen: Rc<dyn PlatformDisplay>,
4885        cx: &mut Context<Self>,
4886    ) {
4887        let options = AgentNotification::window_options(screen, cx);
4888
4889        let project_name = self.workspace.upgrade().and_then(|workspace| {
4890            workspace
4891                .read(cx)
4892                .project()
4893                .read(cx)
4894                .visible_worktrees(cx)
4895                .next()
4896                .map(|worktree| worktree.read(cx).root_name_str().to_string())
4897        });
4898
4899        if let Some(screen_window) = cx
4900            .open_window(options, |_, cx| {
4901                cx.new(|_| {
4902                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4903                })
4904            })
4905            .log_err()
4906            && let Some(pop_up) = screen_window.entity(cx).log_err()
4907        {
4908            self.notification_subscriptions
4909                .entry(screen_window)
4910                .or_insert_with(Vec::new)
4911                .push(cx.subscribe_in(&pop_up, window, {
4912                    |this, _, event, window, cx| match event {
4913                        AgentNotificationEvent::Accepted => {
4914                            let handle = window.window_handle();
4915                            cx.activate(true);
4916
4917                            let workspace_handle = this.workspace.clone();
4918
4919                            // If there are multiple Zed windows, activate the correct one.
4920                            cx.defer(move |cx| {
4921                                handle
4922                                    .update(cx, |_view, window, _cx| {
4923                                        window.activate_window();
4924
4925                                        if let Some(workspace) = workspace_handle.upgrade() {
4926                                            workspace.update(_cx, |workspace, cx| {
4927                                                workspace.focus_panel::<AgentPanel>(window, cx);
4928                                            });
4929                                        }
4930                                    })
4931                                    .log_err();
4932                            });
4933
4934                            this.dismiss_notifications(cx);
4935                        }
4936                        AgentNotificationEvent::Dismissed => {
4937                            this.dismiss_notifications(cx);
4938                        }
4939                    }
4940                }));
4941
4942            self.notifications.push(screen_window);
4943
4944            // If the user manually refocuses the original window, dismiss the popup.
4945            self.notification_subscriptions
4946                .entry(screen_window)
4947                .or_insert_with(Vec::new)
4948                .push({
4949                    let pop_up_weak = pop_up.downgrade();
4950
4951                    cx.observe_window_activation(window, move |_, window, cx| {
4952                        if window.is_window_active()
4953                            && let Some(pop_up) = pop_up_weak.upgrade()
4954                        {
4955                            pop_up.update(cx, |_, cx| {
4956                                cx.emit(AgentNotificationEvent::Dismissed);
4957                            });
4958                        }
4959                    })
4960                });
4961        }
4962    }
4963
4964    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4965        for window in self.notifications.drain(..) {
4966            window
4967                .update(cx, |_, window, _| {
4968                    window.remove_window();
4969                })
4970                .ok();
4971
4972            self.notification_subscriptions.remove(&window);
4973        }
4974    }
4975
4976    fn render_generating(&self, confirmation: bool) -> impl IntoElement {
4977        h_flex()
4978            .id("generating-spinner")
4979            .py_2()
4980            .px(rems_from_px(22.))
4981            .map(|this| {
4982                if confirmation {
4983                    this.gap_2()
4984                        .child(
4985                            h_flex()
4986                                .w_2()
4987                                .child(SpinnerLabel::sand().size(LabelSize::Small)),
4988                        )
4989                        .child(
4990                            LoadingLabel::new("Waiting Confirmation")
4991                                .size(LabelSize::Small)
4992                                .color(Color::Muted),
4993                        )
4994                } else {
4995                    this.child(SpinnerLabel::new().size(LabelSize::Small))
4996                }
4997            })
4998            .into_any_element()
4999    }
5000
5001    fn render_thread_controls(
5002        &self,
5003        thread: &Entity<AcpThread>,
5004        cx: &Context<Self>,
5005    ) -> impl IntoElement {
5006        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
5007        if is_generating {
5008            return self.render_generating(false).into_any_element();
5009        }
5010
5011        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
5012            .shape(ui::IconButtonShape::Square)
5013            .icon_size(IconSize::Small)
5014            .icon_color(Color::Ignored)
5015            .tooltip(Tooltip::text("Open Thread as Markdown"))
5016            .on_click(cx.listener(move |this, _, window, cx| {
5017                if let Some(workspace) = this.workspace.upgrade() {
5018                    this.open_thread_as_markdown(workspace, window, cx)
5019                        .detach_and_log_err(cx);
5020                }
5021            }));
5022
5023        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
5024            .shape(ui::IconButtonShape::Square)
5025            .icon_size(IconSize::Small)
5026            .icon_color(Color::Ignored)
5027            .tooltip(Tooltip::text("Scroll To Top"))
5028            .on_click(cx.listener(move |this, _, _, cx| {
5029                this.scroll_to_top(cx);
5030            }));
5031
5032        let mut container = h_flex()
5033            .id("thread-controls-container")
5034            .group("thread-controls-container")
5035            .w_full()
5036            .py_2()
5037            .px_5()
5038            .gap_px()
5039            .opacity(0.6)
5040            .hover(|style| style.opacity(1.))
5041            .flex_wrap()
5042            .justify_end();
5043
5044        if AgentSettings::get_global(cx).enable_feedback
5045            && self
5046                .thread()
5047                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5048        {
5049            let feedback = self.thread_feedback.feedback;
5050
5051            container = container
5052                .child(
5053                    div().visible_on_hover("thread-controls-container").child(
5054                        Label::new(match feedback {
5055                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
5056                            Some(ThreadFeedback::Negative) => {
5057                                "We appreciate your feedback and will use it to improve."
5058                            }
5059                            None => {
5060                                "Rating the thread sends all of your current conversation to the Zed team."
5061                            }
5062                        })
5063                        .color(Color::Muted)
5064                        .size(LabelSize::XSmall)
5065                        .truncate(),
5066                    ),
5067                )
5068                .child(
5069                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5070                        .shape(ui::IconButtonShape::Square)
5071                        .icon_size(IconSize::Small)
5072                        .icon_color(match feedback {
5073                            Some(ThreadFeedback::Positive) => Color::Accent,
5074                            _ => Color::Ignored,
5075                        })
5076                        .tooltip(Tooltip::text("Helpful Response"))
5077                        .on_click(cx.listener(move |this, _, window, cx| {
5078                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5079                        })),
5080                )
5081                .child(
5082                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5083                        .shape(ui::IconButtonShape::Square)
5084                        .icon_size(IconSize::Small)
5085                        .icon_color(match feedback {
5086                            Some(ThreadFeedback::Negative) => Color::Accent,
5087                            _ => Color::Ignored,
5088                        })
5089                        .tooltip(Tooltip::text("Not Helpful"))
5090                        .on_click(cx.listener(move |this, _, window, cx| {
5091                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5092                        })),
5093                );
5094        }
5095
5096        container
5097            .child(open_as_markdown)
5098            .child(scroll_to_top)
5099            .into_any_element()
5100    }
5101
5102    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5103        h_flex()
5104            .key_context("AgentFeedbackMessageEditor")
5105            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5106                this.thread_feedback.dismiss_comments();
5107                cx.notify();
5108            }))
5109            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5110                this.submit_feedback_message(cx);
5111            }))
5112            .p_2()
5113            .mb_2()
5114            .mx_5()
5115            .gap_1()
5116            .rounded_md()
5117            .border_1()
5118            .border_color(cx.theme().colors().border)
5119            .bg(cx.theme().colors().editor_background)
5120            .child(div().w_full().child(editor))
5121            .child(
5122                h_flex()
5123                    .child(
5124                        IconButton::new("dismiss-feedback-message", IconName::Close)
5125                            .icon_color(Color::Error)
5126                            .icon_size(IconSize::XSmall)
5127                            .shape(ui::IconButtonShape::Square)
5128                            .on_click(cx.listener(move |this, _, _window, cx| {
5129                                this.thread_feedback.dismiss_comments();
5130                                cx.notify();
5131                            })),
5132                    )
5133                    .child(
5134                        IconButton::new("submit-feedback-message", IconName::Return)
5135                            .icon_size(IconSize::XSmall)
5136                            .shape(ui::IconButtonShape::Square)
5137                            .on_click(cx.listener(move |this, _, _window, cx| {
5138                                this.submit_feedback_message(cx);
5139                            })),
5140                    ),
5141            )
5142    }
5143
5144    fn handle_feedback_click(
5145        &mut self,
5146        feedback: ThreadFeedback,
5147        window: &mut Window,
5148        cx: &mut Context<Self>,
5149    ) {
5150        let Some(thread) = self.thread().cloned() else {
5151            return;
5152        };
5153
5154        self.thread_feedback.submit(thread, feedback, window, cx);
5155        cx.notify();
5156    }
5157
5158    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5159        let Some(thread) = self.thread().cloned() else {
5160            return;
5161        };
5162
5163        self.thread_feedback.submit_comments(thread, cx);
5164        cx.notify();
5165    }
5166
5167    fn render_token_limit_callout(
5168        &self,
5169        line_height: Pixels,
5170        cx: &mut Context<Self>,
5171    ) -> Option<Callout> {
5172        let token_usage = self.thread()?.read(cx).token_usage()?;
5173        let ratio = token_usage.ratio();
5174
5175        let (severity, title) = match ratio {
5176            acp_thread::TokenUsageRatio::Normal => return None,
5177            acp_thread::TokenUsageRatio::Warning => {
5178                (Severity::Warning, "Thread reaching the token limit soon")
5179            }
5180            acp_thread::TokenUsageRatio::Exceeded => {
5181                (Severity::Error, "Thread reached the token limit")
5182            }
5183        };
5184
5185        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5186            thread.read(cx).completion_mode() == CompletionMode::Normal
5187                && thread
5188                    .read(cx)
5189                    .model()
5190                    .is_some_and(|model| model.supports_burn_mode())
5191        });
5192
5193        let description = if burn_mode_available {
5194            "To continue, start a new thread from a summary or turn Burn Mode on."
5195        } else {
5196            "To continue, start a new thread from a summary."
5197        };
5198
5199        Some(
5200            Callout::new()
5201                .severity(severity)
5202                .line_height(line_height)
5203                .title(title)
5204                .description(description)
5205                .actions_slot(
5206                    h_flex()
5207                        .gap_0p5()
5208                        .child(
5209                            Button::new("start-new-thread", "Start New Thread")
5210                                .label_size(LabelSize::Small)
5211                                .on_click(cx.listener(|this, _, window, cx| {
5212                                    let Some(thread) = this.thread() else {
5213                                        return;
5214                                    };
5215                                    let session_id = thread.read(cx).session_id().clone();
5216                                    window.dispatch_action(
5217                                        crate::NewNativeAgentThreadFromSummary {
5218                                            from_session_id: session_id,
5219                                        }
5220                                        .boxed_clone(),
5221                                        cx,
5222                                    );
5223                                })),
5224                        )
5225                        .when(burn_mode_available, |this| {
5226                            this.child(
5227                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5228                                    .icon_size(IconSize::XSmall)
5229                                    .on_click(cx.listener(|this, _event, window, cx| {
5230                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5231                                    })),
5232                            )
5233                        }),
5234                ),
5235        )
5236    }
5237
5238    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5239        if !self.is_using_zed_ai_models(cx) {
5240            return None;
5241        }
5242
5243        let user_store = self.project.read(cx).user_store().read(cx);
5244        if user_store.is_usage_based_billing_enabled() {
5245            return None;
5246        }
5247
5248        let plan = user_store
5249            .plan()
5250            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5251
5252        let usage = user_store.model_request_usage()?;
5253
5254        Some(
5255            div()
5256                .child(UsageCallout::new(plan, usage))
5257                .line_height(line_height),
5258        )
5259    }
5260
5261    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5262        self.entry_view_state.update(cx, |entry_view_state, cx| {
5263            entry_view_state.agent_ui_font_size_changed(cx);
5264        });
5265    }
5266
5267    pub(crate) fn insert_dragged_files(
5268        &self,
5269        paths: Vec<project::ProjectPath>,
5270        added_worktrees: Vec<Entity<project::Worktree>>,
5271        window: &mut Window,
5272        cx: &mut Context<Self>,
5273    ) {
5274        self.message_editor.update(cx, |message_editor, cx| {
5275            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5276        })
5277    }
5278
5279    /// Inserts the selected text into the message editor or the message being
5280    /// edited, if any.
5281    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5282        self.active_editor(cx).update(cx, |editor, cx| {
5283            editor.insert_selections(window, cx);
5284        });
5285    }
5286
5287    fn render_thread_retry_status_callout(
5288        &self,
5289        _window: &mut Window,
5290        _cx: &mut Context<Self>,
5291    ) -> Option<Callout> {
5292        let state = self.thread_retry_status.as_ref()?;
5293
5294        let next_attempt_in = state
5295            .duration
5296            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5297        if next_attempt_in.is_zero() {
5298            return None;
5299        }
5300
5301        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5302
5303        let retry_message = if state.max_attempts == 1 {
5304            if next_attempt_in_secs == 1 {
5305                "Retrying. Next attempt in 1 second.".to_string()
5306            } else {
5307                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5308            }
5309        } else if next_attempt_in_secs == 1 {
5310            format!(
5311                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5312                state.attempt, state.max_attempts,
5313            )
5314        } else {
5315            format!(
5316                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5317                state.attempt, state.max_attempts,
5318            )
5319        };
5320
5321        Some(
5322            Callout::new()
5323                .severity(Severity::Warning)
5324                .title(state.last_error.clone())
5325                .description(retry_message),
5326        )
5327    }
5328
5329    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5330        if self.show_codex_windows_warning {
5331            Some(
5332                Callout::new()
5333                    .icon(IconName::Warning)
5334                    .severity(Severity::Warning)
5335                    .title("Codex on Windows")
5336                    .description(
5337                        "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5338                    )
5339                    .actions_slot(
5340                        Button::new("open-wsl-modal", "Open in WSL")
5341                            .icon_size(IconSize::Small)
5342                            .icon_color(Color::Muted)
5343                            .on_click(cx.listener({
5344                                move |_, _, _window, cx| {
5345                                    #[cfg(windows)]
5346                                    _window.dispatch_action(
5347                                        zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5348                                        cx,
5349                                    );
5350                                    cx.notify();
5351                                }
5352                            })),
5353                    )
5354                    .dismiss_action(
5355                        IconButton::new("dismiss", IconName::Close)
5356                            .icon_size(IconSize::Small)
5357                            .icon_color(Color::Muted)
5358                            .tooltip(Tooltip::text("Dismiss Warning"))
5359                            .on_click(cx.listener({
5360                                move |this, _, _, cx| {
5361                                    this.show_codex_windows_warning = false;
5362                                    cx.notify();
5363                                }
5364                            })),
5365                    ),
5366            )
5367        } else {
5368            None
5369        }
5370    }
5371
5372    fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5373        let content = match self.thread_error.as_ref()? {
5374            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5375            ThreadError::Refusal => self.render_refusal_error(cx),
5376            ThreadError::AuthenticationRequired(error) => {
5377                self.render_authentication_required_error(error.clone(), cx)
5378            }
5379            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5380            ThreadError::ModelRequestLimitReached(plan) => {
5381                self.render_model_request_limit_reached_error(*plan, cx)
5382            }
5383            ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5384        };
5385
5386        Some(div().child(content))
5387    }
5388
5389    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5390        v_flex().w_full().justify_end().child(
5391            h_flex()
5392                .p_2()
5393                .pr_3()
5394                .w_full()
5395                .gap_1p5()
5396                .border_t_1()
5397                .border_color(cx.theme().colors().border)
5398                .bg(cx.theme().colors().element_background)
5399                .child(
5400                    h_flex()
5401                        .flex_1()
5402                        .gap_1p5()
5403                        .child(
5404                            Icon::new(IconName::Download)
5405                                .color(Color::Accent)
5406                                .size(IconSize::Small),
5407                        )
5408                        .child(Label::new("New version available").size(LabelSize::Small)),
5409                )
5410                .child(
5411                    Button::new("update-button", format!("Update to v{}", version))
5412                        .label_size(LabelSize::Small)
5413                        .style(ButtonStyle::Tinted(TintColor::Accent))
5414                        .on_click(cx.listener(|this, _, window, cx| {
5415                            this.reset(window, cx);
5416                        })),
5417                ),
5418        )
5419    }
5420
5421    fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
5422        if let Some(thread) = self.as_native_thread(cx) {
5423            Some(thread.read(cx).profile().0.clone())
5424        } else if let Some(mode_selector) = self.mode_selector() {
5425            Some(mode_selector.read(cx).mode().0)
5426        } else {
5427            None
5428        }
5429    }
5430
5431    fn current_model_id(&self, cx: &App) -> Option<String> {
5432        self.model_selector
5433            .as_ref()
5434            .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5435    }
5436
5437    fn current_model_name(&self, cx: &App) -> SharedString {
5438        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5439        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5440        // This provides better clarity about what refused the request
5441        if self.as_native_connection(cx).is_some() {
5442            self.model_selector
5443                .as_ref()
5444                .and_then(|selector| selector.read(cx).active_model(cx))
5445                .map(|model| model.name.clone())
5446                .unwrap_or_else(|| SharedString::from("The model"))
5447        } else {
5448            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5449            self.agent.name()
5450        }
5451    }
5452
5453    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5454        let model_or_agent_name = self.current_model_name(cx);
5455        let refusal_message = format!(
5456            "{} 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.",
5457            model_or_agent_name
5458        );
5459
5460        Callout::new()
5461            .severity(Severity::Error)
5462            .title("Request Refused")
5463            .icon(IconName::XCircle)
5464            .description(refusal_message.clone())
5465            .actions_slot(self.create_copy_button(&refusal_message))
5466            .dismiss_action(self.dismiss_error_button(cx))
5467    }
5468
5469    fn render_any_thread_error(
5470        &mut self,
5471        error: SharedString,
5472        window: &mut Window,
5473        cx: &mut Context<'_, Self>,
5474    ) -> Callout {
5475        let can_resume = self
5476            .thread()
5477            .map_or(false, |thread| thread.read(cx).can_resume(cx));
5478
5479        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5480            let thread = thread.read(cx);
5481            let supports_burn_mode = thread
5482                .model()
5483                .map_or(false, |model| model.supports_burn_mode());
5484            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5485        });
5486
5487        let markdown = if let Some(markdown) = &self.thread_error_markdown {
5488            markdown.clone()
5489        } else {
5490            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5491            self.thread_error_markdown = Some(markdown.clone());
5492            markdown
5493        };
5494
5495        let markdown_style = default_markdown_style(false, true, window, cx);
5496        let description = self
5497            .render_markdown(markdown, markdown_style)
5498            .into_any_element();
5499
5500        Callout::new()
5501            .severity(Severity::Error)
5502            .icon(IconName::XCircle)
5503            .title("An Error Happened")
5504            .description_slot(description)
5505            .actions_slot(
5506                h_flex()
5507                    .gap_0p5()
5508                    .when(can_resume && can_enable_burn_mode, |this| {
5509                        this.child(
5510                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5511                                .icon(IconName::ZedBurnMode)
5512                                .icon_position(IconPosition::Start)
5513                                .icon_size(IconSize::Small)
5514                                .label_size(LabelSize::Small)
5515                                .on_click(cx.listener(|this, _, window, cx| {
5516                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5517                                    this.resume_chat(cx);
5518                                })),
5519                        )
5520                    })
5521                    .when(can_resume, |this| {
5522                        this.child(
5523                            IconButton::new("retry", IconName::RotateCw)
5524                                .icon_size(IconSize::Small)
5525                                .tooltip(Tooltip::text("Retry Generation"))
5526                                .on_click(cx.listener(|this, _, _window, cx| {
5527                                    this.resume_chat(cx);
5528                                })),
5529                        )
5530                    })
5531                    .child(self.create_copy_button(error.to_string())),
5532            )
5533            .dismiss_action(self.dismiss_error_button(cx))
5534    }
5535
5536    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5537        const ERROR_MESSAGE: &str =
5538            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5539
5540        Callout::new()
5541            .severity(Severity::Error)
5542            .icon(IconName::XCircle)
5543            .title("Free Usage Exceeded")
5544            .description(ERROR_MESSAGE)
5545            .actions_slot(
5546                h_flex()
5547                    .gap_0p5()
5548                    .child(self.upgrade_button(cx))
5549                    .child(self.create_copy_button(ERROR_MESSAGE)),
5550            )
5551            .dismiss_action(self.dismiss_error_button(cx))
5552    }
5553
5554    fn render_authentication_required_error(
5555        &self,
5556        error: SharedString,
5557        cx: &mut Context<Self>,
5558    ) -> Callout {
5559        Callout::new()
5560            .severity(Severity::Error)
5561            .title("Authentication Required")
5562            .icon(IconName::XCircle)
5563            .description(error.clone())
5564            .actions_slot(
5565                h_flex()
5566                    .gap_0p5()
5567                    .child(self.authenticate_button(cx))
5568                    .child(self.create_copy_button(error)),
5569            )
5570            .dismiss_action(self.dismiss_error_button(cx))
5571    }
5572
5573    fn render_model_request_limit_reached_error(
5574        &self,
5575        plan: cloud_llm_client::Plan,
5576        cx: &mut Context<Self>,
5577    ) -> Callout {
5578        let error_message = match plan {
5579            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5580                "Upgrade to usage-based billing for more prompts."
5581            }
5582            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5583            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5584            cloud_llm_client::Plan::V2(_) => "",
5585        };
5586
5587        Callout::new()
5588            .severity(Severity::Error)
5589            .title("Model Prompt Limit Reached")
5590            .icon(IconName::XCircle)
5591            .description(error_message)
5592            .actions_slot(
5593                h_flex()
5594                    .gap_0p5()
5595                    .child(self.upgrade_button(cx))
5596                    .child(self.create_copy_button(error_message)),
5597            )
5598            .dismiss_action(self.dismiss_error_button(cx))
5599    }
5600
5601    fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5602        let thread = self.as_native_thread(cx)?;
5603        let supports_burn_mode = thread
5604            .read(cx)
5605            .model()
5606            .is_some_and(|model| model.supports_burn_mode());
5607
5608        let focus_handle = self.focus_handle(cx);
5609
5610        Some(
5611            Callout::new()
5612                .icon(IconName::Info)
5613                .title("Consecutive tool use limit reached.")
5614                .actions_slot(
5615                    h_flex()
5616                        .gap_0p5()
5617                        .when(supports_burn_mode, |this| {
5618                            this.child(
5619                                Button::new("continue-burn-mode", "Continue with Burn Mode")
5620                                    .style(ButtonStyle::Filled)
5621                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5622                                    .layer(ElevationIndex::ModalSurface)
5623                                    .label_size(LabelSize::Small)
5624                                    .key_binding(
5625                                        KeyBinding::for_action_in(
5626                                            &ContinueWithBurnMode,
5627                                            &focus_handle,
5628                                            cx,
5629                                        )
5630                                        .map(|kb| kb.size(rems_from_px(10.))),
5631                                    )
5632                                    .tooltip(Tooltip::text(
5633                                        "Enable Burn Mode for unlimited tool use.",
5634                                    ))
5635                                    .on_click({
5636                                        cx.listener(move |this, _, _window, cx| {
5637                                            thread.update(cx, |thread, cx| {
5638                                                thread
5639                                                    .set_completion_mode(CompletionMode::Burn, cx);
5640                                            });
5641                                            this.resume_chat(cx);
5642                                        })
5643                                    }),
5644                            )
5645                        })
5646                        .child(
5647                            Button::new("continue-conversation", "Continue")
5648                                .layer(ElevationIndex::ModalSurface)
5649                                .label_size(LabelSize::Small)
5650                                .key_binding(
5651                                    KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5652                                        .map(|kb| kb.size(rems_from_px(10.))),
5653                                )
5654                                .on_click(cx.listener(|this, _, _window, cx| {
5655                                    this.resume_chat(cx);
5656                                })),
5657                        ),
5658                ),
5659        )
5660    }
5661
5662    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5663        let message = message.into();
5664
5665        IconButton::new("copy", IconName::Copy)
5666            .icon_size(IconSize::Small)
5667            .tooltip(Tooltip::text("Copy Error Message"))
5668            .on_click(move |_, _, cx| {
5669                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5670            })
5671    }
5672
5673    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5674        IconButton::new("dismiss", IconName::Close)
5675            .icon_size(IconSize::Small)
5676            .tooltip(Tooltip::text("Dismiss Error"))
5677            .on_click(cx.listener({
5678                move |this, _, _, cx| {
5679                    this.clear_thread_error(cx);
5680                    cx.notify();
5681                }
5682            }))
5683    }
5684
5685    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5686        Button::new("authenticate", "Authenticate")
5687            .label_size(LabelSize::Small)
5688            .style(ButtonStyle::Filled)
5689            .on_click(cx.listener({
5690                move |this, _, window, cx| {
5691                    let agent = this.agent.clone();
5692                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
5693                        return;
5694                    };
5695
5696                    let connection = thread.read(cx).connection().clone();
5697                    let err = AuthRequired {
5698                        description: None,
5699                        provider_id: None,
5700                    };
5701                    this.clear_thread_error(cx);
5702                    let this = cx.weak_entity();
5703                    window.defer(cx, |window, cx| {
5704                        Self::handle_auth_required(this, err, agent, connection, window, cx);
5705                    })
5706                }
5707            }))
5708    }
5709
5710    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5711        let agent = self.agent.clone();
5712        let ThreadState::Ready { thread, .. } = &self.thread_state else {
5713            return;
5714        };
5715
5716        let connection = thread.read(cx).connection().clone();
5717        let err = AuthRequired {
5718            description: None,
5719            provider_id: None,
5720        };
5721        self.clear_thread_error(cx);
5722        let this = cx.weak_entity();
5723        window.defer(cx, |window, cx| {
5724            Self::handle_auth_required(this, err, agent, connection, window, cx);
5725        })
5726    }
5727
5728    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5729        Button::new("upgrade", "Upgrade")
5730            .label_size(LabelSize::Small)
5731            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5732            .on_click(cx.listener({
5733                move |this, _, _, cx| {
5734                    this.clear_thread_error(cx);
5735                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5736                }
5737            }))
5738    }
5739
5740    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5741        let task = match entry {
5742            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5743                history.delete_thread(thread.id.clone(), cx)
5744            }),
5745            HistoryEntry::TextThread(text_thread) => {
5746                self.history_store.update(cx, |history, cx| {
5747                    history.delete_text_thread(text_thread.path.clone(), cx)
5748                })
5749            }
5750        };
5751        task.detach_and_log_err(cx);
5752    }
5753
5754    /// Returns the currently active editor, either for a message that is being
5755    /// edited or the editor for a new message.
5756    fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5757        if let Some(index) = self.editing_message
5758            && let Some(editor) = self
5759                .entry_view_state
5760                .read(cx)
5761                .entry(index)
5762                .and_then(|e| e.message_editor())
5763                .cloned()
5764        {
5765            editor
5766        } else {
5767            self.message_editor.clone()
5768        }
5769    }
5770}
5771
5772fn loading_contents_spinner(size: IconSize) -> AnyElement {
5773    Icon::new(IconName::LoadCircle)
5774        .size(size)
5775        .color(Color::Accent)
5776        .with_rotate_animation(3)
5777        .into_any_element()
5778}
5779
5780fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5781    if agent_name == "Zed Agent" {
5782        format!("Message the {} — @ to include context", agent_name)
5783    } else if has_commands {
5784        format!(
5785            "Message {} — @ to include context, / for commands",
5786            agent_name
5787        )
5788    } else {
5789        format!("Message {} — @ to include context", agent_name)
5790    }
5791}
5792
5793impl Focusable for AcpThreadView {
5794    fn focus_handle(&self, cx: &App) -> FocusHandle {
5795        match self.thread_state {
5796            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5797                self.active_editor(cx).focus_handle(cx)
5798            }
5799            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5800                self.focus_handle.clone()
5801            }
5802        }
5803    }
5804}
5805
5806impl Render for AcpThreadView {
5807    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5808        let has_messages = self.list_state.item_count() > 0;
5809        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5810
5811        v_flex()
5812            .size_full()
5813            .key_context("AcpThread")
5814            .on_action(cx.listener(Self::toggle_burn_mode))
5815            .on_action(cx.listener(Self::keep_all))
5816            .on_action(cx.listener(Self::reject_all))
5817            .on_action(cx.listener(Self::allow_always))
5818            .on_action(cx.listener(Self::allow_once))
5819            .on_action(cx.listener(Self::reject_once))
5820            .track_focus(&self.focus_handle)
5821            .bg(cx.theme().colors().panel_background)
5822            .child(match &self.thread_state {
5823                ThreadState::Unauthenticated {
5824                    connection,
5825                    description,
5826                    configuration_view,
5827                    pending_auth_method,
5828                    ..
5829                } => self
5830                    .render_auth_required_state(
5831                        connection,
5832                        description.as_ref(),
5833                        configuration_view.as_ref(),
5834                        pending_auth_method.as_ref(),
5835                        window,
5836                        cx,
5837                    )
5838                    .into_any(),
5839                ThreadState::Loading { .. } => v_flex()
5840                    .flex_1()
5841                    .child(self.render_recent_history(cx))
5842                    .into_any(),
5843                ThreadState::LoadError(e) => v_flex()
5844                    .flex_1()
5845                    .size_full()
5846                    .items_center()
5847                    .justify_end()
5848                    .child(self.render_load_error(e, window, cx))
5849                    .into_any(),
5850                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5851                    if has_messages {
5852                        this.child(
5853                            list(
5854                                self.list_state.clone(),
5855                                cx.processor(|this, index: usize, window, cx| {
5856                                    let Some((entry, len)) = this.thread().and_then(|thread| {
5857                                        let entries = &thread.read(cx).entries();
5858                                        Some((entries.get(index)?, entries.len()))
5859                                    }) else {
5860                                        return Empty.into_any();
5861                                    };
5862                                    this.render_entry(index, len, entry, window, cx)
5863                                }),
5864                            )
5865                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5866                            .flex_grow()
5867                            .into_any(),
5868                        )
5869                        .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5870                        .into_any()
5871                    } else {
5872                        this.child(self.render_recent_history(cx)).into_any()
5873                    }
5874                }),
5875            })
5876            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5877            // above so that the scrollbar doesn't render behind it. The current setup allows
5878            // the scrollbar to stop exactly at the activity bar start.
5879            .when(has_messages, |this| match &self.thread_state {
5880                ThreadState::Ready { thread, .. } => {
5881                    this.children(self.render_activity_bar(thread, window, cx))
5882                }
5883                _ => this,
5884            })
5885            .children(self.render_thread_retry_status_callout(window, cx))
5886            .children({
5887                if cfg!(windows) && self.project.read(cx).is_local() {
5888                    self.render_codex_windows_warning(cx)
5889                } else {
5890                    None
5891                }
5892            })
5893            .children(self.render_thread_error(window, cx))
5894            .when_some(
5895                self.new_server_version_available.as_ref().filter(|_| {
5896                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5897                }),
5898                |this, version| this.child(self.render_new_version_callout(&version, cx)),
5899            )
5900            .children(
5901                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5902                    Some(usage_callout.into_any_element())
5903                } else {
5904                    self.render_token_limit_callout(line_height, cx)
5905                        .map(|token_limit_callout| token_limit_callout.into_any_element())
5906                },
5907            )
5908            .child(self.render_message_editor(window, cx))
5909    }
5910}
5911
5912fn default_markdown_style(
5913    buffer_font: bool,
5914    muted_text: bool,
5915    window: &Window,
5916    cx: &App,
5917) -> MarkdownStyle {
5918    let theme_settings = ThemeSettings::get_global(cx);
5919    let colors = cx.theme().colors();
5920
5921    let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
5922
5923    let mut text_style = window.text_style();
5924    let line_height = buffer_font_size * 1.75;
5925
5926    let font_family = if buffer_font {
5927        theme_settings.buffer_font.family.clone()
5928    } else {
5929        theme_settings.ui_font.family.clone()
5930    };
5931
5932    let font_size = if buffer_font {
5933        theme_settings.agent_buffer_font_size(cx)
5934    } else {
5935        theme_settings.agent_ui_font_size(cx)
5936    };
5937
5938    let text_color = if muted_text {
5939        colors.text_muted
5940    } else {
5941        colors.text
5942    };
5943
5944    text_style.refine(&TextStyleRefinement {
5945        font_family: Some(font_family),
5946        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5947        font_features: Some(theme_settings.ui_font.features.clone()),
5948        font_size: Some(font_size.into()),
5949        line_height: Some(line_height.into()),
5950        color: Some(text_color),
5951        ..Default::default()
5952    });
5953
5954    MarkdownStyle {
5955        base_text_style: text_style.clone(),
5956        syntax: cx.theme().syntax().clone(),
5957        selection_background_color: colors.element_selection_background,
5958        code_block_overflow_x_scroll: true,
5959        heading_level_styles: Some(HeadingLevelStyles {
5960            h1: Some(TextStyleRefinement {
5961                font_size: Some(rems(1.15).into()),
5962                ..Default::default()
5963            }),
5964            h2: Some(TextStyleRefinement {
5965                font_size: Some(rems(1.1).into()),
5966                ..Default::default()
5967            }),
5968            h3: Some(TextStyleRefinement {
5969                font_size: Some(rems(1.05).into()),
5970                ..Default::default()
5971            }),
5972            h4: Some(TextStyleRefinement {
5973                font_size: Some(rems(1.).into()),
5974                ..Default::default()
5975            }),
5976            h5: Some(TextStyleRefinement {
5977                font_size: Some(rems(0.95).into()),
5978                ..Default::default()
5979            }),
5980            h6: Some(TextStyleRefinement {
5981                font_size: Some(rems(0.875).into()),
5982                ..Default::default()
5983            }),
5984        }),
5985        code_block: StyleRefinement {
5986            padding: EdgesRefinement {
5987                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5988                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5989                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5990                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5991            },
5992            margin: EdgesRefinement {
5993                top: Some(Length::Definite(px(8.).into())),
5994                left: Some(Length::Definite(px(0.).into())),
5995                right: Some(Length::Definite(px(0.).into())),
5996                bottom: Some(Length::Definite(px(12.).into())),
5997            },
5998            border_style: Some(BorderStyle::Solid),
5999            border_widths: EdgesRefinement {
6000                top: Some(AbsoluteLength::Pixels(px(1.))),
6001                left: Some(AbsoluteLength::Pixels(px(1.))),
6002                right: Some(AbsoluteLength::Pixels(px(1.))),
6003                bottom: Some(AbsoluteLength::Pixels(px(1.))),
6004            },
6005            border_color: Some(colors.border_variant),
6006            background: Some(colors.editor_background.into()),
6007            text: Some(TextStyleRefinement {
6008                font_family: Some(theme_settings.buffer_font.family.clone()),
6009                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6010                font_features: Some(theme_settings.buffer_font.features.clone()),
6011                font_size: Some(buffer_font_size.into()),
6012                ..Default::default()
6013            }),
6014            ..Default::default()
6015        },
6016        inline_code: TextStyleRefinement {
6017            font_family: Some(theme_settings.buffer_font.family.clone()),
6018            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6019            font_features: Some(theme_settings.buffer_font.features.clone()),
6020            font_size: Some(buffer_font_size.into()),
6021            background_color: Some(colors.editor_foreground.opacity(0.08)),
6022            ..Default::default()
6023        },
6024        link: TextStyleRefinement {
6025            background_color: Some(colors.editor_foreground.opacity(0.025)),
6026            color: Some(colors.text_accent),
6027            underline: Some(UnderlineStyle {
6028                color: Some(colors.text_accent.opacity(0.5)),
6029                thickness: px(1.),
6030                ..Default::default()
6031            }),
6032            ..Default::default()
6033        },
6034        ..Default::default()
6035    }
6036}
6037
6038fn plan_label_markdown_style(
6039    status: &acp::PlanEntryStatus,
6040    window: &Window,
6041    cx: &App,
6042) -> MarkdownStyle {
6043    let default_md_style = default_markdown_style(false, false, window, cx);
6044
6045    MarkdownStyle {
6046        base_text_style: TextStyle {
6047            color: cx.theme().colors().text_muted,
6048            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
6049                Some(gpui::StrikethroughStyle {
6050                    thickness: px(1.),
6051                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
6052                })
6053            } else {
6054                None
6055            },
6056            ..default_md_style.base_text_style
6057        },
6058        ..default_md_style
6059    }
6060}
6061
6062fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
6063    let default_md_style = default_markdown_style(true, false, window, cx);
6064
6065    MarkdownStyle {
6066        base_text_style: TextStyle {
6067            ..default_md_style.base_text_style
6068        },
6069        selection_background_color: cx.theme().colors().element_selection_background,
6070        ..Default::default()
6071    }
6072}
6073
6074#[cfg(test)]
6075pub(crate) mod tests {
6076    use acp_thread::StubAgentConnection;
6077    use agent_client_protocol::SessionId;
6078    use assistant_text_thread::TextThreadStore;
6079    use fs::FakeFs;
6080    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
6081    use project::Project;
6082    use serde_json::json;
6083    use settings::SettingsStore;
6084    use std::any::Any;
6085    use std::path::Path;
6086    use workspace::Item;
6087
6088    use super::*;
6089
6090    #[gpui::test]
6091    async fn test_drop(cx: &mut TestAppContext) {
6092        init_test(cx);
6093
6094        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6095        let weak_view = thread_view.downgrade();
6096        drop(thread_view);
6097        assert!(!weak_view.is_upgradable());
6098    }
6099
6100    #[gpui::test]
6101    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6102        init_test(cx);
6103
6104        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6105
6106        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6107        message_editor.update_in(cx, |editor, window, cx| {
6108            editor.set_text("Hello", window, cx);
6109        });
6110
6111        cx.deactivate_window();
6112
6113        thread_view.update_in(cx, |thread_view, window, cx| {
6114            thread_view.send(window, cx);
6115        });
6116
6117        cx.run_until_parked();
6118
6119        assert!(
6120            cx.windows()
6121                .iter()
6122                .any(|window| window.downcast::<AgentNotification>().is_some())
6123        );
6124    }
6125
6126    #[gpui::test]
6127    async fn test_notification_for_error(cx: &mut TestAppContext) {
6128        init_test(cx);
6129
6130        let (thread_view, cx) =
6131            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6132
6133        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6134        message_editor.update_in(cx, |editor, window, cx| {
6135            editor.set_text("Hello", window, cx);
6136        });
6137
6138        cx.deactivate_window();
6139
6140        thread_view.update_in(cx, |thread_view, window, cx| {
6141            thread_view.send(window, cx);
6142        });
6143
6144        cx.run_until_parked();
6145
6146        assert!(
6147            cx.windows()
6148                .iter()
6149                .any(|window| window.downcast::<AgentNotification>().is_some())
6150        );
6151    }
6152
6153    #[gpui::test]
6154    async fn test_refusal_handling(cx: &mut TestAppContext) {
6155        init_test(cx);
6156
6157        let (thread_view, cx) =
6158            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6159
6160        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6161        message_editor.update_in(cx, |editor, window, cx| {
6162            editor.set_text("Do something harmful", window, cx);
6163        });
6164
6165        thread_view.update_in(cx, |thread_view, window, cx| {
6166            thread_view.send(window, cx);
6167        });
6168
6169        cx.run_until_parked();
6170
6171        // Check that the refusal error is set
6172        thread_view.read_with(cx, |thread_view, _cx| {
6173            assert!(
6174                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6175                "Expected refusal error to be set"
6176            );
6177        });
6178    }
6179
6180    #[gpui::test]
6181    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6182        init_test(cx);
6183
6184        let tool_call_id = acp::ToolCallId("1".into());
6185        let tool_call = acp::ToolCall {
6186            id: tool_call_id.clone(),
6187            title: "Label".into(),
6188            kind: acp::ToolKind::Edit,
6189            status: acp::ToolCallStatus::Pending,
6190            content: vec!["hi".into()],
6191            locations: vec![],
6192            raw_input: None,
6193            raw_output: None,
6194            meta: None,
6195        };
6196        let connection =
6197            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6198                tool_call_id,
6199                vec![acp::PermissionOption {
6200                    id: acp::PermissionOptionId("1".into()),
6201                    name: "Allow".into(),
6202                    kind: acp::PermissionOptionKind::AllowOnce,
6203                    meta: None,
6204                }],
6205            )]));
6206
6207        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6208
6209        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6210
6211        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6212        message_editor.update_in(cx, |editor, window, cx| {
6213            editor.set_text("Hello", window, cx);
6214        });
6215
6216        cx.deactivate_window();
6217
6218        thread_view.update_in(cx, |thread_view, window, cx| {
6219            thread_view.send(window, cx);
6220        });
6221
6222        cx.run_until_parked();
6223
6224        assert!(
6225            cx.windows()
6226                .iter()
6227                .any(|window| window.downcast::<AgentNotification>().is_some())
6228        );
6229    }
6230
6231    #[gpui::test]
6232    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6233        init_test(cx);
6234
6235        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6236
6237        add_to_workspace(thread_view.clone(), cx);
6238
6239        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6240
6241        message_editor.update_in(cx, |editor, window, cx| {
6242            editor.set_text("Hello", window, cx);
6243        });
6244
6245        // Window is active (don't deactivate), but panel will be hidden
6246        // Note: In the test environment, the panel is not actually added to the dock,
6247        // so is_agent_panel_hidden will return true
6248
6249        thread_view.update_in(cx, |thread_view, window, cx| {
6250            thread_view.send(window, cx);
6251        });
6252
6253        cx.run_until_parked();
6254
6255        // Should show notification because window is active but panel is hidden
6256        assert!(
6257            cx.windows()
6258                .iter()
6259                .any(|window| window.downcast::<AgentNotification>().is_some()),
6260            "Expected notification when panel is hidden"
6261        );
6262    }
6263
6264    #[gpui::test]
6265    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6266        init_test(cx);
6267
6268        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6269
6270        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6271        message_editor.update_in(cx, |editor, window, cx| {
6272            editor.set_text("Hello", window, cx);
6273        });
6274
6275        // Deactivate window - should show notification regardless of setting
6276        cx.deactivate_window();
6277
6278        thread_view.update_in(cx, |thread_view, window, cx| {
6279            thread_view.send(window, cx);
6280        });
6281
6282        cx.run_until_parked();
6283
6284        // Should still show notification when window is inactive (existing behavior)
6285        assert!(
6286            cx.windows()
6287                .iter()
6288                .any(|window| window.downcast::<AgentNotification>().is_some()),
6289            "Expected notification when window is inactive"
6290        );
6291    }
6292
6293    #[gpui::test]
6294    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6295        init_test(cx);
6296
6297        // Set notify_when_agent_waiting to Never
6298        cx.update(|cx| {
6299            AgentSettings::override_global(
6300                AgentSettings {
6301                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6302                    ..AgentSettings::get_global(cx).clone()
6303                },
6304                cx,
6305            );
6306        });
6307
6308        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6309
6310        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6311        message_editor.update_in(cx, |editor, window, cx| {
6312            editor.set_text("Hello", window, cx);
6313        });
6314
6315        // Window is active
6316
6317        thread_view.update_in(cx, |thread_view, window, cx| {
6318            thread_view.send(window, cx);
6319        });
6320
6321        cx.run_until_parked();
6322
6323        // Should NOT show notification because notify_when_agent_waiting is Never
6324        assert!(
6325            !cx.windows()
6326                .iter()
6327                .any(|window| window.downcast::<AgentNotification>().is_some()),
6328            "Expected no notification when notify_when_agent_waiting is Never"
6329        );
6330    }
6331
6332    async fn setup_thread_view(
6333        agent: impl AgentServer + 'static,
6334        cx: &mut TestAppContext,
6335    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6336        let fs = FakeFs::new(cx.executor());
6337        let project = Project::test(fs, [], cx).await;
6338        let (workspace, cx) =
6339            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6340
6341        let text_thread_store =
6342            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6343        let history_store =
6344            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6345
6346        let thread_view = cx.update(|window, cx| {
6347            cx.new(|cx| {
6348                AcpThreadView::new(
6349                    Rc::new(agent),
6350                    None,
6351                    None,
6352                    workspace.downgrade(),
6353                    project,
6354                    history_store,
6355                    None,
6356                    window,
6357                    cx,
6358                )
6359            })
6360        });
6361        cx.run_until_parked();
6362        (thread_view, cx)
6363    }
6364
6365    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6366        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6367
6368        workspace
6369            .update_in(cx, |workspace, window, cx| {
6370                workspace.add_item_to_active_pane(
6371                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6372                    None,
6373                    true,
6374                    window,
6375                    cx,
6376                );
6377            })
6378            .unwrap();
6379    }
6380
6381    struct ThreadViewItem(Entity<AcpThreadView>);
6382
6383    impl Item for ThreadViewItem {
6384        type Event = ();
6385
6386        fn include_in_nav_history() -> bool {
6387            false
6388        }
6389
6390        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6391            "Test".into()
6392        }
6393    }
6394
6395    impl EventEmitter<()> for ThreadViewItem {}
6396
6397    impl Focusable for ThreadViewItem {
6398        fn focus_handle(&self, cx: &App) -> FocusHandle {
6399            self.0.read(cx).focus_handle(cx)
6400        }
6401    }
6402
6403    impl Render for ThreadViewItem {
6404        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6405            self.0.clone().into_any_element()
6406        }
6407    }
6408
6409    struct StubAgentServer<C> {
6410        connection: C,
6411    }
6412
6413    impl<C> StubAgentServer<C> {
6414        fn new(connection: C) -> Self {
6415            Self { connection }
6416        }
6417    }
6418
6419    impl StubAgentServer<StubAgentConnection> {
6420        fn default_response() -> Self {
6421            let conn = StubAgentConnection::new();
6422            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6423                acp::ContentChunk {
6424                    content: "Default response".into(),
6425                    meta: None,
6426                },
6427            )]);
6428            Self::new(conn)
6429        }
6430    }
6431
6432    impl<C> AgentServer for StubAgentServer<C>
6433    where
6434        C: 'static + AgentConnection + Send + Clone,
6435    {
6436        fn telemetry_id(&self) -> &'static str {
6437            "test"
6438        }
6439
6440        fn logo(&self) -> ui::IconName {
6441            ui::IconName::Ai
6442        }
6443
6444        fn name(&self) -> SharedString {
6445            "Test".into()
6446        }
6447
6448        fn connect(
6449            &self,
6450            _root_dir: Option<&Path>,
6451            _delegate: AgentServerDelegate,
6452            _cx: &mut App,
6453        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6454            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6455        }
6456
6457        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6458            self
6459        }
6460    }
6461
6462    #[derive(Clone)]
6463    struct SaboteurAgentConnection;
6464
6465    impl AgentConnection for SaboteurAgentConnection {
6466        fn telemetry_id(&self) -> &'static str {
6467            "saboteur"
6468        }
6469
6470        fn new_thread(
6471            self: Rc<Self>,
6472            project: Entity<Project>,
6473            _cwd: &Path,
6474            cx: &mut gpui::App,
6475        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6476            Task::ready(Ok(cx.new(|cx| {
6477                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6478                AcpThread::new(
6479                    "SaboteurAgentConnection",
6480                    self,
6481                    project,
6482                    action_log,
6483                    SessionId("test".into()),
6484                    watch::Receiver::constant(acp::PromptCapabilities {
6485                        image: true,
6486                        audio: true,
6487                        embedded_context: true,
6488                        meta: None,
6489                    }),
6490                    cx,
6491                )
6492            })))
6493        }
6494
6495        fn auth_methods(&self) -> &[acp::AuthMethod] {
6496            &[]
6497        }
6498
6499        fn authenticate(
6500            &self,
6501            _method_id: acp::AuthMethodId,
6502            _cx: &mut App,
6503        ) -> Task<gpui::Result<()>> {
6504            unimplemented!()
6505        }
6506
6507        fn prompt(
6508            &self,
6509            _id: Option<acp_thread::UserMessageId>,
6510            _params: acp::PromptRequest,
6511            _cx: &mut App,
6512        ) -> Task<gpui::Result<acp::PromptResponse>> {
6513            Task::ready(Err(anyhow::anyhow!("Error prompting")))
6514        }
6515
6516        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6517            unimplemented!()
6518        }
6519
6520        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6521            self
6522        }
6523    }
6524
6525    /// Simulates a model which always returns a refusal response
6526    #[derive(Clone)]
6527    struct RefusalAgentConnection;
6528
6529    impl AgentConnection for RefusalAgentConnection {
6530        fn telemetry_id(&self) -> &'static str {
6531            "refusal"
6532        }
6533
6534        fn new_thread(
6535            self: Rc<Self>,
6536            project: Entity<Project>,
6537            _cwd: &Path,
6538            cx: &mut gpui::App,
6539        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6540            Task::ready(Ok(cx.new(|cx| {
6541                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6542                AcpThread::new(
6543                    "RefusalAgentConnection",
6544                    self,
6545                    project,
6546                    action_log,
6547                    SessionId("test".into()),
6548                    watch::Receiver::constant(acp::PromptCapabilities {
6549                        image: true,
6550                        audio: true,
6551                        embedded_context: true,
6552                        meta: None,
6553                    }),
6554                    cx,
6555                )
6556            })))
6557        }
6558
6559        fn auth_methods(&self) -> &[acp::AuthMethod] {
6560            &[]
6561        }
6562
6563        fn authenticate(
6564            &self,
6565            _method_id: acp::AuthMethodId,
6566            _cx: &mut App,
6567        ) -> Task<gpui::Result<()>> {
6568            unimplemented!()
6569        }
6570
6571        fn prompt(
6572            &self,
6573            _id: Option<acp_thread::UserMessageId>,
6574            _params: acp::PromptRequest,
6575            _cx: &mut App,
6576        ) -> Task<gpui::Result<acp::PromptResponse>> {
6577            Task::ready(Ok(acp::PromptResponse {
6578                stop_reason: acp::StopReason::Refusal,
6579                meta: None,
6580            }))
6581        }
6582
6583        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6584            unimplemented!()
6585        }
6586
6587        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6588            self
6589        }
6590    }
6591
6592    pub(crate) fn init_test(cx: &mut TestAppContext) {
6593        cx.update(|cx| {
6594            let settings_store = SettingsStore::test(cx);
6595            cx.set_global(settings_store);
6596            theme::init(theme::LoadThemes::JustBase, cx);
6597            release_channel::init(SemanticVersion::default(), cx);
6598            prompt_store::init(cx)
6599        });
6600    }
6601
6602    #[gpui::test]
6603    async fn test_rewind_views(cx: &mut TestAppContext) {
6604        init_test(cx);
6605
6606        let fs = FakeFs::new(cx.executor());
6607        fs.insert_tree(
6608            "/project",
6609            json!({
6610                "test1.txt": "old content 1",
6611                "test2.txt": "old content 2"
6612            }),
6613        )
6614        .await;
6615        let project = Project::test(fs, [Path::new("/project")], cx).await;
6616        let (workspace, cx) =
6617            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6618
6619        let text_thread_store =
6620            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6621        let history_store =
6622            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6623
6624        let connection = Rc::new(StubAgentConnection::new());
6625        let thread_view = cx.update(|window, cx| {
6626            cx.new(|cx| {
6627                AcpThreadView::new(
6628                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6629                    None,
6630                    None,
6631                    workspace.downgrade(),
6632                    project.clone(),
6633                    history_store.clone(),
6634                    None,
6635                    window,
6636                    cx,
6637                )
6638            })
6639        });
6640
6641        cx.run_until_parked();
6642
6643        let thread = thread_view
6644            .read_with(cx, |view, _| view.thread().cloned())
6645            .unwrap();
6646
6647        // First user message
6648        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6649            id: acp::ToolCallId("tool1".into()),
6650            title: "Edit file 1".into(),
6651            kind: acp::ToolKind::Edit,
6652            status: acp::ToolCallStatus::Completed,
6653            content: vec![acp::ToolCallContent::Diff {
6654                diff: acp::Diff {
6655                    path: "/project/test1.txt".into(),
6656                    old_text: Some("old content 1".into()),
6657                    new_text: "new content 1".into(),
6658                    meta: None,
6659                },
6660            }],
6661            locations: vec![],
6662            raw_input: None,
6663            raw_output: None,
6664            meta: None,
6665        })]);
6666
6667        thread
6668            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6669            .await
6670            .unwrap();
6671        cx.run_until_parked();
6672
6673        thread.read_with(cx, |thread, _| {
6674            assert_eq!(thread.entries().len(), 2);
6675        });
6676
6677        thread_view.read_with(cx, |view, cx| {
6678            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6679                assert!(
6680                    entry_view_state
6681                        .entry(0)
6682                        .unwrap()
6683                        .message_editor()
6684                        .is_some()
6685                );
6686                assert!(entry_view_state.entry(1).unwrap().has_content());
6687            });
6688        });
6689
6690        // Second user message
6691        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6692            id: acp::ToolCallId("tool2".into()),
6693            title: "Edit file 2".into(),
6694            kind: acp::ToolKind::Edit,
6695            status: acp::ToolCallStatus::Completed,
6696            content: vec![acp::ToolCallContent::Diff {
6697                diff: acp::Diff {
6698                    path: "/project/test2.txt".into(),
6699                    old_text: Some("old content 2".into()),
6700                    new_text: "new content 2".into(),
6701                    meta: None,
6702                },
6703            }],
6704            locations: vec![],
6705            raw_input: None,
6706            raw_output: None,
6707            meta: None,
6708        })]);
6709
6710        thread
6711            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6712            .await
6713            .unwrap();
6714        cx.run_until_parked();
6715
6716        let second_user_message_id = thread.read_with(cx, |thread, _| {
6717            assert_eq!(thread.entries().len(), 4);
6718            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6719                panic!();
6720            };
6721            user_message.id.clone().unwrap()
6722        });
6723
6724        thread_view.read_with(cx, |view, cx| {
6725            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6726                assert!(
6727                    entry_view_state
6728                        .entry(0)
6729                        .unwrap()
6730                        .message_editor()
6731                        .is_some()
6732                );
6733                assert!(entry_view_state.entry(1).unwrap().has_content());
6734                assert!(
6735                    entry_view_state
6736                        .entry(2)
6737                        .unwrap()
6738                        .message_editor()
6739                        .is_some()
6740                );
6741                assert!(entry_view_state.entry(3).unwrap().has_content());
6742            });
6743        });
6744
6745        // Rewind to first message
6746        thread
6747            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6748            .await
6749            .unwrap();
6750
6751        cx.run_until_parked();
6752
6753        thread.read_with(cx, |thread, _| {
6754            assert_eq!(thread.entries().len(), 2);
6755        });
6756
6757        thread_view.read_with(cx, |view, cx| {
6758            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6759                assert!(
6760                    entry_view_state
6761                        .entry(0)
6762                        .unwrap()
6763                        .message_editor()
6764                        .is_some()
6765                );
6766                assert!(entry_view_state.entry(1).unwrap().has_content());
6767
6768                // Old views should be dropped
6769                assert!(entry_view_state.entry(2).is_none());
6770                assert!(entry_view_state.entry(3).is_none());
6771            });
6772        });
6773    }
6774
6775    #[gpui::test]
6776    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6777        init_test(cx);
6778
6779        let connection = StubAgentConnection::new();
6780
6781        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6782            acp::ContentChunk {
6783                content: acp::ContentBlock::Text(acp::TextContent {
6784                    text: "Response".into(),
6785                    annotations: None,
6786                    meta: None,
6787                }),
6788                meta: None,
6789            },
6790        )]);
6791
6792        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6793        add_to_workspace(thread_view.clone(), cx);
6794
6795        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6796        message_editor.update_in(cx, |editor, window, cx| {
6797            editor.set_text("Original message to edit", window, cx);
6798        });
6799        thread_view.update_in(cx, |thread_view, window, cx| {
6800            thread_view.send(window, cx);
6801        });
6802
6803        cx.run_until_parked();
6804
6805        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6806            assert_eq!(view.editing_message, None);
6807
6808            view.entry_view_state
6809                .read(cx)
6810                .entry(0)
6811                .unwrap()
6812                .message_editor()
6813                .unwrap()
6814                .clone()
6815        });
6816
6817        // Focus
6818        cx.focus(&user_message_editor);
6819        thread_view.read_with(cx, |view, _cx| {
6820            assert_eq!(view.editing_message, Some(0));
6821        });
6822
6823        // Edit
6824        user_message_editor.update_in(cx, |editor, window, cx| {
6825            editor.set_text("Edited message content", window, cx);
6826        });
6827
6828        // Cancel
6829        user_message_editor.update_in(cx, |_editor, window, cx| {
6830            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6831        });
6832
6833        thread_view.read_with(cx, |view, _cx| {
6834            assert_eq!(view.editing_message, None);
6835        });
6836
6837        user_message_editor.read_with(cx, |editor, cx| {
6838            assert_eq!(editor.text(cx), "Original message to edit");
6839        });
6840    }
6841
6842    #[gpui::test]
6843    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6844        init_test(cx);
6845
6846        let connection = StubAgentConnection::new();
6847
6848        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6849        add_to_workspace(thread_view.clone(), cx);
6850
6851        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6852        let mut events = cx.events(&message_editor);
6853        message_editor.update_in(cx, |editor, window, cx| {
6854            editor.set_text("", window, cx);
6855        });
6856
6857        message_editor.update_in(cx, |_editor, window, cx| {
6858            window.dispatch_action(Box::new(Chat), cx);
6859        });
6860        cx.run_until_parked();
6861        // We shouldn't have received any messages
6862        assert!(matches!(
6863            events.try_next(),
6864            Err(futures::channel::mpsc::TryRecvError { .. })
6865        ));
6866    }
6867
6868    #[gpui::test]
6869    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6870        init_test(cx);
6871
6872        let connection = StubAgentConnection::new();
6873
6874        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6875            acp::ContentChunk {
6876                content: acp::ContentBlock::Text(acp::TextContent {
6877                    text: "Response".into(),
6878                    annotations: None,
6879                    meta: None,
6880                }),
6881                meta: None,
6882            },
6883        )]);
6884
6885        let (thread_view, cx) =
6886            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6887        add_to_workspace(thread_view.clone(), cx);
6888
6889        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6890        message_editor.update_in(cx, |editor, window, cx| {
6891            editor.set_text("Original message to edit", window, cx);
6892        });
6893        thread_view.update_in(cx, |thread_view, window, cx| {
6894            thread_view.send(window, cx);
6895        });
6896
6897        cx.run_until_parked();
6898
6899        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6900            assert_eq!(view.editing_message, None);
6901            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6902
6903            view.entry_view_state
6904                .read(cx)
6905                .entry(0)
6906                .unwrap()
6907                .message_editor()
6908                .unwrap()
6909                .clone()
6910        });
6911
6912        // Focus
6913        cx.focus(&user_message_editor);
6914
6915        // Edit
6916        user_message_editor.update_in(cx, |editor, window, cx| {
6917            editor.set_text("Edited message content", window, cx);
6918        });
6919
6920        // Send
6921        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6922            acp::ContentChunk {
6923                content: acp::ContentBlock::Text(acp::TextContent {
6924                    text: "New Response".into(),
6925                    annotations: None,
6926                    meta: None,
6927                }),
6928                meta: None,
6929            },
6930        )]);
6931
6932        user_message_editor.update_in(cx, |_editor, window, cx| {
6933            window.dispatch_action(Box::new(Chat), cx);
6934        });
6935
6936        cx.run_until_parked();
6937
6938        thread_view.read_with(cx, |view, cx| {
6939            assert_eq!(view.editing_message, None);
6940
6941            let entries = view.thread().unwrap().read(cx).entries();
6942            assert_eq!(entries.len(), 2);
6943            assert_eq!(
6944                entries[0].to_markdown(cx),
6945                "## User\n\nEdited message content\n\n"
6946            );
6947            assert_eq!(
6948                entries[1].to_markdown(cx),
6949                "## Assistant\n\nNew Response\n\n"
6950            );
6951
6952            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6953                assert!(!state.entry(1).unwrap().has_content());
6954                state.entry(0).unwrap().message_editor().unwrap().clone()
6955            });
6956
6957            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6958        })
6959    }
6960
6961    #[gpui::test]
6962    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6963        init_test(cx);
6964
6965        let connection = StubAgentConnection::new();
6966
6967        let (thread_view, cx) =
6968            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6969        add_to_workspace(thread_view.clone(), cx);
6970
6971        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6972        message_editor.update_in(cx, |editor, window, cx| {
6973            editor.set_text("Original message to edit", window, cx);
6974        });
6975        thread_view.update_in(cx, |thread_view, window, cx| {
6976            thread_view.send(window, cx);
6977        });
6978
6979        cx.run_until_parked();
6980
6981        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6982            let thread = view.thread().unwrap().read(cx);
6983            assert_eq!(thread.entries().len(), 1);
6984
6985            let editor = view
6986                .entry_view_state
6987                .read(cx)
6988                .entry(0)
6989                .unwrap()
6990                .message_editor()
6991                .unwrap()
6992                .clone();
6993
6994            (editor, thread.session_id().clone())
6995        });
6996
6997        // Focus
6998        cx.focus(&user_message_editor);
6999
7000        thread_view.read_with(cx, |view, _cx| {
7001            assert_eq!(view.editing_message, Some(0));
7002        });
7003
7004        // Edit
7005        user_message_editor.update_in(cx, |editor, window, cx| {
7006            editor.set_text("Edited message content", window, cx);
7007        });
7008
7009        thread_view.read_with(cx, |view, _cx| {
7010            assert_eq!(view.editing_message, Some(0));
7011        });
7012
7013        // Finish streaming response
7014        cx.update(|_, cx| {
7015            connection.send_update(
7016                session_id.clone(),
7017                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7018                    content: acp::ContentBlock::Text(acp::TextContent {
7019                        text: "Response".into(),
7020                        annotations: None,
7021                        meta: None,
7022                    }),
7023                    meta: None,
7024                }),
7025                cx,
7026            );
7027            connection.end_turn(session_id, acp::StopReason::EndTurn);
7028        });
7029
7030        thread_view.read_with(cx, |view, _cx| {
7031            assert_eq!(view.editing_message, Some(0));
7032        });
7033
7034        cx.run_until_parked();
7035
7036        // Should still be editing
7037        cx.update(|window, cx| {
7038            assert!(user_message_editor.focus_handle(cx).is_focused(window));
7039            assert_eq!(thread_view.read(cx).editing_message, Some(0));
7040            assert_eq!(
7041                user_message_editor.read(cx).text(cx),
7042                "Edited message content"
7043            );
7044        });
7045    }
7046
7047    #[gpui::test]
7048    async fn test_interrupt(cx: &mut TestAppContext) {
7049        init_test(cx);
7050
7051        let connection = StubAgentConnection::new();
7052
7053        let (thread_view, cx) =
7054            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7055        add_to_workspace(thread_view.clone(), cx);
7056
7057        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7058        message_editor.update_in(cx, |editor, window, cx| {
7059            editor.set_text("Message 1", window, cx);
7060        });
7061        thread_view.update_in(cx, |thread_view, window, cx| {
7062            thread_view.send(window, cx);
7063        });
7064
7065        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
7066            let thread = view.thread().unwrap();
7067
7068            (thread.clone(), thread.read(cx).session_id().clone())
7069        });
7070
7071        cx.run_until_parked();
7072
7073        cx.update(|_, cx| {
7074            connection.send_update(
7075                session_id.clone(),
7076                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7077                    content: "Message 1 resp".into(),
7078                    meta: None,
7079                }),
7080                cx,
7081            );
7082        });
7083
7084        cx.run_until_parked();
7085
7086        thread.read_with(cx, |thread, cx| {
7087            assert_eq!(
7088                thread.to_markdown(cx),
7089                indoc::indoc! {"
7090                    ## User
7091
7092                    Message 1
7093
7094                    ## Assistant
7095
7096                    Message 1 resp
7097
7098                "}
7099            )
7100        });
7101
7102        message_editor.update_in(cx, |editor, window, cx| {
7103            editor.set_text("Message 2", window, cx);
7104        });
7105        thread_view.update_in(cx, |thread_view, window, cx| {
7106            thread_view.send(window, cx);
7107        });
7108
7109        cx.update(|_, cx| {
7110            // Simulate a response sent after beginning to cancel
7111            connection.send_update(
7112                session_id.clone(),
7113                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7114                    content: "onse".into(),
7115                    meta: None,
7116                }),
7117                cx,
7118            );
7119        });
7120
7121        cx.run_until_parked();
7122
7123        // Last Message 1 response should appear before Message 2
7124        thread.read_with(cx, |thread, cx| {
7125            assert_eq!(
7126                thread.to_markdown(cx),
7127                indoc::indoc! {"
7128                    ## User
7129
7130                    Message 1
7131
7132                    ## Assistant
7133
7134                    Message 1 response
7135
7136                    ## User
7137
7138                    Message 2
7139
7140                "}
7141            )
7142        });
7143
7144        cx.update(|_, cx| {
7145            connection.send_update(
7146                session_id.clone(),
7147                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7148                    content: "Message 2 response".into(),
7149                    meta: None,
7150                }),
7151                cx,
7152            );
7153            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7154        });
7155
7156        cx.run_until_parked();
7157
7158        thread.read_with(cx, |thread, cx| {
7159            assert_eq!(
7160                thread.to_markdown(cx),
7161                indoc::indoc! {"
7162                    ## User
7163
7164                    Message 1
7165
7166                    ## Assistant
7167
7168                    Message 1 response
7169
7170                    ## User
7171
7172                    Message 2
7173
7174                    ## Assistant
7175
7176                    Message 2 response
7177
7178                "}
7179            )
7180        });
7181    }
7182
7183    #[gpui::test]
7184    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7185        init_test(cx);
7186
7187        let connection = StubAgentConnection::new();
7188        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7189            acp::ContentChunk {
7190                content: acp::ContentBlock::Text(acp::TextContent {
7191                    text: "Response".into(),
7192                    annotations: None,
7193                    meta: None,
7194                }),
7195                meta: None,
7196            },
7197        )]);
7198
7199        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7200        add_to_workspace(thread_view.clone(), cx);
7201
7202        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7203        message_editor.update_in(cx, |editor, window, cx| {
7204            editor.set_text("Original message to edit", window, cx)
7205        });
7206        thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7207        cx.run_until_parked();
7208
7209        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7210            thread_view
7211                .entry_view_state
7212                .read(cx)
7213                .entry(0)
7214                .expect("Should have at least one entry")
7215                .message_editor()
7216                .expect("Should have message editor")
7217                .clone()
7218        });
7219
7220        cx.focus(&user_message_editor);
7221        thread_view.read_with(cx, |thread_view, _cx| {
7222            assert_eq!(thread_view.editing_message, Some(0));
7223        });
7224
7225        // Ensure to edit the focused message before proceeding otherwise, since
7226        // its content is not different from what was sent, focus will be lost.
7227        user_message_editor.update_in(cx, |editor, window, cx| {
7228            editor.set_text("Original message to edit with ", window, cx)
7229        });
7230
7231        // Create a simple buffer with some text so we can create a selection
7232        // that will then be added to the message being edited.
7233        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7234            (thread_view.workspace.clone(), thread_view.project.clone())
7235        });
7236        let buffer = project.update(cx, |project, cx| {
7237            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7238        });
7239
7240        workspace
7241            .update_in(cx, |workspace, window, cx| {
7242                let editor = cx.new(|cx| {
7243                    let mut editor =
7244                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7245
7246                    editor.change_selections(Default::default(), window, cx, |selections| {
7247                        selections.select_ranges([8..15]);
7248                    });
7249
7250                    editor
7251                });
7252                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7253            })
7254            .unwrap();
7255
7256        thread_view.update_in(cx, |thread_view, window, cx| {
7257            assert_eq!(thread_view.editing_message, Some(0));
7258            thread_view.insert_selections(window, cx);
7259        });
7260
7261        user_message_editor.read_with(cx, |editor, cx| {
7262            let text = editor.editor().read(cx).text(cx);
7263            let expected_text = String::from("Original message to edit with selection ");
7264
7265            assert_eq!(text, expected_text);
7266        });
7267    }
7268
7269    #[gpui::test]
7270    async fn test_insert_selections(cx: &mut TestAppContext) {
7271        init_test(cx);
7272
7273        let connection = StubAgentConnection::new();
7274        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7275            acp::ContentChunk {
7276                content: acp::ContentBlock::Text(acp::TextContent {
7277                    text: "Response".into(),
7278                    annotations: None,
7279                    meta: None,
7280                }),
7281                meta: None,
7282            },
7283        )]);
7284
7285        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7286        add_to_workspace(thread_view.clone(), cx);
7287
7288        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7289        message_editor.update_in(cx, |editor, window, cx| {
7290            editor.set_text("Can you review this snippet ", window, cx)
7291        });
7292
7293        // Create a simple buffer with some text so we can create a selection
7294        // that will then be added to the message being edited.
7295        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7296            (thread_view.workspace.clone(), thread_view.project.clone())
7297        });
7298        let buffer = project.update(cx, |project, cx| {
7299            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7300        });
7301
7302        workspace
7303            .update_in(cx, |workspace, window, cx| {
7304                let editor = cx.new(|cx| {
7305                    let mut editor =
7306                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7307
7308                    editor.change_selections(Default::default(), window, cx, |selections| {
7309                        selections.select_ranges([8..15]);
7310                    });
7311
7312                    editor
7313                });
7314                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7315            })
7316            .unwrap();
7317
7318        thread_view.update_in(cx, |thread_view, window, cx| {
7319            assert_eq!(thread_view.editing_message, None);
7320            thread_view.insert_selections(window, cx);
7321        });
7322
7323        thread_view.read_with(cx, |thread_view, cx| {
7324            let text = thread_view.message_editor.read(cx).text(cx);
7325            let expected_txt = String::from("Can you review this snippet selection ");
7326
7327            assert_eq!(text, expected_txt);
7328        })
7329    }
7330
7331    #[gpui::test]
7332    async fn test_initialize_timeout(cx: &mut TestAppContext) {
7333        init_test(cx);
7334
7335        struct InfiniteInitialize;
7336
7337        impl AgentServer for InfiniteInitialize {
7338            fn telemetry_id(&self) -> &'static str {
7339                "test"
7340            }
7341
7342            fn logo(&self) -> ui::IconName {
7343                ui::IconName::Ai
7344            }
7345
7346            fn name(&self) -> SharedString {
7347                "Test".into()
7348            }
7349
7350            fn connect(
7351                &self,
7352                _root_dir: Option<&Path>,
7353                _delegate: AgentServerDelegate,
7354                cx: &mut App,
7355            ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>>
7356            {
7357                cx.spawn(async |_| futures::future::pending().await)
7358            }
7359
7360            fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7361                self
7362            }
7363        }
7364
7365        let (thread_view, cx) = setup_thread_view(InfiniteInitialize, cx).await;
7366
7367        cx.executor().advance_clock(Duration::from_secs(31));
7368        cx.run_until_parked();
7369
7370        let error = thread_view.read_with(cx, |thread_view, _| match &thread_view.thread_state {
7371            ThreadState::LoadError(err) => err.clone(),
7372            _ => panic!("Incorrect thread state"),
7373        });
7374
7375        match error {
7376            LoadError::Other(str) => assert!(str.contains("initialize")),
7377            _ => panic!("Unexpected load error"),
7378        }
7379    }
7380}