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