thread_view.rs

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