thread_view.rs

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