thread_view.rs

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