thread_view.rs

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