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