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