thread_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
   3    AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
   4    ToolCallStatus, UserMessageId,
   5};
   6use acp_thread::{AgentConnection, Plan};
   7use action_log::{ActionLog, ActionLogTelemetry};
   8use agent::{DbThreadMetadata, 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::{Anchor, 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, OpenAgentDiff, OpenHistory, QueueMessage, RejectAll, RejectOnce,
  75    SendNextQueuedMessage, 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 telemetry = ActionLogTelemetry::from(thread);
4345        let changed_buffers = action_log.read(cx).changed_buffers(cx);
4346        let plan = thread.plan();
4347
4348        if changed_buffers.is_empty() && plan.is_empty() && self.message_queue.is_empty() {
4349            return None;
4350        }
4351
4352        // Temporarily always enable ACP edit controls. This is temporary, to lessen the
4353        // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
4354        // be, which blocks you from being able to accept or reject edits. This switches the
4355        // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
4356        // block you from using the panel.
4357        let pending_edits = false;
4358
4359        v_flex()
4360            .mt_1()
4361            .mx_2()
4362            .bg(self.activity_bar_bg(cx))
4363            .border_1()
4364            .border_b_0()
4365            .border_color(cx.theme().colors().border)
4366            .rounded_t_md()
4367            .shadow(vec![gpui::BoxShadow {
4368                color: gpui::black().opacity(0.15),
4369                offset: point(px(1.), px(-1.)),
4370                blur_radius: px(3.),
4371                spread_radius: px(0.),
4372            }])
4373            .when(!plan.is_empty(), |this| {
4374                this.child(self.render_plan_summary(plan, window, cx))
4375                    .when(self.plan_expanded, |parent| {
4376                        parent.child(self.render_plan_entries(plan, window, cx))
4377                    })
4378            })
4379            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
4380                this.child(Divider::horizontal().color(DividerColor::Border))
4381            })
4382            .when(!changed_buffers.is_empty(), |this| {
4383                this.child(self.render_edits_summary(
4384                    &changed_buffers,
4385                    self.edits_expanded,
4386                    pending_edits,
4387                    cx,
4388                ))
4389                .when(self.edits_expanded, |parent| {
4390                    parent.child(self.render_edited_files(
4391                        action_log,
4392                        telemetry,
4393                        &changed_buffers,
4394                        pending_edits,
4395                        cx,
4396                    ))
4397                })
4398            })
4399            .when(!self.message_queue.is_empty(), |this| {
4400                this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
4401                    this.child(Divider::horizontal().color(DividerColor::Border))
4402                })
4403                .child(self.render_message_queue_summary(window, cx))
4404                .when(self.queue_expanded, |parent| {
4405                    parent.child(self.render_message_queue_entries(window, cx))
4406                })
4407            })
4408            .into_any()
4409            .into()
4410    }
4411
4412    fn render_plan_summary(
4413        &self,
4414        plan: &Plan,
4415        window: &mut Window,
4416        cx: &Context<Self>,
4417    ) -> impl IntoElement {
4418        let stats = plan.stats();
4419
4420        let title = if let Some(entry) = stats.in_progress_entry
4421            && !self.plan_expanded
4422        {
4423            h_flex()
4424                .cursor_default()
4425                .relative()
4426                .w_full()
4427                .gap_1()
4428                .truncate()
4429                .child(
4430                    Label::new("Current:")
4431                        .size(LabelSize::Small)
4432                        .color(Color::Muted),
4433                )
4434                .child(
4435                    div()
4436                        .text_xs()
4437                        .text_color(cx.theme().colors().text_muted)
4438                        .line_clamp(1)
4439                        .child(MarkdownElement::new(
4440                            entry.content.clone(),
4441                            plan_label_markdown_style(&entry.status, window, cx),
4442                        )),
4443                )
4444                .when(stats.pending > 0, |this| {
4445                    this.child(
4446                        h_flex()
4447                            .absolute()
4448                            .top_0()
4449                            .right_0()
4450                            .h_full()
4451                            .child(div().min_w_8().h_full().bg(linear_gradient(
4452                                90.,
4453                                linear_color_stop(self.activity_bar_bg(cx), 1.),
4454                                linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
4455                            )))
4456                            .child(
4457                                div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
4458                                    Label::new(format!("{} left", stats.pending))
4459                                        .size(LabelSize::Small)
4460                                        .color(Color::Muted),
4461                                ),
4462                            ),
4463                    )
4464                })
4465        } else {
4466            let status_label = if stats.pending == 0 {
4467                "All Done".to_string()
4468            } else if stats.completed == 0 {
4469                format!("{} Tasks", plan.entries.len())
4470            } else {
4471                format!("{}/{}", stats.completed, plan.entries.len())
4472            };
4473
4474            h_flex()
4475                .w_full()
4476                .gap_1()
4477                .justify_between()
4478                .child(
4479                    Label::new("Plan")
4480                        .size(LabelSize::Small)
4481                        .color(Color::Muted),
4482                )
4483                .child(
4484                    Label::new(status_label)
4485                        .size(LabelSize::Small)
4486                        .color(Color::Muted)
4487                        .mr_1(),
4488                )
4489        };
4490
4491        h_flex()
4492            .id("plan_summary")
4493            .p_1()
4494            .w_full()
4495            .gap_1()
4496            .when(self.plan_expanded, |this| {
4497                this.border_b_1().border_color(cx.theme().colors().border)
4498            })
4499            .child(Disclosure::new("plan_disclosure", self.plan_expanded))
4500            .child(title)
4501            .on_click(cx.listener(|this, _, _, cx| {
4502                this.plan_expanded = !this.plan_expanded;
4503                cx.notify();
4504            }))
4505    }
4506
4507    fn render_plan_entries(
4508        &self,
4509        plan: &Plan,
4510        window: &mut Window,
4511        cx: &Context<Self>,
4512    ) -> impl IntoElement {
4513        v_flex()
4514            .id("plan_items_list")
4515            .max_h_40()
4516            .overflow_y_scroll()
4517            .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
4518                let element = h_flex()
4519                    .py_1()
4520                    .px_2()
4521                    .gap_2()
4522                    .justify_between()
4523                    .bg(cx.theme().colors().editor_background)
4524                    .when(index < plan.entries.len() - 1, |parent| {
4525                        parent.border_color(cx.theme().colors().border).border_b_1()
4526                    })
4527                    .child(
4528                        h_flex()
4529                            .id(("plan_entry", index))
4530                            .gap_1p5()
4531                            .max_w_full()
4532                            .overflow_x_scroll()
4533                            .text_xs()
4534                            .text_color(cx.theme().colors().text_muted)
4535                            .child(match entry.status {
4536                                acp::PlanEntryStatus::InProgress => {
4537                                    Icon::new(IconName::TodoProgress)
4538                                        .size(IconSize::Small)
4539                                        .color(Color::Accent)
4540                                        .with_rotate_animation(2)
4541                                        .into_any_element()
4542                                }
4543                                acp::PlanEntryStatus::Completed => {
4544                                    Icon::new(IconName::TodoComplete)
4545                                        .size(IconSize::Small)
4546                                        .color(Color::Success)
4547                                        .into_any_element()
4548                                }
4549                                acp::PlanEntryStatus::Pending | _ => {
4550                                    Icon::new(IconName::TodoPending)
4551                                        .size(IconSize::Small)
4552                                        .color(Color::Muted)
4553                                        .into_any_element()
4554                                }
4555                            })
4556                            .child(MarkdownElement::new(
4557                                entry.content.clone(),
4558                                plan_label_markdown_style(&entry.status, window, cx),
4559                            )),
4560                    );
4561
4562                Some(element)
4563            }))
4564            .into_any_element()
4565    }
4566
4567    fn render_edits_summary(
4568        &self,
4569        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4570        expanded: bool,
4571        pending_edits: bool,
4572        cx: &Context<Self>,
4573    ) -> Div {
4574        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
4575
4576        let focus_handle = self.focus_handle(cx);
4577
4578        h_flex()
4579            .p_1()
4580            .justify_between()
4581            .flex_wrap()
4582            .when(expanded, |this| {
4583                this.border_b_1().border_color(cx.theme().colors().border)
4584            })
4585            .child(
4586                h_flex()
4587                    .id("edits-container")
4588                    .cursor_pointer()
4589                    .gap_1()
4590                    .child(Disclosure::new("edits-disclosure", expanded))
4591                    .map(|this| {
4592                        if pending_edits {
4593                            this.child(
4594                                Label::new(format!(
4595                                    "Editing {} {}",
4596                                    changed_buffers.len(),
4597                                    if changed_buffers.len() == 1 {
4598                                        "file"
4599                                    } else {
4600                                        "files"
4601                                    }
4602                                ))
4603                                .color(Color::Muted)
4604                                .size(LabelSize::Small)
4605                                .with_animation(
4606                                    "edit-label",
4607                                    Animation::new(Duration::from_secs(2))
4608                                        .repeat()
4609                                        .with_easing(pulsating_between(0.3, 0.7)),
4610                                    |label, delta| label.alpha(delta),
4611                                ),
4612                            )
4613                        } else {
4614                            let stats = DiffStats::all_files(changed_buffers, cx);
4615                            let dot_divider = || {
4616                                Label::new("")
4617                                    .size(LabelSize::XSmall)
4618                                    .color(Color::Disabled)
4619                            };
4620
4621                            this.child(
4622                                Label::new("Edits")
4623                                    .size(LabelSize::Small)
4624                                    .color(Color::Muted),
4625                            )
4626                            .child(dot_divider())
4627                            .child(
4628                                Label::new(format!(
4629                                    "{} {}",
4630                                    changed_buffers.len(),
4631                                    if changed_buffers.len() == 1 {
4632                                        "file"
4633                                    } else {
4634                                        "files"
4635                                    }
4636                                ))
4637                                .size(LabelSize::Small)
4638                                .color(Color::Muted),
4639                            )
4640                            .child(dot_divider())
4641                            .child(DiffStat::new(
4642                                "total",
4643                                stats.lines_added as usize,
4644                                stats.lines_removed as usize,
4645                            ))
4646                        }
4647                    })
4648                    .on_click(cx.listener(|this, _, _, cx| {
4649                        this.edits_expanded = !this.edits_expanded;
4650                        cx.notify();
4651                    })),
4652            )
4653            .child(
4654                h_flex()
4655                    .gap_1()
4656                    .child(
4657                        IconButton::new("review-changes", IconName::ListTodo)
4658                            .icon_size(IconSize::Small)
4659                            .tooltip({
4660                                let focus_handle = focus_handle.clone();
4661                                move |_window, cx| {
4662                                    Tooltip::for_action_in(
4663                                        "Review Changes",
4664                                        &OpenAgentDiff,
4665                                        &focus_handle,
4666                                        cx,
4667                                    )
4668                                }
4669                            })
4670                            .on_click(cx.listener(|_, _, window, cx| {
4671                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
4672                            })),
4673                    )
4674                    .child(Divider::vertical().color(DividerColor::Border))
4675                    .child(
4676                        Button::new("reject-all-changes", "Reject All")
4677                            .label_size(LabelSize::Small)
4678                            .disabled(pending_edits)
4679                            .when(pending_edits, |this| {
4680                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
4681                            })
4682                            .key_binding(
4683                                KeyBinding::for_action_in(&RejectAll, &focus_handle.clone(), cx)
4684                                    .map(|kb| kb.size(rems_from_px(10.))),
4685                            )
4686                            .on_click(cx.listener(move |this, _, window, cx| {
4687                                this.reject_all(&RejectAll, window, cx);
4688                            })),
4689                    )
4690                    .child(
4691                        Button::new("keep-all-changes", "Keep All")
4692                            .label_size(LabelSize::Small)
4693                            .disabled(pending_edits)
4694                            .when(pending_edits, |this| {
4695                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
4696                            })
4697                            .key_binding(
4698                                KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
4699                                    .map(|kb| kb.size(rems_from_px(10.))),
4700                            )
4701                            .on_click(cx.listener(move |this, _, window, cx| {
4702                                this.keep_all(&KeepAll, window, cx);
4703                            })),
4704                    ),
4705            )
4706    }
4707
4708    fn render_edited_files(
4709        &self,
4710        action_log: &Entity<ActionLog>,
4711        telemetry: ActionLogTelemetry,
4712        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4713        pending_edits: bool,
4714        cx: &Context<Self>,
4715    ) -> impl IntoElement {
4716        let editor_bg_color = cx.theme().colors().editor_background;
4717
4718        v_flex()
4719            .id("edited_files_list")
4720            .max_h_40()
4721            .overflow_y_scroll()
4722            .children(
4723                changed_buffers
4724                    .iter()
4725                    .enumerate()
4726                    .flat_map(|(index, (buffer, diff))| {
4727                        let file = buffer.read(cx).file()?;
4728                        let path = file.path();
4729                        let path_style = file.path_style(cx);
4730                        let separator = file.path_style(cx).primary_separator();
4731
4732                        let file_path = path.parent().and_then(|parent| {
4733                            if parent.is_empty() {
4734                                None
4735                            } else {
4736                                Some(
4737                                    Label::new(format!(
4738                                        "{}{separator}",
4739                                        parent.display(path_style)
4740                                    ))
4741                                    .color(Color::Muted)
4742                                    .size(LabelSize::XSmall)
4743                                    .buffer_font(cx),
4744                                )
4745                            }
4746                        });
4747
4748                        let file_name = path.file_name().map(|name| {
4749                            Label::new(name.to_string())
4750                                .size(LabelSize::XSmall)
4751                                .buffer_font(cx)
4752                                .ml_1()
4753                        });
4754
4755                        let full_path = path.display(path_style).to_string();
4756
4757                        let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
4758                            .map(Icon::from_path)
4759                            .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
4760                            .unwrap_or_else(|| {
4761                                Icon::new(IconName::File)
4762                                    .color(Color::Muted)
4763                                    .size(IconSize::Small)
4764                            });
4765
4766                        let overlay_gradient = linear_gradient(
4767                            90.,
4768                            linear_color_stop(editor_bg_color, 1.),
4769                            linear_color_stop(editor_bg_color.opacity(0.2), 0.),
4770                        );
4771
4772                        let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
4773
4774                        let element = h_flex()
4775                            .group("edited-code")
4776                            .id(("file-container", index))
4777                            .py_1()
4778                            .pl_2()
4779                            .pr_1()
4780                            .gap_2()
4781                            .justify_between()
4782                            .bg(editor_bg_color)
4783                            .when(index < changed_buffers.len() - 1, |parent| {
4784                                parent.border_color(cx.theme().colors().border).border_b_1()
4785                            })
4786                            .child(
4787                                h_flex()
4788                                    .id(("file-name-row", index))
4789                                    .relative()
4790                                    .pr_8()
4791                                    .w_full()
4792                                    .child(
4793                                        h_flex()
4794                                            .id(("file-name-path", index))
4795                                            .cursor_pointer()
4796                                            .pr_0p5()
4797                                            .gap_0p5()
4798                                            .hover(|s| s.bg(cx.theme().colors().element_hover))
4799                                            .rounded_xs()
4800                                            .child(file_icon)
4801                                            .children(file_name)
4802                                            .children(file_path)
4803                                            .child(
4804                                                DiffStat::new(
4805                                                    "file",
4806                                                    file_stats.lines_added as usize,
4807                                                    file_stats.lines_removed as usize,
4808                                                )
4809                                                .label_size(LabelSize::XSmall),
4810                                            )
4811                                            .tooltip(move |_, cx| {
4812                                                Tooltip::with_meta(
4813                                                    "Go to File",
4814                                                    None,
4815                                                    full_path.clone(),
4816                                                    cx,
4817                                                )
4818                                            })
4819                                            .on_click({
4820                                                let buffer = buffer.clone();
4821                                                cx.listener(move |this, _, window, cx| {
4822                                                    this.open_edited_buffer(&buffer, window, cx);
4823                                                })
4824                                            }),
4825                                    )
4826                                    .child(
4827                                        div()
4828                                            .absolute()
4829                                            .h_full()
4830                                            .w_12()
4831                                            .top_0()
4832                                            .bottom_0()
4833                                            .right_0()
4834                                            .bg(overlay_gradient),
4835                                    ),
4836                            )
4837                            .child(
4838                                h_flex()
4839                                    .gap_1()
4840                                    .visible_on_hover("edited-code")
4841                                    .child(
4842                                        Button::new("review", "Review")
4843                                            .label_size(LabelSize::Small)
4844                                            .on_click({
4845                                                let buffer = buffer.clone();
4846                                                cx.listener(move |this, _, window, cx| {
4847                                                    this.open_edited_buffer(&buffer, window, cx);
4848                                                })
4849                                            }),
4850                                    )
4851                                    .child(Divider::vertical().color(DividerColor::BorderVariant))
4852                                    .child(
4853                                        Button::new("reject-file", "Reject")
4854                                            .label_size(LabelSize::Small)
4855                                            .disabled(pending_edits)
4856                                            .on_click({
4857                                                let buffer = buffer.clone();
4858                                                let action_log = action_log.clone();
4859                                                let telemetry = telemetry.clone();
4860                                                move |_, _, cx| {
4861                                                    action_log.update(cx, |action_log, cx| {
4862                                                        action_log
4863                                                    .reject_edits_in_ranges(
4864                                                        buffer.clone(),
4865                                                        vec![Anchor::min_max_range_for_buffer(
4866                                                            buffer.read(cx).remote_id(),
4867                                                        )],
4868                                                        Some(telemetry.clone()),
4869                                                        cx,
4870                                                    )
4871                                                    .detach_and_log_err(cx);
4872                                                    })
4873                                                }
4874                                            }),
4875                                    )
4876                                    .child(
4877                                        Button::new("keep-file", "Keep")
4878                                            .label_size(LabelSize::Small)
4879                                            .disabled(pending_edits)
4880                                            .on_click({
4881                                                let buffer = buffer.clone();
4882                                                let action_log = action_log.clone();
4883                                                let telemetry = telemetry.clone();
4884                                                move |_, _, cx| {
4885                                                    action_log.update(cx, |action_log, cx| {
4886                                                        action_log.keep_edits_in_range(
4887                                                            buffer.clone(),
4888                                                            Anchor::min_max_range_for_buffer(
4889                                                                buffer.read(cx).remote_id(),
4890                                                            ),
4891                                                            Some(telemetry.clone()),
4892                                                            cx,
4893                                                        );
4894                                                    })
4895                                                }
4896                                            }),
4897                                    ),
4898                            );
4899
4900                        Some(element)
4901                    }),
4902            )
4903            .into_any_element()
4904    }
4905
4906    fn render_message_queue_summary(
4907        &self,
4908        _window: &mut Window,
4909        cx: &Context<Self>,
4910    ) -> impl IntoElement {
4911        let queue_count = self.message_queue.len();
4912        let title: SharedString = if queue_count == 1 {
4913            "1 Queued Message".into()
4914        } else {
4915            format!("{} Queued Messages", queue_count).into()
4916        };
4917
4918        h_flex()
4919            .p_1()
4920            .w_full()
4921            .gap_1()
4922            .justify_between()
4923            .when(self.queue_expanded, |this| {
4924                this.border_b_1().border_color(cx.theme().colors().border)
4925            })
4926            .child(
4927                h_flex()
4928                    .id("queue_summary")
4929                    .gap_1()
4930                    .child(Disclosure::new("queue_disclosure", self.queue_expanded))
4931                    .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
4932                    .on_click(cx.listener(|this, _, _, cx| {
4933                        this.queue_expanded = !this.queue_expanded;
4934                        cx.notify();
4935                    })),
4936            )
4937            .child(
4938                Button::new("clear_queue", "Clear All")
4939                    .label_size(LabelSize::Small)
4940                    .key_binding(KeyBinding::for_action(&ClearMessageQueue, cx))
4941                    .on_click(cx.listener(|this, _, _, cx| {
4942                        this.message_queue.clear();
4943                        cx.notify();
4944                    })),
4945            )
4946    }
4947
4948    fn render_message_queue_entries(
4949        &self,
4950        _window: &mut Window,
4951        cx: &Context<Self>,
4952    ) -> impl IntoElement {
4953        let message_editor = self.message_editor.read(cx);
4954        let focus_handle = message_editor.focus_handle(cx);
4955
4956        v_flex()
4957            .id("message_queue_list")
4958            .max_h_40()
4959            .overflow_y_scroll()
4960            .children(
4961                self.message_queue
4962                    .iter()
4963                    .enumerate()
4964                    .map(|(index, queued)| {
4965                        let is_next = index == 0;
4966                        let icon_color = if is_next { Color::Accent } else { Color::Muted };
4967                        let queue_len = self.message_queue.len();
4968
4969                        let preview = queued
4970                            .content
4971                            .iter()
4972                            .find_map(|block| match block {
4973                                acp::ContentBlock::Text(text) => {
4974                                    text.text.lines().next().map(str::to_owned)
4975                                }
4976                                _ => None,
4977                            })
4978                            .unwrap_or_default();
4979
4980                        h_flex()
4981                            .group("queue_entry")
4982                            .w_full()
4983                            .p_1()
4984                            .pl_2()
4985                            .gap_1()
4986                            .justify_between()
4987                            .bg(cx.theme().colors().editor_background)
4988                            .when(index < queue_len - 1, |parent| {
4989                                parent.border_color(cx.theme().colors().border).border_b_1()
4990                            })
4991                            .child(
4992                                h_flex()
4993                                    .id(("queued_prompt", index))
4994                                    .min_w_0()
4995                                    .w_full()
4996                                    .gap_1p5()
4997                                    .child(
4998                                        Icon::new(IconName::Circle)
4999                                            .size(IconSize::Small)
5000                                            .color(icon_color),
5001                                    )
5002                                    .child(
5003                                        Label::new(preview)
5004                                            .size(LabelSize::XSmall)
5005                                            .color(Color::Muted)
5006                                            .buffer_font(cx)
5007                                            .truncate(),
5008                                    )
5009                                    .when(is_next, |this| {
5010                                        this.tooltip(Tooltip::text("Next Prompt in the Queue"))
5011                                    }),
5012                            )
5013                            .child(
5014                                h_flex()
5015                                    .flex_none()
5016                                    .gap_1()
5017                                    .visible_on_hover("queue_entry")
5018                                    .child(
5019                                        Button::new(("delete", index), "Remove")
5020                                            .label_size(LabelSize::Small)
5021                                            .on_click(cx.listener(move |this, _, _, cx| {
5022                                                if index < this.message_queue.len() {
5023                                                    this.message_queue.remove(index);
5024                                                    cx.notify();
5025                                                }
5026                                            })),
5027                                    )
5028                                    .child(
5029                                        Button::new(("send_now", index), "Send Now")
5030                                            .style(ButtonStyle::Outlined)
5031                                            .label_size(LabelSize::Small)
5032                                            .when(is_next, |this| {
5033                                                this.key_binding(
5034                                                    KeyBinding::for_action_in(
5035                                                        &SendNextQueuedMessage,
5036                                                        &focus_handle.clone(),
5037                                                        cx,
5038                                                    )
5039                                                    .map(|kb| kb.size(rems_from_px(10.))),
5040                                                )
5041                                            })
5042                                            .on_click(cx.listener(move |this, _, window, cx| {
5043                                                this.send_queued_message_at_index(
5044                                                    index, true, window, cx,
5045                                                );
5046                                            })),
5047                                    ),
5048                            )
5049                    }),
5050            )
5051            .into_any_element()
5052    }
5053
5054    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
5055        let focus_handle = self.message_editor.focus_handle(cx);
5056        let editor_bg_color = cx.theme().colors().editor_background;
5057        let (expand_icon, expand_tooltip) = if self.editor_expanded {
5058            (IconName::Minimize, "Minimize Message Editor")
5059        } else {
5060            (IconName::Maximize, "Expand Message Editor")
5061        };
5062
5063        let backdrop = div()
5064            .size_full()
5065            .absolute()
5066            .inset_0()
5067            .bg(cx.theme().colors().panel_background)
5068            .opacity(0.8)
5069            .block_mouse_except_scroll();
5070
5071        let enable_editor = match self.thread_state {
5072            ThreadState::Ready { .. } => true,
5073            ThreadState::Loading { .. }
5074            | ThreadState::Unauthenticated { .. }
5075            | ThreadState::LoadError(..) => false,
5076        };
5077
5078        v_flex()
5079            .on_action(cx.listener(Self::expand_message_editor))
5080            .p_2()
5081            .gap_2()
5082            .border_t_1()
5083            .border_color(cx.theme().colors().border)
5084            .bg(editor_bg_color)
5085            .when(self.editor_expanded, |this| {
5086                this.h(vh(0.8, window)).size_full().justify_between()
5087            })
5088            .child(
5089                v_flex()
5090                    .relative()
5091                    .size_full()
5092                    .pt_1()
5093                    .pr_2p5()
5094                    .child(self.message_editor.clone())
5095                    .child(
5096                        h_flex()
5097                            .absolute()
5098                            .top_0()
5099                            .right_0()
5100                            .opacity(0.5)
5101                            .hover(|this| this.opacity(1.0))
5102                            .child(
5103                                IconButton::new("toggle-height", expand_icon)
5104                                    .icon_size(IconSize::Small)
5105                                    .icon_color(Color::Muted)
5106                                    .tooltip({
5107                                        move |_window, cx| {
5108                                            Tooltip::for_action_in(
5109                                                expand_tooltip,
5110                                                &ExpandMessageEditor,
5111                                                &focus_handle,
5112                                                cx,
5113                                            )
5114                                        }
5115                                    })
5116                                    .on_click(cx.listener(|this, _, window, cx| {
5117                                        this.expand_message_editor(
5118                                            &ExpandMessageEditor,
5119                                            window,
5120                                            cx,
5121                                        );
5122                                    })),
5123                            ),
5124                    ),
5125            )
5126            .child(
5127                h_flex()
5128                    .flex_none()
5129                    .flex_wrap()
5130                    .justify_between()
5131                    .child(
5132                        h_flex()
5133                            .gap_0p5()
5134                            .child(self.render_add_context_button(cx))
5135                            .child(self.render_follow_toggle(cx))
5136                            .children(self.render_burn_mode_toggle(cx)),
5137                    )
5138                    .child(
5139                        h_flex()
5140                            .gap_1()
5141                            .children(self.render_token_usage(cx))
5142                            .children(self.profile_selector.clone())
5143                            // Either config_options_view OR (mode_selector + model_selector)
5144                            .children(self.config_options_view.clone())
5145                            .when(self.config_options_view.is_none(), |this| {
5146                                this.children(self.mode_selector().cloned())
5147                                    .children(self.model_selector.clone())
5148                            })
5149                            .child(self.render_send_button(cx)),
5150                    ),
5151            )
5152            .when(!enable_editor, |this| this.child(backdrop))
5153            .into_any()
5154    }
5155
5156    pub(crate) fn as_native_connection(
5157        &self,
5158        cx: &App,
5159    ) -> Option<Rc<agent::NativeAgentConnection>> {
5160        let acp_thread = self.thread()?.read(cx);
5161        acp_thread.connection().clone().downcast()
5162    }
5163
5164    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
5165        let acp_thread = self.thread()?.read(cx);
5166        self.as_native_connection(cx)?
5167            .thread(acp_thread.session_id(), cx)
5168    }
5169
5170    fn is_imported_thread(&self, cx: &App) -> bool {
5171        let Some(thread) = self.as_native_thread(cx) else {
5172            return false;
5173        };
5174        thread.read(cx).is_imported()
5175    }
5176
5177    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
5178        self.as_native_thread(cx)
5179            .and_then(|thread| thread.read(cx).model())
5180            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
5181    }
5182
5183    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
5184        let thread = self.thread()?.read(cx);
5185        let usage = thread.token_usage()?;
5186        let is_generating = thread.status() != ThreadStatus::Idle;
5187
5188        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
5189        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
5190
5191        Some(
5192            h_flex()
5193                .flex_shrink_0()
5194                .gap_0p5()
5195                .mr_1p5()
5196                .child(
5197                    Label::new(used)
5198                        .size(LabelSize::Small)
5199                        .color(Color::Muted)
5200                        .map(|label| {
5201                            if is_generating {
5202                                label
5203                                    .with_animation(
5204                                        "used-tokens-label",
5205                                        Animation::new(Duration::from_secs(2))
5206                                            .repeat()
5207                                            .with_easing(pulsating_between(0.3, 0.8)),
5208                                        |label, delta| label.alpha(delta),
5209                                    )
5210                                    .into_any()
5211                            } else {
5212                                label.into_any_element()
5213                            }
5214                        }),
5215                )
5216                .child(
5217                    Label::new("/")
5218                        .size(LabelSize::Small)
5219                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
5220                )
5221                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
5222        )
5223    }
5224
5225    fn toggle_burn_mode(
5226        &mut self,
5227        _: &ToggleBurnMode,
5228        _window: &mut Window,
5229        cx: &mut Context<Self>,
5230    ) {
5231        let Some(thread) = self.as_native_thread(cx) else {
5232            return;
5233        };
5234
5235        thread.update(cx, |thread, cx| {
5236            let current_mode = thread.completion_mode();
5237            thread.set_completion_mode(
5238                match current_mode {
5239                    CompletionMode::Burn => CompletionMode::Normal,
5240                    CompletionMode::Normal => CompletionMode::Burn,
5241                },
5242                cx,
5243            );
5244        });
5245    }
5246
5247    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
5248        let Some(thread) = self.thread() else {
5249            return;
5250        };
5251        let telemetry = ActionLogTelemetry::from(thread.read(cx));
5252        let action_log = thread.read(cx).action_log().clone();
5253        action_log.update(cx, |action_log, cx| {
5254            action_log.keep_all_edits(Some(telemetry), cx)
5255        });
5256    }
5257
5258    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
5259        let Some(thread) = self.thread() else {
5260            return;
5261        };
5262        let telemetry = ActionLogTelemetry::from(thread.read(cx));
5263        let action_log = thread.read(cx).action_log().clone();
5264        action_log
5265            .update(cx, |action_log, cx| {
5266                action_log.reject_all_edits(Some(telemetry), cx)
5267            })
5268            .detach();
5269    }
5270
5271    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
5272        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
5273    }
5274
5275    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
5276        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
5277    }
5278
5279    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
5280        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
5281    }
5282
5283    fn authorize_pending_tool_call(
5284        &mut self,
5285        kind: acp::PermissionOptionKind,
5286        window: &mut Window,
5287        cx: &mut Context<Self>,
5288    ) -> Option<()> {
5289        let thread = self.thread()?.read(cx);
5290        let tool_call = thread.first_tool_awaiting_confirmation()?;
5291        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
5292            return None;
5293        };
5294        let option = options.iter().find(|o| o.kind == kind)?;
5295
5296        self.authorize_tool_call(
5297            tool_call.id.clone(),
5298            option.option_id.clone(),
5299            option.kind,
5300            window,
5301            cx,
5302        );
5303
5304        Some(())
5305    }
5306
5307    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
5308        let thread = self.as_native_thread(cx)?.read(cx);
5309
5310        if thread
5311            .model()
5312            .is_none_or(|model| !model.supports_burn_mode())
5313        {
5314            return None;
5315        }
5316
5317        let active_completion_mode = thread.completion_mode();
5318        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
5319        let icon = if burn_mode_enabled {
5320            IconName::ZedBurnModeOn
5321        } else {
5322            IconName::ZedBurnMode
5323        };
5324
5325        Some(
5326            IconButton::new("burn-mode", icon)
5327                .icon_size(IconSize::Small)
5328                .icon_color(Color::Muted)
5329                .toggle_state(burn_mode_enabled)
5330                .selected_icon_color(Color::Error)
5331                .on_click(cx.listener(|this, _event, window, cx| {
5332                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5333                }))
5334                .tooltip(move |_window, cx| {
5335                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
5336                        .into()
5337                })
5338                .into_any_element(),
5339        )
5340    }
5341
5342    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
5343        let message_editor = self.message_editor.read(cx);
5344        let is_editor_empty = message_editor.is_empty(cx);
5345        let focus_handle = message_editor.focus_handle(cx);
5346
5347        let is_generating = self
5348            .thread()
5349            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
5350
5351        if self.is_loading_contents {
5352            div()
5353                .id("loading-message-content")
5354                .px_1()
5355                .tooltip(Tooltip::text("Loading Added Context…"))
5356                .child(loading_contents_spinner(IconSize::default()))
5357                .into_any_element()
5358        } else if is_generating && is_editor_empty {
5359            IconButton::new("stop-generation", IconName::Stop)
5360                .icon_color(Color::Error)
5361                .style(ButtonStyle::Tinted(TintColor::Error))
5362                .tooltip(move |_window, cx| {
5363                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
5364                })
5365                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
5366                .into_any_element()
5367        } else {
5368            IconButton::new("send-message", IconName::Send)
5369                .style(ButtonStyle::Filled)
5370                .map(|this| {
5371                    if is_editor_empty && !is_generating {
5372                        this.disabled(true).icon_color(Color::Muted)
5373                    } else {
5374                        this.icon_color(Color::Accent)
5375                    }
5376                })
5377                .tooltip(move |_window, cx| {
5378                    if is_editor_empty && !is_generating {
5379                        Tooltip::for_action("Type to Send", &Chat, cx)
5380                    } else {
5381                        let title = if is_generating {
5382                            "Stop and Send Message"
5383                        } else {
5384                            "Send"
5385                        };
5386
5387                        let focus_handle = focus_handle.clone();
5388
5389                        Tooltip::element(move |_window, cx| {
5390                            v_flex()
5391                                .gap_1()
5392                                .child(
5393                                    h_flex()
5394                                        .gap_2()
5395                                        .justify_between()
5396                                        .child(Label::new(title))
5397                                        .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
5398                                )
5399                                .child(
5400                                    h_flex()
5401                                        .pt_1()
5402                                        .gap_2()
5403                                        .justify_between()
5404                                        .border_t_1()
5405                                        .border_color(cx.theme().colors().border_variant)
5406                                        .child(Label::new("Queue Message"))
5407                                        .child(KeyBinding::for_action_in(
5408                                            &QueueMessage,
5409                                            &focus_handle,
5410                                            cx,
5411                                        )),
5412                                )
5413                                .into_any_element()
5414                        })(_window, cx)
5415                    }
5416                })
5417                .on_click(cx.listener(|this, _, window, cx| {
5418                    this.send(window, cx);
5419                }))
5420                .into_any_element()
5421        }
5422    }
5423
5424    fn is_following(&self, cx: &App) -> bool {
5425        match self.thread().map(|thread| thread.read(cx).status()) {
5426            Some(ThreadStatus::Generating) => self
5427                .workspace
5428                .read_with(cx, |workspace, _| {
5429                    workspace.is_being_followed(CollaboratorId::Agent)
5430                })
5431                .unwrap_or(false),
5432            _ => self.should_be_following,
5433        }
5434    }
5435
5436    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5437        let following = self.is_following(cx);
5438
5439        self.should_be_following = !following;
5440        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
5441            self.workspace
5442                .update(cx, |workspace, cx| {
5443                    if following {
5444                        workspace.unfollow(CollaboratorId::Agent, window, cx);
5445                    } else {
5446                        workspace.follow(CollaboratorId::Agent, window, cx);
5447                    }
5448                })
5449                .ok();
5450        }
5451
5452        telemetry::event!("Follow Agent Selected", following = !following);
5453    }
5454
5455    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
5456        let following = self.is_following(cx);
5457
5458        let tooltip_label = if following {
5459            if self.agent.name() == "Zed Agent" {
5460                format!("Stop Following the {}", self.agent.name())
5461            } else {
5462                format!("Stop Following {}", self.agent.name())
5463            }
5464        } else {
5465            if self.agent.name() == "Zed Agent" {
5466                format!("Follow the {}", self.agent.name())
5467            } else {
5468                format!("Follow {}", self.agent.name())
5469            }
5470        };
5471
5472        IconButton::new("follow-agent", IconName::Crosshair)
5473            .icon_size(IconSize::Small)
5474            .icon_color(Color::Muted)
5475            .toggle_state(following)
5476            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
5477            .tooltip(move |_window, cx| {
5478                if following {
5479                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
5480                } else {
5481                    Tooltip::with_meta(
5482                        tooltip_label.clone(),
5483                        Some(&Follow),
5484                        "Track the agent's location as it reads and edits files.",
5485                        cx,
5486                    )
5487                }
5488            })
5489            .on_click(cx.listener(move |this, _, window, cx| {
5490                this.toggle_following(window, cx);
5491            }))
5492    }
5493
5494    fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5495        let message_editor = self.message_editor.clone();
5496        let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
5497
5498        IconButton::new("add-context", IconName::AtSign)
5499            .icon_size(IconSize::Small)
5500            .icon_color(Color::Muted)
5501            .when(!menu_visible, |this| {
5502                this.tooltip(move |_window, cx| {
5503                    Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
5504                })
5505            })
5506            .on_click(cx.listener(move |_this, _, window, cx| {
5507                let message_editor_clone = message_editor.clone();
5508
5509                window.defer(cx, move |window, cx| {
5510                    message_editor_clone.update(cx, |message_editor, cx| {
5511                        message_editor.trigger_completion_menu(window, cx);
5512                    });
5513                });
5514            }))
5515    }
5516
5517    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
5518        let workspace = self.workspace.clone();
5519        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
5520            Self::open_link(text, &workspace, window, cx);
5521        })
5522    }
5523
5524    fn open_link(
5525        url: SharedString,
5526        workspace: &WeakEntity<Workspace>,
5527        window: &mut Window,
5528        cx: &mut App,
5529    ) {
5530        let Some(workspace) = workspace.upgrade() else {
5531            cx.open_url(&url);
5532            return;
5533        };
5534
5535        if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
5536        {
5537            workspace.update(cx, |workspace, cx| match mention {
5538                MentionUri::File { abs_path } => {
5539                    let project = workspace.project();
5540                    let Some(path) =
5541                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
5542                    else {
5543                        return;
5544                    };
5545
5546                    workspace
5547                        .open_path(path, None, true, window, cx)
5548                        .detach_and_log_err(cx);
5549                }
5550                MentionUri::PastedImage => {}
5551                MentionUri::Directory { abs_path } => {
5552                    let project = workspace.project();
5553                    let Some(entry_id) = project.update(cx, |project, cx| {
5554                        let path = project.find_project_path(abs_path, cx)?;
5555                        project.entry_for_path(&path, cx).map(|entry| entry.id)
5556                    }) else {
5557                        return;
5558                    };
5559
5560                    project.update(cx, |_, cx| {
5561                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
5562                    });
5563                }
5564                MentionUri::Symbol {
5565                    abs_path: path,
5566                    line_range,
5567                    ..
5568                }
5569                | MentionUri::Selection {
5570                    abs_path: Some(path),
5571                    line_range,
5572                } => {
5573                    let project = workspace.project();
5574                    let Some(path) =
5575                        project.update(cx, |project, cx| project.find_project_path(path, cx))
5576                    else {
5577                        return;
5578                    };
5579
5580                    let item = workspace.open_path(path, None, true, window, cx);
5581                    window
5582                        .spawn(cx, async move |cx| {
5583                            let Some(editor) = item.await?.downcast::<Editor>() else {
5584                                return Ok(());
5585                            };
5586                            let range = Point::new(*line_range.start(), 0)
5587                                ..Point::new(*line_range.start(), 0);
5588                            editor
5589                                .update_in(cx, |editor, window, cx| {
5590                                    editor.change_selections(
5591                                        SelectionEffects::scroll(Autoscroll::center()),
5592                                        window,
5593                                        cx,
5594                                        |s| s.select_ranges(vec![range]),
5595                                    );
5596                                })
5597                                .ok();
5598                            anyhow::Ok(())
5599                        })
5600                        .detach_and_log_err(cx);
5601                }
5602                MentionUri::Selection { abs_path: None, .. } => {}
5603                MentionUri::Thread { id, name } => {
5604                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5605                        panel.update(cx, |panel, cx| {
5606                            panel.load_agent_thread(
5607                                DbThreadMetadata {
5608                                    id,
5609                                    title: name.into(),
5610                                    updated_at: Default::default(),
5611                                },
5612                                window,
5613                                cx,
5614                            )
5615                        });
5616                    }
5617                }
5618                MentionUri::TextThread { path, .. } => {
5619                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5620                        panel.update(cx, |panel, cx| {
5621                            panel
5622                                .open_saved_text_thread(path.as_path().into(), window, cx)
5623                                .detach_and_log_err(cx);
5624                        });
5625                    }
5626                }
5627                MentionUri::Rule { id, .. } => {
5628                    let PromptId::User { uuid } = id else {
5629                        return;
5630                    };
5631                    window.dispatch_action(
5632                        Box::new(OpenRulesLibrary {
5633                            prompt_to_select: Some(uuid.0),
5634                        }),
5635                        cx,
5636                    )
5637                }
5638                MentionUri::Fetch { url } => {
5639                    cx.open_url(url.as_str());
5640                }
5641            })
5642        } else {
5643            cx.open_url(&url);
5644        }
5645    }
5646
5647    fn open_tool_call_location(
5648        &self,
5649        entry_ix: usize,
5650        location_ix: usize,
5651        window: &mut Window,
5652        cx: &mut Context<Self>,
5653    ) -> Option<()> {
5654        let (tool_call_location, agent_location) = self
5655            .thread()?
5656            .read(cx)
5657            .entries()
5658            .get(entry_ix)?
5659            .location(location_ix)?;
5660
5661        let project_path = self
5662            .project
5663            .read(cx)
5664            .find_project_path(&tool_call_location.path, cx)?;
5665
5666        let open_task = self
5667            .workspace
5668            .update(cx, |workspace, cx| {
5669                workspace.open_path(project_path, None, true, window, cx)
5670            })
5671            .log_err()?;
5672        window
5673            .spawn(cx, async move |cx| {
5674                let item = open_task.await?;
5675
5676                let Some(active_editor) = item.downcast::<Editor>() else {
5677                    return anyhow::Ok(());
5678                };
5679
5680                active_editor.update_in(cx, |editor, window, cx| {
5681                    let multibuffer = editor.buffer().read(cx);
5682                    let buffer = multibuffer.as_singleton();
5683                    if agent_location.buffer.upgrade() == buffer {
5684                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
5685                        let anchor =
5686                            editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
5687                        editor.change_selections(Default::default(), window, cx, |selections| {
5688                            selections.select_anchor_ranges([anchor..anchor]);
5689                        })
5690                    } else {
5691                        let row = tool_call_location.line.unwrap_or_default();
5692                        editor.change_selections(Default::default(), window, cx, |selections| {
5693                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
5694                        })
5695                    }
5696                })?;
5697
5698                anyhow::Ok(())
5699            })
5700            .detach_and_log_err(cx);
5701
5702        None
5703    }
5704
5705    pub fn open_thread_as_markdown(
5706        &self,
5707        workspace: Entity<Workspace>,
5708        window: &mut Window,
5709        cx: &mut App,
5710    ) -> Task<Result<()>> {
5711        let markdown_language_task = workspace
5712            .read(cx)
5713            .app_state()
5714            .languages
5715            .language_for_name("Markdown");
5716
5717        let (thread_title, markdown) = if let Some(thread) = self.thread() {
5718            let thread = thread.read(cx);
5719            (thread.title().to_string(), thread.to_markdown(cx))
5720        } else {
5721            return Task::ready(Ok(()));
5722        };
5723
5724        let project = workspace.read(cx).project().clone();
5725        window.spawn(cx, async move |cx| {
5726            let markdown_language = markdown_language_task.await?;
5727
5728            let buffer = project
5729                .update(cx, |project, cx| project.create_buffer(false, cx))
5730                .await?;
5731
5732            buffer.update(cx, |buffer, cx| {
5733                buffer.set_text(markdown, cx);
5734                buffer.set_language(Some(markdown_language), cx);
5735                buffer.set_capability(language::Capability::ReadWrite, cx);
5736            });
5737
5738            workspace.update_in(cx, |workspace, window, cx| {
5739                let buffer = cx
5740                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5741
5742                workspace.add_item_to_active_pane(
5743                    Box::new(cx.new(|cx| {
5744                        let mut editor =
5745                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5746                        editor.set_breadcrumb_header(thread_title);
5747                        editor
5748                    })),
5749                    None,
5750                    true,
5751                    window,
5752                    cx,
5753                );
5754            })?;
5755            anyhow::Ok(())
5756        })
5757    }
5758
5759    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
5760        self.list_state.scroll_to(ListOffset::default());
5761        cx.notify();
5762    }
5763
5764    fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
5765        let Some(thread) = self.thread() else {
5766            return;
5767        };
5768
5769        let entries = thread.read(cx).entries();
5770        if entries.is_empty() {
5771            return;
5772        }
5773
5774        // Find the most recent user message and scroll it to the top of the viewport.
5775        // (Fallback: if no user message exists, scroll to the bottom.)
5776        if let Some(ix) = entries
5777            .iter()
5778            .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
5779        {
5780            self.list_state.scroll_to(ListOffset {
5781                item_ix: ix,
5782                offset_in_item: px(0.0),
5783            });
5784            cx.notify();
5785        } else {
5786            self.scroll_to_bottom(cx);
5787        }
5788    }
5789
5790    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
5791        if let Some(thread) = self.thread() {
5792            let entry_count = thread.read(cx).entries().len();
5793            self.list_state.reset(entry_count);
5794            cx.notify();
5795        }
5796    }
5797
5798    fn notify_with_sound(
5799        &mut self,
5800        caption: impl Into<SharedString>,
5801        icon: IconName,
5802        window: &mut Window,
5803        cx: &mut Context<Self>,
5804    ) {
5805        self.play_notification_sound(window, cx);
5806        self.show_notification(caption, icon, window, cx);
5807    }
5808
5809    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
5810        let settings = AgentSettings::get_global(cx);
5811        if settings.play_sound_when_agent_done && !window.is_window_active() {
5812            Audio::play_sound(Sound::AgentDone, cx);
5813        }
5814    }
5815
5816    fn show_notification(
5817        &mut self,
5818        caption: impl Into<SharedString>,
5819        icon: IconName,
5820        window: &mut Window,
5821        cx: &mut Context<Self>,
5822    ) {
5823        if !self.notifications.is_empty() {
5824            return;
5825        }
5826
5827        let settings = AgentSettings::get_global(cx);
5828
5829        let window_is_inactive = !window.is_window_active();
5830        let panel_is_hidden = self
5831            .workspace
5832            .upgrade()
5833            .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
5834            .unwrap_or(true);
5835
5836        let should_notify = window_is_inactive || panel_is_hidden;
5837
5838        if !should_notify {
5839            return;
5840        }
5841
5842        // TODO: Change this once we have title summarization for external agents.
5843        let title = self.agent.name();
5844
5845        match settings.notify_when_agent_waiting {
5846            NotifyWhenAgentWaiting::PrimaryScreen => {
5847                if let Some(primary) = cx.primary_display() {
5848                    self.pop_up(icon, caption.into(), title, window, primary, cx);
5849                }
5850            }
5851            NotifyWhenAgentWaiting::AllScreens => {
5852                let caption = caption.into();
5853                for screen in cx.displays() {
5854                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
5855                }
5856            }
5857            NotifyWhenAgentWaiting::Never => {
5858                // Don't show anything
5859            }
5860        }
5861    }
5862
5863    fn pop_up(
5864        &mut self,
5865        icon: IconName,
5866        caption: SharedString,
5867        title: SharedString,
5868        window: &mut Window,
5869        screen: Rc<dyn PlatformDisplay>,
5870        cx: &mut Context<Self>,
5871    ) {
5872        let options = AgentNotification::window_options(screen, cx);
5873
5874        let project_name = self.workspace.upgrade().and_then(|workspace| {
5875            workspace
5876                .read(cx)
5877                .project()
5878                .read(cx)
5879                .visible_worktrees(cx)
5880                .next()
5881                .map(|worktree| worktree.read(cx).root_name_str().to_string())
5882        });
5883
5884        if let Some(screen_window) = cx
5885            .open_window(options, |_window, cx| {
5886                cx.new(|_cx| {
5887                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
5888                })
5889            })
5890            .log_err()
5891            && let Some(pop_up) = screen_window.entity(cx).log_err()
5892        {
5893            self.notification_subscriptions
5894                .entry(screen_window)
5895                .or_insert_with(Vec::new)
5896                .push(cx.subscribe_in(&pop_up, window, {
5897                    |this, _, event, window, cx| match event {
5898                        AgentNotificationEvent::Accepted => {
5899                            let handle = window.window_handle();
5900                            cx.activate(true);
5901
5902                            let workspace_handle = this.workspace.clone();
5903
5904                            // If there are multiple Zed windows, activate the correct one.
5905                            cx.defer(move |cx| {
5906                                handle
5907                                    .update(cx, |_view, window, _cx| {
5908                                        window.activate_window();
5909
5910                                        if let Some(workspace) = workspace_handle.upgrade() {
5911                                            workspace.update(_cx, |workspace, cx| {
5912                                                workspace.focus_panel::<AgentPanel>(window, cx);
5913                                            });
5914                                        }
5915                                    })
5916                                    .log_err();
5917                            });
5918
5919                            this.dismiss_notifications(cx);
5920                        }
5921                        AgentNotificationEvent::Dismissed => {
5922                            this.dismiss_notifications(cx);
5923                        }
5924                    }
5925                }));
5926
5927            self.notifications.push(screen_window);
5928
5929            // If the user manually refocuses the original window, dismiss the popup.
5930            self.notification_subscriptions
5931                .entry(screen_window)
5932                .or_insert_with(Vec::new)
5933                .push({
5934                    let pop_up_weak = pop_up.downgrade();
5935
5936                    cx.observe_window_activation(window, move |_, window, cx| {
5937                        if window.is_window_active()
5938                            && let Some(pop_up) = pop_up_weak.upgrade()
5939                        {
5940                            pop_up.update(cx, |_, cx| {
5941                                cx.emit(AgentNotificationEvent::Dismissed);
5942                            });
5943                        }
5944                    })
5945                });
5946        }
5947    }
5948
5949    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
5950        for window in self.notifications.drain(..) {
5951            window
5952                .update(cx, |_, window, _| {
5953                    window.remove_window();
5954                })
5955                .ok();
5956
5957            self.notification_subscriptions.remove(&window);
5958        }
5959    }
5960
5961    fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
5962        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
5963        let elapsed_label = show_stats
5964            .then(|| {
5965                self.turn_started_at.and_then(|started_at| {
5966                    let elapsed = started_at.elapsed();
5967                    (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
5968                })
5969            })
5970            .flatten();
5971
5972        let is_waiting = confirmation
5973            || self
5974                .thread()
5975                .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
5976
5977        let turn_tokens_label = elapsed_label
5978            .is_some()
5979            .then(|| {
5980                self.turn_tokens
5981                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
5982                    .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
5983            })
5984            .flatten();
5985
5986        let arrow_icon = if is_waiting {
5987            IconName::ArrowUp
5988        } else {
5989            IconName::ArrowDown
5990        };
5991
5992        h_flex()
5993            .id("generating-spinner")
5994            .py_2()
5995            .px(rems_from_px(22.))
5996            .gap_2()
5997            .map(|this| {
5998                if confirmation {
5999                    this.child(
6000                        h_flex()
6001                            .w_2()
6002                            .child(SpinnerLabel::sand().size(LabelSize::Small)),
6003                    )
6004                    .child(
6005                        div().min_w(rems(8.)).child(
6006                            LoadingLabel::new("Waiting Confirmation")
6007                                .size(LabelSize::Small)
6008                                .color(Color::Muted),
6009                        ),
6010                    )
6011                } else {
6012                    this.child(SpinnerLabel::new().size(LabelSize::Small))
6013                }
6014            })
6015            .when_some(elapsed_label, |this, elapsed| {
6016                this.child(
6017                    Label::new(elapsed)
6018                        .size(LabelSize::Small)
6019                        .color(Color::Muted),
6020                )
6021            })
6022            .when_some(turn_tokens_label, |this, tokens| {
6023                this.child(
6024                    h_flex()
6025                        .gap_0p5()
6026                        .child(
6027                            Icon::new(arrow_icon)
6028                                .size(IconSize::XSmall)
6029                                .color(Color::Muted),
6030                        )
6031                        .child(
6032                            Label::new(format!("{} tokens", tokens))
6033                                .size(LabelSize::Small)
6034                                .color(Color::Muted),
6035                        ),
6036                )
6037            })
6038            .into_any_element()
6039    }
6040
6041    fn render_thread_controls(
6042        &self,
6043        thread: &Entity<AcpThread>,
6044        cx: &Context<Self>,
6045    ) -> impl IntoElement {
6046        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
6047        if is_generating {
6048            return self.render_generating(false, cx).into_any_element();
6049        }
6050
6051        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
6052            .shape(ui::IconButtonShape::Square)
6053            .icon_size(IconSize::Small)
6054            .icon_color(Color::Ignored)
6055            .tooltip(Tooltip::text("Open Thread as Markdown"))
6056            .on_click(cx.listener(move |this, _, window, cx| {
6057                if let Some(workspace) = this.workspace.upgrade() {
6058                    this.open_thread_as_markdown(workspace, window, cx)
6059                        .detach_and_log_err(cx);
6060                }
6061            }));
6062
6063        let scroll_to_recent_user_prompt =
6064            IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
6065                .shape(ui::IconButtonShape::Square)
6066                .icon_size(IconSize::Small)
6067                .icon_color(Color::Ignored)
6068                .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
6069                .on_click(cx.listener(move |this, _, _, cx| {
6070                    this.scroll_to_most_recent_user_prompt(cx);
6071                }));
6072
6073        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
6074            .shape(ui::IconButtonShape::Square)
6075            .icon_size(IconSize::Small)
6076            .icon_color(Color::Ignored)
6077            .tooltip(Tooltip::text("Scroll To Top"))
6078            .on_click(cx.listener(move |this, _, _, cx| {
6079                this.scroll_to_top(cx);
6080            }));
6081
6082        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6083        let last_turn_clock = show_stats
6084            .then(|| {
6085                self.last_turn_duration
6086                    .filter(|&duration| duration > STOPWATCH_THRESHOLD)
6087                    .map(|duration| {
6088                        Label::new(duration_alt_display(duration))
6089                            .size(LabelSize::Small)
6090                            .color(Color::Muted)
6091                    })
6092            })
6093            .flatten();
6094
6095        let last_turn_tokens = last_turn_clock
6096            .is_some()
6097            .then(|| {
6098                self.last_turn_tokens
6099                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6100                    .map(|tokens| {
6101                        Label::new(format!(
6102                            "{} tokens",
6103                            crate::text_thread_editor::humanize_token_count(tokens)
6104                        ))
6105                        .size(LabelSize::Small)
6106                        .color(Color::Muted)
6107                    })
6108            })
6109            .flatten();
6110
6111        let mut container = h_flex()
6112            .w_full()
6113            .py_2()
6114            .px_5()
6115            .gap_px()
6116            .opacity(0.6)
6117            .hover(|s| s.opacity(1.))
6118            .justify_end()
6119            .when(
6120                last_turn_tokens.is_some() || last_turn_clock.is_some(),
6121                |this| {
6122                    this.child(
6123                        h_flex()
6124                            .gap_1()
6125                            .px_1()
6126                            .when_some(last_turn_tokens, |this, label| this.child(label))
6127                            .when_some(last_turn_clock, |this, label| this.child(label)),
6128                    )
6129                },
6130            );
6131
6132        if AgentSettings::get_global(cx).enable_feedback
6133            && self
6134                .thread()
6135                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
6136        {
6137            let feedback = self.thread_feedback.feedback;
6138
6139            let tooltip_meta = || {
6140                SharedString::new(
6141                    "Rating the thread sends all of your current conversation to the Zed team.",
6142                )
6143            };
6144
6145            container = container
6146                .child(
6147                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
6148                        .shape(ui::IconButtonShape::Square)
6149                        .icon_size(IconSize::Small)
6150                        .icon_color(match feedback {
6151                            Some(ThreadFeedback::Positive) => Color::Accent,
6152                            _ => Color::Ignored,
6153                        })
6154                        .tooltip(move |window, cx| match feedback {
6155                            Some(ThreadFeedback::Positive) => {
6156                                Tooltip::text("Thanks for your feedback!")(window, cx)
6157                            }
6158                            _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
6159                        })
6160                        .on_click(cx.listener(move |this, _, window, cx| {
6161                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
6162                        })),
6163                )
6164                .child(
6165                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
6166                        .shape(ui::IconButtonShape::Square)
6167                        .icon_size(IconSize::Small)
6168                        .icon_color(match feedback {
6169                            Some(ThreadFeedback::Negative) => Color::Accent,
6170                            _ => Color::Ignored,
6171                        })
6172                        .tooltip(move |window, cx| match feedback {
6173                            Some(ThreadFeedback::Negative) => {
6174                                Tooltip::text(
6175                                    "We appreciate your feedback and will use it to improve in the future.",
6176                                )(window, cx)
6177                            }
6178                            _ => {
6179                                Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
6180                            }
6181                        })
6182                        .on_click(cx.listener(move |this, _, window, cx| {
6183                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
6184                        })),
6185                );
6186        }
6187
6188        if cx.has_flag::<AgentSharingFeatureFlag>()
6189            && self.is_imported_thread(cx)
6190            && self
6191                .project
6192                .read(cx)
6193                .client()
6194                .status()
6195                .borrow()
6196                .is_connected()
6197        {
6198            let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
6199                .shape(ui::IconButtonShape::Square)
6200                .icon_size(IconSize::Small)
6201                .icon_color(Color::Ignored)
6202                .tooltip(Tooltip::text("Sync with source thread"))
6203                .on_click(cx.listener(move |this, _, window, cx| {
6204                    this.sync_thread(window, cx);
6205                }));
6206
6207            container = container.child(sync_button);
6208        }
6209
6210        if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
6211            let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
6212                .shape(ui::IconButtonShape::Square)
6213                .icon_size(IconSize::Small)
6214                .icon_color(Color::Ignored)
6215                .tooltip(Tooltip::text("Share Thread"))
6216                .on_click(cx.listener(move |this, _, window, cx| {
6217                    this.share_thread(window, cx);
6218                }));
6219
6220            container = container.child(share_button);
6221        }
6222
6223        container
6224            .child(open_as_markdown)
6225            .child(scroll_to_recent_user_prompt)
6226            .child(scroll_to_top)
6227            .into_any_element()
6228    }
6229
6230    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
6231        h_flex()
6232            .key_context("AgentFeedbackMessageEditor")
6233            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
6234                this.thread_feedback.dismiss_comments();
6235                cx.notify();
6236            }))
6237            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
6238                this.submit_feedback_message(cx);
6239            }))
6240            .p_2()
6241            .mb_2()
6242            .mx_5()
6243            .gap_1()
6244            .rounded_md()
6245            .border_1()
6246            .border_color(cx.theme().colors().border)
6247            .bg(cx.theme().colors().editor_background)
6248            .child(div().w_full().child(editor))
6249            .child(
6250                h_flex()
6251                    .child(
6252                        IconButton::new("dismiss-feedback-message", IconName::Close)
6253                            .icon_color(Color::Error)
6254                            .icon_size(IconSize::XSmall)
6255                            .shape(ui::IconButtonShape::Square)
6256                            .on_click(cx.listener(move |this, _, _window, cx| {
6257                                this.thread_feedback.dismiss_comments();
6258                                cx.notify();
6259                            })),
6260                    )
6261                    .child(
6262                        IconButton::new("submit-feedback-message", IconName::Return)
6263                            .icon_size(IconSize::XSmall)
6264                            .shape(ui::IconButtonShape::Square)
6265                            .on_click(cx.listener(move |this, _, _window, cx| {
6266                                this.submit_feedback_message(cx);
6267                            })),
6268                    ),
6269            )
6270    }
6271
6272    fn handle_feedback_click(
6273        &mut self,
6274        feedback: ThreadFeedback,
6275        window: &mut Window,
6276        cx: &mut Context<Self>,
6277    ) {
6278        let Some(thread) = self.thread().cloned() else {
6279            return;
6280        };
6281
6282        self.thread_feedback.submit(thread, feedback, window, cx);
6283        cx.notify();
6284    }
6285
6286    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
6287        let Some(thread) = self.thread().cloned() else {
6288            return;
6289        };
6290
6291        self.thread_feedback.submit_comments(thread, cx);
6292        cx.notify();
6293    }
6294
6295    fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
6296        if self.token_limit_callout_dismissed {
6297            return None;
6298        }
6299
6300        let token_usage = self.thread()?.read(cx).token_usage()?;
6301        let ratio = token_usage.ratio();
6302
6303        let (severity, icon, title) = match ratio {
6304            acp_thread::TokenUsageRatio::Normal => return None,
6305            acp_thread::TokenUsageRatio::Warning => (
6306                Severity::Warning,
6307                IconName::Warning,
6308                "Thread reaching the token limit soon",
6309            ),
6310            acp_thread::TokenUsageRatio::Exceeded => (
6311                Severity::Error,
6312                IconName::XCircle,
6313                "Thread reached the token limit",
6314            ),
6315        };
6316
6317        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
6318            thread.read(cx).completion_mode() == CompletionMode::Normal
6319                && thread
6320                    .read(cx)
6321                    .model()
6322                    .is_some_and(|model| model.supports_burn_mode())
6323        });
6324
6325        let description = if burn_mode_available {
6326            "To continue, start a new thread from a summary or turn Burn Mode on."
6327        } else {
6328            "To continue, start a new thread from a summary."
6329        };
6330
6331        Some(
6332            Callout::new()
6333                .severity(severity)
6334                .icon(icon)
6335                .title(title)
6336                .description(description)
6337                .actions_slot(
6338                    h_flex()
6339                        .gap_0p5()
6340                        .child(
6341                            Button::new("start-new-thread", "Start New Thread")
6342                                .label_size(LabelSize::Small)
6343                                .on_click(cx.listener(|this, _, window, cx| {
6344                                    let Some(thread) = this.thread() else {
6345                                        return;
6346                                    };
6347                                    let session_id = thread.read(cx).session_id().clone();
6348                                    window.dispatch_action(
6349                                        crate::NewNativeAgentThreadFromSummary {
6350                                            from_session_id: session_id,
6351                                        }
6352                                        .boxed_clone(),
6353                                        cx,
6354                                    );
6355                                })),
6356                        )
6357                        .when(burn_mode_available, |this| {
6358                            this.child(
6359                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
6360                                    .icon_size(IconSize::XSmall)
6361                                    .on_click(cx.listener(|this, _event, window, cx| {
6362                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6363                                    })),
6364                            )
6365                        }),
6366                )
6367                .dismiss_action(self.dismiss_error_button(cx)),
6368        )
6369    }
6370
6371    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
6372        if !self.is_using_zed_ai_models(cx) {
6373            return None;
6374        }
6375
6376        let user_store = self.project.read(cx).user_store().read(cx);
6377        if user_store.is_usage_based_billing_enabled() {
6378            return None;
6379        }
6380
6381        let plan = user_store
6382            .plan()
6383            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
6384
6385        let usage = user_store.model_request_usage()?;
6386
6387        Some(
6388            div()
6389                .child(UsageCallout::new(plan, usage))
6390                .line_height(line_height),
6391        )
6392    }
6393
6394    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
6395        self.entry_view_state.update(cx, |entry_view_state, cx| {
6396            entry_view_state.agent_ui_font_size_changed(cx);
6397        });
6398    }
6399
6400    pub(crate) fn insert_dragged_files(
6401        &self,
6402        paths: Vec<project::ProjectPath>,
6403        added_worktrees: Vec<Entity<project::Worktree>>,
6404        window: &mut Window,
6405        cx: &mut Context<Self>,
6406    ) {
6407        self.message_editor.update(cx, |message_editor, cx| {
6408            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
6409        })
6410    }
6411
6412    /// Inserts the selected text into the message editor or the message being
6413    /// edited, if any.
6414    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
6415        self.active_editor(cx).update(cx, |editor, cx| {
6416            editor.insert_selections(window, cx);
6417        });
6418    }
6419
6420    fn render_thread_retry_status_callout(
6421        &self,
6422        _window: &mut Window,
6423        _cx: &mut Context<Self>,
6424    ) -> Option<Callout> {
6425        let state = self.thread_retry_status.as_ref()?;
6426
6427        let next_attempt_in = state
6428            .duration
6429            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
6430        if next_attempt_in.is_zero() {
6431            return None;
6432        }
6433
6434        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
6435
6436        let retry_message = if state.max_attempts == 1 {
6437            if next_attempt_in_secs == 1 {
6438                "Retrying. Next attempt in 1 second.".to_string()
6439            } else {
6440                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
6441            }
6442        } else if next_attempt_in_secs == 1 {
6443            format!(
6444                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
6445                state.attempt, state.max_attempts,
6446            )
6447        } else {
6448            format!(
6449                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
6450                state.attempt, state.max_attempts,
6451            )
6452        };
6453
6454        Some(
6455            Callout::new()
6456                .severity(Severity::Warning)
6457                .title(state.last_error.clone())
6458                .description(retry_message),
6459        )
6460    }
6461
6462    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
6463        Callout::new()
6464            .icon(IconName::Warning)
6465            .severity(Severity::Warning)
6466            .title("Codex on Windows")
6467            .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
6468            .actions_slot(
6469                Button::new("open-wsl-modal", "Open in WSL")
6470                    .icon_size(IconSize::Small)
6471                    .icon_color(Color::Muted)
6472                    .on_click(cx.listener({
6473                        move |_, _, _window, cx| {
6474                            #[cfg(windows)]
6475                            _window.dispatch_action(
6476                                zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
6477                                cx,
6478                            );
6479                            cx.notify();
6480                        }
6481                    })),
6482            )
6483            .dismiss_action(
6484                IconButton::new("dismiss", IconName::Close)
6485                    .icon_size(IconSize::Small)
6486                    .icon_color(Color::Muted)
6487                    .tooltip(Tooltip::text("Dismiss Warning"))
6488                    .on_click(cx.listener({
6489                        move |this, _, _, cx| {
6490                            this.show_codex_windows_warning = false;
6491                            cx.notify();
6492                        }
6493                    })),
6494            )
6495    }
6496
6497    fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
6498        let content = match self.thread_error.as_ref()? {
6499            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
6500            ThreadError::Refusal => self.render_refusal_error(cx),
6501            ThreadError::AuthenticationRequired(error) => {
6502                self.render_authentication_required_error(error.clone(), cx)
6503            }
6504            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
6505            ThreadError::ModelRequestLimitReached(plan) => {
6506                self.render_model_request_limit_reached_error(*plan, cx)
6507            }
6508            ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
6509        };
6510
6511        Some(div().child(content))
6512    }
6513
6514    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
6515        v_flex().w_full().justify_end().child(
6516            h_flex()
6517                .p_2()
6518                .pr_3()
6519                .w_full()
6520                .gap_1p5()
6521                .border_t_1()
6522                .border_color(cx.theme().colors().border)
6523                .bg(cx.theme().colors().element_background)
6524                .child(
6525                    h_flex()
6526                        .flex_1()
6527                        .gap_1p5()
6528                        .child(
6529                            Icon::new(IconName::Download)
6530                                .color(Color::Accent)
6531                                .size(IconSize::Small),
6532                        )
6533                        .child(Label::new("New version available").size(LabelSize::Small)),
6534                )
6535                .child(
6536                    Button::new("update-button", format!("Update to v{}", version))
6537                        .label_size(LabelSize::Small)
6538                        .style(ButtonStyle::Tinted(TintColor::Accent))
6539                        .on_click(cx.listener(|this, _, window, cx| {
6540                            this.reset(window, cx);
6541                        })),
6542                ),
6543        )
6544    }
6545
6546    fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
6547        if let Some(thread) = self.as_native_thread(cx) {
6548            Some(thread.read(cx).profile().0.clone())
6549        } else if let Some(mode_selector) = self.mode_selector() {
6550            Some(mode_selector.read(cx).mode().0)
6551        } else {
6552            None
6553        }
6554    }
6555
6556    fn current_model_id(&self, cx: &App) -> Option<String> {
6557        self.model_selector
6558            .as_ref()
6559            .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
6560    }
6561
6562    fn current_model_name(&self, cx: &App) -> SharedString {
6563        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
6564        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
6565        // This provides better clarity about what refused the request
6566        if self.as_native_connection(cx).is_some() {
6567            self.model_selector
6568                .as_ref()
6569                .and_then(|selector| selector.read(cx).active_model(cx))
6570                .map(|model| model.name.clone())
6571                .unwrap_or_else(|| SharedString::from("The model"))
6572        } else {
6573            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
6574            self.agent.name()
6575        }
6576    }
6577
6578    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
6579        let model_or_agent_name = self.current_model_name(cx);
6580        let refusal_message = format!(
6581            "{} 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.",
6582            model_or_agent_name
6583        );
6584
6585        Callout::new()
6586            .severity(Severity::Error)
6587            .title("Request Refused")
6588            .icon(IconName::XCircle)
6589            .description(refusal_message.clone())
6590            .actions_slot(self.create_copy_button(&refusal_message))
6591            .dismiss_action(self.dismiss_error_button(cx))
6592    }
6593
6594    fn render_any_thread_error(
6595        &mut self,
6596        error: SharedString,
6597        window: &mut Window,
6598        cx: &mut Context<'_, Self>,
6599    ) -> Callout {
6600        let can_resume = self
6601            .thread()
6602            .map_or(false, |thread| thread.read(cx).can_resume(cx));
6603
6604        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
6605            let thread = thread.read(cx);
6606            let supports_burn_mode = thread
6607                .model()
6608                .map_or(false, |model| model.supports_burn_mode());
6609            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
6610        });
6611
6612        let markdown = if let Some(markdown) = &self.thread_error_markdown {
6613            markdown.clone()
6614        } else {
6615            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
6616            self.thread_error_markdown = Some(markdown.clone());
6617            markdown
6618        };
6619
6620        let markdown_style = default_markdown_style(false, true, window, cx);
6621        let description = self
6622            .render_markdown(markdown, markdown_style)
6623            .into_any_element();
6624
6625        Callout::new()
6626            .severity(Severity::Error)
6627            .icon(IconName::XCircle)
6628            .title("An Error Happened")
6629            .description_slot(description)
6630            .actions_slot(
6631                h_flex()
6632                    .gap_0p5()
6633                    .when(can_resume && can_enable_burn_mode, |this| {
6634                        this.child(
6635                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
6636                                .icon(IconName::ZedBurnMode)
6637                                .icon_position(IconPosition::Start)
6638                                .icon_size(IconSize::Small)
6639                                .label_size(LabelSize::Small)
6640                                .on_click(cx.listener(|this, _, window, cx| {
6641                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6642                                    this.resume_chat(cx);
6643                                })),
6644                        )
6645                    })
6646                    .when(can_resume, |this| {
6647                        this.child(
6648                            IconButton::new("retry", IconName::RotateCw)
6649                                .icon_size(IconSize::Small)
6650                                .tooltip(Tooltip::text("Retry Generation"))
6651                                .on_click(cx.listener(|this, _, _window, cx| {
6652                                    this.resume_chat(cx);
6653                                })),
6654                        )
6655                    })
6656                    .child(self.create_copy_button(error.to_string())),
6657            )
6658            .dismiss_action(self.dismiss_error_button(cx))
6659    }
6660
6661    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
6662        const ERROR_MESSAGE: &str =
6663            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
6664
6665        Callout::new()
6666            .severity(Severity::Error)
6667            .icon(IconName::XCircle)
6668            .title("Free Usage Exceeded")
6669            .description(ERROR_MESSAGE)
6670            .actions_slot(
6671                h_flex()
6672                    .gap_0p5()
6673                    .child(self.upgrade_button(cx))
6674                    .child(self.create_copy_button(ERROR_MESSAGE)),
6675            )
6676            .dismiss_action(self.dismiss_error_button(cx))
6677    }
6678
6679    fn render_authentication_required_error(
6680        &self,
6681        error: SharedString,
6682        cx: &mut Context<Self>,
6683    ) -> Callout {
6684        Callout::new()
6685            .severity(Severity::Error)
6686            .title("Authentication Required")
6687            .icon(IconName::XCircle)
6688            .description(error.clone())
6689            .actions_slot(
6690                h_flex()
6691                    .gap_0p5()
6692                    .child(self.authenticate_button(cx))
6693                    .child(self.create_copy_button(error)),
6694            )
6695            .dismiss_action(self.dismiss_error_button(cx))
6696    }
6697
6698    fn render_model_request_limit_reached_error(
6699        &self,
6700        plan: cloud_llm_client::Plan,
6701        cx: &mut Context<Self>,
6702    ) -> Callout {
6703        let error_message = match plan {
6704            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
6705                "Upgrade to usage-based billing for more prompts."
6706            }
6707            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
6708            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
6709            cloud_llm_client::Plan::V2(_) => "",
6710        };
6711
6712        Callout::new()
6713            .severity(Severity::Error)
6714            .title("Model Prompt Limit Reached")
6715            .icon(IconName::XCircle)
6716            .description(error_message)
6717            .actions_slot(
6718                h_flex()
6719                    .gap_0p5()
6720                    .child(self.upgrade_button(cx))
6721                    .child(self.create_copy_button(error_message)),
6722            )
6723            .dismiss_action(self.dismiss_error_button(cx))
6724    }
6725
6726    fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
6727        let thread = self.as_native_thread(cx)?;
6728        let supports_burn_mode = thread
6729            .read(cx)
6730            .model()
6731            .is_some_and(|model| model.supports_burn_mode());
6732
6733        let focus_handle = self.focus_handle(cx);
6734
6735        Some(
6736            Callout::new()
6737                .icon(IconName::Info)
6738                .title("Consecutive tool use limit reached.")
6739                .actions_slot(
6740                    h_flex()
6741                        .gap_0p5()
6742                        .when(supports_burn_mode, |this| {
6743                            this.child(
6744                                Button::new("continue-burn-mode", "Continue with Burn Mode")
6745                                    .style(ButtonStyle::Filled)
6746                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6747                                    .layer(ElevationIndex::ModalSurface)
6748                                    .label_size(LabelSize::Small)
6749                                    .key_binding(
6750                                        KeyBinding::for_action_in(
6751                                            &ContinueWithBurnMode,
6752                                            &focus_handle,
6753                                            cx,
6754                                        )
6755                                        .map(|kb| kb.size(rems_from_px(10.))),
6756                                    )
6757                                    .tooltip(Tooltip::text(
6758                                        "Enable Burn Mode for unlimited tool use.",
6759                                    ))
6760                                    .on_click({
6761                                        cx.listener(move |this, _, _window, cx| {
6762                                            thread.update(cx, |thread, cx| {
6763                                                thread
6764                                                    .set_completion_mode(CompletionMode::Burn, cx);
6765                                            });
6766                                            this.resume_chat(cx);
6767                                        })
6768                                    }),
6769                            )
6770                        })
6771                        .child(
6772                            Button::new("continue-conversation", "Continue")
6773                                .layer(ElevationIndex::ModalSurface)
6774                                .label_size(LabelSize::Small)
6775                                .key_binding(
6776                                    KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
6777                                        .map(|kb| kb.size(rems_from_px(10.))),
6778                                )
6779                                .on_click(cx.listener(|this, _, _window, cx| {
6780                                    this.resume_chat(cx);
6781                                })),
6782                        ),
6783                ),
6784        )
6785    }
6786
6787    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
6788        let message = message.into();
6789
6790        CopyButton::new(message).tooltip_label("Copy Error Message")
6791    }
6792
6793    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6794        IconButton::new("dismiss", IconName::Close)
6795            .icon_size(IconSize::Small)
6796            .tooltip(Tooltip::text("Dismiss"))
6797            .on_click(cx.listener({
6798                move |this, _, _, cx| {
6799                    this.clear_thread_error(cx);
6800                    cx.notify();
6801                }
6802            }))
6803    }
6804
6805    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6806        Button::new("authenticate", "Authenticate")
6807            .label_size(LabelSize::Small)
6808            .style(ButtonStyle::Filled)
6809            .on_click(cx.listener({
6810                move |this, _, window, cx| {
6811                    let agent = this.agent.clone();
6812                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
6813                        return;
6814                    };
6815
6816                    let connection = thread.read(cx).connection().clone();
6817                    this.clear_thread_error(cx);
6818                    if let Some(message) = this.in_flight_prompt.take() {
6819                        this.message_editor.update(cx, |editor, cx| {
6820                            editor.set_message(message, window, cx);
6821                        });
6822                    }
6823                    let this = cx.weak_entity();
6824                    window.defer(cx, |window, cx| {
6825                        Self::handle_auth_required(
6826                            this,
6827                            AuthRequired::new(),
6828                            agent,
6829                            connection,
6830                            window,
6831                            cx,
6832                        );
6833                    })
6834                }
6835            }))
6836    }
6837
6838    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6839        let agent = self.agent.clone();
6840        let ThreadState::Ready { thread, .. } = &self.thread_state else {
6841            return;
6842        };
6843
6844        let connection = thread.read(cx).connection().clone();
6845        self.clear_thread_error(cx);
6846        let this = cx.weak_entity();
6847        window.defer(cx, |window, cx| {
6848            Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
6849        })
6850    }
6851
6852    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6853        Button::new("upgrade", "Upgrade")
6854            .label_size(LabelSize::Small)
6855            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6856            .on_click(cx.listener({
6857                move |this, _, _, cx| {
6858                    this.clear_thread_error(cx);
6859                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
6860                }
6861            }))
6862    }
6863
6864    pub fn delete_history_entry(&mut self, entry: DbThreadMetadata, cx: &mut Context<Self>) {
6865        let task = self
6866            .thread_store
6867            .update(cx, |store, cx| store.delete_thread(entry.id.clone(), cx));
6868        task.detach_and_log_err(cx);
6869    }
6870
6871    /// Returns the currently active editor, either for a message that is being
6872    /// edited or the editor for a new message.
6873    fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
6874        if let Some(index) = self.editing_message
6875            && let Some(editor) = self
6876                .entry_view_state
6877                .read(cx)
6878                .entry(index)
6879                .and_then(|e| e.message_editor())
6880                .cloned()
6881        {
6882            editor
6883        } else {
6884            self.message_editor.clone()
6885        }
6886    }
6887}
6888
6889fn loading_contents_spinner(size: IconSize) -> AnyElement {
6890    Icon::new(IconName::LoadCircle)
6891        .size(size)
6892        .color(Color::Accent)
6893        .with_rotate_animation(3)
6894        .into_any_element()
6895}
6896
6897fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
6898    if agent_name == "Zed Agent" {
6899        format!("Message the {} — @ to include context", agent_name)
6900    } else if has_commands {
6901        format!(
6902            "Message {} — @ to include context, / for commands",
6903            agent_name
6904        )
6905    } else {
6906        format!("Message {} — @ to include context", agent_name)
6907    }
6908}
6909
6910impl Focusable for AcpThreadView {
6911    fn focus_handle(&self, cx: &App) -> FocusHandle {
6912        match self.thread_state {
6913            ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
6914            ThreadState::Loading { .. }
6915            | ThreadState::LoadError(_)
6916            | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
6917        }
6918    }
6919}
6920
6921#[cfg(any(test, feature = "test-support"))]
6922impl AcpThreadView {
6923    /// Expands a tool call so its content is visible.
6924    /// This is primarily useful for visual testing.
6925    pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
6926        self.expanded_tool_calls.insert(tool_call_id);
6927        cx.notify();
6928    }
6929}
6930
6931impl Render for AcpThreadView {
6932    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6933        let has_messages = self.list_state.item_count() > 0;
6934        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
6935
6936        v_flex()
6937            .size_full()
6938            .key_context("AcpThread")
6939            .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
6940                this.cancel_generation(cx);
6941            }))
6942            .on_action(cx.listener(Self::toggle_burn_mode))
6943            .on_action(cx.listener(Self::keep_all))
6944            .on_action(cx.listener(Self::reject_all))
6945            .on_action(cx.listener(Self::allow_always))
6946            .on_action(cx.listener(Self::allow_once))
6947            .on_action(cx.listener(Self::reject_once))
6948            .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
6949                this.send_queued_message_at_index(0, true, window, cx);
6950            }))
6951            .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
6952                this.message_queue.clear();
6953                cx.notify();
6954            }))
6955            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
6956                if let Some(config_options_view) = this.config_options_view.as_ref() {
6957                    let handled = config_options_view.update(cx, |view, cx| {
6958                        view.toggle_category_picker(
6959                            acp::SessionConfigOptionCategory::Mode,
6960                            window,
6961                            cx,
6962                        )
6963                    });
6964                    if handled {
6965                        return;
6966                    }
6967                }
6968
6969                if let Some(profile_selector) = this.profile_selector.as_ref() {
6970                    profile_selector.read(cx).menu_handle().toggle(window, cx);
6971                } else if let Some(mode_selector) = this.mode_selector() {
6972                    mode_selector.read(cx).menu_handle().toggle(window, cx);
6973                }
6974            }))
6975            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
6976                if let Some(config_options_view) = this.config_options_view.as_ref() {
6977                    let handled = config_options_view.update(cx, |view, cx| {
6978                        view.cycle_category_option(
6979                            acp::SessionConfigOptionCategory::Mode,
6980                            false,
6981                            cx,
6982                        )
6983                    });
6984                    if handled {
6985                        return;
6986                    }
6987                }
6988
6989                if let Some(profile_selector) = this.profile_selector.as_ref() {
6990                    profile_selector.update(cx, |profile_selector, cx| {
6991                        profile_selector.cycle_profile(cx);
6992                    });
6993                } else if let Some(mode_selector) = this.mode_selector() {
6994                    mode_selector.update(cx, |mode_selector, cx| {
6995                        mode_selector.cycle_mode(window, cx);
6996                    });
6997                }
6998            }))
6999            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
7000                if let Some(config_options_view) = this.config_options_view.as_ref() {
7001                    let handled = config_options_view.update(cx, |view, cx| {
7002                        view.toggle_category_picker(
7003                            acp::SessionConfigOptionCategory::Model,
7004                            window,
7005                            cx,
7006                        )
7007                    });
7008                    if handled {
7009                        return;
7010                    }
7011                }
7012
7013                if let Some(model_selector) = this.model_selector.as_ref() {
7014                    model_selector
7015                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
7016                }
7017            }))
7018            .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
7019                if let Some(config_options_view) = this.config_options_view.as_ref() {
7020                    let handled = config_options_view.update(cx, |view, cx| {
7021                        view.cycle_category_option(
7022                            acp::SessionConfigOptionCategory::Model,
7023                            true,
7024                            cx,
7025                        )
7026                    });
7027                    if handled {
7028                        return;
7029                    }
7030                }
7031
7032                if let Some(model_selector) = this.model_selector.as_ref() {
7033                    model_selector.update(cx, |model_selector, cx| {
7034                        model_selector.cycle_favorite_models(window, cx);
7035                    });
7036                }
7037            }))
7038            .track_focus(&self.focus_handle)
7039            .bg(cx.theme().colors().panel_background)
7040            .child(match &self.thread_state {
7041                ThreadState::Unauthenticated {
7042                    connection,
7043                    description,
7044                    configuration_view,
7045                    pending_auth_method,
7046                    ..
7047                } => v_flex()
7048                    .flex_1()
7049                    .size_full()
7050                    .justify_end()
7051                    .child(self.render_auth_required_state(
7052                        connection,
7053                        description.as_ref(),
7054                        configuration_view.as_ref(),
7055                        pending_auth_method.as_ref(),
7056                        window,
7057                        cx,
7058                    ))
7059                    .into_any_element(),
7060                ThreadState::Loading { .. } => v_flex()
7061                    .flex_1()
7062                    .child(self.render_recent_history(cx))
7063                    .into_any(),
7064                ThreadState::LoadError(e) => v_flex()
7065                    .flex_1()
7066                    .size_full()
7067                    .items_center()
7068                    .justify_end()
7069                    .child(self.render_load_error(e, window, cx))
7070                    .into_any(),
7071                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
7072                    if has_messages {
7073                        this.child(
7074                            list(
7075                                self.list_state.clone(),
7076                                cx.processor(|this, index: usize, window, cx| {
7077                                    let Some((entry, len)) = this.thread().and_then(|thread| {
7078                                        let entries = &thread.read(cx).entries();
7079                                        Some((entries.get(index)?, entries.len()))
7080                                    }) else {
7081                                        return Empty.into_any();
7082                                    };
7083                                    this.render_entry(index, len, entry, window, cx)
7084                                }),
7085                            )
7086                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
7087                            .flex_grow()
7088                            .into_any(),
7089                        )
7090                        .vertical_scrollbar_for(&self.list_state, window, cx)
7091                        .into_any()
7092                    } else {
7093                        this.child(self.render_recent_history(cx)).into_any()
7094                    }
7095                }),
7096            })
7097            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
7098            // above so that the scrollbar doesn't render behind it. The current setup allows
7099            // the scrollbar to stop exactly at the activity bar start.
7100            .when(has_messages, |this| match &self.thread_state {
7101                ThreadState::Ready { thread, .. } => {
7102                    this.children(self.render_activity_bar(thread, window, cx))
7103                }
7104                _ => this,
7105            })
7106            .children(self.render_thread_retry_status_callout(window, cx))
7107            .when(self.show_codex_windows_warning, |this| {
7108                this.child(self.render_codex_windows_warning(cx))
7109            })
7110            .children(self.render_thread_error(window, cx))
7111            .when_some(
7112                self.new_server_version_available.as_ref().filter(|_| {
7113                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
7114                }),
7115                |this, version| this.child(self.render_new_version_callout(&version, cx)),
7116            )
7117            .children(
7118                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
7119                    Some(usage_callout.into_any_element())
7120                } else {
7121                    self.render_token_limit_callout(cx)
7122                        .map(|token_limit_callout| token_limit_callout.into_any_element())
7123                },
7124            )
7125            .child(self.render_message_editor(window, cx))
7126    }
7127}
7128
7129fn default_markdown_style(
7130    buffer_font: bool,
7131    muted_text: bool,
7132    window: &Window,
7133    cx: &App,
7134) -> MarkdownStyle {
7135    let theme_settings = ThemeSettings::get_global(cx);
7136    let colors = cx.theme().colors();
7137
7138    let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
7139
7140    let mut text_style = window.text_style();
7141    let line_height = buffer_font_size * 1.75;
7142
7143    let font_family = if buffer_font {
7144        theme_settings.buffer_font.family.clone()
7145    } else {
7146        theme_settings.ui_font.family.clone()
7147    };
7148
7149    let font_size = if buffer_font {
7150        theme_settings.agent_buffer_font_size(cx)
7151    } else {
7152        theme_settings.agent_ui_font_size(cx)
7153    };
7154
7155    let text_color = if muted_text {
7156        colors.text_muted
7157    } else {
7158        colors.text
7159    };
7160
7161    text_style.refine(&TextStyleRefinement {
7162        font_family: Some(font_family),
7163        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
7164        font_features: Some(theme_settings.ui_font.features.clone()),
7165        font_size: Some(font_size.into()),
7166        line_height: Some(line_height.into()),
7167        color: Some(text_color),
7168        ..Default::default()
7169    });
7170
7171    MarkdownStyle {
7172        base_text_style: text_style.clone(),
7173        syntax: cx.theme().syntax().clone(),
7174        selection_background_color: colors.element_selection_background,
7175        code_block_overflow_x_scroll: true,
7176        heading_level_styles: Some(HeadingLevelStyles {
7177            h1: Some(TextStyleRefinement {
7178                font_size: Some(rems(1.15).into()),
7179                ..Default::default()
7180            }),
7181            h2: Some(TextStyleRefinement {
7182                font_size: Some(rems(1.1).into()),
7183                ..Default::default()
7184            }),
7185            h3: Some(TextStyleRefinement {
7186                font_size: Some(rems(1.05).into()),
7187                ..Default::default()
7188            }),
7189            h4: Some(TextStyleRefinement {
7190                font_size: Some(rems(1.).into()),
7191                ..Default::default()
7192            }),
7193            h5: Some(TextStyleRefinement {
7194                font_size: Some(rems(0.95).into()),
7195                ..Default::default()
7196            }),
7197            h6: Some(TextStyleRefinement {
7198                font_size: Some(rems(0.875).into()),
7199                ..Default::default()
7200            }),
7201        }),
7202        code_block: StyleRefinement {
7203            padding: EdgesRefinement {
7204                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7205                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7206                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7207                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7208            },
7209            margin: EdgesRefinement {
7210                top: Some(Length::Definite(px(8.).into())),
7211                left: Some(Length::Definite(px(0.).into())),
7212                right: Some(Length::Definite(px(0.).into())),
7213                bottom: Some(Length::Definite(px(12.).into())),
7214            },
7215            border_style: Some(BorderStyle::Solid),
7216            border_widths: EdgesRefinement {
7217                top: Some(AbsoluteLength::Pixels(px(1.))),
7218                left: Some(AbsoluteLength::Pixels(px(1.))),
7219                right: Some(AbsoluteLength::Pixels(px(1.))),
7220                bottom: Some(AbsoluteLength::Pixels(px(1.))),
7221            },
7222            border_color: Some(colors.border_variant),
7223            background: Some(colors.editor_background.into()),
7224            text: TextStyleRefinement {
7225                font_family: Some(theme_settings.buffer_font.family.clone()),
7226                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7227                font_features: Some(theme_settings.buffer_font.features.clone()),
7228                font_size: Some(buffer_font_size.into()),
7229                ..Default::default()
7230            },
7231            ..Default::default()
7232        },
7233        inline_code: TextStyleRefinement {
7234            font_family: Some(theme_settings.buffer_font.family.clone()),
7235            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7236            font_features: Some(theme_settings.buffer_font.features.clone()),
7237            font_size: Some(buffer_font_size.into()),
7238            background_color: Some(colors.editor_foreground.opacity(0.08)),
7239            ..Default::default()
7240        },
7241        link: TextStyleRefinement {
7242            background_color: Some(colors.editor_foreground.opacity(0.025)),
7243            color: Some(colors.text_accent),
7244            underline: Some(UnderlineStyle {
7245                color: Some(colors.text_accent.opacity(0.5)),
7246                thickness: px(1.),
7247                ..Default::default()
7248            }),
7249            ..Default::default()
7250        },
7251        ..Default::default()
7252    }
7253}
7254
7255fn plan_label_markdown_style(
7256    status: &acp::PlanEntryStatus,
7257    window: &Window,
7258    cx: &App,
7259) -> MarkdownStyle {
7260    let default_md_style = default_markdown_style(false, false, window, cx);
7261
7262    MarkdownStyle {
7263        base_text_style: TextStyle {
7264            color: cx.theme().colors().text_muted,
7265            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
7266                Some(gpui::StrikethroughStyle {
7267                    thickness: px(1.),
7268                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
7269                })
7270            } else {
7271                None
7272            },
7273            ..default_md_style.base_text_style
7274        },
7275        ..default_md_style
7276    }
7277}
7278
7279fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
7280    let default_md_style = default_markdown_style(true, false, window, cx);
7281
7282    MarkdownStyle {
7283        base_text_style: TextStyle {
7284            ..default_md_style.base_text_style
7285        },
7286        selection_background_color: cx.theme().colors().element_selection_background,
7287        ..Default::default()
7288    }
7289}
7290
7291#[cfg(test)]
7292pub(crate) mod tests {
7293    use acp_thread::StubAgentConnection;
7294    use agent_client_protocol::SessionId;
7295    use editor::MultiBufferOffset;
7296    use fs::FakeFs;
7297    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
7298    use project::Project;
7299    use serde_json::json;
7300    use settings::SettingsStore;
7301    use std::any::Any;
7302    use std::path::Path;
7303    use workspace::Item;
7304
7305    use super::*;
7306
7307    #[gpui::test]
7308    async fn test_drop(cx: &mut TestAppContext) {
7309        init_test(cx);
7310
7311        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7312        let weak_view = thread_view.downgrade();
7313        drop(thread_view);
7314        assert!(!weak_view.is_upgradable());
7315    }
7316
7317    #[gpui::test]
7318    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
7319        init_test(cx);
7320
7321        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7322
7323        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7324        message_editor.update_in(cx, |editor, window, cx| {
7325            editor.set_text("Hello", window, cx);
7326        });
7327
7328        cx.deactivate_window();
7329
7330        thread_view.update_in(cx, |thread_view, window, cx| {
7331            thread_view.send(window, cx);
7332        });
7333
7334        cx.run_until_parked();
7335
7336        assert!(
7337            cx.windows()
7338                .iter()
7339                .any(|window| window.downcast::<AgentNotification>().is_some())
7340        );
7341    }
7342
7343    #[gpui::test]
7344    async fn test_notification_for_error(cx: &mut TestAppContext) {
7345        init_test(cx);
7346
7347        let (thread_view, cx) =
7348            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
7349
7350        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7351        message_editor.update_in(cx, |editor, window, cx| {
7352            editor.set_text("Hello", window, cx);
7353        });
7354
7355        cx.deactivate_window();
7356
7357        thread_view.update_in(cx, |thread_view, window, cx| {
7358            thread_view.send(window, cx);
7359        });
7360
7361        cx.run_until_parked();
7362
7363        assert!(
7364            cx.windows()
7365                .iter()
7366                .any(|window| window.downcast::<AgentNotification>().is_some())
7367        );
7368    }
7369
7370    #[gpui::test]
7371    async fn test_refusal_handling(cx: &mut TestAppContext) {
7372        init_test(cx);
7373
7374        let (thread_view, cx) =
7375            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
7376
7377        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7378        message_editor.update_in(cx, |editor, window, cx| {
7379            editor.set_text("Do something harmful", window, cx);
7380        });
7381
7382        thread_view.update_in(cx, |thread_view, window, cx| {
7383            thread_view.send(window, cx);
7384        });
7385
7386        cx.run_until_parked();
7387
7388        // Check that the refusal error is set
7389        thread_view.read_with(cx, |thread_view, _cx| {
7390            assert!(
7391                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
7392                "Expected refusal error to be set"
7393            );
7394        });
7395    }
7396
7397    #[gpui::test]
7398    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
7399        init_test(cx);
7400
7401        let tool_call_id = acp::ToolCallId::new("1");
7402        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
7403            .kind(acp::ToolKind::Edit)
7404            .content(vec!["hi".into()]);
7405        let connection =
7406            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
7407                tool_call_id,
7408                vec![acp::PermissionOption::new(
7409                    "1",
7410                    "Allow",
7411                    acp::PermissionOptionKind::AllowOnce,
7412                )],
7413            )]));
7414
7415        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
7416
7417        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7418
7419        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7420        message_editor.update_in(cx, |editor, window, cx| {
7421            editor.set_text("Hello", window, cx);
7422        });
7423
7424        cx.deactivate_window();
7425
7426        thread_view.update_in(cx, |thread_view, window, cx| {
7427            thread_view.send(window, cx);
7428        });
7429
7430        cx.run_until_parked();
7431
7432        assert!(
7433            cx.windows()
7434                .iter()
7435                .any(|window| window.downcast::<AgentNotification>().is_some())
7436        );
7437    }
7438
7439    #[gpui::test]
7440    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
7441        init_test(cx);
7442
7443        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7444
7445        add_to_workspace(thread_view.clone(), cx);
7446
7447        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7448
7449        message_editor.update_in(cx, |editor, window, cx| {
7450            editor.set_text("Hello", window, cx);
7451        });
7452
7453        // Window is active (don't deactivate), but panel will be hidden
7454        // Note: In the test environment, the panel is not actually added to the dock,
7455        // so is_agent_panel_hidden will return true
7456
7457        thread_view.update_in(cx, |thread_view, window, cx| {
7458            thread_view.send(window, cx);
7459        });
7460
7461        cx.run_until_parked();
7462
7463        // Should show notification because window is active but panel is hidden
7464        assert!(
7465            cx.windows()
7466                .iter()
7467                .any(|window| window.downcast::<AgentNotification>().is_some()),
7468            "Expected notification when panel is hidden"
7469        );
7470    }
7471
7472    #[gpui::test]
7473    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
7474        init_test(cx);
7475
7476        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7477
7478        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7479        message_editor.update_in(cx, |editor, window, cx| {
7480            editor.set_text("Hello", window, cx);
7481        });
7482
7483        // Deactivate window - should show notification regardless of setting
7484        cx.deactivate_window();
7485
7486        thread_view.update_in(cx, |thread_view, window, cx| {
7487            thread_view.send(window, cx);
7488        });
7489
7490        cx.run_until_parked();
7491
7492        // Should still show notification when window is inactive (existing behavior)
7493        assert!(
7494            cx.windows()
7495                .iter()
7496                .any(|window| window.downcast::<AgentNotification>().is_some()),
7497            "Expected notification when window is inactive"
7498        );
7499    }
7500
7501    #[gpui::test]
7502    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
7503        init_test(cx);
7504
7505        // Set notify_when_agent_waiting to Never
7506        cx.update(|cx| {
7507            AgentSettings::override_global(
7508                AgentSettings {
7509                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
7510                    ..AgentSettings::get_global(cx).clone()
7511                },
7512                cx,
7513            );
7514        });
7515
7516        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7517
7518        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7519        message_editor.update_in(cx, |editor, window, cx| {
7520            editor.set_text("Hello", window, cx);
7521        });
7522
7523        // Window is active
7524
7525        thread_view.update_in(cx, |thread_view, window, cx| {
7526            thread_view.send(window, cx);
7527        });
7528
7529        cx.run_until_parked();
7530
7531        // Should NOT show notification because notify_when_agent_waiting is Never
7532        assert!(
7533            !cx.windows()
7534                .iter()
7535                .any(|window| window.downcast::<AgentNotification>().is_some()),
7536            "Expected no notification when notify_when_agent_waiting is Never"
7537        );
7538    }
7539
7540    #[gpui::test]
7541    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
7542        init_test(cx);
7543
7544        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7545
7546        let weak_view = thread_view.downgrade();
7547
7548        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7549        message_editor.update_in(cx, |editor, window, cx| {
7550            editor.set_text("Hello", window, cx);
7551        });
7552
7553        cx.deactivate_window();
7554
7555        thread_view.update_in(cx, |thread_view, window, cx| {
7556            thread_view.send(window, cx);
7557        });
7558
7559        cx.run_until_parked();
7560
7561        // Verify notification is shown
7562        assert!(
7563            cx.windows()
7564                .iter()
7565                .any(|window| window.downcast::<AgentNotification>().is_some()),
7566            "Expected notification to be shown"
7567        );
7568
7569        // Drop the thread view (simulating navigation to a new thread)
7570        drop(thread_view);
7571        drop(message_editor);
7572        // Trigger an update to flush effects, which will call release_dropped_entities
7573        cx.update(|_window, _cx| {});
7574        cx.run_until_parked();
7575
7576        // Verify the entity was actually released
7577        assert!(
7578            !weak_view.is_upgradable(),
7579            "Thread view entity should be released after dropping"
7580        );
7581
7582        // The notification should be automatically closed via on_release
7583        assert!(
7584            !cx.windows()
7585                .iter()
7586                .any(|window| window.downcast::<AgentNotification>().is_some()),
7587            "Notification should be closed when thread view is dropped"
7588        );
7589    }
7590
7591    async fn setup_thread_view(
7592        agent: impl AgentServer + 'static,
7593        cx: &mut TestAppContext,
7594    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
7595        let fs = FakeFs::new(cx.executor());
7596        let project = Project::test(fs, [], cx).await;
7597        let (workspace, cx) =
7598            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7599
7600        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
7601
7602        let thread_view = cx.update(|window, cx| {
7603            cx.new(|cx| {
7604                AcpThreadView::new(
7605                    Rc::new(agent),
7606                    None,
7607                    None,
7608                    workspace.downgrade(),
7609                    project,
7610                    thread_store,
7611                    None,
7612                    false,
7613                    window,
7614                    cx,
7615                )
7616            })
7617        });
7618        cx.run_until_parked();
7619        (thread_view, cx)
7620    }
7621
7622    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
7623        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
7624
7625        workspace
7626            .update_in(cx, |workspace, window, cx| {
7627                workspace.add_item_to_active_pane(
7628                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
7629                    None,
7630                    true,
7631                    window,
7632                    cx,
7633                );
7634            })
7635            .unwrap();
7636    }
7637
7638    struct ThreadViewItem(Entity<AcpThreadView>);
7639
7640    impl Item for ThreadViewItem {
7641        type Event = ();
7642
7643        fn include_in_nav_history() -> bool {
7644            false
7645        }
7646
7647        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
7648            "Test".into()
7649        }
7650    }
7651
7652    impl EventEmitter<()> for ThreadViewItem {}
7653
7654    impl Focusable for ThreadViewItem {
7655        fn focus_handle(&self, cx: &App) -> FocusHandle {
7656            self.0.read(cx).focus_handle(cx)
7657        }
7658    }
7659
7660    impl Render for ThreadViewItem {
7661        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7662            self.0.clone().into_any_element()
7663        }
7664    }
7665
7666    struct StubAgentServer<C> {
7667        connection: C,
7668    }
7669
7670    impl<C> StubAgentServer<C> {
7671        fn new(connection: C) -> Self {
7672            Self { connection }
7673        }
7674    }
7675
7676    impl StubAgentServer<StubAgentConnection> {
7677        fn default_response() -> Self {
7678            let conn = StubAgentConnection::new();
7679            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7680                acp::ContentChunk::new("Default response".into()),
7681            )]);
7682            Self::new(conn)
7683        }
7684    }
7685
7686    impl<C> AgentServer for StubAgentServer<C>
7687    where
7688        C: 'static + AgentConnection + Send + Clone,
7689    {
7690        fn logo(&self) -> ui::IconName {
7691            ui::IconName::Ai
7692        }
7693
7694        fn name(&self) -> SharedString {
7695            "Test".into()
7696        }
7697
7698        fn connect(
7699            &self,
7700            _root_dir: Option<&Path>,
7701            _delegate: AgentServerDelegate,
7702            _cx: &mut App,
7703        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
7704            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
7705        }
7706
7707        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7708            self
7709        }
7710    }
7711
7712    #[derive(Clone)]
7713    struct SaboteurAgentConnection;
7714
7715    impl AgentConnection for SaboteurAgentConnection {
7716        fn telemetry_id(&self) -> SharedString {
7717            "saboteur".into()
7718        }
7719
7720        fn new_thread(
7721            self: Rc<Self>,
7722            project: Entity<Project>,
7723            _cwd: &Path,
7724            cx: &mut gpui::App,
7725        ) -> Task<gpui::Result<Entity<AcpThread>>> {
7726            Task::ready(Ok(cx.new(|cx| {
7727                let action_log = cx.new(|_| ActionLog::new(project.clone()));
7728                AcpThread::new(
7729                    "SaboteurAgentConnection",
7730                    self,
7731                    project,
7732                    action_log,
7733                    SessionId::new("test"),
7734                    watch::Receiver::constant(
7735                        acp::PromptCapabilities::new()
7736                            .image(true)
7737                            .audio(true)
7738                            .embedded_context(true),
7739                    ),
7740                    cx,
7741                )
7742            })))
7743        }
7744
7745        fn auth_methods(&self) -> &[acp::AuthMethod] {
7746            &[]
7747        }
7748
7749        fn authenticate(
7750            &self,
7751            _method_id: acp::AuthMethodId,
7752            _cx: &mut App,
7753        ) -> Task<gpui::Result<()>> {
7754            unimplemented!()
7755        }
7756
7757        fn prompt(
7758            &self,
7759            _id: Option<acp_thread::UserMessageId>,
7760            _params: acp::PromptRequest,
7761            _cx: &mut App,
7762        ) -> Task<gpui::Result<acp::PromptResponse>> {
7763            Task::ready(Err(anyhow::anyhow!("Error prompting")))
7764        }
7765
7766        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
7767            unimplemented!()
7768        }
7769
7770        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7771            self
7772        }
7773    }
7774
7775    /// Simulates a model which always returns a refusal response
7776    #[derive(Clone)]
7777    struct RefusalAgentConnection;
7778
7779    impl AgentConnection for RefusalAgentConnection {
7780        fn telemetry_id(&self) -> SharedString {
7781            "refusal".into()
7782        }
7783
7784        fn new_thread(
7785            self: Rc<Self>,
7786            project: Entity<Project>,
7787            _cwd: &Path,
7788            cx: &mut gpui::App,
7789        ) -> Task<gpui::Result<Entity<AcpThread>>> {
7790            Task::ready(Ok(cx.new(|cx| {
7791                let action_log = cx.new(|_| ActionLog::new(project.clone()));
7792                AcpThread::new(
7793                    "RefusalAgentConnection",
7794                    self,
7795                    project,
7796                    action_log,
7797                    SessionId::new("test"),
7798                    watch::Receiver::constant(
7799                        acp::PromptCapabilities::new()
7800                            .image(true)
7801                            .audio(true)
7802                            .embedded_context(true),
7803                    ),
7804                    cx,
7805                )
7806            })))
7807        }
7808
7809        fn auth_methods(&self) -> &[acp::AuthMethod] {
7810            &[]
7811        }
7812
7813        fn authenticate(
7814            &self,
7815            _method_id: acp::AuthMethodId,
7816            _cx: &mut App,
7817        ) -> Task<gpui::Result<()>> {
7818            unimplemented!()
7819        }
7820
7821        fn prompt(
7822            &self,
7823            _id: Option<acp_thread::UserMessageId>,
7824            _params: acp::PromptRequest,
7825            _cx: &mut App,
7826        ) -> Task<gpui::Result<acp::PromptResponse>> {
7827            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
7828        }
7829
7830        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
7831            unimplemented!()
7832        }
7833
7834        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7835            self
7836        }
7837    }
7838
7839    pub(crate) fn init_test(cx: &mut TestAppContext) {
7840        cx.update(|cx| {
7841            let settings_store = SettingsStore::test(cx);
7842            cx.set_global(settings_store);
7843            theme::init(theme::LoadThemes::JustBase, cx);
7844            release_channel::init(semver::Version::new(0, 0, 0), cx);
7845            prompt_store::init(cx)
7846        });
7847    }
7848
7849    #[gpui::test]
7850    async fn test_rewind_views(cx: &mut TestAppContext) {
7851        init_test(cx);
7852
7853        let fs = FakeFs::new(cx.executor());
7854        fs.insert_tree(
7855            "/project",
7856            json!({
7857                "test1.txt": "old content 1",
7858                "test2.txt": "old content 2"
7859            }),
7860        )
7861        .await;
7862        let project = Project::test(fs, [Path::new("/project")], cx).await;
7863        let (workspace, cx) =
7864            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7865
7866        let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
7867
7868        let connection = Rc::new(StubAgentConnection::new());
7869        let thread_view = cx.update(|window, cx| {
7870            cx.new(|cx| {
7871                AcpThreadView::new(
7872                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
7873                    None,
7874                    None,
7875                    workspace.downgrade(),
7876                    project.clone(),
7877                    thread_store.clone(),
7878                    None,
7879                    false,
7880                    window,
7881                    cx,
7882                )
7883            })
7884        });
7885
7886        cx.run_until_parked();
7887
7888        let thread = thread_view
7889            .read_with(cx, |view, _| view.thread().cloned())
7890            .unwrap();
7891
7892        // First user message
7893        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
7894            acp::ToolCall::new("tool1", "Edit file 1")
7895                .kind(acp::ToolKind::Edit)
7896                .status(acp::ToolCallStatus::Completed)
7897                .content(vec![acp::ToolCallContent::Diff(
7898                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
7899                )]),
7900        )]);
7901
7902        thread
7903            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
7904            .await
7905            .unwrap();
7906        cx.run_until_parked();
7907
7908        thread.read_with(cx, |thread, _| {
7909            assert_eq!(thread.entries().len(), 2);
7910        });
7911
7912        thread_view.read_with(cx, |view, cx| {
7913            view.entry_view_state.read_with(cx, |entry_view_state, _| {
7914                assert!(
7915                    entry_view_state
7916                        .entry(0)
7917                        .unwrap()
7918                        .message_editor()
7919                        .is_some()
7920                );
7921                assert!(entry_view_state.entry(1).unwrap().has_content());
7922            });
7923        });
7924
7925        // Second user message
7926        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
7927            acp::ToolCall::new("tool2", "Edit file 2")
7928                .kind(acp::ToolKind::Edit)
7929                .status(acp::ToolCallStatus::Completed)
7930                .content(vec![acp::ToolCallContent::Diff(
7931                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
7932                )]),
7933        )]);
7934
7935        thread
7936            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
7937            .await
7938            .unwrap();
7939        cx.run_until_parked();
7940
7941        let second_user_message_id = thread.read_with(cx, |thread, _| {
7942            assert_eq!(thread.entries().len(), 4);
7943            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
7944                panic!();
7945            };
7946            user_message.id.clone().unwrap()
7947        });
7948
7949        thread_view.read_with(cx, |view, cx| {
7950            view.entry_view_state.read_with(cx, |entry_view_state, _| {
7951                assert!(
7952                    entry_view_state
7953                        .entry(0)
7954                        .unwrap()
7955                        .message_editor()
7956                        .is_some()
7957                );
7958                assert!(entry_view_state.entry(1).unwrap().has_content());
7959                assert!(
7960                    entry_view_state
7961                        .entry(2)
7962                        .unwrap()
7963                        .message_editor()
7964                        .is_some()
7965                );
7966                assert!(entry_view_state.entry(3).unwrap().has_content());
7967            });
7968        });
7969
7970        // Rewind to first message
7971        thread
7972            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
7973            .await
7974            .unwrap();
7975
7976        cx.run_until_parked();
7977
7978        thread.read_with(cx, |thread, _| {
7979            assert_eq!(thread.entries().len(), 2);
7980        });
7981
7982        thread_view.read_with(cx, |view, cx| {
7983            view.entry_view_state.read_with(cx, |entry_view_state, _| {
7984                assert!(
7985                    entry_view_state
7986                        .entry(0)
7987                        .unwrap()
7988                        .message_editor()
7989                        .is_some()
7990                );
7991                assert!(entry_view_state.entry(1).unwrap().has_content());
7992
7993                // Old views should be dropped
7994                assert!(entry_view_state.entry(2).is_none());
7995                assert!(entry_view_state.entry(3).is_none());
7996            });
7997        });
7998    }
7999
8000    #[gpui::test]
8001    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
8002        init_test(cx);
8003
8004        let connection = StubAgentConnection::new();
8005
8006        // Each user prompt will result in a user message entry plus an agent message entry.
8007        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8008            acp::ContentChunk::new("Response 1".into()),
8009        )]);
8010
8011        let (thread_view, cx) =
8012            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8013
8014        let thread = thread_view
8015            .read_with(cx, |view, _| view.thread().cloned())
8016            .unwrap();
8017
8018        thread
8019            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
8020            .await
8021            .unwrap();
8022        cx.run_until_parked();
8023
8024        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8025            acp::ContentChunk::new("Response 2".into()),
8026        )]);
8027
8028        thread
8029            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
8030            .await
8031            .unwrap();
8032        cx.run_until_parked();
8033
8034        // Move somewhere else first so we're not trivially already on the last user prompt.
8035        thread_view.update(cx, |view, cx| {
8036            view.scroll_to_top(cx);
8037        });
8038        cx.run_until_parked();
8039
8040        thread_view.update(cx, |view, cx| {
8041            view.scroll_to_most_recent_user_prompt(cx);
8042            let scroll_top = view.list_state.logical_scroll_top();
8043            // Entries layout is: [User1, Assistant1, User2, Assistant2]
8044            assert_eq!(scroll_top.item_ix, 2);
8045        });
8046    }
8047
8048    #[gpui::test]
8049    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
8050        cx: &mut TestAppContext,
8051    ) {
8052        init_test(cx);
8053
8054        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8055
8056        // With no entries, scrolling should be a no-op and must not panic.
8057        thread_view.update(cx, |view, cx| {
8058            view.scroll_to_most_recent_user_prompt(cx);
8059            let scroll_top = view.list_state.logical_scroll_top();
8060            assert_eq!(scroll_top.item_ix, 0);
8061        });
8062    }
8063
8064    #[gpui::test]
8065    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
8066        init_test(cx);
8067
8068        let connection = StubAgentConnection::new();
8069
8070        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8071            acp::ContentChunk::new("Response".into()),
8072        )]);
8073
8074        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8075        add_to_workspace(thread_view.clone(), cx);
8076
8077        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8078        message_editor.update_in(cx, |editor, window, cx| {
8079            editor.set_text("Original message to edit", window, cx);
8080        });
8081        thread_view.update_in(cx, |thread_view, window, cx| {
8082            thread_view.send(window, cx);
8083        });
8084
8085        cx.run_until_parked();
8086
8087        let user_message_editor = thread_view.read_with(cx, |view, cx| {
8088            assert_eq!(view.editing_message, None);
8089
8090            view.entry_view_state
8091                .read(cx)
8092                .entry(0)
8093                .unwrap()
8094                .message_editor()
8095                .unwrap()
8096                .clone()
8097        });
8098
8099        // Focus
8100        cx.focus(&user_message_editor);
8101        thread_view.read_with(cx, |view, _cx| {
8102            assert_eq!(view.editing_message, Some(0));
8103        });
8104
8105        // Edit
8106        user_message_editor.update_in(cx, |editor, window, cx| {
8107            editor.set_text("Edited message content", window, cx);
8108        });
8109
8110        // Cancel
8111        user_message_editor.update_in(cx, |_editor, window, cx| {
8112            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
8113        });
8114
8115        thread_view.read_with(cx, |view, _cx| {
8116            assert_eq!(view.editing_message, None);
8117        });
8118
8119        user_message_editor.read_with(cx, |editor, cx| {
8120            assert_eq!(editor.text(cx), "Original message to edit");
8121        });
8122    }
8123
8124    #[gpui::test]
8125    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
8126        init_test(cx);
8127
8128        let connection = StubAgentConnection::new();
8129
8130        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8131        add_to_workspace(thread_view.clone(), cx);
8132
8133        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8134        let mut events = cx.events(&message_editor);
8135        message_editor.update_in(cx, |editor, window, cx| {
8136            editor.set_text("", window, cx);
8137        });
8138
8139        message_editor.update_in(cx, |_editor, window, cx| {
8140            window.dispatch_action(Box::new(Chat), cx);
8141        });
8142        cx.run_until_parked();
8143        // We shouldn't have received any messages
8144        assert!(matches!(
8145            events.try_next(),
8146            Err(futures::channel::mpsc::TryRecvError { .. })
8147        ));
8148    }
8149
8150    #[gpui::test]
8151    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
8152        init_test(cx);
8153
8154        let connection = StubAgentConnection::new();
8155
8156        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8157            acp::ContentChunk::new("Response".into()),
8158        )]);
8159
8160        let (thread_view, cx) =
8161            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8162        add_to_workspace(thread_view.clone(), cx);
8163
8164        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8165        message_editor.update_in(cx, |editor, window, cx| {
8166            editor.set_text("Original message to edit", window, cx);
8167        });
8168        thread_view.update_in(cx, |thread_view, window, cx| {
8169            thread_view.send(window, cx);
8170        });
8171
8172        cx.run_until_parked();
8173
8174        let user_message_editor = thread_view.read_with(cx, |view, cx| {
8175            assert_eq!(view.editing_message, None);
8176            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
8177
8178            view.entry_view_state
8179                .read(cx)
8180                .entry(0)
8181                .unwrap()
8182                .message_editor()
8183                .unwrap()
8184                .clone()
8185        });
8186
8187        // Focus
8188        cx.focus(&user_message_editor);
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        // Send
8196        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8197            acp::ContentChunk::new("New Response".into()),
8198        )]);
8199
8200        user_message_editor.update_in(cx, |_editor, window, cx| {
8201            window.dispatch_action(Box::new(Chat), cx);
8202        });
8203
8204        cx.run_until_parked();
8205
8206        thread_view.read_with(cx, |view, cx| {
8207            assert_eq!(view.editing_message, None);
8208
8209            let entries = view.thread().unwrap().read(cx).entries();
8210            assert_eq!(entries.len(), 2);
8211            assert_eq!(
8212                entries[0].to_markdown(cx),
8213                "## User\n\nEdited message content\n\n"
8214            );
8215            assert_eq!(
8216                entries[1].to_markdown(cx),
8217                "## Assistant\n\nNew Response\n\n"
8218            );
8219
8220            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
8221                assert!(!state.entry(1).unwrap().has_content());
8222                state.entry(0).unwrap().message_editor().unwrap().clone()
8223            });
8224
8225            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
8226        })
8227    }
8228
8229    #[gpui::test]
8230    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
8231        init_test(cx);
8232
8233        let connection = StubAgentConnection::new();
8234
8235        let (thread_view, cx) =
8236            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8237        add_to_workspace(thread_view.clone(), cx);
8238
8239        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8240        message_editor.update_in(cx, |editor, window, cx| {
8241            editor.set_text("Original message to edit", window, cx);
8242        });
8243        thread_view.update_in(cx, |thread_view, window, cx| {
8244            thread_view.send(window, cx);
8245        });
8246
8247        cx.run_until_parked();
8248
8249        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
8250            let thread = view.thread().unwrap().read(cx);
8251            assert_eq!(thread.entries().len(), 1);
8252
8253            let editor = view
8254                .entry_view_state
8255                .read(cx)
8256                .entry(0)
8257                .unwrap()
8258                .message_editor()
8259                .unwrap()
8260                .clone();
8261
8262            (editor, thread.session_id().clone())
8263        });
8264
8265        // Focus
8266        cx.focus(&user_message_editor);
8267
8268        thread_view.read_with(cx, |view, _cx| {
8269            assert_eq!(view.editing_message, Some(0));
8270        });
8271
8272        // Edit
8273        user_message_editor.update_in(cx, |editor, window, cx| {
8274            editor.set_text("Edited message content", window, cx);
8275        });
8276
8277        thread_view.read_with(cx, |view, _cx| {
8278            assert_eq!(view.editing_message, Some(0));
8279        });
8280
8281        // Finish streaming response
8282        cx.update(|_, cx| {
8283            connection.send_update(
8284                session_id.clone(),
8285                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
8286                cx,
8287            );
8288            connection.end_turn(session_id, acp::StopReason::EndTurn);
8289        });
8290
8291        thread_view.read_with(cx, |view, _cx| {
8292            assert_eq!(view.editing_message, Some(0));
8293        });
8294
8295        cx.run_until_parked();
8296
8297        // Should still be editing
8298        cx.update(|window, cx| {
8299            assert!(user_message_editor.focus_handle(cx).is_focused(window));
8300            assert_eq!(thread_view.read(cx).editing_message, Some(0));
8301            assert_eq!(
8302                user_message_editor.read(cx).text(cx),
8303                "Edited message content"
8304            );
8305        });
8306    }
8307
8308    struct GeneratingThreadSetup {
8309        thread_view: Entity<AcpThreadView>,
8310        thread: Entity<AcpThread>,
8311        message_editor: Entity<MessageEditor>,
8312    }
8313
8314    async fn setup_generating_thread(
8315        cx: &mut TestAppContext,
8316    ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
8317        let connection = StubAgentConnection::new();
8318
8319        let (thread_view, cx) =
8320            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8321        add_to_workspace(thread_view.clone(), cx);
8322
8323        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8324        message_editor.update_in(cx, |editor, window, cx| {
8325            editor.set_text("Hello", window, cx);
8326        });
8327        thread_view.update_in(cx, |thread_view, window, cx| {
8328            thread_view.send(window, cx);
8329        });
8330
8331        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8332            let thread = view.thread().unwrap();
8333            (thread.clone(), thread.read(cx).session_id().clone())
8334        });
8335
8336        cx.run_until_parked();
8337
8338        cx.update(|_, cx| {
8339            connection.send_update(
8340                session_id.clone(),
8341                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8342                    "Response chunk".into(),
8343                )),
8344                cx,
8345            );
8346        });
8347
8348        cx.run_until_parked();
8349
8350        thread.read_with(cx, |thread, _cx| {
8351            assert_eq!(thread.status(), ThreadStatus::Generating);
8352        });
8353
8354        (
8355            GeneratingThreadSetup {
8356                thread_view,
8357                thread,
8358                message_editor,
8359            },
8360            cx,
8361        )
8362    }
8363
8364    #[gpui::test]
8365    async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
8366        init_test(cx);
8367
8368        let (setup, cx) = setup_generating_thread(cx).await;
8369
8370        let focus_handle = setup
8371            .thread_view
8372            .read_with(cx, |view, _cx| view.focus_handle.clone());
8373        cx.update(|window, cx| {
8374            window.focus(&focus_handle, cx);
8375        });
8376
8377        setup.thread_view.update_in(cx, |_, window, cx| {
8378            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8379        });
8380
8381        cx.run_until_parked();
8382
8383        setup.thread.read_with(cx, |thread, _cx| {
8384            assert_eq!(thread.status(), ThreadStatus::Idle);
8385        });
8386    }
8387
8388    #[gpui::test]
8389    async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
8390        init_test(cx);
8391
8392        let (setup, cx) = setup_generating_thread(cx).await;
8393
8394        let editor_focus_handle = setup
8395            .message_editor
8396            .read_with(cx, |editor, cx| editor.focus_handle(cx));
8397        cx.update(|window, cx| {
8398            window.focus(&editor_focus_handle, cx);
8399        });
8400
8401        setup.message_editor.update_in(cx, |_, window, cx| {
8402            window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
8403        });
8404
8405        cx.run_until_parked();
8406
8407        setup.thread.read_with(cx, |thread, _cx| {
8408            assert_eq!(thread.status(), ThreadStatus::Idle);
8409        });
8410    }
8411
8412    #[gpui::test]
8413    async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
8414        init_test(cx);
8415
8416        let (thread_view, cx) =
8417            setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
8418        add_to_workspace(thread_view.clone(), cx);
8419
8420        let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
8421
8422        thread.read_with(cx, |thread, _cx| {
8423            assert_eq!(thread.status(), ThreadStatus::Idle);
8424        });
8425
8426        let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
8427        cx.update(|window, cx| {
8428            window.focus(&focus_handle, cx);
8429        });
8430
8431        thread_view.update_in(cx, |_, window, cx| {
8432            window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8433        });
8434
8435        cx.run_until_parked();
8436
8437        thread.read_with(cx, |thread, _cx| {
8438            assert_eq!(thread.status(), ThreadStatus::Idle);
8439        });
8440    }
8441
8442    #[gpui::test]
8443    async fn test_interrupt(cx: &mut TestAppContext) {
8444        init_test(cx);
8445
8446        let connection = StubAgentConnection::new();
8447
8448        let (thread_view, cx) =
8449            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8450        add_to_workspace(thread_view.clone(), cx);
8451
8452        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8453        message_editor.update_in(cx, |editor, window, cx| {
8454            editor.set_text("Message 1", window, cx);
8455        });
8456        thread_view.update_in(cx, |thread_view, window, cx| {
8457            thread_view.send(window, cx);
8458        });
8459
8460        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8461            let thread = view.thread().unwrap();
8462
8463            (thread.clone(), thread.read(cx).session_id().clone())
8464        });
8465
8466        cx.run_until_parked();
8467
8468        cx.update(|_, cx| {
8469            connection.send_update(
8470                session_id.clone(),
8471                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8472                    "Message 1 resp".into(),
8473                )),
8474                cx,
8475            );
8476        });
8477
8478        cx.run_until_parked();
8479
8480        thread.read_with(cx, |thread, cx| {
8481            assert_eq!(
8482                thread.to_markdown(cx),
8483                indoc::indoc! {"
8484                    ## User
8485
8486                    Message 1
8487
8488                    ## Assistant
8489
8490                    Message 1 resp
8491
8492                "}
8493            )
8494        });
8495
8496        message_editor.update_in(cx, |editor, window, cx| {
8497            editor.set_text("Message 2", window, cx);
8498        });
8499        thread_view.update_in(cx, |thread_view, window, cx| {
8500            thread_view.send(window, cx);
8501        });
8502
8503        cx.update(|_, cx| {
8504            // Simulate a response sent after beginning to cancel
8505            connection.send_update(
8506                session_id.clone(),
8507                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
8508                cx,
8509            );
8510        });
8511
8512        cx.run_until_parked();
8513
8514        // Last Message 1 response should appear before Message 2
8515        thread.read_with(cx, |thread, cx| {
8516            assert_eq!(
8517                thread.to_markdown(cx),
8518                indoc::indoc! {"
8519                    ## User
8520
8521                    Message 1
8522
8523                    ## Assistant
8524
8525                    Message 1 response
8526
8527                    ## User
8528
8529                    Message 2
8530
8531                "}
8532            )
8533        });
8534
8535        cx.update(|_, cx| {
8536            connection.send_update(
8537                session_id.clone(),
8538                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8539                    "Message 2 response".into(),
8540                )),
8541                cx,
8542            );
8543            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
8544        });
8545
8546        cx.run_until_parked();
8547
8548        thread.read_with(cx, |thread, cx| {
8549            assert_eq!(
8550                thread.to_markdown(cx),
8551                indoc::indoc! {"
8552                    ## User
8553
8554                    Message 1
8555
8556                    ## Assistant
8557
8558                    Message 1 response
8559
8560                    ## User
8561
8562                    Message 2
8563
8564                    ## Assistant
8565
8566                    Message 2 response
8567
8568                "}
8569            )
8570        });
8571    }
8572
8573    #[gpui::test]
8574    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
8575        init_test(cx);
8576
8577        let connection = StubAgentConnection::new();
8578        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8579            acp::ContentChunk::new("Response".into()),
8580        )]);
8581
8582        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8583        add_to_workspace(thread_view.clone(), cx);
8584
8585        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8586        message_editor.update_in(cx, |editor, window, cx| {
8587            editor.set_text("Original message to edit", window, cx)
8588        });
8589        thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
8590        cx.run_until_parked();
8591
8592        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
8593            thread_view
8594                .entry_view_state
8595                .read(cx)
8596                .entry(0)
8597                .expect("Should have at least one entry")
8598                .message_editor()
8599                .expect("Should have message editor")
8600                .clone()
8601        });
8602
8603        cx.focus(&user_message_editor);
8604        thread_view.read_with(cx, |thread_view, _cx| {
8605            assert_eq!(thread_view.editing_message, Some(0));
8606        });
8607
8608        // Ensure to edit the focused message before proceeding otherwise, since
8609        // its content is not different from what was sent, focus will be lost.
8610        user_message_editor.update_in(cx, |editor, window, cx| {
8611            editor.set_text("Original message to edit with ", window, cx)
8612        });
8613
8614        // Create a simple buffer with some text so we can create a selection
8615        // that will then be added to the message being edited.
8616        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8617            (thread_view.workspace.clone(), thread_view.project.clone())
8618        });
8619        let buffer = project.update(cx, |project, cx| {
8620            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8621        });
8622
8623        workspace
8624            .update_in(cx, |workspace, window, cx| {
8625                let editor = cx.new(|cx| {
8626                    let mut editor =
8627                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8628
8629                    editor.change_selections(Default::default(), window, cx, |selections| {
8630                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8631                    });
8632
8633                    editor
8634                });
8635                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8636            })
8637            .unwrap();
8638
8639        thread_view.update_in(cx, |thread_view, window, cx| {
8640            assert_eq!(thread_view.editing_message, Some(0));
8641            thread_view.insert_selections(window, cx);
8642        });
8643
8644        user_message_editor.read_with(cx, |editor, cx| {
8645            let text = editor.editor().read(cx).text(cx);
8646            let expected_text = String::from("Original message to edit with selection ");
8647
8648            assert_eq!(text, expected_text);
8649        });
8650    }
8651
8652    #[gpui::test]
8653    async fn test_insert_selections(cx: &mut TestAppContext) {
8654        init_test(cx);
8655
8656        let connection = StubAgentConnection::new();
8657        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8658            acp::ContentChunk::new("Response".into()),
8659        )]);
8660
8661        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8662        add_to_workspace(thread_view.clone(), cx);
8663
8664        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8665        message_editor.update_in(cx, |editor, window, cx| {
8666            editor.set_text("Can you review this snippet ", window, cx)
8667        });
8668
8669        // Create a simple buffer with some text so we can create a selection
8670        // that will then be added to the message being edited.
8671        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8672            (thread_view.workspace.clone(), thread_view.project.clone())
8673        });
8674        let buffer = project.update(cx, |project, cx| {
8675            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8676        });
8677
8678        workspace
8679            .update_in(cx, |workspace, window, cx| {
8680                let editor = cx.new(|cx| {
8681                    let mut editor =
8682                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8683
8684                    editor.change_selections(Default::default(), window, cx, |selections| {
8685                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8686                    });
8687
8688                    editor
8689                });
8690                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8691            })
8692            .unwrap();
8693
8694        thread_view.update_in(cx, |thread_view, window, cx| {
8695            assert_eq!(thread_view.editing_message, None);
8696            thread_view.insert_selections(window, cx);
8697        });
8698
8699        thread_view.read_with(cx, |thread_view, cx| {
8700            let text = thread_view.message_editor.read(cx).text(cx);
8701            let expected_txt = String::from("Can you review this snippet selection ");
8702
8703            assert_eq!(text, expected_txt);
8704        })
8705    }
8706}