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