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