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).primary_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_max_range_for_buffer(
4107                                                            buffer.read(cx).remote_id(),
4108                                                        )],
4109                                                        Some(telemetry.clone()),
4110                                                        cx,
4111                                                    )
4112                                                    .detach_and_log_err(cx);
4113                                            })
4114                                        }
4115                                    }),
4116                            )
4117                            .child(
4118                                Button::new("keep-file", "Keep")
4119                                    .label_size(LabelSize::Small)
4120                                    .disabled(pending_edits)
4121                                    .on_click({
4122                                        let buffer = buffer.clone();
4123                                        let action_log = action_log.clone();
4124                                        let telemetry = telemetry.clone();
4125                                        move |_, _, cx| {
4126                                            action_log.update(cx, |action_log, cx| {
4127                                                action_log.keep_edits_in_range(
4128                                                    buffer.clone(),
4129                                                    Anchor::min_max_range_for_buffer(
4130                                                        buffer.read(cx).remote_id(),
4131                                                    ),
4132                                                    Some(telemetry.clone()),
4133                                                    cx,
4134                                                );
4135                                            })
4136                                        }
4137                                    }),
4138                            ),
4139                    );
4140
4141                Some(element)
4142            },
4143        ))
4144    }
4145
4146    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
4147        let focus_handle = self.message_editor.focus_handle(cx);
4148        let editor_bg_color = cx.theme().colors().editor_background;
4149        let (expand_icon, expand_tooltip) = if self.editor_expanded {
4150            (IconName::Minimize, "Minimize Message Editor")
4151        } else {
4152            (IconName::Maximize, "Expand Message Editor")
4153        };
4154
4155        let backdrop = div()
4156            .size_full()
4157            .absolute()
4158            .inset_0()
4159            .bg(cx.theme().colors().panel_background)
4160            .opacity(0.8)
4161            .block_mouse_except_scroll();
4162
4163        let enable_editor = match self.thread_state {
4164            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
4165            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
4166        };
4167
4168        v_flex()
4169            .on_action(cx.listener(Self::expand_message_editor))
4170            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
4171                if let Some(profile_selector) = this.profile_selector.as_ref() {
4172                    profile_selector.read(cx).menu_handle().toggle(window, cx);
4173                } else if let Some(mode_selector) = this.mode_selector() {
4174                    mode_selector.read(cx).menu_handle().toggle(window, cx);
4175                }
4176            }))
4177            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
4178                if let Some(mode_selector) = this.mode_selector() {
4179                    mode_selector.update(cx, |mode_selector, cx| {
4180                        mode_selector.cycle_mode(window, cx);
4181                    });
4182                }
4183            }))
4184            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
4185                if let Some(model_selector) = this.model_selector.as_ref() {
4186                    model_selector
4187                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
4188                }
4189            }))
4190            .p_2()
4191            .gap_2()
4192            .border_t_1()
4193            .border_color(cx.theme().colors().border)
4194            .bg(editor_bg_color)
4195            .when(self.editor_expanded, |this| {
4196                this.h(vh(0.8, window)).size_full().justify_between()
4197            })
4198            .child(
4199                v_flex()
4200                    .relative()
4201                    .size_full()
4202                    .pt_1()
4203                    .pr_2p5()
4204                    .child(self.message_editor.clone())
4205                    .child(
4206                        h_flex()
4207                            .absolute()
4208                            .top_0()
4209                            .right_0()
4210                            .opacity(0.5)
4211                            .hover(|this| this.opacity(1.0))
4212                            .child(
4213                                IconButton::new("toggle-height", expand_icon)
4214                                    .icon_size(IconSize::Small)
4215                                    .icon_color(Color::Muted)
4216                                    .tooltip({
4217                                        move |_window, cx| {
4218                                            Tooltip::for_action_in(
4219                                                expand_tooltip,
4220                                                &ExpandMessageEditor,
4221                                                &focus_handle,
4222                                                cx,
4223                                            )
4224                                        }
4225                                    })
4226                                    .on_click(cx.listener(|this, _, window, cx| {
4227                                        this.expand_message_editor(
4228                                            &ExpandMessageEditor,
4229                                            window,
4230                                            cx,
4231                                        );
4232                                    })),
4233                            ),
4234                    ),
4235            )
4236            .child(
4237                h_flex()
4238                    .flex_none()
4239                    .flex_wrap()
4240                    .justify_between()
4241                    .child(
4242                        h_flex()
4243                            .gap_0p5()
4244                            .child(self.render_add_context_button(cx))
4245                            .child(self.render_follow_toggle(cx))
4246                            .children(self.render_burn_mode_toggle(cx)),
4247                    )
4248                    .child(
4249                        h_flex()
4250                            .gap_1()
4251                            .children(self.render_token_usage(cx))
4252                            .children(self.profile_selector.clone())
4253                            .children(self.mode_selector().cloned())
4254                            .children(self.model_selector.clone())
4255                            .child(self.render_send_button(cx)),
4256                    ),
4257            )
4258            .when(!enable_editor, |this| this.child(backdrop))
4259            .into_any()
4260    }
4261
4262    pub(crate) fn as_native_connection(
4263        &self,
4264        cx: &App,
4265    ) -> Option<Rc<agent::NativeAgentConnection>> {
4266        let acp_thread = self.thread()?.read(cx);
4267        acp_thread.connection().clone().downcast()
4268    }
4269
4270    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4271        let acp_thread = self.thread()?.read(cx);
4272        self.as_native_connection(cx)?
4273            .thread(acp_thread.session_id(), cx)
4274    }
4275
4276    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4277        self.as_native_thread(cx)
4278            .and_then(|thread| thread.read(cx).model())
4279            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4280    }
4281
4282    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4283        let thread = self.thread()?.read(cx);
4284        let usage = thread.token_usage()?;
4285        let is_generating = thread.status() != ThreadStatus::Idle;
4286
4287        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4288        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4289
4290        Some(
4291            h_flex()
4292                .flex_shrink_0()
4293                .gap_0p5()
4294                .mr_1p5()
4295                .child(
4296                    Label::new(used)
4297                        .size(LabelSize::Small)
4298                        .color(Color::Muted)
4299                        .map(|label| {
4300                            if is_generating {
4301                                label
4302                                    .with_animation(
4303                                        "used-tokens-label",
4304                                        Animation::new(Duration::from_secs(2))
4305                                            .repeat()
4306                                            .with_easing(pulsating_between(0.3, 0.8)),
4307                                        |label, delta| label.alpha(delta),
4308                                    )
4309                                    .into_any()
4310                            } else {
4311                                label.into_any_element()
4312                            }
4313                        }),
4314                )
4315                .child(
4316                    Label::new("/")
4317                        .size(LabelSize::Small)
4318                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4319                )
4320                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4321        )
4322    }
4323
4324    fn toggle_burn_mode(
4325        &mut self,
4326        _: &ToggleBurnMode,
4327        _window: &mut Window,
4328        cx: &mut Context<Self>,
4329    ) {
4330        let Some(thread) = self.as_native_thread(cx) else {
4331            return;
4332        };
4333
4334        thread.update(cx, |thread, cx| {
4335            let current_mode = thread.completion_mode();
4336            thread.set_completion_mode(
4337                match current_mode {
4338                    CompletionMode::Burn => CompletionMode::Normal,
4339                    CompletionMode::Normal => CompletionMode::Burn,
4340                },
4341                cx,
4342            );
4343        });
4344    }
4345
4346    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4347        let Some(thread) = self.thread() else {
4348            return;
4349        };
4350        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4351        let action_log = thread.read(cx).action_log().clone();
4352        action_log.update(cx, |action_log, cx| {
4353            action_log.keep_all_edits(Some(telemetry), cx)
4354        });
4355    }
4356
4357    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4358        let Some(thread) = self.thread() else {
4359            return;
4360        };
4361        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4362        let action_log = thread.read(cx).action_log().clone();
4363        action_log
4364            .update(cx, |action_log, cx| {
4365                action_log.reject_all_edits(Some(telemetry), cx)
4366            })
4367            .detach();
4368    }
4369
4370    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4371        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4372    }
4373
4374    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4375        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4376    }
4377
4378    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4379        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4380    }
4381
4382    fn authorize_pending_tool_call(
4383        &mut self,
4384        kind: acp::PermissionOptionKind,
4385        window: &mut Window,
4386        cx: &mut Context<Self>,
4387    ) -> Option<()> {
4388        let thread = self.thread()?.read(cx);
4389        let tool_call = thread.first_tool_awaiting_confirmation()?;
4390        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4391            return None;
4392        };
4393        let option = options.iter().find(|o| o.kind == kind)?;
4394
4395        self.authorize_tool_call(
4396            tool_call.id.clone(),
4397            option.id.clone(),
4398            option.kind,
4399            window,
4400            cx,
4401        );
4402
4403        Some(())
4404    }
4405
4406    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4407        let thread = self.as_native_thread(cx)?.read(cx);
4408
4409        if thread
4410            .model()
4411            .is_none_or(|model| !model.supports_burn_mode())
4412        {
4413            return None;
4414        }
4415
4416        let active_completion_mode = thread.completion_mode();
4417        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4418        let icon = if burn_mode_enabled {
4419            IconName::ZedBurnModeOn
4420        } else {
4421            IconName::ZedBurnMode
4422        };
4423
4424        Some(
4425            IconButton::new("burn-mode", icon)
4426                .icon_size(IconSize::Small)
4427                .icon_color(Color::Muted)
4428                .toggle_state(burn_mode_enabled)
4429                .selected_icon_color(Color::Error)
4430                .on_click(cx.listener(|this, _event, window, cx| {
4431                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4432                }))
4433                .tooltip(move |_window, cx| {
4434                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4435                        .into()
4436                })
4437                .into_any_element(),
4438        )
4439    }
4440
4441    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4442        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4443        let is_generating = self
4444            .thread()
4445            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4446
4447        if self.is_loading_contents {
4448            div()
4449                .id("loading-message-content")
4450                .px_1()
4451                .tooltip(Tooltip::text("Loading Added Context…"))
4452                .child(loading_contents_spinner(IconSize::default()))
4453                .into_any_element()
4454        } else if is_generating && is_editor_empty {
4455            IconButton::new("stop-generation", IconName::Stop)
4456                .icon_color(Color::Error)
4457                .style(ButtonStyle::Tinted(ui::TintColor::Error))
4458                .tooltip(move |_window, cx| {
4459                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
4460                })
4461                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4462                .into_any_element()
4463        } else {
4464            let send_btn_tooltip = if is_editor_empty && !is_generating {
4465                "Type to Send"
4466            } else if is_generating {
4467                "Stop and Send Message"
4468            } else {
4469                "Send"
4470            };
4471
4472            IconButton::new("send-message", IconName::Send)
4473                .style(ButtonStyle::Filled)
4474                .map(|this| {
4475                    if is_editor_empty && !is_generating {
4476                        this.disabled(true).icon_color(Color::Muted)
4477                    } else {
4478                        this.icon_color(Color::Accent)
4479                    }
4480                })
4481                .tooltip(move |_window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, cx))
4482                .on_click(cx.listener(|this, _, window, cx| {
4483                    this.send(window, cx);
4484                }))
4485                .into_any_element()
4486        }
4487    }
4488
4489    fn is_following(&self, cx: &App) -> bool {
4490        match self.thread().map(|thread| thread.read(cx).status()) {
4491            Some(ThreadStatus::Generating) => self
4492                .workspace
4493                .read_with(cx, |workspace, _| {
4494                    workspace.is_being_followed(CollaboratorId::Agent)
4495                })
4496                .unwrap_or(false),
4497            _ => self.should_be_following,
4498        }
4499    }
4500
4501    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4502        let following = self.is_following(cx);
4503
4504        self.should_be_following = !following;
4505        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4506            self.workspace
4507                .update(cx, |workspace, cx| {
4508                    if following {
4509                        workspace.unfollow(CollaboratorId::Agent, window, cx);
4510                    } else {
4511                        workspace.follow(CollaboratorId::Agent, window, cx);
4512                    }
4513                })
4514                .ok();
4515        }
4516
4517        telemetry::event!("Follow Agent Selected", following = !following);
4518    }
4519
4520    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4521        let following = self.is_following(cx);
4522
4523        let tooltip_label = if following {
4524            if self.agent.name() == "Zed Agent" {
4525                format!("Stop Following the {}", self.agent.name())
4526            } else {
4527                format!("Stop Following {}", self.agent.name())
4528            }
4529        } else {
4530            if self.agent.name() == "Zed Agent" {
4531                format!("Follow the {}", self.agent.name())
4532            } else {
4533                format!("Follow {}", self.agent.name())
4534            }
4535        };
4536
4537        IconButton::new("follow-agent", IconName::Crosshair)
4538            .icon_size(IconSize::Small)
4539            .icon_color(Color::Muted)
4540            .toggle_state(following)
4541            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4542            .tooltip(move |_window, cx| {
4543                if following {
4544                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4545                } else {
4546                    Tooltip::with_meta(
4547                        tooltip_label.clone(),
4548                        Some(&Follow),
4549                        "Track the agent's location as it reads and edits files.",
4550                        cx,
4551                    )
4552                }
4553            })
4554            .on_click(cx.listener(move |this, _, window, cx| {
4555                this.toggle_following(window, cx);
4556            }))
4557    }
4558
4559    fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4560        let message_editor = self.message_editor.clone();
4561        let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
4562
4563        IconButton::new("add-context", IconName::AtSign)
4564            .icon_size(IconSize::Small)
4565            .icon_color(Color::Muted)
4566            .when(!menu_visible, |this| {
4567                this.tooltip(move |_window, cx| {
4568                    Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
4569                })
4570            })
4571            .on_click(cx.listener(move |_this, _, window, cx| {
4572                let message_editor_clone = message_editor.clone();
4573
4574                window.defer(cx, move |window, cx| {
4575                    message_editor_clone.update(cx, |message_editor, cx| {
4576                        message_editor.trigger_completion_menu(window, cx);
4577                    });
4578                });
4579            }))
4580    }
4581
4582    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4583        let workspace = self.workspace.clone();
4584        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4585            Self::open_link(text, &workspace, window, cx);
4586        })
4587    }
4588
4589    fn open_link(
4590        url: SharedString,
4591        workspace: &WeakEntity<Workspace>,
4592        window: &mut Window,
4593        cx: &mut App,
4594    ) {
4595        let Some(workspace) = workspace.upgrade() else {
4596            cx.open_url(&url);
4597            return;
4598        };
4599
4600        if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
4601        {
4602            workspace.update(cx, |workspace, cx| match mention {
4603                MentionUri::File { abs_path } => {
4604                    let project = workspace.project();
4605                    let Some(path) =
4606                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4607                    else {
4608                        return;
4609                    };
4610
4611                    workspace
4612                        .open_path(path, None, true, window, cx)
4613                        .detach_and_log_err(cx);
4614                }
4615                MentionUri::PastedImage => {}
4616                MentionUri::Directory { abs_path } => {
4617                    let project = workspace.project();
4618                    let Some(entry_id) = project.update(cx, |project, cx| {
4619                        let path = project.find_project_path(abs_path, cx)?;
4620                        project.entry_for_path(&path, cx).map(|entry| entry.id)
4621                    }) else {
4622                        return;
4623                    };
4624
4625                    project.update(cx, |_, cx| {
4626                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
4627                    });
4628                }
4629                MentionUri::Symbol {
4630                    abs_path: path,
4631                    line_range,
4632                    ..
4633                }
4634                | MentionUri::Selection {
4635                    abs_path: Some(path),
4636                    line_range,
4637                } => {
4638                    let project = workspace.project();
4639                    let Some(path) =
4640                        project.update(cx, |project, cx| project.find_project_path(path, cx))
4641                    else {
4642                        return;
4643                    };
4644
4645                    let item = workspace.open_path(path, None, true, window, cx);
4646                    window
4647                        .spawn(cx, async move |cx| {
4648                            let Some(editor) = item.await?.downcast::<Editor>() else {
4649                                return Ok(());
4650                            };
4651                            let range = Point::new(*line_range.start(), 0)
4652                                ..Point::new(*line_range.start(), 0);
4653                            editor
4654                                .update_in(cx, |editor, window, cx| {
4655                                    editor.change_selections(
4656                                        SelectionEffects::scroll(Autoscroll::center()),
4657                                        window,
4658                                        cx,
4659                                        |s| s.select_ranges(vec![range]),
4660                                    );
4661                                })
4662                                .ok();
4663                            anyhow::Ok(())
4664                        })
4665                        .detach_and_log_err(cx);
4666                }
4667                MentionUri::Selection { abs_path: None, .. } => {}
4668                MentionUri::Thread { id, name } => {
4669                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4670                        panel.update(cx, |panel, cx| {
4671                            panel.load_agent_thread(
4672                                DbThreadMetadata {
4673                                    id,
4674                                    title: name.into(),
4675                                    updated_at: Default::default(),
4676                                },
4677                                window,
4678                                cx,
4679                            )
4680                        });
4681                    }
4682                }
4683                MentionUri::TextThread { path, .. } => {
4684                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4685                        panel.update(cx, |panel, cx| {
4686                            panel
4687                                .open_saved_text_thread(path.as_path().into(), window, cx)
4688                                .detach_and_log_err(cx);
4689                        });
4690                    }
4691                }
4692                MentionUri::Rule { id, .. } => {
4693                    let PromptId::User { uuid } = id else {
4694                        return;
4695                    };
4696                    window.dispatch_action(
4697                        Box::new(OpenRulesLibrary {
4698                            prompt_to_select: Some(uuid.0),
4699                        }),
4700                        cx,
4701                    )
4702                }
4703                MentionUri::Fetch { url } => {
4704                    cx.open_url(url.as_str());
4705                }
4706            })
4707        } else {
4708            cx.open_url(&url);
4709        }
4710    }
4711
4712    fn open_tool_call_location(
4713        &self,
4714        entry_ix: usize,
4715        location_ix: usize,
4716        window: &mut Window,
4717        cx: &mut Context<Self>,
4718    ) -> Option<()> {
4719        let (tool_call_location, agent_location) = self
4720            .thread()?
4721            .read(cx)
4722            .entries()
4723            .get(entry_ix)?
4724            .location(location_ix)?;
4725
4726        let project_path = self
4727            .project
4728            .read(cx)
4729            .find_project_path(&tool_call_location.path, cx)?;
4730
4731        let open_task = self
4732            .workspace
4733            .update(cx, |workspace, cx| {
4734                workspace.open_path(project_path, None, true, window, cx)
4735            })
4736            .log_err()?;
4737        window
4738            .spawn(cx, async move |cx| {
4739                let item = open_task.await?;
4740
4741                let Some(active_editor) = item.downcast::<Editor>() else {
4742                    return anyhow::Ok(());
4743                };
4744
4745                active_editor.update_in(cx, |editor, window, cx| {
4746                    let multibuffer = editor.buffer().read(cx);
4747                    let buffer = multibuffer.as_singleton();
4748                    if agent_location.buffer.upgrade() == buffer {
4749                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4750                        let anchor =
4751                            editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
4752                        editor.change_selections(Default::default(), window, cx, |selections| {
4753                            selections.select_anchor_ranges([anchor..anchor]);
4754                        })
4755                    } else {
4756                        let row = tool_call_location.line.unwrap_or_default();
4757                        editor.change_selections(Default::default(), window, cx, |selections| {
4758                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4759                        })
4760                    }
4761                })?;
4762
4763                anyhow::Ok(())
4764            })
4765            .detach_and_log_err(cx);
4766
4767        None
4768    }
4769
4770    pub fn open_thread_as_markdown(
4771        &self,
4772        workspace: Entity<Workspace>,
4773        window: &mut Window,
4774        cx: &mut App,
4775    ) -> Task<Result<()>> {
4776        let markdown_language_task = workspace
4777            .read(cx)
4778            .app_state()
4779            .languages
4780            .language_for_name("Markdown");
4781
4782        let (thread_title, markdown) = if let Some(thread) = self.thread() {
4783            let thread = thread.read(cx);
4784            (thread.title().to_string(), thread.to_markdown(cx))
4785        } else {
4786            return Task::ready(Ok(()));
4787        };
4788
4789        let project = workspace.read(cx).project().clone();
4790        window.spawn(cx, async move |cx| {
4791            let markdown_language = markdown_language_task.await?;
4792
4793            let buffer = project
4794                .update(cx, |project, cx| project.create_buffer(false, cx))?
4795                .await?;
4796
4797            buffer.update(cx, |buffer, cx| {
4798                buffer.set_text(markdown, cx);
4799                buffer.set_language(Some(markdown_language), cx);
4800                buffer.set_capability(language::Capability::ReadWrite, cx);
4801            })?;
4802
4803            workspace.update_in(cx, |workspace, window, cx| {
4804                let buffer = cx
4805                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4806
4807                workspace.add_item_to_active_pane(
4808                    Box::new(cx.new(|cx| {
4809                        let mut editor =
4810                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4811                        editor.set_breadcrumb_header(thread_title);
4812                        editor
4813                    })),
4814                    None,
4815                    true,
4816                    window,
4817                    cx,
4818                );
4819            })?;
4820            anyhow::Ok(())
4821        })
4822    }
4823
4824    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4825        self.list_state.scroll_to(ListOffset::default());
4826        cx.notify();
4827    }
4828
4829    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4830        if let Some(thread) = self.thread() {
4831            let entry_count = thread.read(cx).entries().len();
4832            self.list_state.reset(entry_count);
4833            cx.notify();
4834        }
4835    }
4836
4837    fn notify_with_sound(
4838        &mut self,
4839        caption: impl Into<SharedString>,
4840        icon: IconName,
4841        window: &mut Window,
4842        cx: &mut Context<Self>,
4843    ) {
4844        self.play_notification_sound(window, cx);
4845        self.show_notification(caption, icon, window, cx);
4846    }
4847
4848    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4849        let settings = AgentSettings::get_global(cx);
4850        if settings.play_sound_when_agent_done && !window.is_window_active() {
4851            Audio::play_sound(Sound::AgentDone, cx);
4852        }
4853    }
4854
4855    fn show_notification(
4856        &mut self,
4857        caption: impl Into<SharedString>,
4858        icon: IconName,
4859        window: &mut Window,
4860        cx: &mut Context<Self>,
4861    ) {
4862        if !self.notifications.is_empty() {
4863            return;
4864        }
4865
4866        let settings = AgentSettings::get_global(cx);
4867
4868        let window_is_inactive = !window.is_window_active();
4869        let panel_is_hidden = self
4870            .workspace
4871            .upgrade()
4872            .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
4873            .unwrap_or(true);
4874
4875        let should_notify = window_is_inactive || panel_is_hidden;
4876
4877        if !should_notify {
4878            return;
4879        }
4880
4881        // TODO: Change this once we have title summarization for external agents.
4882        let title = self.agent.name();
4883
4884        match settings.notify_when_agent_waiting {
4885            NotifyWhenAgentWaiting::PrimaryScreen => {
4886                if let Some(primary) = cx.primary_display() {
4887                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4888                }
4889            }
4890            NotifyWhenAgentWaiting::AllScreens => {
4891                let caption = caption.into();
4892                for screen in cx.displays() {
4893                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4894                }
4895            }
4896            NotifyWhenAgentWaiting::Never => {
4897                // Don't show anything
4898            }
4899        }
4900    }
4901
4902    fn pop_up(
4903        &mut self,
4904        icon: IconName,
4905        caption: SharedString,
4906        title: SharedString,
4907        window: &mut Window,
4908        screen: Rc<dyn PlatformDisplay>,
4909        cx: &mut Context<Self>,
4910    ) {
4911        let options = AgentNotification::window_options(screen, cx);
4912
4913        let project_name = self.workspace.upgrade().and_then(|workspace| {
4914            workspace
4915                .read(cx)
4916                .project()
4917                .read(cx)
4918                .visible_worktrees(cx)
4919                .next()
4920                .map(|worktree| worktree.read(cx).root_name_str().to_string())
4921        });
4922
4923        if let Some(screen_window) = cx
4924            .open_window(options, |_, cx| {
4925                cx.new(|_| {
4926                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4927                })
4928            })
4929            .log_err()
4930            && let Some(pop_up) = screen_window.entity(cx).log_err()
4931        {
4932            self.notification_subscriptions
4933                .entry(screen_window)
4934                .or_insert_with(Vec::new)
4935                .push(cx.subscribe_in(&pop_up, window, {
4936                    |this, _, event, window, cx| match event {
4937                        AgentNotificationEvent::Accepted => {
4938                            let handle = window.window_handle();
4939                            cx.activate(true);
4940
4941                            let workspace_handle = this.workspace.clone();
4942
4943                            // If there are multiple Zed windows, activate the correct one.
4944                            cx.defer(move |cx| {
4945                                handle
4946                                    .update(cx, |_view, window, _cx| {
4947                                        window.activate_window();
4948
4949                                        if let Some(workspace) = workspace_handle.upgrade() {
4950                                            workspace.update(_cx, |workspace, cx| {
4951                                                workspace.focus_panel::<AgentPanel>(window, cx);
4952                                            });
4953                                        }
4954                                    })
4955                                    .log_err();
4956                            });
4957
4958                            this.dismiss_notifications(cx);
4959                        }
4960                        AgentNotificationEvent::Dismissed => {
4961                            this.dismiss_notifications(cx);
4962                        }
4963                    }
4964                }));
4965
4966            self.notifications.push(screen_window);
4967
4968            // If the user manually refocuses the original window, dismiss the popup.
4969            self.notification_subscriptions
4970                .entry(screen_window)
4971                .or_insert_with(Vec::new)
4972                .push({
4973                    let pop_up_weak = pop_up.downgrade();
4974
4975                    cx.observe_window_activation(window, move |_, window, cx| {
4976                        if window.is_window_active()
4977                            && let Some(pop_up) = pop_up_weak.upgrade()
4978                        {
4979                            pop_up.update(cx, |_, cx| {
4980                                cx.emit(AgentNotificationEvent::Dismissed);
4981                            });
4982                        }
4983                    })
4984                });
4985        }
4986    }
4987
4988    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4989        for window in self.notifications.drain(..) {
4990            window
4991                .update(cx, |_, window, _| {
4992                    window.remove_window();
4993                })
4994                .ok();
4995
4996            self.notification_subscriptions.remove(&window);
4997        }
4998    }
4999
5000    fn render_generating(&self, confirmation: bool) -> impl IntoElement {
5001        h_flex()
5002            .id("generating-spinner")
5003            .py_2()
5004            .px(rems_from_px(22.))
5005            .map(|this| {
5006                if confirmation {
5007                    this.gap_2()
5008                        .child(
5009                            h_flex()
5010                                .w_2()
5011                                .child(SpinnerLabel::sand().size(LabelSize::Small)),
5012                        )
5013                        .child(
5014                            LoadingLabel::new("Waiting Confirmation")
5015                                .size(LabelSize::Small)
5016                                .color(Color::Muted),
5017                        )
5018                } else {
5019                    this.child(SpinnerLabel::new().size(LabelSize::Small))
5020                }
5021            })
5022            .into_any_element()
5023    }
5024
5025    fn render_thread_controls(
5026        &self,
5027        thread: &Entity<AcpThread>,
5028        cx: &Context<Self>,
5029    ) -> impl IntoElement {
5030        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
5031        if is_generating {
5032            return self.render_generating(false).into_any_element();
5033        }
5034
5035        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
5036            .shape(ui::IconButtonShape::Square)
5037            .icon_size(IconSize::Small)
5038            .icon_color(Color::Ignored)
5039            .tooltip(Tooltip::text("Open Thread as Markdown"))
5040            .on_click(cx.listener(move |this, _, window, cx| {
5041                if let Some(workspace) = this.workspace.upgrade() {
5042                    this.open_thread_as_markdown(workspace, window, cx)
5043                        .detach_and_log_err(cx);
5044                }
5045            }));
5046
5047        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
5048            .shape(ui::IconButtonShape::Square)
5049            .icon_size(IconSize::Small)
5050            .icon_color(Color::Ignored)
5051            .tooltip(Tooltip::text("Scroll To Top"))
5052            .on_click(cx.listener(move |this, _, _, cx| {
5053                this.scroll_to_top(cx);
5054            }));
5055
5056        let mut container = h_flex()
5057            .w_full()
5058            .py_2()
5059            .px_5()
5060            .gap_px()
5061            .opacity(0.6)
5062            .hover(|s| s.opacity(1.))
5063            .justify_end();
5064
5065        if AgentSettings::get_global(cx).enable_feedback
5066            && self
5067                .thread()
5068                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5069        {
5070            let feedback = self.thread_feedback.feedback;
5071
5072            let tooltip_meta = || {
5073                SharedString::new(
5074                    "Rating the thread sends all of your current conversation to the Zed team.",
5075                )
5076            };
5077
5078            container = container
5079                .child(
5080                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5081                        .shape(ui::IconButtonShape::Square)
5082                        .icon_size(IconSize::Small)
5083                        .icon_color(match feedback {
5084                            Some(ThreadFeedback::Positive) => Color::Accent,
5085                            _ => Color::Ignored,
5086                        })
5087                        .tooltip(move |window, cx| match feedback {
5088                            Some(ThreadFeedback::Positive) => {
5089                                Tooltip::text("Thanks for your feedback!")(window, cx)
5090                            }
5091                            _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
5092                        })
5093                        .on_click(cx.listener(move |this, _, window, cx| {
5094                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5095                        })),
5096                )
5097                .child(
5098                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5099                        .shape(ui::IconButtonShape::Square)
5100                        .icon_size(IconSize::Small)
5101                        .icon_color(match feedback {
5102                            Some(ThreadFeedback::Negative) => Color::Accent,
5103                            _ => Color::Ignored,
5104                        })
5105                        .tooltip(move |window, cx| match feedback {
5106                            Some(ThreadFeedback::Negative) => {
5107                                Tooltip::text(
5108                                    "We appreciate your feedback and will use it to improve in the future.",
5109                                )(window, cx)
5110                            }
5111                            _ => {
5112                                Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
5113                            }
5114                        })
5115                        .on_click(cx.listener(move |this, _, window, cx| {
5116                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5117                        })),
5118                );
5119        }
5120
5121        container
5122            .child(open_as_markdown)
5123            .child(scroll_to_top)
5124            .into_any_element()
5125    }
5126
5127    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5128        h_flex()
5129            .key_context("AgentFeedbackMessageEditor")
5130            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5131                this.thread_feedback.dismiss_comments();
5132                cx.notify();
5133            }))
5134            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5135                this.submit_feedback_message(cx);
5136            }))
5137            .p_2()
5138            .mb_2()
5139            .mx_5()
5140            .gap_1()
5141            .rounded_md()
5142            .border_1()
5143            .border_color(cx.theme().colors().border)
5144            .bg(cx.theme().colors().editor_background)
5145            .child(div().w_full().child(editor))
5146            .child(
5147                h_flex()
5148                    .child(
5149                        IconButton::new("dismiss-feedback-message", IconName::Close)
5150                            .icon_color(Color::Error)
5151                            .icon_size(IconSize::XSmall)
5152                            .shape(ui::IconButtonShape::Square)
5153                            .on_click(cx.listener(move |this, _, _window, cx| {
5154                                this.thread_feedback.dismiss_comments();
5155                                cx.notify();
5156                            })),
5157                    )
5158                    .child(
5159                        IconButton::new("submit-feedback-message", IconName::Return)
5160                            .icon_size(IconSize::XSmall)
5161                            .shape(ui::IconButtonShape::Square)
5162                            .on_click(cx.listener(move |this, _, _window, cx| {
5163                                this.submit_feedback_message(cx);
5164                            })),
5165                    ),
5166            )
5167    }
5168
5169    fn handle_feedback_click(
5170        &mut self,
5171        feedback: ThreadFeedback,
5172        window: &mut Window,
5173        cx: &mut Context<Self>,
5174    ) {
5175        let Some(thread) = self.thread().cloned() else {
5176            return;
5177        };
5178
5179        self.thread_feedback.submit(thread, feedback, window, cx);
5180        cx.notify();
5181    }
5182
5183    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5184        let Some(thread) = self.thread().cloned() else {
5185            return;
5186        };
5187
5188        self.thread_feedback.submit_comments(thread, cx);
5189        cx.notify();
5190    }
5191
5192    fn render_token_limit_callout(
5193        &self,
5194        line_height: Pixels,
5195        cx: &mut Context<Self>,
5196    ) -> Option<Callout> {
5197        let token_usage = self.thread()?.read(cx).token_usage()?;
5198        let ratio = token_usage.ratio();
5199
5200        let (severity, title) = match ratio {
5201            acp_thread::TokenUsageRatio::Normal => return None,
5202            acp_thread::TokenUsageRatio::Warning => {
5203                (Severity::Warning, "Thread reaching the token limit soon")
5204            }
5205            acp_thread::TokenUsageRatio::Exceeded => {
5206                (Severity::Error, "Thread reached the token limit")
5207            }
5208        };
5209
5210        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5211            thread.read(cx).completion_mode() == CompletionMode::Normal
5212                && thread
5213                    .read(cx)
5214                    .model()
5215                    .is_some_and(|model| model.supports_burn_mode())
5216        });
5217
5218        let description = if burn_mode_available {
5219            "To continue, start a new thread from a summary or turn Burn Mode on."
5220        } else {
5221            "To continue, start a new thread from a summary."
5222        };
5223
5224        Some(
5225            Callout::new()
5226                .severity(severity)
5227                .line_height(line_height)
5228                .title(title)
5229                .description(description)
5230                .actions_slot(
5231                    h_flex()
5232                        .gap_0p5()
5233                        .child(
5234                            Button::new("start-new-thread", "Start New Thread")
5235                                .label_size(LabelSize::Small)
5236                                .on_click(cx.listener(|this, _, window, cx| {
5237                                    let Some(thread) = this.thread() else {
5238                                        return;
5239                                    };
5240                                    let session_id = thread.read(cx).session_id().clone();
5241                                    window.dispatch_action(
5242                                        crate::NewNativeAgentThreadFromSummary {
5243                                            from_session_id: session_id,
5244                                        }
5245                                        .boxed_clone(),
5246                                        cx,
5247                                    );
5248                                })),
5249                        )
5250                        .when(burn_mode_available, |this| {
5251                            this.child(
5252                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5253                                    .icon_size(IconSize::XSmall)
5254                                    .on_click(cx.listener(|this, _event, window, cx| {
5255                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5256                                    })),
5257                            )
5258                        }),
5259                ),
5260        )
5261    }
5262
5263    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5264        if !self.is_using_zed_ai_models(cx) {
5265            return None;
5266        }
5267
5268        let user_store = self.project.read(cx).user_store().read(cx);
5269        if user_store.is_usage_based_billing_enabled() {
5270            return None;
5271        }
5272
5273        let plan = user_store
5274            .plan()
5275            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5276
5277        let usage = user_store.model_request_usage()?;
5278
5279        Some(
5280            div()
5281                .child(UsageCallout::new(plan, usage))
5282                .line_height(line_height),
5283        )
5284    }
5285
5286    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5287        self.entry_view_state.update(cx, |entry_view_state, cx| {
5288            entry_view_state.agent_ui_font_size_changed(cx);
5289        });
5290    }
5291
5292    pub(crate) fn insert_dragged_files(
5293        &self,
5294        paths: Vec<project::ProjectPath>,
5295        added_worktrees: Vec<Entity<project::Worktree>>,
5296        window: &mut Window,
5297        cx: &mut Context<Self>,
5298    ) {
5299        self.message_editor.update(cx, |message_editor, cx| {
5300            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5301        })
5302    }
5303
5304    /// Inserts the selected text into the message editor or the message being
5305    /// edited, if any.
5306    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5307        self.active_editor(cx).update(cx, |editor, cx| {
5308            editor.insert_selections(window, cx);
5309        });
5310    }
5311
5312    fn render_thread_retry_status_callout(
5313        &self,
5314        _window: &mut Window,
5315        _cx: &mut Context<Self>,
5316    ) -> Option<Callout> {
5317        let state = self.thread_retry_status.as_ref()?;
5318
5319        let next_attempt_in = state
5320            .duration
5321            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5322        if next_attempt_in.is_zero() {
5323            return None;
5324        }
5325
5326        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5327
5328        let retry_message = if state.max_attempts == 1 {
5329            if next_attempt_in_secs == 1 {
5330                "Retrying. Next attempt in 1 second.".to_string()
5331            } else {
5332                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5333            }
5334        } else if next_attempt_in_secs == 1 {
5335            format!(
5336                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5337                state.attempt, state.max_attempts,
5338            )
5339        } else {
5340            format!(
5341                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5342                state.attempt, state.max_attempts,
5343            )
5344        };
5345
5346        Some(
5347            Callout::new()
5348                .severity(Severity::Warning)
5349                .title(state.last_error.clone())
5350                .description(retry_message),
5351        )
5352    }
5353
5354    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5355        if self.show_codex_windows_warning {
5356            Some(
5357                Callout::new()
5358                    .icon(IconName::Warning)
5359                    .severity(Severity::Warning)
5360                    .title("Codex on Windows")
5361                    .description(
5362                        "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5363                    )
5364                    .actions_slot(
5365                        Button::new("open-wsl-modal", "Open in WSL")
5366                            .icon_size(IconSize::Small)
5367                            .icon_color(Color::Muted)
5368                            .on_click(cx.listener({
5369                                move |_, _, _window, cx| {
5370                                    #[cfg(windows)]
5371                                    _window.dispatch_action(
5372                                        zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5373                                        cx,
5374                                    );
5375                                    cx.notify();
5376                                }
5377                            })),
5378                    )
5379                    .dismiss_action(
5380                        IconButton::new("dismiss", IconName::Close)
5381                            .icon_size(IconSize::Small)
5382                            .icon_color(Color::Muted)
5383                            .tooltip(Tooltip::text("Dismiss Warning"))
5384                            .on_click(cx.listener({
5385                                move |this, _, _, cx| {
5386                                    this.show_codex_windows_warning = false;
5387                                    cx.notify();
5388                                }
5389                            })),
5390                    ),
5391            )
5392        } else {
5393            None
5394        }
5395    }
5396
5397    fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5398        let content = match self.thread_error.as_ref()? {
5399            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5400            ThreadError::Refusal => self.render_refusal_error(cx),
5401            ThreadError::AuthenticationRequired(error) => {
5402                self.render_authentication_required_error(error.clone(), cx)
5403            }
5404            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5405            ThreadError::ModelRequestLimitReached(plan) => {
5406                self.render_model_request_limit_reached_error(*plan, cx)
5407            }
5408            ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5409        };
5410
5411        Some(div().child(content))
5412    }
5413
5414    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5415        v_flex().w_full().justify_end().child(
5416            h_flex()
5417                .p_2()
5418                .pr_3()
5419                .w_full()
5420                .gap_1p5()
5421                .border_t_1()
5422                .border_color(cx.theme().colors().border)
5423                .bg(cx.theme().colors().element_background)
5424                .child(
5425                    h_flex()
5426                        .flex_1()
5427                        .gap_1p5()
5428                        .child(
5429                            Icon::new(IconName::Download)
5430                                .color(Color::Accent)
5431                                .size(IconSize::Small),
5432                        )
5433                        .child(Label::new("New version available").size(LabelSize::Small)),
5434                )
5435                .child(
5436                    Button::new("update-button", format!("Update to v{}", version))
5437                        .label_size(LabelSize::Small)
5438                        .style(ButtonStyle::Tinted(TintColor::Accent))
5439                        .on_click(cx.listener(|this, _, window, cx| {
5440                            this.reset(window, cx);
5441                        })),
5442                ),
5443        )
5444    }
5445
5446    fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
5447        if let Some(thread) = self.as_native_thread(cx) {
5448            Some(thread.read(cx).profile().0.clone())
5449        } else if let Some(mode_selector) = self.mode_selector() {
5450            Some(mode_selector.read(cx).mode().0)
5451        } else {
5452            None
5453        }
5454    }
5455
5456    fn current_model_id(&self, cx: &App) -> Option<String> {
5457        self.model_selector
5458            .as_ref()
5459            .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5460    }
5461
5462    fn current_model_name(&self, cx: &App) -> SharedString {
5463        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5464        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5465        // This provides better clarity about what refused the request
5466        if self.as_native_connection(cx).is_some() {
5467            self.model_selector
5468                .as_ref()
5469                .and_then(|selector| selector.read(cx).active_model(cx))
5470                .map(|model| model.name.clone())
5471                .unwrap_or_else(|| SharedString::from("The model"))
5472        } else {
5473            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5474            self.agent.name()
5475        }
5476    }
5477
5478    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5479        let model_or_agent_name = self.current_model_name(cx);
5480        let refusal_message = format!(
5481            "{} 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.",
5482            model_or_agent_name
5483        );
5484
5485        Callout::new()
5486            .severity(Severity::Error)
5487            .title("Request Refused")
5488            .icon(IconName::XCircle)
5489            .description(refusal_message.clone())
5490            .actions_slot(self.create_copy_button(&refusal_message))
5491            .dismiss_action(self.dismiss_error_button(cx))
5492    }
5493
5494    fn render_any_thread_error(
5495        &mut self,
5496        error: SharedString,
5497        window: &mut Window,
5498        cx: &mut Context<'_, Self>,
5499    ) -> Callout {
5500        let can_resume = self
5501            .thread()
5502            .map_or(false, |thread| thread.read(cx).can_resume(cx));
5503
5504        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5505            let thread = thread.read(cx);
5506            let supports_burn_mode = thread
5507                .model()
5508                .map_or(false, |model| model.supports_burn_mode());
5509            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5510        });
5511
5512        let markdown = if let Some(markdown) = &self.thread_error_markdown {
5513            markdown.clone()
5514        } else {
5515            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5516            self.thread_error_markdown = Some(markdown.clone());
5517            markdown
5518        };
5519
5520        let markdown_style = default_markdown_style(false, true, window, cx);
5521        let description = self
5522            .render_markdown(markdown, markdown_style)
5523            .into_any_element();
5524
5525        Callout::new()
5526            .severity(Severity::Error)
5527            .icon(IconName::XCircle)
5528            .title("An Error Happened")
5529            .description_slot(description)
5530            .actions_slot(
5531                h_flex()
5532                    .gap_0p5()
5533                    .when(can_resume && can_enable_burn_mode, |this| {
5534                        this.child(
5535                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5536                                .icon(IconName::ZedBurnMode)
5537                                .icon_position(IconPosition::Start)
5538                                .icon_size(IconSize::Small)
5539                                .label_size(LabelSize::Small)
5540                                .on_click(cx.listener(|this, _, window, cx| {
5541                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5542                                    this.resume_chat(cx);
5543                                })),
5544                        )
5545                    })
5546                    .when(can_resume, |this| {
5547                        this.child(
5548                            IconButton::new("retry", IconName::RotateCw)
5549                                .icon_size(IconSize::Small)
5550                                .tooltip(Tooltip::text("Retry Generation"))
5551                                .on_click(cx.listener(|this, _, _window, cx| {
5552                                    this.resume_chat(cx);
5553                                })),
5554                        )
5555                    })
5556                    .child(self.create_copy_button(error.to_string())),
5557            )
5558            .dismiss_action(self.dismiss_error_button(cx))
5559    }
5560
5561    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5562        const ERROR_MESSAGE: &str =
5563            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5564
5565        Callout::new()
5566            .severity(Severity::Error)
5567            .icon(IconName::XCircle)
5568            .title("Free Usage Exceeded")
5569            .description(ERROR_MESSAGE)
5570            .actions_slot(
5571                h_flex()
5572                    .gap_0p5()
5573                    .child(self.upgrade_button(cx))
5574                    .child(self.create_copy_button(ERROR_MESSAGE)),
5575            )
5576            .dismiss_action(self.dismiss_error_button(cx))
5577    }
5578
5579    fn render_authentication_required_error(
5580        &self,
5581        error: SharedString,
5582        cx: &mut Context<Self>,
5583    ) -> Callout {
5584        Callout::new()
5585            .severity(Severity::Error)
5586            .title("Authentication Required")
5587            .icon(IconName::XCircle)
5588            .description(error.clone())
5589            .actions_slot(
5590                h_flex()
5591                    .gap_0p5()
5592                    .child(self.authenticate_button(cx))
5593                    .child(self.create_copy_button(error)),
5594            )
5595            .dismiss_action(self.dismiss_error_button(cx))
5596    }
5597
5598    fn render_model_request_limit_reached_error(
5599        &self,
5600        plan: cloud_llm_client::Plan,
5601        cx: &mut Context<Self>,
5602    ) -> Callout {
5603        let error_message = match plan {
5604            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5605                "Upgrade to usage-based billing for more prompts."
5606            }
5607            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5608            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5609            cloud_llm_client::Plan::V2(_) => "",
5610        };
5611
5612        Callout::new()
5613            .severity(Severity::Error)
5614            .title("Model Prompt Limit Reached")
5615            .icon(IconName::XCircle)
5616            .description(error_message)
5617            .actions_slot(
5618                h_flex()
5619                    .gap_0p5()
5620                    .child(self.upgrade_button(cx))
5621                    .child(self.create_copy_button(error_message)),
5622            )
5623            .dismiss_action(self.dismiss_error_button(cx))
5624    }
5625
5626    fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5627        let thread = self.as_native_thread(cx)?;
5628        let supports_burn_mode = thread
5629            .read(cx)
5630            .model()
5631            .is_some_and(|model| model.supports_burn_mode());
5632
5633        let focus_handle = self.focus_handle(cx);
5634
5635        Some(
5636            Callout::new()
5637                .icon(IconName::Info)
5638                .title("Consecutive tool use limit reached.")
5639                .actions_slot(
5640                    h_flex()
5641                        .gap_0p5()
5642                        .when(supports_burn_mode, |this| {
5643                            this.child(
5644                                Button::new("continue-burn-mode", "Continue with Burn Mode")
5645                                    .style(ButtonStyle::Filled)
5646                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5647                                    .layer(ElevationIndex::ModalSurface)
5648                                    .label_size(LabelSize::Small)
5649                                    .key_binding(
5650                                        KeyBinding::for_action_in(
5651                                            &ContinueWithBurnMode,
5652                                            &focus_handle,
5653                                            cx,
5654                                        )
5655                                        .map(|kb| kb.size(rems_from_px(10.))),
5656                                    )
5657                                    .tooltip(Tooltip::text(
5658                                        "Enable Burn Mode for unlimited tool use.",
5659                                    ))
5660                                    .on_click({
5661                                        cx.listener(move |this, _, _window, cx| {
5662                                            thread.update(cx, |thread, cx| {
5663                                                thread
5664                                                    .set_completion_mode(CompletionMode::Burn, cx);
5665                                            });
5666                                            this.resume_chat(cx);
5667                                        })
5668                                    }),
5669                            )
5670                        })
5671                        .child(
5672                            Button::new("continue-conversation", "Continue")
5673                                .layer(ElevationIndex::ModalSurface)
5674                                .label_size(LabelSize::Small)
5675                                .key_binding(
5676                                    KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5677                                        .map(|kb| kb.size(rems_from_px(10.))),
5678                                )
5679                                .on_click(cx.listener(|this, _, _window, cx| {
5680                                    this.resume_chat(cx);
5681                                })),
5682                        ),
5683                ),
5684        )
5685    }
5686
5687    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5688        let message = message.into();
5689
5690        IconButton::new("copy", IconName::Copy)
5691            .icon_size(IconSize::Small)
5692            .tooltip(Tooltip::text("Copy Error Message"))
5693            .on_click(move |_, _, cx| {
5694                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5695            })
5696    }
5697
5698    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5699        IconButton::new("dismiss", IconName::Close)
5700            .icon_size(IconSize::Small)
5701            .tooltip(Tooltip::text("Dismiss Error"))
5702            .on_click(cx.listener({
5703                move |this, _, _, cx| {
5704                    this.clear_thread_error(cx);
5705                    cx.notify();
5706                }
5707            }))
5708    }
5709
5710    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5711        Button::new("authenticate", "Authenticate")
5712            .label_size(LabelSize::Small)
5713            .style(ButtonStyle::Filled)
5714            .on_click(cx.listener({
5715                move |this, _, window, cx| {
5716                    let agent = this.agent.clone();
5717                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
5718                        return;
5719                    };
5720
5721                    let connection = thread.read(cx).connection().clone();
5722                    let err = AuthRequired {
5723                        description: None,
5724                        provider_id: None,
5725                    };
5726                    this.clear_thread_error(cx);
5727                    if let Some(message) = this.in_flight_prompt.take() {
5728                        this.message_editor.update(cx, |editor, cx| {
5729                            editor.set_message(message, window, cx);
5730                        });
5731                    }
5732                    let this = cx.weak_entity();
5733                    window.defer(cx, |window, cx| {
5734                        Self::handle_auth_required(this, err, agent, connection, window, cx);
5735                    })
5736                }
5737            }))
5738    }
5739
5740    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5741        let agent = self.agent.clone();
5742        let ThreadState::Ready { thread, .. } = &self.thread_state else {
5743            return;
5744        };
5745
5746        let connection = thread.read(cx).connection().clone();
5747        let err = AuthRequired {
5748            description: None,
5749            provider_id: None,
5750        };
5751        self.clear_thread_error(cx);
5752        let this = cx.weak_entity();
5753        window.defer(cx, |window, cx| {
5754            Self::handle_auth_required(this, err, agent, connection, window, cx);
5755        })
5756    }
5757
5758    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5759        Button::new("upgrade", "Upgrade")
5760            .label_size(LabelSize::Small)
5761            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5762            .on_click(cx.listener({
5763                move |this, _, _, cx| {
5764                    this.clear_thread_error(cx);
5765                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5766                }
5767            }))
5768    }
5769
5770    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5771        let task = match entry {
5772            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5773                history.delete_thread(thread.id.clone(), cx)
5774            }),
5775            HistoryEntry::TextThread(text_thread) => {
5776                self.history_store.update(cx, |history, cx| {
5777                    history.delete_text_thread(text_thread.path.clone(), cx)
5778                })
5779            }
5780        };
5781        task.detach_and_log_err(cx);
5782    }
5783
5784    /// Returns the currently active editor, either for a message that is being
5785    /// edited or the editor for a new message.
5786    fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5787        if let Some(index) = self.editing_message
5788            && let Some(editor) = self
5789                .entry_view_state
5790                .read(cx)
5791                .entry(index)
5792                .and_then(|e| e.message_editor())
5793                .cloned()
5794        {
5795            editor
5796        } else {
5797            self.message_editor.clone()
5798        }
5799    }
5800}
5801
5802fn loading_contents_spinner(size: IconSize) -> AnyElement {
5803    Icon::new(IconName::LoadCircle)
5804        .size(size)
5805        .color(Color::Accent)
5806        .with_rotate_animation(3)
5807        .into_any_element()
5808}
5809
5810fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5811    if agent_name == "Zed Agent" {
5812        format!("Message the {} — @ to include context", agent_name)
5813    } else if has_commands {
5814        format!(
5815            "Message {} — @ to include context, / for commands",
5816            agent_name
5817        )
5818    } else {
5819        format!("Message {} — @ to include context", agent_name)
5820    }
5821}
5822
5823impl Focusable for AcpThreadView {
5824    fn focus_handle(&self, cx: &App) -> FocusHandle {
5825        match self.thread_state {
5826            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5827                self.active_editor(cx).focus_handle(cx)
5828            }
5829            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5830                self.focus_handle.clone()
5831            }
5832        }
5833    }
5834}
5835
5836impl Render for AcpThreadView {
5837    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5838        let has_messages = self.list_state.item_count() > 0;
5839        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5840
5841        v_flex()
5842            .size_full()
5843            .key_context("AcpThread")
5844            .on_action(cx.listener(Self::toggle_burn_mode))
5845            .on_action(cx.listener(Self::keep_all))
5846            .on_action(cx.listener(Self::reject_all))
5847            .on_action(cx.listener(Self::allow_always))
5848            .on_action(cx.listener(Self::allow_once))
5849            .on_action(cx.listener(Self::reject_once))
5850            .track_focus(&self.focus_handle)
5851            .bg(cx.theme().colors().panel_background)
5852            .child(match &self.thread_state {
5853                ThreadState::Unauthenticated {
5854                    connection,
5855                    description,
5856                    configuration_view,
5857                    pending_auth_method,
5858                    ..
5859                } => self
5860                    .render_auth_required_state(
5861                        connection,
5862                        description.as_ref(),
5863                        configuration_view.as_ref(),
5864                        pending_auth_method.as_ref(),
5865                        window,
5866                        cx,
5867                    )
5868                    .into_any(),
5869                ThreadState::Loading { .. } => v_flex()
5870                    .flex_1()
5871                    .child(self.render_recent_history(cx))
5872                    .into_any(),
5873                ThreadState::LoadError(e) => v_flex()
5874                    .flex_1()
5875                    .size_full()
5876                    .items_center()
5877                    .justify_end()
5878                    .child(self.render_load_error(e, window, cx))
5879                    .into_any(),
5880                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5881                    if has_messages {
5882                        this.child(
5883                            list(
5884                                self.list_state.clone(),
5885                                cx.processor(|this, index: usize, window, cx| {
5886                                    let Some((entry, len)) = this.thread().and_then(|thread| {
5887                                        let entries = &thread.read(cx).entries();
5888                                        Some((entries.get(index)?, entries.len()))
5889                                    }) else {
5890                                        return Empty.into_any();
5891                                    };
5892                                    this.render_entry(index, len, entry, window, cx)
5893                                }),
5894                            )
5895                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5896                            .flex_grow()
5897                            .into_any(),
5898                        )
5899                        .vertical_scrollbar_for(&self.list_state, window, cx)
5900                        .into_any()
5901                    } else {
5902                        this.child(self.render_recent_history(cx)).into_any()
5903                    }
5904                }),
5905            })
5906            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5907            // above so that the scrollbar doesn't render behind it. The current setup allows
5908            // the scrollbar to stop exactly at the activity bar start.
5909            .when(has_messages, |this| match &self.thread_state {
5910                ThreadState::Ready { thread, .. } => {
5911                    this.children(self.render_activity_bar(thread, window, cx))
5912                }
5913                _ => this,
5914            })
5915            .children(self.render_thread_retry_status_callout(window, cx))
5916            .children({
5917                if cfg!(windows) && self.project.read(cx).is_local() {
5918                    self.render_codex_windows_warning(cx)
5919                } else {
5920                    None
5921                }
5922            })
5923            .children(self.render_thread_error(window, cx))
5924            .when_some(
5925                self.new_server_version_available.as_ref().filter(|_| {
5926                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5927                }),
5928                |this, version| this.child(self.render_new_version_callout(&version, cx)),
5929            )
5930            .children(
5931                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5932                    Some(usage_callout.into_any_element())
5933                } else {
5934                    self.render_token_limit_callout(line_height, cx)
5935                        .map(|token_limit_callout| token_limit_callout.into_any_element())
5936                },
5937            )
5938            .child(self.render_message_editor(window, cx))
5939    }
5940}
5941
5942fn default_markdown_style(
5943    buffer_font: bool,
5944    muted_text: bool,
5945    window: &Window,
5946    cx: &App,
5947) -> MarkdownStyle {
5948    let theme_settings = ThemeSettings::get_global(cx);
5949    let colors = cx.theme().colors();
5950
5951    let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
5952
5953    let mut text_style = window.text_style();
5954    let line_height = buffer_font_size * 1.75;
5955
5956    let font_family = if buffer_font {
5957        theme_settings.buffer_font.family.clone()
5958    } else {
5959        theme_settings.ui_font.family.clone()
5960    };
5961
5962    let font_size = if buffer_font {
5963        theme_settings.agent_buffer_font_size(cx)
5964    } else {
5965        theme_settings.agent_ui_font_size(cx)
5966    };
5967
5968    let text_color = if muted_text {
5969        colors.text_muted
5970    } else {
5971        colors.text
5972    };
5973
5974    text_style.refine(&TextStyleRefinement {
5975        font_family: Some(font_family),
5976        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5977        font_features: Some(theme_settings.ui_font.features.clone()),
5978        font_size: Some(font_size.into()),
5979        line_height: Some(line_height.into()),
5980        color: Some(text_color),
5981        ..Default::default()
5982    });
5983
5984    MarkdownStyle {
5985        base_text_style: text_style.clone(),
5986        syntax: cx.theme().syntax().clone(),
5987        selection_background_color: colors.element_selection_background,
5988        code_block_overflow_x_scroll: true,
5989        heading_level_styles: Some(HeadingLevelStyles {
5990            h1: Some(TextStyleRefinement {
5991                font_size: Some(rems(1.15).into()),
5992                ..Default::default()
5993            }),
5994            h2: Some(TextStyleRefinement {
5995                font_size: Some(rems(1.1).into()),
5996                ..Default::default()
5997            }),
5998            h3: Some(TextStyleRefinement {
5999                font_size: Some(rems(1.05).into()),
6000                ..Default::default()
6001            }),
6002            h4: Some(TextStyleRefinement {
6003                font_size: Some(rems(1.).into()),
6004                ..Default::default()
6005            }),
6006            h5: Some(TextStyleRefinement {
6007                font_size: Some(rems(0.95).into()),
6008                ..Default::default()
6009            }),
6010            h6: Some(TextStyleRefinement {
6011                font_size: Some(rems(0.875).into()),
6012                ..Default::default()
6013            }),
6014        }),
6015        code_block: StyleRefinement {
6016            padding: EdgesRefinement {
6017                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6018                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6019                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6020                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6021            },
6022            margin: EdgesRefinement {
6023                top: Some(Length::Definite(px(8.).into())),
6024                left: Some(Length::Definite(px(0.).into())),
6025                right: Some(Length::Definite(px(0.).into())),
6026                bottom: Some(Length::Definite(px(12.).into())),
6027            },
6028            border_style: Some(BorderStyle::Solid),
6029            border_widths: EdgesRefinement {
6030                top: Some(AbsoluteLength::Pixels(px(1.))),
6031                left: Some(AbsoluteLength::Pixels(px(1.))),
6032                right: Some(AbsoluteLength::Pixels(px(1.))),
6033                bottom: Some(AbsoluteLength::Pixels(px(1.))),
6034            },
6035            border_color: Some(colors.border_variant),
6036            background: Some(colors.editor_background.into()),
6037            text: Some(TextStyleRefinement {
6038                font_family: Some(theme_settings.buffer_font.family.clone()),
6039                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6040                font_features: Some(theme_settings.buffer_font.features.clone()),
6041                font_size: Some(buffer_font_size.into()),
6042                ..Default::default()
6043            }),
6044            ..Default::default()
6045        },
6046        inline_code: TextStyleRefinement {
6047            font_family: Some(theme_settings.buffer_font.family.clone()),
6048            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6049            font_features: Some(theme_settings.buffer_font.features.clone()),
6050            font_size: Some(buffer_font_size.into()),
6051            background_color: Some(colors.editor_foreground.opacity(0.08)),
6052            ..Default::default()
6053        },
6054        link: TextStyleRefinement {
6055            background_color: Some(colors.editor_foreground.opacity(0.025)),
6056            color: Some(colors.text_accent),
6057            underline: Some(UnderlineStyle {
6058                color: Some(colors.text_accent.opacity(0.5)),
6059                thickness: px(1.),
6060                ..Default::default()
6061            }),
6062            ..Default::default()
6063        },
6064        ..Default::default()
6065    }
6066}
6067
6068fn plan_label_markdown_style(
6069    status: &acp::PlanEntryStatus,
6070    window: &Window,
6071    cx: &App,
6072) -> MarkdownStyle {
6073    let default_md_style = default_markdown_style(false, false, window, cx);
6074
6075    MarkdownStyle {
6076        base_text_style: TextStyle {
6077            color: cx.theme().colors().text_muted,
6078            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
6079                Some(gpui::StrikethroughStyle {
6080                    thickness: px(1.),
6081                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
6082                })
6083            } else {
6084                None
6085            },
6086            ..default_md_style.base_text_style
6087        },
6088        ..default_md_style
6089    }
6090}
6091
6092fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
6093    let default_md_style = default_markdown_style(true, false, window, cx);
6094
6095    MarkdownStyle {
6096        base_text_style: TextStyle {
6097            ..default_md_style.base_text_style
6098        },
6099        selection_background_color: cx.theme().colors().element_selection_background,
6100        ..Default::default()
6101    }
6102}
6103
6104#[cfg(test)]
6105pub(crate) mod tests {
6106    use acp_thread::StubAgentConnection;
6107    use agent_client_protocol::SessionId;
6108    use assistant_text_thread::TextThreadStore;
6109    use editor::MultiBufferOffset;
6110    use fs::FakeFs;
6111    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
6112    use project::Project;
6113    use serde_json::json;
6114    use settings::SettingsStore;
6115    use std::any::Any;
6116    use std::path::Path;
6117    use workspace::Item;
6118
6119    use super::*;
6120
6121    #[gpui::test]
6122    async fn test_drop(cx: &mut TestAppContext) {
6123        init_test(cx);
6124
6125        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6126        let weak_view = thread_view.downgrade();
6127        drop(thread_view);
6128        assert!(!weak_view.is_upgradable());
6129    }
6130
6131    #[gpui::test]
6132    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6133        init_test(cx);
6134
6135        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6136
6137        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6138        message_editor.update_in(cx, |editor, window, cx| {
6139            editor.set_text("Hello", window, cx);
6140        });
6141
6142        cx.deactivate_window();
6143
6144        thread_view.update_in(cx, |thread_view, window, cx| {
6145            thread_view.send(window, cx);
6146        });
6147
6148        cx.run_until_parked();
6149
6150        assert!(
6151            cx.windows()
6152                .iter()
6153                .any(|window| window.downcast::<AgentNotification>().is_some())
6154        );
6155    }
6156
6157    #[gpui::test]
6158    async fn test_notification_for_error(cx: &mut TestAppContext) {
6159        init_test(cx);
6160
6161        let (thread_view, cx) =
6162            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6163
6164        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6165        message_editor.update_in(cx, |editor, window, cx| {
6166            editor.set_text("Hello", window, cx);
6167        });
6168
6169        cx.deactivate_window();
6170
6171        thread_view.update_in(cx, |thread_view, window, cx| {
6172            thread_view.send(window, cx);
6173        });
6174
6175        cx.run_until_parked();
6176
6177        assert!(
6178            cx.windows()
6179                .iter()
6180                .any(|window| window.downcast::<AgentNotification>().is_some())
6181        );
6182    }
6183
6184    #[gpui::test]
6185    async fn test_refusal_handling(cx: &mut TestAppContext) {
6186        init_test(cx);
6187
6188        let (thread_view, cx) =
6189            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6190
6191        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6192        message_editor.update_in(cx, |editor, window, cx| {
6193            editor.set_text("Do something harmful", window, cx);
6194        });
6195
6196        thread_view.update_in(cx, |thread_view, window, cx| {
6197            thread_view.send(window, cx);
6198        });
6199
6200        cx.run_until_parked();
6201
6202        // Check that the refusal error is set
6203        thread_view.read_with(cx, |thread_view, _cx| {
6204            assert!(
6205                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6206                "Expected refusal error to be set"
6207            );
6208        });
6209    }
6210
6211    #[gpui::test]
6212    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6213        init_test(cx);
6214
6215        let tool_call_id = acp::ToolCallId("1".into());
6216        let tool_call = acp::ToolCall {
6217            id: tool_call_id.clone(),
6218            title: "Label".into(),
6219            kind: acp::ToolKind::Edit,
6220            status: acp::ToolCallStatus::Pending,
6221            content: vec!["hi".into()],
6222            locations: vec![],
6223            raw_input: None,
6224            raw_output: None,
6225            meta: None,
6226        };
6227        let connection =
6228            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6229                tool_call_id,
6230                vec![acp::PermissionOption {
6231                    id: acp::PermissionOptionId("1".into()),
6232                    name: "Allow".into(),
6233                    kind: acp::PermissionOptionKind::AllowOnce,
6234                    meta: None,
6235                }],
6236            )]));
6237
6238        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6239
6240        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6241
6242        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6243        message_editor.update_in(cx, |editor, window, cx| {
6244            editor.set_text("Hello", window, cx);
6245        });
6246
6247        cx.deactivate_window();
6248
6249        thread_view.update_in(cx, |thread_view, window, cx| {
6250            thread_view.send(window, cx);
6251        });
6252
6253        cx.run_until_parked();
6254
6255        assert!(
6256            cx.windows()
6257                .iter()
6258                .any(|window| window.downcast::<AgentNotification>().is_some())
6259        );
6260    }
6261
6262    #[gpui::test]
6263    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6264        init_test(cx);
6265
6266        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6267
6268        add_to_workspace(thread_view.clone(), cx);
6269
6270        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6271
6272        message_editor.update_in(cx, |editor, window, cx| {
6273            editor.set_text("Hello", window, cx);
6274        });
6275
6276        // Window is active (don't deactivate), but panel will be hidden
6277        // Note: In the test environment, the panel is not actually added to the dock,
6278        // so is_agent_panel_hidden will return true
6279
6280        thread_view.update_in(cx, |thread_view, window, cx| {
6281            thread_view.send(window, cx);
6282        });
6283
6284        cx.run_until_parked();
6285
6286        // Should show notification because window is active but panel is hidden
6287        assert!(
6288            cx.windows()
6289                .iter()
6290                .any(|window| window.downcast::<AgentNotification>().is_some()),
6291            "Expected notification when panel is hidden"
6292        );
6293    }
6294
6295    #[gpui::test]
6296    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6297        init_test(cx);
6298
6299        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6300
6301        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6302        message_editor.update_in(cx, |editor, window, cx| {
6303            editor.set_text("Hello", window, cx);
6304        });
6305
6306        // Deactivate window - should show notification regardless of setting
6307        cx.deactivate_window();
6308
6309        thread_view.update_in(cx, |thread_view, window, cx| {
6310            thread_view.send(window, cx);
6311        });
6312
6313        cx.run_until_parked();
6314
6315        // Should still show notification when window is inactive (existing behavior)
6316        assert!(
6317            cx.windows()
6318                .iter()
6319                .any(|window| window.downcast::<AgentNotification>().is_some()),
6320            "Expected notification when window is inactive"
6321        );
6322    }
6323
6324    #[gpui::test]
6325    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6326        init_test(cx);
6327
6328        // Set notify_when_agent_waiting to Never
6329        cx.update(|cx| {
6330            AgentSettings::override_global(
6331                AgentSettings {
6332                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6333                    ..AgentSettings::get_global(cx).clone()
6334                },
6335                cx,
6336            );
6337        });
6338
6339        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6340
6341        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6342        message_editor.update_in(cx, |editor, window, cx| {
6343            editor.set_text("Hello", window, cx);
6344        });
6345
6346        // Window is active
6347
6348        thread_view.update_in(cx, |thread_view, window, cx| {
6349            thread_view.send(window, cx);
6350        });
6351
6352        cx.run_until_parked();
6353
6354        // Should NOT show notification because notify_when_agent_waiting is Never
6355        assert!(
6356            !cx.windows()
6357                .iter()
6358                .any(|window| window.downcast::<AgentNotification>().is_some()),
6359            "Expected no notification when notify_when_agent_waiting is Never"
6360        );
6361    }
6362
6363    async fn setup_thread_view(
6364        agent: impl AgentServer + 'static,
6365        cx: &mut TestAppContext,
6366    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6367        let fs = FakeFs::new(cx.executor());
6368        let project = Project::test(fs, [], cx).await;
6369        let (workspace, cx) =
6370            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6371
6372        let text_thread_store =
6373            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6374        let history_store =
6375            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6376
6377        let thread_view = cx.update(|window, cx| {
6378            cx.new(|cx| {
6379                AcpThreadView::new(
6380                    Rc::new(agent),
6381                    None,
6382                    None,
6383                    workspace.downgrade(),
6384                    project,
6385                    history_store,
6386                    None,
6387                    window,
6388                    cx,
6389                )
6390            })
6391        });
6392        cx.run_until_parked();
6393        (thread_view, cx)
6394    }
6395
6396    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6397        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6398
6399        workspace
6400            .update_in(cx, |workspace, window, cx| {
6401                workspace.add_item_to_active_pane(
6402                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6403                    None,
6404                    true,
6405                    window,
6406                    cx,
6407                );
6408            })
6409            .unwrap();
6410    }
6411
6412    struct ThreadViewItem(Entity<AcpThreadView>);
6413
6414    impl Item for ThreadViewItem {
6415        type Event = ();
6416
6417        fn include_in_nav_history() -> bool {
6418            false
6419        }
6420
6421        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6422            "Test".into()
6423        }
6424    }
6425
6426    impl EventEmitter<()> for ThreadViewItem {}
6427
6428    impl Focusable for ThreadViewItem {
6429        fn focus_handle(&self, cx: &App) -> FocusHandle {
6430            self.0.read(cx).focus_handle(cx)
6431        }
6432    }
6433
6434    impl Render for ThreadViewItem {
6435        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6436            self.0.clone().into_any_element()
6437        }
6438    }
6439
6440    struct StubAgentServer<C> {
6441        connection: C,
6442    }
6443
6444    impl<C> StubAgentServer<C> {
6445        fn new(connection: C) -> Self {
6446            Self { connection }
6447        }
6448    }
6449
6450    impl StubAgentServer<StubAgentConnection> {
6451        fn default_response() -> Self {
6452            let conn = StubAgentConnection::new();
6453            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6454                acp::ContentChunk {
6455                    content: "Default response".into(),
6456                    meta: None,
6457                },
6458            )]);
6459            Self::new(conn)
6460        }
6461    }
6462
6463    impl<C> AgentServer for StubAgentServer<C>
6464    where
6465        C: 'static + AgentConnection + Send + Clone,
6466    {
6467        fn telemetry_id(&self) -> &'static str {
6468            "test"
6469        }
6470
6471        fn logo(&self) -> ui::IconName {
6472            ui::IconName::Ai
6473        }
6474
6475        fn name(&self) -> SharedString {
6476            "Test".into()
6477        }
6478
6479        fn connect(
6480            &self,
6481            _root_dir: Option<&Path>,
6482            _delegate: AgentServerDelegate,
6483            _cx: &mut App,
6484        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6485            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6486        }
6487
6488        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6489            self
6490        }
6491    }
6492
6493    #[derive(Clone)]
6494    struct SaboteurAgentConnection;
6495
6496    impl AgentConnection for SaboteurAgentConnection {
6497        fn telemetry_id(&self) -> &'static str {
6498            "saboteur"
6499        }
6500
6501        fn new_thread(
6502            self: Rc<Self>,
6503            project: Entity<Project>,
6504            _cwd: &Path,
6505            cx: &mut gpui::App,
6506        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6507            Task::ready(Ok(cx.new(|cx| {
6508                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6509                AcpThread::new(
6510                    "SaboteurAgentConnection",
6511                    self,
6512                    project,
6513                    action_log,
6514                    SessionId("test".into()),
6515                    watch::Receiver::constant(acp::PromptCapabilities {
6516                        image: true,
6517                        audio: true,
6518                        embedded_context: true,
6519                        meta: None,
6520                    }),
6521                    cx,
6522                )
6523            })))
6524        }
6525
6526        fn auth_methods(&self) -> &[acp::AuthMethod] {
6527            &[]
6528        }
6529
6530        fn authenticate(
6531            &self,
6532            _method_id: acp::AuthMethodId,
6533            _cx: &mut App,
6534        ) -> Task<gpui::Result<()>> {
6535            unimplemented!()
6536        }
6537
6538        fn prompt(
6539            &self,
6540            _id: Option<acp_thread::UserMessageId>,
6541            _params: acp::PromptRequest,
6542            _cx: &mut App,
6543        ) -> Task<gpui::Result<acp::PromptResponse>> {
6544            Task::ready(Err(anyhow::anyhow!("Error prompting")))
6545        }
6546
6547        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6548            unimplemented!()
6549        }
6550
6551        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6552            self
6553        }
6554    }
6555
6556    /// Simulates a model which always returns a refusal response
6557    #[derive(Clone)]
6558    struct RefusalAgentConnection;
6559
6560    impl AgentConnection for RefusalAgentConnection {
6561        fn telemetry_id(&self) -> &'static str {
6562            "refusal"
6563        }
6564
6565        fn new_thread(
6566            self: Rc<Self>,
6567            project: Entity<Project>,
6568            _cwd: &Path,
6569            cx: &mut gpui::App,
6570        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6571            Task::ready(Ok(cx.new(|cx| {
6572                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6573                AcpThread::new(
6574                    "RefusalAgentConnection",
6575                    self,
6576                    project,
6577                    action_log,
6578                    SessionId("test".into()),
6579                    watch::Receiver::constant(acp::PromptCapabilities {
6580                        image: true,
6581                        audio: true,
6582                        embedded_context: true,
6583                        meta: None,
6584                    }),
6585                    cx,
6586                )
6587            })))
6588        }
6589
6590        fn auth_methods(&self) -> &[acp::AuthMethod] {
6591            &[]
6592        }
6593
6594        fn authenticate(
6595            &self,
6596            _method_id: acp::AuthMethodId,
6597            _cx: &mut App,
6598        ) -> Task<gpui::Result<()>> {
6599            unimplemented!()
6600        }
6601
6602        fn prompt(
6603            &self,
6604            _id: Option<acp_thread::UserMessageId>,
6605            _params: acp::PromptRequest,
6606            _cx: &mut App,
6607        ) -> Task<gpui::Result<acp::PromptResponse>> {
6608            Task::ready(Ok(acp::PromptResponse {
6609                stop_reason: acp::StopReason::Refusal,
6610                meta: None,
6611            }))
6612        }
6613
6614        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6615            unimplemented!()
6616        }
6617
6618        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6619            self
6620        }
6621    }
6622
6623    pub(crate) fn init_test(cx: &mut TestAppContext) {
6624        cx.update(|cx| {
6625            let settings_store = SettingsStore::test(cx);
6626            cx.set_global(settings_store);
6627            theme::init(theme::LoadThemes::JustBase, cx);
6628            release_channel::init(semver::Version::new(0, 0, 0), cx);
6629            prompt_store::init(cx)
6630        });
6631    }
6632
6633    #[gpui::test]
6634    async fn test_rewind_views(cx: &mut TestAppContext) {
6635        init_test(cx);
6636
6637        let fs = FakeFs::new(cx.executor());
6638        fs.insert_tree(
6639            "/project",
6640            json!({
6641                "test1.txt": "old content 1",
6642                "test2.txt": "old content 2"
6643            }),
6644        )
6645        .await;
6646        let project = Project::test(fs, [Path::new("/project")], cx).await;
6647        let (workspace, cx) =
6648            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6649
6650        let text_thread_store =
6651            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6652        let history_store =
6653            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6654
6655        let connection = Rc::new(StubAgentConnection::new());
6656        let thread_view = cx.update(|window, cx| {
6657            cx.new(|cx| {
6658                AcpThreadView::new(
6659                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6660                    None,
6661                    None,
6662                    workspace.downgrade(),
6663                    project.clone(),
6664                    history_store.clone(),
6665                    None,
6666                    window,
6667                    cx,
6668                )
6669            })
6670        });
6671
6672        cx.run_until_parked();
6673
6674        let thread = thread_view
6675            .read_with(cx, |view, _| view.thread().cloned())
6676            .unwrap();
6677
6678        // First user message
6679        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6680            id: acp::ToolCallId("tool1".into()),
6681            title: "Edit file 1".into(),
6682            kind: acp::ToolKind::Edit,
6683            status: acp::ToolCallStatus::Completed,
6684            content: vec![acp::ToolCallContent::Diff {
6685                diff: acp::Diff {
6686                    path: "/project/test1.txt".into(),
6687                    old_text: Some("old content 1".into()),
6688                    new_text: "new content 1".into(),
6689                    meta: None,
6690                },
6691            }],
6692            locations: vec![],
6693            raw_input: None,
6694            raw_output: None,
6695            meta: None,
6696        })]);
6697
6698        thread
6699            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6700            .await
6701            .unwrap();
6702        cx.run_until_parked();
6703
6704        thread.read_with(cx, |thread, _| {
6705            assert_eq!(thread.entries().len(), 2);
6706        });
6707
6708        thread_view.read_with(cx, |view, cx| {
6709            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6710                assert!(
6711                    entry_view_state
6712                        .entry(0)
6713                        .unwrap()
6714                        .message_editor()
6715                        .is_some()
6716                );
6717                assert!(entry_view_state.entry(1).unwrap().has_content());
6718            });
6719        });
6720
6721        // Second user message
6722        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6723            id: acp::ToolCallId("tool2".into()),
6724            title: "Edit file 2".into(),
6725            kind: acp::ToolKind::Edit,
6726            status: acp::ToolCallStatus::Completed,
6727            content: vec![acp::ToolCallContent::Diff {
6728                diff: acp::Diff {
6729                    path: "/project/test2.txt".into(),
6730                    old_text: Some("old content 2".into()),
6731                    new_text: "new content 2".into(),
6732                    meta: None,
6733                },
6734            }],
6735            locations: vec![],
6736            raw_input: None,
6737            raw_output: None,
6738            meta: None,
6739        })]);
6740
6741        thread
6742            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6743            .await
6744            .unwrap();
6745        cx.run_until_parked();
6746
6747        let second_user_message_id = thread.read_with(cx, |thread, _| {
6748            assert_eq!(thread.entries().len(), 4);
6749            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6750                panic!();
6751            };
6752            user_message.id.clone().unwrap()
6753        });
6754
6755        thread_view.read_with(cx, |view, cx| {
6756            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6757                assert!(
6758                    entry_view_state
6759                        .entry(0)
6760                        .unwrap()
6761                        .message_editor()
6762                        .is_some()
6763                );
6764                assert!(entry_view_state.entry(1).unwrap().has_content());
6765                assert!(
6766                    entry_view_state
6767                        .entry(2)
6768                        .unwrap()
6769                        .message_editor()
6770                        .is_some()
6771                );
6772                assert!(entry_view_state.entry(3).unwrap().has_content());
6773            });
6774        });
6775
6776        // Rewind to first message
6777        thread
6778            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6779            .await
6780            .unwrap();
6781
6782        cx.run_until_parked();
6783
6784        thread.read_with(cx, |thread, _| {
6785            assert_eq!(thread.entries().len(), 2);
6786        });
6787
6788        thread_view.read_with(cx, |view, cx| {
6789            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6790                assert!(
6791                    entry_view_state
6792                        .entry(0)
6793                        .unwrap()
6794                        .message_editor()
6795                        .is_some()
6796                );
6797                assert!(entry_view_state.entry(1).unwrap().has_content());
6798
6799                // Old views should be dropped
6800                assert!(entry_view_state.entry(2).is_none());
6801                assert!(entry_view_state.entry(3).is_none());
6802            });
6803        });
6804    }
6805
6806    #[gpui::test]
6807    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6808        init_test(cx);
6809
6810        let connection = StubAgentConnection::new();
6811
6812        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6813            acp::ContentChunk {
6814                content: acp::ContentBlock::Text(acp::TextContent {
6815                    text: "Response".into(),
6816                    annotations: None,
6817                    meta: None,
6818                }),
6819                meta: None,
6820            },
6821        )]);
6822
6823        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6824        add_to_workspace(thread_view.clone(), cx);
6825
6826        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6827        message_editor.update_in(cx, |editor, window, cx| {
6828            editor.set_text("Original message to edit", window, cx);
6829        });
6830        thread_view.update_in(cx, |thread_view, window, cx| {
6831            thread_view.send(window, cx);
6832        });
6833
6834        cx.run_until_parked();
6835
6836        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6837            assert_eq!(view.editing_message, None);
6838
6839            view.entry_view_state
6840                .read(cx)
6841                .entry(0)
6842                .unwrap()
6843                .message_editor()
6844                .unwrap()
6845                .clone()
6846        });
6847
6848        // Focus
6849        cx.focus(&user_message_editor);
6850        thread_view.read_with(cx, |view, _cx| {
6851            assert_eq!(view.editing_message, Some(0));
6852        });
6853
6854        // Edit
6855        user_message_editor.update_in(cx, |editor, window, cx| {
6856            editor.set_text("Edited message content", window, cx);
6857        });
6858
6859        // Cancel
6860        user_message_editor.update_in(cx, |_editor, window, cx| {
6861            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6862        });
6863
6864        thread_view.read_with(cx, |view, _cx| {
6865            assert_eq!(view.editing_message, None);
6866        });
6867
6868        user_message_editor.read_with(cx, |editor, cx| {
6869            assert_eq!(editor.text(cx), "Original message to edit");
6870        });
6871    }
6872
6873    #[gpui::test]
6874    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6875        init_test(cx);
6876
6877        let connection = StubAgentConnection::new();
6878
6879        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6880        add_to_workspace(thread_view.clone(), cx);
6881
6882        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6883        let mut events = cx.events(&message_editor);
6884        message_editor.update_in(cx, |editor, window, cx| {
6885            editor.set_text("", window, cx);
6886        });
6887
6888        message_editor.update_in(cx, |_editor, window, cx| {
6889            window.dispatch_action(Box::new(Chat), cx);
6890        });
6891        cx.run_until_parked();
6892        // We shouldn't have received any messages
6893        assert!(matches!(
6894            events.try_next(),
6895            Err(futures::channel::mpsc::TryRecvError { .. })
6896        ));
6897    }
6898
6899    #[gpui::test]
6900    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6901        init_test(cx);
6902
6903        let connection = StubAgentConnection::new();
6904
6905        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6906            acp::ContentChunk {
6907                content: acp::ContentBlock::Text(acp::TextContent {
6908                    text: "Response".into(),
6909                    annotations: None,
6910                    meta: None,
6911                }),
6912                meta: None,
6913            },
6914        )]);
6915
6916        let (thread_view, cx) =
6917            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6918        add_to_workspace(thread_view.clone(), cx);
6919
6920        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6921        message_editor.update_in(cx, |editor, window, cx| {
6922            editor.set_text("Original message to edit", window, cx);
6923        });
6924        thread_view.update_in(cx, |thread_view, window, cx| {
6925            thread_view.send(window, cx);
6926        });
6927
6928        cx.run_until_parked();
6929
6930        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6931            assert_eq!(view.editing_message, None);
6932            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6933
6934            view.entry_view_state
6935                .read(cx)
6936                .entry(0)
6937                .unwrap()
6938                .message_editor()
6939                .unwrap()
6940                .clone()
6941        });
6942
6943        // Focus
6944        cx.focus(&user_message_editor);
6945
6946        // Edit
6947        user_message_editor.update_in(cx, |editor, window, cx| {
6948            editor.set_text("Edited message content", window, cx);
6949        });
6950
6951        // Send
6952        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6953            acp::ContentChunk {
6954                content: acp::ContentBlock::Text(acp::TextContent {
6955                    text: "New Response".into(),
6956                    annotations: None,
6957                    meta: None,
6958                }),
6959                meta: None,
6960            },
6961        )]);
6962
6963        user_message_editor.update_in(cx, |_editor, window, cx| {
6964            window.dispatch_action(Box::new(Chat), cx);
6965        });
6966
6967        cx.run_until_parked();
6968
6969        thread_view.read_with(cx, |view, cx| {
6970            assert_eq!(view.editing_message, None);
6971
6972            let entries = view.thread().unwrap().read(cx).entries();
6973            assert_eq!(entries.len(), 2);
6974            assert_eq!(
6975                entries[0].to_markdown(cx),
6976                "## User\n\nEdited message content\n\n"
6977            );
6978            assert_eq!(
6979                entries[1].to_markdown(cx),
6980                "## Assistant\n\nNew Response\n\n"
6981            );
6982
6983            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6984                assert!(!state.entry(1).unwrap().has_content());
6985                state.entry(0).unwrap().message_editor().unwrap().clone()
6986            });
6987
6988            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6989        })
6990    }
6991
6992    #[gpui::test]
6993    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6994        init_test(cx);
6995
6996        let connection = StubAgentConnection::new();
6997
6998        let (thread_view, cx) =
6999            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7000        add_to_workspace(thread_view.clone(), cx);
7001
7002        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7003        message_editor.update_in(cx, |editor, window, cx| {
7004            editor.set_text("Original message to edit", window, cx);
7005        });
7006        thread_view.update_in(cx, |thread_view, window, cx| {
7007            thread_view.send(window, cx);
7008        });
7009
7010        cx.run_until_parked();
7011
7012        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
7013            let thread = view.thread().unwrap().read(cx);
7014            assert_eq!(thread.entries().len(), 1);
7015
7016            let editor = view
7017                .entry_view_state
7018                .read(cx)
7019                .entry(0)
7020                .unwrap()
7021                .message_editor()
7022                .unwrap()
7023                .clone();
7024
7025            (editor, thread.session_id().clone())
7026        });
7027
7028        // Focus
7029        cx.focus(&user_message_editor);
7030
7031        thread_view.read_with(cx, |view, _cx| {
7032            assert_eq!(view.editing_message, Some(0));
7033        });
7034
7035        // Edit
7036        user_message_editor.update_in(cx, |editor, window, cx| {
7037            editor.set_text("Edited message content", window, cx);
7038        });
7039
7040        thread_view.read_with(cx, |view, _cx| {
7041            assert_eq!(view.editing_message, Some(0));
7042        });
7043
7044        // Finish streaming response
7045        cx.update(|_, cx| {
7046            connection.send_update(
7047                session_id.clone(),
7048                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7049                    content: acp::ContentBlock::Text(acp::TextContent {
7050                        text: "Response".into(),
7051                        annotations: None,
7052                        meta: None,
7053                    }),
7054                    meta: None,
7055                }),
7056                cx,
7057            );
7058            connection.end_turn(session_id, acp::StopReason::EndTurn);
7059        });
7060
7061        thread_view.read_with(cx, |view, _cx| {
7062            assert_eq!(view.editing_message, Some(0));
7063        });
7064
7065        cx.run_until_parked();
7066
7067        // Should still be editing
7068        cx.update(|window, cx| {
7069            assert!(user_message_editor.focus_handle(cx).is_focused(window));
7070            assert_eq!(thread_view.read(cx).editing_message, Some(0));
7071            assert_eq!(
7072                user_message_editor.read(cx).text(cx),
7073                "Edited message content"
7074            );
7075        });
7076    }
7077
7078    #[gpui::test]
7079    async fn test_interrupt(cx: &mut TestAppContext) {
7080        init_test(cx);
7081
7082        let connection = StubAgentConnection::new();
7083
7084        let (thread_view, cx) =
7085            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7086        add_to_workspace(thread_view.clone(), cx);
7087
7088        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7089        message_editor.update_in(cx, |editor, window, cx| {
7090            editor.set_text("Message 1", window, cx);
7091        });
7092        thread_view.update_in(cx, |thread_view, window, cx| {
7093            thread_view.send(window, cx);
7094        });
7095
7096        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
7097            let thread = view.thread().unwrap();
7098
7099            (thread.clone(), thread.read(cx).session_id().clone())
7100        });
7101
7102        cx.run_until_parked();
7103
7104        cx.update(|_, cx| {
7105            connection.send_update(
7106                session_id.clone(),
7107                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7108                    content: "Message 1 resp".into(),
7109                    meta: None,
7110                }),
7111                cx,
7112            );
7113        });
7114
7115        cx.run_until_parked();
7116
7117        thread.read_with(cx, |thread, cx| {
7118            assert_eq!(
7119                thread.to_markdown(cx),
7120                indoc::indoc! {"
7121                    ## User
7122
7123                    Message 1
7124
7125                    ## Assistant
7126
7127                    Message 1 resp
7128
7129                "}
7130            )
7131        });
7132
7133        message_editor.update_in(cx, |editor, window, cx| {
7134            editor.set_text("Message 2", window, cx);
7135        });
7136        thread_view.update_in(cx, |thread_view, window, cx| {
7137            thread_view.send(window, cx);
7138        });
7139
7140        cx.update(|_, cx| {
7141            // Simulate a response sent after beginning to cancel
7142            connection.send_update(
7143                session_id.clone(),
7144                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7145                    content: "onse".into(),
7146                    meta: None,
7147                }),
7148                cx,
7149            );
7150        });
7151
7152        cx.run_until_parked();
7153
7154        // Last Message 1 response should appear before Message 2
7155        thread.read_with(cx, |thread, cx| {
7156            assert_eq!(
7157                thread.to_markdown(cx),
7158                indoc::indoc! {"
7159                    ## User
7160
7161                    Message 1
7162
7163                    ## Assistant
7164
7165                    Message 1 response
7166
7167                    ## User
7168
7169                    Message 2
7170
7171                "}
7172            )
7173        });
7174
7175        cx.update(|_, cx| {
7176            connection.send_update(
7177                session_id.clone(),
7178                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7179                    content: "Message 2 response".into(),
7180                    meta: None,
7181                }),
7182                cx,
7183            );
7184            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7185        });
7186
7187        cx.run_until_parked();
7188
7189        thread.read_with(cx, |thread, cx| {
7190            assert_eq!(
7191                thread.to_markdown(cx),
7192                indoc::indoc! {"
7193                    ## User
7194
7195                    Message 1
7196
7197                    ## Assistant
7198
7199                    Message 1 response
7200
7201                    ## User
7202
7203                    Message 2
7204
7205                    ## Assistant
7206
7207                    Message 2 response
7208
7209                "}
7210            )
7211        });
7212    }
7213
7214    #[gpui::test]
7215    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7216        init_test(cx);
7217
7218        let connection = StubAgentConnection::new();
7219        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7220            acp::ContentChunk {
7221                content: acp::ContentBlock::Text(acp::TextContent {
7222                    text: "Response".into(),
7223                    annotations: None,
7224                    meta: None,
7225                }),
7226                meta: None,
7227            },
7228        )]);
7229
7230        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7231        add_to_workspace(thread_view.clone(), cx);
7232
7233        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7234        message_editor.update_in(cx, |editor, window, cx| {
7235            editor.set_text("Original message to edit", window, cx)
7236        });
7237        thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7238        cx.run_until_parked();
7239
7240        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7241            thread_view
7242                .entry_view_state
7243                .read(cx)
7244                .entry(0)
7245                .expect("Should have at least one entry")
7246                .message_editor()
7247                .expect("Should have message editor")
7248                .clone()
7249        });
7250
7251        cx.focus(&user_message_editor);
7252        thread_view.read_with(cx, |thread_view, _cx| {
7253            assert_eq!(thread_view.editing_message, Some(0));
7254        });
7255
7256        // Ensure to edit the focused message before proceeding otherwise, since
7257        // its content is not different from what was sent, focus will be lost.
7258        user_message_editor.update_in(cx, |editor, window, cx| {
7259            editor.set_text("Original message to edit with ", window, cx)
7260        });
7261
7262        // Create a simple buffer with some text so we can create a selection
7263        // that will then be added to the message being edited.
7264        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7265            (thread_view.workspace.clone(), thread_view.project.clone())
7266        });
7267        let buffer = project.update(cx, |project, cx| {
7268            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7269        });
7270
7271        workspace
7272            .update_in(cx, |workspace, window, cx| {
7273                let editor = cx.new(|cx| {
7274                    let mut editor =
7275                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7276
7277                    editor.change_selections(Default::default(), window, cx, |selections| {
7278                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7279                    });
7280
7281                    editor
7282                });
7283                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7284            })
7285            .unwrap();
7286
7287        thread_view.update_in(cx, |thread_view, window, cx| {
7288            assert_eq!(thread_view.editing_message, Some(0));
7289            thread_view.insert_selections(window, cx);
7290        });
7291
7292        user_message_editor.read_with(cx, |editor, cx| {
7293            let text = editor.editor().read(cx).text(cx);
7294            let expected_text = String::from("Original message to edit with selection ");
7295
7296            assert_eq!(text, expected_text);
7297        });
7298    }
7299
7300    #[gpui::test]
7301    async fn test_insert_selections(cx: &mut TestAppContext) {
7302        init_test(cx);
7303
7304        let connection = StubAgentConnection::new();
7305        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7306            acp::ContentChunk {
7307                content: acp::ContentBlock::Text(acp::TextContent {
7308                    text: "Response".into(),
7309                    annotations: None,
7310                    meta: None,
7311                }),
7312                meta: None,
7313            },
7314        )]);
7315
7316        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7317        add_to_workspace(thread_view.clone(), cx);
7318
7319        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7320        message_editor.update_in(cx, |editor, window, cx| {
7321            editor.set_text("Can you review this snippet ", window, cx)
7322        });
7323
7324        // Create a simple buffer with some text so we can create a selection
7325        // that will then be added to the message being edited.
7326        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7327            (thread_view.workspace.clone(), thread_view.project.clone())
7328        });
7329        let buffer = project.update(cx, |project, cx| {
7330            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7331        });
7332
7333        workspace
7334            .update_in(cx, |workspace, window, cx| {
7335                let editor = cx.new(|cx| {
7336                    let mut editor =
7337                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7338
7339                    editor.change_selections(Default::default(), window, cx, |selections| {
7340                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7341                    });
7342
7343                    editor
7344                });
7345                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7346            })
7347            .unwrap();
7348
7349        thread_view.update_in(cx, |thread_view, window, cx| {
7350            assert_eq!(thread_view.editing_message, None);
7351            thread_view.insert_selections(window, cx);
7352        });
7353
7354        thread_view.read_with(cx, |thread_view, cx| {
7355            let text = thread_view.message_editor.read(cx).text(cx);
7356            let expected_txt = String::from("Can you review this snippet selection ");
7357
7358            assert_eq!(text, expected_txt);
7359        })
7360    }
7361}