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