thread_view.rs

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