thread_view.rs

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