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