thread_view.rs

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