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};
  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::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
  39use std::cell::RefCell;
  40use std::path::Path;
  41use std::sync::Arc;
  42use std::time::Instant;
  43use std::{collections::BTreeMap, rc::Rc, time::Duration};
  44use terminal_view::terminal_panel::TerminalPanel;
  45use text::Anchor;
  46use theme::{AgentFontSize, ThemeSettings};
  47use ui::{
  48    Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
  49    PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
  50};
  51use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  52use workspace::{CollaboratorId, Workspace};
  53use zed_actions::agent::{Chat, ToggleModelSelector};
  54use zed_actions::assistant::OpenRulesLibrary;
  55
  56use super::entry_view_state::EntryViewState;
  57use crate::acp::AcpModelSelectorPopover;
  58use crate::acp::ModeSelector;
  59use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
  60use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  61use crate::agent_diff::AgentDiff;
  62use crate::profile_selector::{ProfileProvider, ProfileSelector};
  63
  64use crate::ui::{
  65    AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
  66    UsageCallout,
  67};
  68use crate::{
  69    AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ContinueThread, ContinueWithBurnMode,
  70    CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, OpenHistory, RejectAll,
  71    RejectOnce, ToggleBurnMode, ToggleProfileSelector,
  72};
  73
  74#[derive(Copy, Clone, Debug, PartialEq, Eq)]
  75enum ThreadFeedback {
  76    Positive,
  77    Negative,
  78}
  79
  80#[derive(Debug)]
  81enum ThreadError {
  82    PaymentRequired,
  83    ModelRequestLimitReached(cloud_llm_client::Plan),
  84    ToolUseLimitReached,
  85    Refusal,
  86    AuthenticationRequired(SharedString),
  87    Other(SharedString),
  88}
  89
  90impl ThreadError {
  91    fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
  92        if error.is::<language_model::PaymentRequiredError>() {
  93            Self::PaymentRequired
  94        } else if error.is::<language_model::ToolUseLimitReachedError>() {
  95            Self::ToolUseLimitReached
  96        } else if let Some(error) =
  97            error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
  98        {
  99            Self::ModelRequestLimitReached(error.plan)
 100        } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
 101            && acp_error.code == acp::ErrorCode::AUTH_REQUIRED.code
 102        {
 103            Self::AuthenticationRequired(acp_error.message.clone().into())
 104        } else {
 105            let string = error.to_string();
 106            // TODO: we should have Gemini return better errors here.
 107            if agent.clone().downcast::<agent_servers::Gemini>().is_some()
 108                && string.contains("Could not load the default credentials")
 109                || string.contains("API key not valid")
 110                || string.contains("Request had invalid authentication credentials")
 111            {
 112                Self::AuthenticationRequired(string.into())
 113            } else {
 114                Self::Other(error.to_string().into())
 115            }
 116        }
 117    }
 118}
 119
 120impl ProfileProvider for Entity<agent2::Thread> {
 121    fn profile_id(&self, cx: &App) -> AgentProfileId {
 122        self.read(cx).profile().clone()
 123    }
 124
 125    fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
 126        self.update(cx, |thread, _cx| {
 127            thread.set_profile(profile_id);
 128        });
 129    }
 130
 131    fn profiles_supported(&self, cx: &App) -> bool {
 132        self.read(cx)
 133            .model()
 134            .is_some_and(|model| model.supports_tools())
 135    }
 136}
 137
 138#[derive(Default)]
 139struct ThreadFeedbackState {
 140    feedback: Option<ThreadFeedback>,
 141    comments_editor: Option<Entity<Editor>>,
 142}
 143
 144impl ThreadFeedbackState {
 145    pub fn submit(
 146        &mut self,
 147        thread: Entity<AcpThread>,
 148        feedback: ThreadFeedback,
 149        window: &mut Window,
 150        cx: &mut App,
 151    ) {
 152        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 153            return;
 154        };
 155
 156        if self.feedback == Some(feedback) {
 157            return;
 158        }
 159
 160        self.feedback = Some(feedback);
 161        match feedback {
 162            ThreadFeedback::Positive => {
 163                self.comments_editor = None;
 164            }
 165            ThreadFeedback::Negative => {
 166                self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
 167            }
 168        }
 169        let session_id = thread.read(cx).session_id().clone();
 170        let agent_name = telemetry.agent_name();
 171        let task = telemetry.thread_data(&session_id, cx);
 172        let rating = match feedback {
 173            ThreadFeedback::Positive => "positive",
 174            ThreadFeedback::Negative => "negative",
 175        };
 176        cx.background_spawn(async move {
 177            let thread = task.await?;
 178            telemetry::event!(
 179                "Agent Thread Rated",
 180                session_id = session_id,
 181                rating = rating,
 182                agent = agent_name,
 183                thread = thread
 184            );
 185            anyhow::Ok(())
 186        })
 187        .detach_and_log_err(cx);
 188    }
 189
 190    pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
 191        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 192            return;
 193        };
 194
 195        let Some(comments) = self
 196            .comments_editor
 197            .as_ref()
 198            .map(|editor| editor.read(cx).text(cx))
 199            .filter(|text| !text.trim().is_empty())
 200        else {
 201            return;
 202        };
 203
 204        self.comments_editor.take();
 205
 206        let session_id = thread.read(cx).session_id().clone();
 207        let agent_name = telemetry.agent_name();
 208        let task = telemetry.thread_data(&session_id, cx);
 209        cx.background_spawn(async move {
 210            let thread = task.await?;
 211            telemetry::event!(
 212                "Agent Thread Feedback Comments",
 213                session_id = session_id,
 214                comments = comments,
 215                agent = agent_name,
 216                thread = thread
 217            );
 218            anyhow::Ok(())
 219        })
 220        .detach_and_log_err(cx);
 221    }
 222
 223    pub fn clear(&mut self) {
 224        *self = Self::default()
 225    }
 226
 227    pub fn dismiss_comments(&mut self) {
 228        self.comments_editor.take();
 229    }
 230
 231    fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
 232        let buffer = cx.new(|cx| {
 233            let empty_string = String::new();
 234            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
 235        });
 236
 237        let editor = cx.new(|cx| {
 238            let mut editor = Editor::new(
 239                editor::EditorMode::AutoHeight {
 240                    min_lines: 1,
 241                    max_lines: Some(4),
 242                },
 243                buffer,
 244                None,
 245                window,
 246                cx,
 247            );
 248            editor.set_placeholder_text(
 249                "What went wrong? Share your feedback so we can improve.",
 250                window,
 251                cx,
 252            );
 253            editor
 254        });
 255
 256        editor.read(cx).focus_handle(cx).focus(window);
 257        editor
 258    }
 259}
 260
 261pub struct AcpThreadView {
 262    agent: Rc<dyn AgentServer>,
 263    workspace: WeakEntity<Workspace>,
 264    project: Entity<Project>,
 265    thread_state: ThreadState,
 266    login: Option<task::SpawnInTerminal>,
 267    history_store: Entity<HistoryStore>,
 268    hovered_recent_history_item: Option<usize>,
 269    entry_view_state: Entity<EntryViewState>,
 270    message_editor: Entity<MessageEditor>,
 271    focus_handle: FocusHandle,
 272    model_selector: Option<Entity<AcpModelSelectorPopover>>,
 273    profile_selector: Option<Entity<ProfileSelector>>,
 274    notifications: Vec<WindowHandle<AgentNotification>>,
 275    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 276    thread_retry_status: Option<RetryStatus>,
 277    thread_error: Option<ThreadError>,
 278    thread_feedback: ThreadFeedbackState,
 279    list_state: ListState,
 280    auth_task: Option<Task<()>>,
 281    expanded_tool_calls: HashSet<acp::ToolCallId>,
 282    expanded_thinking_blocks: HashSet<(usize, usize)>,
 283    edits_expanded: bool,
 284    plan_expanded: bool,
 285    editor_expanded: bool,
 286    should_be_following: bool,
 287    editing_message: Option<usize>,
 288    prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
 289    available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
 290    is_loading_contents: bool,
 291    new_server_version_available: Option<SharedString>,
 292    _cancel_task: Option<Task<()>>,
 293    _subscriptions: [Subscription; 4],
 294}
 295
 296enum ThreadState {
 297    Loading(Entity<LoadingView>),
 298    Ready {
 299        thread: Entity<AcpThread>,
 300        title_editor: Option<Entity<Editor>>,
 301        mode_selector: Option<Entity<ModeSelector>>,
 302        _subscriptions: Vec<Subscription>,
 303    },
 304    LoadError(LoadError),
 305    Unauthenticated {
 306        connection: Rc<dyn AgentConnection>,
 307        description: Option<Entity<Markdown>>,
 308        configuration_view: Option<AnyView>,
 309        pending_auth_method: Option<acp::AuthMethodId>,
 310        _subscription: Option<Subscription>,
 311    },
 312}
 313
 314struct LoadingView {
 315    title: SharedString,
 316    _load_task: Task<()>,
 317    _update_title_task: Task<anyhow::Result<()>>,
 318}
 319
 320impl AcpThreadView {
 321    pub fn new(
 322        agent: Rc<dyn AgentServer>,
 323        resume_thread: Option<DbThreadMetadata>,
 324        summarize_thread: Option<DbThreadMetadata>,
 325        workspace: WeakEntity<Workspace>,
 326        project: Entity<Project>,
 327        history_store: Entity<HistoryStore>,
 328        prompt_store: Option<Entity<PromptStore>>,
 329        window: &mut Window,
 330        cx: &mut Context<Self>,
 331    ) -> Self {
 332        let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
 333        let available_commands = Rc::new(RefCell::new(vec![]));
 334
 335        let placeholder = if agent.name() == "Zed Agent" {
 336            format!("Message the {} — @ to include context", agent.name())
 337        } else if agent.name() == "Claude Code" || !available_commands.borrow().is_empty() {
 338            format!(
 339                "Message {} — @ to include context, / for commands",
 340                agent.name()
 341            )
 342        } else {
 343            format!("Message {} — @ to include context", agent.name())
 344        };
 345
 346        let message_editor = cx.new(|cx| {
 347            let mut editor = MessageEditor::new(
 348                workspace.clone(),
 349                project.clone(),
 350                history_store.clone(),
 351                prompt_store.clone(),
 352                prompt_capabilities.clone(),
 353                available_commands.clone(),
 354                agent.name(),
 355                &placeholder,
 356                editor::EditorMode::AutoHeight {
 357                    min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
 358                    max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
 359                },
 360                window,
 361                cx,
 362            );
 363            if let Some(entry) = summarize_thread {
 364                editor.insert_thread_summary(entry, window, cx);
 365            }
 366            editor
 367        });
 368
 369        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 370
 371        let entry_view_state = cx.new(|_| {
 372            EntryViewState::new(
 373                workspace.clone(),
 374                project.clone(),
 375                history_store.clone(),
 376                prompt_store.clone(),
 377                prompt_capabilities.clone(),
 378                available_commands.clone(),
 379                agent.name(),
 380            )
 381        });
 382
 383        let subscriptions = [
 384            cx.observe_global_in::<SettingsStore>(window, Self::agent_font_size_changed),
 385            cx.observe_global_in::<AgentFontSize>(window, Self::agent_font_size_changed),
 386            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 387            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 388        ];
 389
 390        Self {
 391            agent: agent.clone(),
 392            workspace: workspace.clone(),
 393            project: project.clone(),
 394            entry_view_state,
 395            thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
 396            login: None,
 397            message_editor,
 398            model_selector: None,
 399            profile_selector: None,
 400
 401            notifications: Vec::new(),
 402            notification_subscriptions: HashMap::default(),
 403            list_state: list_state,
 404            thread_retry_status: None,
 405            thread_error: None,
 406            thread_feedback: Default::default(),
 407            auth_task: None,
 408            expanded_tool_calls: HashSet::default(),
 409            expanded_thinking_blocks: HashSet::default(),
 410            editing_message: None,
 411            edits_expanded: false,
 412            plan_expanded: false,
 413            prompt_capabilities,
 414            available_commands,
 415            editor_expanded: false,
 416            should_be_following: false,
 417            history_store,
 418            hovered_recent_history_item: None,
 419            is_loading_contents: false,
 420            _subscriptions: subscriptions,
 421            _cancel_task: None,
 422            focus_handle: cx.focus_handle(),
 423            new_server_version_available: None,
 424        }
 425    }
 426
 427    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 428        self.thread_state = Self::initial_state(
 429            self.agent.clone(),
 430            None,
 431            self.workspace.clone(),
 432            self.project.clone(),
 433            window,
 434            cx,
 435        );
 436        self.available_commands.replace(vec![]);
 437        self.new_server_version_available.take();
 438        cx.notify();
 439    }
 440
 441    fn initial_state(
 442        agent: Rc<dyn AgentServer>,
 443        resume_thread: Option<DbThreadMetadata>,
 444        workspace: WeakEntity<Workspace>,
 445        project: Entity<Project>,
 446        window: &mut Window,
 447        cx: &mut Context<Self>,
 448    ) -> ThreadState {
 449        if project.read(cx).is_via_collab()
 450            && agent.clone().downcast::<NativeAgentServer>().is_none()
 451        {
 452            return ThreadState::LoadError(LoadError::Other(
 453                "External agents are not yet supported in shared projects.".into(),
 454            ));
 455        }
 456        let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 457        // Pick the first non-single-file worktree for the root directory if there are any,
 458        // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
 459        worktrees.sort_by(|l, r| {
 460            l.read(cx)
 461                .is_single_file()
 462                .cmp(&r.read(cx).is_single_file())
 463        });
 464        let root_dir = worktrees
 465            .into_iter()
 466            .filter_map(|worktree| {
 467                if worktree.read(cx).is_single_file() {
 468                    Some(worktree.read(cx).abs_path().parent()?.into())
 469                } else {
 470                    Some(worktree.read(cx).abs_path())
 471                }
 472            })
 473            .next();
 474        let (status_tx, mut status_rx) = watch::channel("Loading…".into());
 475        let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
 476        let delegate = AgentServerDelegate::new(
 477            project.read(cx).agent_server_store().clone(),
 478            project.clone(),
 479            Some(status_tx),
 480            Some(new_version_available_tx),
 481        );
 482
 483        let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
 484        let load_task = cx.spawn_in(window, async move |this, cx| {
 485            let connection = match connect_task.await {
 486                Ok((connection, login)) => {
 487                    this.update(cx, |this, _| this.login = login).ok();
 488                    connection
 489                }
 490                Err(err) => {
 491                    this.update_in(cx, |this, window, cx| {
 492                        if err.downcast_ref::<LoadError>().is_some() {
 493                            this.handle_load_error(err, window, cx);
 494                        } else {
 495                            this.handle_thread_error(err, cx);
 496                        }
 497                        cx.notify();
 498                    })
 499                    .log_err();
 500                    return;
 501                }
 502            };
 503
 504            let result = if let Some(native_agent) = connection
 505                .clone()
 506                .downcast::<agent2::NativeAgentConnection>()
 507                && let Some(resume) = resume_thread.clone()
 508            {
 509                cx.update(|_, cx| {
 510                    native_agent
 511                        .0
 512                        .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
 513                })
 514                .log_err()
 515            } else {
 516                let root_dir = if let Some(acp_agent) = connection
 517                    .clone()
 518                    .downcast::<agent_servers::AcpConnection>()
 519                {
 520                    acp_agent.root_dir().into()
 521                } else {
 522                    root_dir.unwrap_or(paths::home_dir().as_path().into())
 523                };
 524                cx.update(|_, cx| {
 525                    connection
 526                        .clone()
 527                        .new_thread(project.clone(), &root_dir, cx)
 528                })
 529                .log_err()
 530            };
 531
 532            let Some(result) = result else {
 533                return;
 534            };
 535
 536            let result = match result.await {
 537                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 538                    Ok(err) => {
 539                        cx.update(|window, cx| {
 540                            Self::handle_auth_required(this, err, agent, connection, window, cx)
 541                        })
 542                        .log_err();
 543                        return;
 544                    }
 545                    Err(err) => Err(err),
 546                },
 547                Ok(thread) => Ok(thread),
 548            };
 549
 550            this.update_in(cx, |this, window, cx| {
 551                match result {
 552                    Ok(thread) => {
 553                        let action_log = thread.read(cx).action_log().clone();
 554
 555                        this.prompt_capabilities
 556                            .replace(thread.read(cx).prompt_capabilities());
 557
 558                        let count = thread.read(cx).entries().len();
 559                        this.entry_view_state.update(cx, |view_state, cx| {
 560                            for ix in 0..count {
 561                                view_state.sync_entry(ix, &thread, window, cx);
 562                            }
 563                            this.list_state.splice_focusable(
 564                                0..0,
 565                                (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
 566                            );
 567                        });
 568
 569                        if let Some(resume) = resume_thread {
 570                            this.history_store.update(cx, |history, cx| {
 571                                history.push_recently_opened_entry(
 572                                    HistoryEntryId::AcpThread(resume.id),
 573                                    cx,
 574                                );
 575                            });
 576                        }
 577
 578                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 579
 580                        this.model_selector = thread
 581                            .read(cx)
 582                            .connection()
 583                            .model_selector(thread.read(cx).session_id())
 584                            .map(|selector| {
 585                                cx.new(|cx| {
 586                                    AcpModelSelectorPopover::new(
 587                                        selector,
 588                                        PopoverMenuHandle::default(),
 589                                        this.focus_handle(cx),
 590                                        window,
 591                                        cx,
 592                                    )
 593                                })
 594                            });
 595
 596                        let mode_selector = thread
 597                            .read(cx)
 598                            .connection()
 599                            .session_modes(thread.read(cx).session_id(), cx)
 600                            .map(|session_modes| {
 601                                let fs = this.project.read(cx).fs().clone();
 602                                let focus_handle = this.focus_handle(cx);
 603                                cx.new(|_cx| {
 604                                    ModeSelector::new(
 605                                        session_modes,
 606                                        this.agent.clone(),
 607                                        fs,
 608                                        focus_handle,
 609                                    )
 610                                })
 611                            });
 612
 613                        let mut subscriptions = vec![
 614                            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 615                            cx.observe(&action_log, |_, _, cx| cx.notify()),
 616                        ];
 617
 618                        let title_editor =
 619                            if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
 620                                let editor = cx.new(|cx| {
 621                                    let mut editor = Editor::single_line(window, cx);
 622                                    editor.set_text(thread.read(cx).title(), window, cx);
 623                                    editor
 624                                });
 625                                subscriptions.push(cx.subscribe_in(
 626                                    &editor,
 627                                    window,
 628                                    Self::handle_title_editor_event,
 629                                ));
 630                                Some(editor)
 631                            } else {
 632                                None
 633                            };
 634
 635                        this.thread_state = ThreadState::Ready {
 636                            thread,
 637                            title_editor,
 638                            mode_selector,
 639                            _subscriptions: subscriptions,
 640                        };
 641                        this.message_editor.focus_handle(cx).focus(window);
 642
 643                        this.profile_selector = this.as_native_thread(cx).map(|thread| {
 644                            cx.new(|cx| {
 645                                ProfileSelector::new(
 646                                    <dyn Fs>::global(cx),
 647                                    Arc::new(thread.clone()),
 648                                    this.focus_handle(cx),
 649                                    cx,
 650                                )
 651                            })
 652                        });
 653
 654                        cx.notify();
 655                    }
 656                    Err(err) => {
 657                        this.handle_load_error(err, window, cx);
 658                    }
 659                };
 660            })
 661            .log_err();
 662        });
 663
 664        cx.spawn(async move |this, cx| {
 665            while let Ok(new_version) = new_version_available_rx.recv().await {
 666                if let Some(new_version) = new_version {
 667                    this.update(cx, |this, cx| {
 668                        this.new_server_version_available = Some(new_version.into());
 669                        cx.notify();
 670                    })
 671                    .log_err();
 672                }
 673            }
 674        })
 675        .detach();
 676
 677        let loading_view = cx.new(|cx| {
 678            let update_title_task = cx.spawn(async move |this, cx| {
 679                loop {
 680                    let status = status_rx.recv().await?;
 681                    this.update(cx, |this: &mut LoadingView, cx| {
 682                        this.title = status;
 683                        cx.notify();
 684                    })?;
 685                }
 686            });
 687
 688            LoadingView {
 689                title: "Loading…".into(),
 690                _load_task: load_task,
 691                _update_title_task: update_title_task,
 692            }
 693        });
 694
 695        ThreadState::Loading(loading_view)
 696    }
 697
 698    fn handle_auth_required(
 699        this: WeakEntity<Self>,
 700        err: AuthRequired,
 701        agent: Rc<dyn AgentServer>,
 702        connection: Rc<dyn AgentConnection>,
 703        window: &mut Window,
 704        cx: &mut App,
 705    ) {
 706        let agent_name = agent.name();
 707        let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
 708            let registry = LanguageModelRegistry::global(cx);
 709
 710            let sub = window.subscribe(&registry, cx, {
 711                let provider_id = provider_id.clone();
 712                let this = this.clone();
 713                move |_, ev, window, cx| {
 714                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
 715                        && &provider_id == updated_provider_id
 716                        && LanguageModelRegistry::global(cx)
 717                            .read(cx)
 718                            .provider(&provider_id)
 719                            .map_or(false, |provider| provider.is_authenticated(cx))
 720                    {
 721                        this.update(cx, |this, cx| {
 722                            this.reset(window, cx);
 723                        })
 724                        .ok();
 725                    }
 726                }
 727            });
 728
 729            let view = registry.read(cx).provider(&provider_id).map(|provider| {
 730                provider.configuration_view(
 731                    language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
 732                    window,
 733                    cx,
 734                )
 735            });
 736
 737            (view, Some(sub))
 738        } else {
 739            (None, None)
 740        };
 741
 742        this.update(cx, |this, cx| {
 743            this.thread_state = ThreadState::Unauthenticated {
 744                pending_auth_method: None,
 745                connection,
 746                configuration_view,
 747                description: err
 748                    .description
 749                    .clone()
 750                    .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
 751                _subscription: subscription,
 752            };
 753            if this.message_editor.focus_handle(cx).is_focused(window) {
 754                this.focus_handle.focus(window)
 755            }
 756            cx.notify();
 757        })
 758        .ok();
 759    }
 760
 761    fn handle_load_error(
 762        &mut self,
 763        err: anyhow::Error,
 764        window: &mut Window,
 765        cx: &mut Context<Self>,
 766    ) {
 767        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 768            self.thread_state = ThreadState::LoadError(load_err.clone());
 769        } else {
 770            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 771        }
 772        if self.message_editor.focus_handle(cx).is_focused(window) {
 773            self.focus_handle.focus(window)
 774        }
 775        cx.notify();
 776    }
 777
 778    pub fn workspace(&self) -> &WeakEntity<Workspace> {
 779        &self.workspace
 780    }
 781
 782    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 783        match &self.thread_state {
 784            ThreadState::Ready { thread, .. } => Some(thread),
 785            ThreadState::Unauthenticated { .. }
 786            | ThreadState::Loading { .. }
 787            | ThreadState::LoadError { .. } => None,
 788        }
 789    }
 790
 791    pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
 792        match &self.thread_state {
 793            ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
 794            ThreadState::Unauthenticated { .. }
 795            | ThreadState::Loading { .. }
 796            | ThreadState::LoadError { .. } => None,
 797        }
 798    }
 799
 800    pub fn title(&self, cx: &App) -> SharedString {
 801        match &self.thread_state {
 802            ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
 803            ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
 804            ThreadState::LoadError(error) => match error {
 805                LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
 806                LoadError::FailedToInstall(_) => {
 807                    format!("Failed to Install {}", self.agent.name()).into()
 808                }
 809                LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
 810                LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
 811            },
 812        }
 813    }
 814
 815    pub fn title_editor(&self) -> Option<Entity<Editor>> {
 816        if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
 817            title_editor.clone()
 818        } else {
 819            None
 820        }
 821    }
 822
 823    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 824        self.thread_error.take();
 825        self.thread_retry_status.take();
 826
 827        if let Some(thread) = self.thread() {
 828            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 829        }
 830    }
 831
 832    pub fn expand_message_editor(
 833        &mut self,
 834        _: &ExpandMessageEditor,
 835        _window: &mut Window,
 836        cx: &mut Context<Self>,
 837    ) {
 838        self.set_editor_is_expanded(!self.editor_expanded, cx);
 839        cx.notify();
 840    }
 841
 842    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 843        self.editor_expanded = is_expanded;
 844        self.message_editor.update(cx, |editor, cx| {
 845            if is_expanded {
 846                editor.set_mode(
 847                    EditorMode::Full {
 848                        scale_ui_elements_with_buffer_font_size: false,
 849                        show_active_line_background: false,
 850                        sized_by_content: false,
 851                    },
 852                    cx,
 853                )
 854            } else {
 855                let agent_settings = AgentSettings::get_global(cx);
 856                editor.set_mode(
 857                    EditorMode::AutoHeight {
 858                        min_lines: agent_settings.message_editor_min_lines,
 859                        max_lines: Some(agent_settings.set_message_editor_max_lines()),
 860                    },
 861                    cx,
 862                )
 863            }
 864        });
 865        cx.notify();
 866    }
 867
 868    pub fn handle_title_editor_event(
 869        &mut self,
 870        title_editor: &Entity<Editor>,
 871        event: &EditorEvent,
 872        window: &mut Window,
 873        cx: &mut Context<Self>,
 874    ) {
 875        let Some(thread) = self.thread() else { return };
 876
 877        match event {
 878            EditorEvent::BufferEdited => {
 879                let new_title = title_editor.read(cx).text(cx);
 880                thread.update(cx, |thread, cx| {
 881                    thread
 882                        .set_title(new_title.into(), cx)
 883                        .detach_and_log_err(cx);
 884                })
 885            }
 886            EditorEvent::Blurred => {
 887                if title_editor.read(cx).text(cx).is_empty() {
 888                    title_editor.update(cx, |editor, cx| {
 889                        editor.set_text("New Thread", window, cx);
 890                    });
 891                }
 892            }
 893            _ => {}
 894        }
 895    }
 896
 897    pub fn handle_message_editor_event(
 898        &mut self,
 899        _: &Entity<MessageEditor>,
 900        event: &MessageEditorEvent,
 901        window: &mut Window,
 902        cx: &mut Context<Self>,
 903    ) {
 904        match event {
 905            MessageEditorEvent::Send => self.send(window, cx),
 906            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 907            MessageEditorEvent::Focus => {
 908                self.cancel_editing(&Default::default(), window, cx);
 909            }
 910            MessageEditorEvent::LostFocus => {}
 911        }
 912    }
 913
 914    pub fn handle_entry_view_event(
 915        &mut self,
 916        _: &Entity<EntryViewState>,
 917        event: &EntryViewEvent,
 918        window: &mut Window,
 919        cx: &mut Context<Self>,
 920    ) {
 921        match &event.view_event {
 922            ViewEvent::NewDiff(tool_call_id) => {
 923                if AgentSettings::get_global(cx).expand_edit_card {
 924                    self.expanded_tool_calls.insert(tool_call_id.clone());
 925                }
 926            }
 927            ViewEvent::NewTerminal(tool_call_id) => {
 928                if AgentSettings::get_global(cx).expand_terminal_card {
 929                    self.expanded_tool_calls.insert(tool_call_id.clone());
 930                }
 931            }
 932            ViewEvent::TerminalMovedToBackground(tool_call_id) => {
 933                self.expanded_tool_calls.remove(tool_call_id);
 934            }
 935            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 936                if let Some(thread) = self.thread()
 937                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 938                        thread.read(cx).entries().get(event.entry_index)
 939                    && user_message.id.is_some()
 940                {
 941                    self.editing_message = Some(event.entry_index);
 942                    cx.notify();
 943                }
 944            }
 945            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
 946                if let Some(thread) = self.thread()
 947                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 948                        thread.read(cx).entries().get(event.entry_index)
 949                    && user_message.id.is_some()
 950                {
 951                    if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
 952                        self.editing_message = None;
 953                        cx.notify();
 954                    }
 955                }
 956            }
 957            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 958                self.regenerate(event.entry_index, editor.clone(), window, cx);
 959            }
 960            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 961                self.cancel_editing(&Default::default(), window, cx);
 962            }
 963        }
 964    }
 965
 966    fn resume_chat(&mut self, cx: &mut Context<Self>) {
 967        self.thread_error.take();
 968        let Some(thread) = self.thread() else {
 969            return;
 970        };
 971        if !thread.read(cx).can_resume(cx) {
 972            return;
 973        }
 974
 975        let task = thread.update(cx, |thread, cx| thread.resume(cx));
 976        cx.spawn(async move |this, cx| {
 977            let result = task.await;
 978
 979            this.update(cx, |this, cx| {
 980                if let Err(err) = result {
 981                    this.handle_thread_error(err, cx);
 982                }
 983            })
 984        })
 985        .detach();
 986    }
 987
 988    fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 989        let Some(thread) = self.thread() else { return };
 990
 991        if self.is_loading_contents {
 992            return;
 993        }
 994
 995        self.history_store.update(cx, |history, cx| {
 996            history.push_recently_opened_entry(
 997                HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
 998                cx,
 999            );
1000        });
1001
1002        if thread.read(cx).status() != ThreadStatus::Idle {
1003            self.stop_current_and_send_new_message(window, cx);
1004            return;
1005        }
1006
1007        let text = self.message_editor.read(cx).text(cx);
1008        let text = text.trim();
1009        if text == "/login" || text == "/logout" {
1010            let ThreadState::Ready { thread, .. } = &self.thread_state else {
1011                return;
1012            };
1013
1014            let connection = thread.read(cx).connection().clone();
1015            if !connection
1016                .auth_methods()
1017                .iter()
1018                .any(|method| method.id.0.as_ref() == "claude-login")
1019            {
1020                return;
1021            };
1022            let this = cx.weak_entity();
1023            let agent = self.agent.clone();
1024            window.defer(cx, |window, cx| {
1025                Self::handle_auth_required(
1026                    this,
1027                    AuthRequired {
1028                        description: None,
1029                        provider_id: None,
1030                    },
1031                    agent,
1032                    connection,
1033                    window,
1034                    cx,
1035                );
1036            });
1037            cx.notify();
1038            return;
1039        }
1040
1041        let contents = self
1042            .message_editor
1043            .update(cx, |message_editor, cx| message_editor.contents(cx));
1044        self.send_impl(contents, window, cx)
1045    }
1046
1047    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1048        let Some(thread) = self.thread().cloned() else {
1049            return;
1050        };
1051
1052        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1053
1054        let contents = self
1055            .message_editor
1056            .update(cx, |message_editor, cx| message_editor.contents(cx));
1057
1058        cx.spawn_in(window, async move |this, cx| {
1059            cancelled.await;
1060
1061            this.update_in(cx, |this, window, cx| {
1062                this.send_impl(contents, window, cx);
1063            })
1064            .ok();
1065        })
1066        .detach();
1067    }
1068
1069    fn send_impl(
1070        &mut self,
1071        contents: Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
1072        window: &mut Window,
1073        cx: &mut Context<Self>,
1074    ) {
1075        let agent_telemetry_id = self.agent.telemetry_id();
1076
1077        self.thread_error.take();
1078        self.editing_message.take();
1079        self.thread_feedback.clear();
1080
1081        let Some(thread) = self.thread() else {
1082            return;
1083        };
1084        let thread = thread.downgrade();
1085        if self.should_be_following {
1086            self.workspace
1087                .update(cx, |workspace, cx| {
1088                    workspace.follow(CollaboratorId::Agent, window, cx);
1089                })
1090                .ok();
1091        }
1092
1093        self.is_loading_contents = true;
1094        let guard = cx.new(|_| ());
1095        cx.observe_release(&guard, |this, _guard, cx| {
1096            this.is_loading_contents = false;
1097            cx.notify();
1098        })
1099        .detach();
1100
1101        let task = cx.spawn_in(window, async move |this, cx| {
1102            let (contents, tracked_buffers) = contents.await?;
1103
1104            if contents.is_empty() {
1105                return Ok(());
1106            }
1107
1108            this.update_in(cx, |this, window, cx| {
1109                this.set_editor_is_expanded(false, cx);
1110                this.scroll_to_bottom(cx);
1111                this.message_editor.update(cx, |message_editor, cx| {
1112                    message_editor.clear(window, cx);
1113                });
1114            })?;
1115            let send = thread.update(cx, |thread, cx| {
1116                thread.action_log().update(cx, |action_log, cx| {
1117                    for buffer in tracked_buffers {
1118                        action_log.buffer_read(buffer, cx)
1119                    }
1120                });
1121                drop(guard);
1122
1123                telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1124
1125                thread.send(contents, cx)
1126            })?;
1127            send.await
1128        });
1129
1130        cx.spawn(async move |this, cx| {
1131            if let Err(err) = task.await {
1132                this.update(cx, |this, cx| {
1133                    this.handle_thread_error(err, cx);
1134                })
1135                .ok();
1136            } else {
1137                this.update(cx, |this, cx| {
1138                    this.should_be_following = this
1139                        .workspace
1140                        .update(cx, |workspace, _| {
1141                            workspace.is_being_followed(CollaboratorId::Agent)
1142                        })
1143                        .unwrap_or_default();
1144                })
1145                .ok();
1146            }
1147        })
1148        .detach();
1149    }
1150
1151    fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1152        let Some(thread) = self.thread().cloned() else {
1153            return;
1154        };
1155
1156        if let Some(index) = self.editing_message.take()
1157            && let Some(editor) = self
1158                .entry_view_state
1159                .read(cx)
1160                .entry(index)
1161                .and_then(|e| e.message_editor())
1162                .cloned()
1163        {
1164            editor.update(cx, |editor, cx| {
1165                if let Some(user_message) = thread
1166                    .read(cx)
1167                    .entries()
1168                    .get(index)
1169                    .and_then(|e| e.user_message())
1170                {
1171                    editor.set_message(user_message.chunks.clone(), window, cx);
1172                }
1173            })
1174        };
1175        self.focus_handle(cx).focus(window);
1176        cx.notify();
1177    }
1178
1179    fn regenerate(
1180        &mut self,
1181        entry_ix: usize,
1182        message_editor: Entity<MessageEditor>,
1183        window: &mut Window,
1184        cx: &mut Context<Self>,
1185    ) {
1186        let Some(thread) = self.thread().cloned() else {
1187            return;
1188        };
1189        if self.is_loading_contents {
1190            return;
1191        }
1192
1193        let Some(user_message_id) = thread.update(cx, |thread, _| {
1194            thread.entries().get(entry_ix)?.user_message()?.id.clone()
1195        }) else {
1196            return;
1197        };
1198
1199        cx.spawn_in(window, async move |this, cx| {
1200            thread
1201                .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1202                .await?;
1203            let contents =
1204                message_editor.update(cx, |message_editor, cx| message_editor.contents(cx))?;
1205            this.update_in(cx, |this, window, cx| {
1206                this.send_impl(contents, window, cx);
1207            })?;
1208            anyhow::Ok(())
1209        })
1210        .detach();
1211    }
1212
1213    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
1214        if let Some(thread) = self.thread() {
1215            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
1216        }
1217    }
1218
1219    fn open_edited_buffer(
1220        &mut self,
1221        buffer: &Entity<Buffer>,
1222        window: &mut Window,
1223        cx: &mut Context<Self>,
1224    ) {
1225        let Some(thread) = self.thread() else {
1226            return;
1227        };
1228
1229        let Some(diff) =
1230            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1231        else {
1232            return;
1233        };
1234
1235        diff.update(cx, |diff, cx| {
1236            diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1237        })
1238    }
1239
1240    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1241        let Some(thread) = self.as_native_thread(cx) else {
1242            return;
1243        };
1244        let project_context = thread.read(cx).project_context().read(cx);
1245
1246        let project_entry_ids = project_context
1247            .worktrees
1248            .iter()
1249            .flat_map(|worktree| worktree.rules_file.as_ref())
1250            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1251            .collect::<Vec<_>>();
1252
1253        self.workspace
1254            .update(cx, move |workspace, cx| {
1255                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1256                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1257                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1258                let project = workspace.project().read(cx);
1259                let project_paths = project_entry_ids
1260                    .into_iter()
1261                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1262                    .collect::<Vec<_>>();
1263                for project_path in project_paths {
1264                    workspace
1265                        .open_path(project_path, None, true, window, cx)
1266                        .detach_and_log_err(cx);
1267                }
1268            })
1269            .ok();
1270    }
1271
1272    fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1273        self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1274        cx.notify();
1275    }
1276
1277    fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1278        self.thread_error = None;
1279        cx.notify();
1280    }
1281
1282    fn handle_thread_event(
1283        &mut self,
1284        thread: &Entity<AcpThread>,
1285        event: &AcpThreadEvent,
1286        window: &mut Window,
1287        cx: &mut Context<Self>,
1288    ) {
1289        match event {
1290            AcpThreadEvent::NewEntry => {
1291                let len = thread.read(cx).entries().len();
1292                let index = len - 1;
1293                self.entry_view_state.update(cx, |view_state, cx| {
1294                    view_state.sync_entry(index, thread, window, cx);
1295                    self.list_state.splice_focusable(
1296                        index..index,
1297                        [view_state
1298                            .entry(index)
1299                            .and_then(|entry| entry.focus_handle(cx))],
1300                    );
1301                });
1302            }
1303            AcpThreadEvent::EntryUpdated(index) => {
1304                self.entry_view_state.update(cx, |view_state, cx| {
1305                    view_state.sync_entry(*index, thread, window, cx)
1306                });
1307            }
1308            AcpThreadEvent::EntriesRemoved(range) => {
1309                self.entry_view_state
1310                    .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1311                self.list_state.splice(range.clone(), 0);
1312            }
1313            AcpThreadEvent::ToolAuthorizationRequired => {
1314                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1315            }
1316            AcpThreadEvent::Retry(retry) => {
1317                self.thread_retry_status = Some(retry.clone());
1318            }
1319            AcpThreadEvent::Stopped => {
1320                self.thread_retry_status.take();
1321                let used_tools = thread.read(cx).used_tools_since_last_user_message();
1322                self.notify_with_sound(
1323                    if used_tools {
1324                        "Finished running tools"
1325                    } else {
1326                        "New message"
1327                    },
1328                    IconName::ZedAssistant,
1329                    window,
1330                    cx,
1331                );
1332            }
1333            AcpThreadEvent::Refusal => {
1334                self.thread_retry_status.take();
1335                self.thread_error = Some(ThreadError::Refusal);
1336                let model_or_agent_name = self.get_current_model_name(cx);
1337                let notification_message =
1338                    format!("{} refused to respond to this request", model_or_agent_name);
1339                self.notify_with_sound(&notification_message, IconName::Warning, window, cx);
1340            }
1341            AcpThreadEvent::Error => {
1342                self.thread_retry_status.take();
1343                self.notify_with_sound(
1344                    "Agent stopped due to an error",
1345                    IconName::Warning,
1346                    window,
1347                    cx,
1348                );
1349            }
1350            AcpThreadEvent::LoadError(error) => {
1351                self.thread_retry_status.take();
1352                self.thread_state = ThreadState::LoadError(error.clone());
1353                if self.message_editor.focus_handle(cx).is_focused(window) {
1354                    self.focus_handle.focus(window)
1355                }
1356            }
1357            AcpThreadEvent::TitleUpdated => {
1358                let title = thread.read(cx).title();
1359                if let Some(title_editor) = self.title_editor() {
1360                    title_editor.update(cx, |editor, cx| {
1361                        if editor.text(cx) != title {
1362                            editor.set_text(title, window, cx);
1363                        }
1364                    });
1365                }
1366            }
1367            AcpThreadEvent::PromptCapabilitiesUpdated => {
1368                self.prompt_capabilities
1369                    .replace(thread.read(cx).prompt_capabilities());
1370            }
1371            AcpThreadEvent::TokenUsageUpdated => {}
1372            AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1373                let mut available_commands = available_commands.clone();
1374
1375                if thread
1376                    .read(cx)
1377                    .connection()
1378                    .auth_methods()
1379                    .iter()
1380                    .any(|method| method.id.0.as_ref() == "claude-login")
1381                {
1382                    available_commands.push(acp::AvailableCommand {
1383                        name: "login".to_owned(),
1384                        description: "Authenticate".to_owned(),
1385                        input: None,
1386                        meta: None,
1387                    });
1388                    available_commands.push(acp::AvailableCommand {
1389                        name: "logout".to_owned(),
1390                        description: "Authenticate".to_owned(),
1391                        input: None,
1392                        meta: None,
1393                    });
1394                }
1395
1396                self.available_commands.replace(available_commands);
1397            }
1398            AcpThreadEvent::ModeUpdated(_mode) => {
1399                // The connection keeps track of the mode
1400                cx.notify();
1401            }
1402        }
1403        cx.notify();
1404    }
1405
1406    fn authenticate(
1407        &mut self,
1408        method: acp::AuthMethodId,
1409        window: &mut Window,
1410        cx: &mut Context<Self>,
1411    ) {
1412        let ThreadState::Unauthenticated {
1413            connection,
1414            pending_auth_method,
1415            configuration_view,
1416            ..
1417        } = &mut self.thread_state
1418        else {
1419            return;
1420        };
1421
1422        if method.0.as_ref() == "gemini-api-key" {
1423            let registry = LanguageModelRegistry::global(cx);
1424            let provider = registry
1425                .read(cx)
1426                .provider(&language_model::GOOGLE_PROVIDER_ID)
1427                .unwrap();
1428            if !provider.is_authenticated(cx) {
1429                let this = cx.weak_entity();
1430                let agent = self.agent.clone();
1431                let connection = connection.clone();
1432                window.defer(cx, |window, cx| {
1433                    Self::handle_auth_required(
1434                        this,
1435                        AuthRequired {
1436                            description: Some("GEMINI_API_KEY must be set".to_owned()),
1437                            provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1438                        },
1439                        agent,
1440                        connection,
1441                        window,
1442                        cx,
1443                    );
1444                });
1445                return;
1446            }
1447        } else if method.0.as_ref() == "anthropic-api-key" {
1448            let registry = LanguageModelRegistry::global(cx);
1449            let provider = registry
1450                .read(cx)
1451                .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1452                .unwrap();
1453            let this = cx.weak_entity();
1454            let agent = self.agent.clone();
1455            let connection = connection.clone();
1456            window.defer(cx, move |window, cx| {
1457                if !provider.is_authenticated(cx) {
1458                    Self::handle_auth_required(
1459                        this,
1460                        AuthRequired {
1461                            description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1462                            provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1463                        },
1464                        agent,
1465                        connection,
1466                        window,
1467                        cx,
1468                    );
1469                } else {
1470                    this.update(cx, |this, cx| {
1471                        this.thread_state = Self::initial_state(
1472                            agent,
1473                            None,
1474                            this.workspace.clone(),
1475                            this.project.clone(),
1476                            window,
1477                            cx,
1478                        )
1479                    })
1480                    .ok();
1481                }
1482            });
1483            return;
1484        } else if method.0.as_ref() == "vertex-ai"
1485            && std::env::var("GOOGLE_API_KEY").is_err()
1486            && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1487                || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1488        {
1489            let this = cx.weak_entity();
1490            let agent = self.agent.clone();
1491            let connection = connection.clone();
1492
1493            window.defer(cx, |window, cx| {
1494                    Self::handle_auth_required(
1495                        this,
1496                        AuthRequired {
1497                            description: Some(
1498                                "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1499                                    .to_owned(),
1500                            ),
1501                            provider_id: None,
1502                        },
1503                        agent,
1504                        connection,
1505                        window,
1506                        cx,
1507                    )
1508                });
1509            return;
1510        }
1511
1512        self.thread_error.take();
1513        configuration_view.take();
1514        pending_auth_method.replace(method.clone());
1515        let authenticate = if (method.0.as_ref() == "claude-login"
1516            || method.0.as_ref() == "spawn-gemini-cli")
1517            && let Some(login) = self.login.clone()
1518        {
1519            if let Some(workspace) = self.workspace.upgrade() {
1520                Self::spawn_external_agent_login(login, workspace, false, window, cx)
1521            } else {
1522                Task::ready(Ok(()))
1523            }
1524        } else {
1525            connection.authenticate(method, cx)
1526        };
1527        cx.notify();
1528        self.auth_task =
1529            Some(cx.spawn_in(window, {
1530                let agent = self.agent.clone();
1531                async move |this, cx| {
1532                    let result = authenticate.await;
1533
1534                    match &result {
1535                        Ok(_) => telemetry::event!(
1536                            "Authenticate Agent Succeeded",
1537                            agent = agent.telemetry_id()
1538                        ),
1539                        Err(_) => {
1540                            telemetry::event!(
1541                                "Authenticate Agent Failed",
1542                                agent = agent.telemetry_id(),
1543                            )
1544                        }
1545                    }
1546
1547                    this.update_in(cx, |this, window, cx| {
1548                        if let Err(err) = result {
1549                            if let ThreadState::Unauthenticated {
1550                                pending_auth_method,
1551                                ..
1552                            } = &mut this.thread_state
1553                            {
1554                                pending_auth_method.take();
1555                            }
1556                            this.handle_thread_error(err, cx);
1557                        } else {
1558                            this.reset(window, cx);
1559                        }
1560                        this.auth_task.take()
1561                    })
1562                    .ok();
1563                }
1564            }));
1565    }
1566
1567    fn spawn_external_agent_login(
1568        login: task::SpawnInTerminal,
1569        workspace: Entity<Workspace>,
1570        previous_attempt: bool,
1571        window: &mut Window,
1572        cx: &mut App,
1573    ) -> Task<Result<()>> {
1574        let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1575            return Task::ready(Ok(()));
1576        };
1577        let project = workspace.read(cx).project().clone();
1578        let cwd = project.read(cx).first_project_directory(cx);
1579        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1580
1581        window.spawn(cx, async move |cx| {
1582            let mut task = login.clone();
1583            task.command = task
1584                .command
1585                .map(|command| anyhow::Ok(shlex::try_quote(&command)?.to_string()))
1586                .transpose()?;
1587            task.args = task
1588                .args
1589                .iter()
1590                .map(|arg| {
1591                    Ok(shlex::try_quote(arg)
1592                        .context("Failed to quote argument")?
1593                        .to_string())
1594                })
1595                .collect::<Result<Vec<_>>>()?;
1596            task.full_label = task.label.clone();
1597            task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1598            task.command_label = task.label.clone();
1599            task.use_new_terminal = true;
1600            task.allow_concurrent_runs = true;
1601            task.hide = task::HideStrategy::Always;
1602            task.shell = shell;
1603
1604            let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1605                terminal_panel.spawn_task(&task, window, cx)
1606            })?;
1607
1608            let terminal = terminal.await?;
1609            let mut exit_status = terminal
1610                .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1611                .fuse();
1612
1613            let logged_in = cx
1614                .spawn({
1615                    let terminal = terminal.clone();
1616                    async move |cx| {
1617                        loop {
1618                            cx.background_executor().timer(Duration::from_secs(1)).await;
1619                            let content =
1620                                terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1621                            if content.contains("Login successful")
1622                                || content.contains("Type your message")
1623                            {
1624                                return anyhow::Ok(());
1625                            }
1626                        }
1627                    }
1628                })
1629                .fuse();
1630            futures::pin_mut!(logged_in);
1631            futures::select_biased! {
1632                result = logged_in => {
1633                    if let Err(e) = result {
1634                        log::error!("{e}");
1635                        return Err(anyhow!("exited before logging in"));
1636                    }
1637                }
1638                _ = exit_status => {
1639                    if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server())? && login.label.contains("gemini") {
1640                        return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, true, window, cx))?.await
1641                    }
1642                    return Err(anyhow!("exited before logging in"));
1643                }
1644            }
1645            terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1646            Ok(())
1647        })
1648    }
1649
1650    fn authorize_tool_call(
1651        &mut self,
1652        tool_call_id: acp::ToolCallId,
1653        option_id: acp::PermissionOptionId,
1654        option_kind: acp::PermissionOptionKind,
1655        window: &mut Window,
1656        cx: &mut Context<Self>,
1657    ) {
1658        let Some(thread) = self.thread() else {
1659            return;
1660        };
1661        thread.update(cx, |thread, cx| {
1662            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1663        });
1664        if self.should_be_following {
1665            self.workspace
1666                .update(cx, |workspace, cx| {
1667                    workspace.follow(CollaboratorId::Agent, window, cx);
1668                })
1669                .ok();
1670        }
1671        cx.notify();
1672    }
1673
1674    fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1675        let Some(thread) = self.thread() else {
1676            return;
1677        };
1678
1679        thread
1680            .update(cx, |thread, cx| {
1681                thread.restore_checkpoint(message_id.clone(), cx)
1682            })
1683            .detach_and_log_err(cx);
1684    }
1685
1686    fn render_entry(
1687        &self,
1688        entry_ix: usize,
1689        total_entries: usize,
1690        entry: &AgentThreadEntry,
1691        window: &mut Window,
1692        cx: &Context<Self>,
1693    ) -> AnyElement {
1694        let primary = match &entry {
1695            AgentThreadEntry::UserMessage(message) => {
1696                let Some(editor) = self
1697                    .entry_view_state
1698                    .read(cx)
1699                    .entry(entry_ix)
1700                    .and_then(|entry| entry.message_editor())
1701                    .cloned()
1702                else {
1703                    return Empty.into_any_element();
1704                };
1705
1706                let editing = self.editing_message == Some(entry_ix);
1707                let editor_focus = editor.focus_handle(cx).is_focused(window);
1708                let focus_border = cx.theme().colors().border_focused;
1709
1710                let rules_item = if entry_ix == 0 {
1711                    self.render_rules_item(cx)
1712                } else {
1713                    None
1714                };
1715
1716                let has_checkpoint_button = message
1717                    .checkpoint
1718                    .as_ref()
1719                    .is_some_and(|checkpoint| checkpoint.show);
1720
1721                let agent_name = self.agent.name();
1722
1723                v_flex()
1724                    .id(("user_message", entry_ix))
1725                    .map(|this| {
1726                        if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none()  {
1727                            this.pt(rems_from_px(18.))
1728                        } else if rules_item.is_some() {
1729                            this.pt_3()
1730                        } else {
1731                            this.pt_2()
1732                        }
1733                    })
1734                    .pb_3()
1735                    .px_2()
1736                    .gap_1p5()
1737                    .w_full()
1738                    .children(rules_item)
1739                    .children(message.id.clone().and_then(|message_id| {
1740                        message.checkpoint.as_ref()?.show.then(|| {
1741                            h_flex()
1742                                .px_3()
1743                                .gap_2()
1744                                .child(Divider::horizontal())
1745                                .child(
1746                                    Button::new("restore-checkpoint", "Restore Checkpoint")
1747                                        .icon(IconName::Undo)
1748                                        .icon_size(IconSize::XSmall)
1749                                        .icon_position(IconPosition::Start)
1750                                        .label_size(LabelSize::XSmall)
1751                                        .icon_color(Color::Muted)
1752                                        .color(Color::Muted)
1753                                        .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
1754                                        .on_click(cx.listener(move |this, _, _window, cx| {
1755                                            this.restore_checkpoint(&message_id, cx);
1756                                        }))
1757                                )
1758                                .child(Divider::horizontal())
1759                        })
1760                    }))
1761                    .child(
1762                        div()
1763                            .relative()
1764                            .child(
1765                                div()
1766                                    .py_3()
1767                                    .px_2()
1768                                    .rounded_md()
1769                                    .shadow_md()
1770                                    .bg(cx.theme().colors().editor_background)
1771                                    .border_1()
1772                                    .when(editing && !editor_focus, |this| this.border_dashed())
1773                                    .border_color(cx.theme().colors().border)
1774                                    .map(|this|{
1775                                        if editing && editor_focus {
1776                                            this.border_color(focus_border)
1777                                        } else if message.id.is_some() {
1778                                            this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1779                                        } else {
1780                                            this
1781                                        }
1782                                    })
1783                                    .text_xs()
1784                                    .child(editor.clone().into_any_element()),
1785                            )
1786                            .when(editor_focus, |this| {
1787                                let base_container = h_flex()
1788                                    .absolute()
1789                                    .top_neg_3p5()
1790                                    .right_3()
1791                                    .gap_1()
1792                                    .rounded_sm()
1793                                    .border_1()
1794                                    .border_color(cx.theme().colors().border)
1795                                    .bg(cx.theme().colors().editor_background)
1796                                    .overflow_hidden();
1797
1798                                if message.id.is_some() {
1799                                    this.child(
1800                                        base_container
1801                                            .child(
1802                                                IconButton::new("cancel", IconName::Close)
1803                                                    .disabled(self.is_loading_contents)
1804                                                    .icon_color(Color::Error)
1805                                                    .icon_size(IconSize::XSmall)
1806                                                    .on_click(cx.listener(Self::cancel_editing))
1807                                            )
1808                                            .child(
1809                                                if self.is_loading_contents {
1810                                                    div()
1811                                                        .id("loading-edited-message-content")
1812                                                        .tooltip(Tooltip::text("Loading Added Context…"))
1813                                                        .child(loading_contents_spinner(IconSize::XSmall))
1814                                                        .into_any_element()
1815                                                } else {
1816                                                    IconButton::new("regenerate", IconName::Return)
1817                                                        .icon_color(Color::Muted)
1818                                                        .icon_size(IconSize::XSmall)
1819                                                        .tooltip(Tooltip::text(
1820                                                            "Editing will restart the thread from this point."
1821                                                        ))
1822                                                        .on_click(cx.listener({
1823                                                            let editor = editor.clone();
1824                                                            move |this, _, window, cx| {
1825                                                                this.regenerate(
1826                                                                    entry_ix, editor.clone(), window, cx,
1827                                                                );
1828                                                            }
1829                                                        })).into_any_element()
1830                                                }
1831                                            )
1832                                    )
1833                                } else {
1834                                    this.child(
1835                                        base_container
1836                                            .border_dashed()
1837                                            .child(
1838                                                IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1839                                                    .icon_size(IconSize::Small)
1840                                                    .icon_color(Color::Muted)
1841                                                    .style(ButtonStyle::Transparent)
1842                                                    .tooltip(move |_window, cx| {
1843                                                        cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1844                                                            .into()
1845                                                    })
1846                                            )
1847                                    )
1848                                }
1849                            }),
1850                    )
1851                    .into_any()
1852            }
1853            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1854                let is_last = entry_ix + 1 == total_entries;
1855
1856                let style = default_markdown_style(false, false, window, cx);
1857                let message_body = v_flex()
1858                    .w_full()
1859                    .gap_3()
1860                    .children(chunks.iter().enumerate().filter_map(
1861                        |(chunk_ix, chunk)| match chunk {
1862                            AssistantMessageChunk::Message { block } => {
1863                                block.markdown().map(|md| {
1864                                    self.render_markdown(md.clone(), style.clone())
1865                                        .into_any_element()
1866                                })
1867                            }
1868                            AssistantMessageChunk::Thought { block } => {
1869                                block.markdown().map(|md| {
1870                                    self.render_thinking_block(
1871                                        entry_ix,
1872                                        chunk_ix,
1873                                        md.clone(),
1874                                        window,
1875                                        cx,
1876                                    )
1877                                    .into_any_element()
1878                                })
1879                            }
1880                        },
1881                    ))
1882                    .into_any();
1883
1884                v_flex()
1885                    .px_5()
1886                    .py_1p5()
1887                    .when(is_last, |this| this.pb_4())
1888                    .w_full()
1889                    .text_ui(cx)
1890                    .child(message_body)
1891                    .into_any()
1892            }
1893            AgentThreadEntry::ToolCall(tool_call) => {
1894                let has_terminals = tool_call.terminals().next().is_some();
1895
1896                div().w_full().map(|this| {
1897                    if has_terminals {
1898                        this.children(tool_call.terminals().map(|terminal| {
1899                            self.render_terminal_tool_call(
1900                                entry_ix, terminal, tool_call, window, cx,
1901                            )
1902                        }))
1903                    } else {
1904                        this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1905                    }
1906                })
1907            }
1908            .into_any(),
1909        };
1910
1911        let Some(thread) = self.thread() else {
1912            return primary;
1913        };
1914
1915        let primary = if entry_ix == total_entries - 1 {
1916            v_flex()
1917                .w_full()
1918                .child(primary)
1919                .child(self.render_thread_controls(&thread, cx))
1920                .when_some(
1921                    self.thread_feedback.comments_editor.clone(),
1922                    |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
1923                )
1924                .into_any_element()
1925        } else {
1926            primary
1927        };
1928
1929        if let Some(editing_index) = self.editing_message.as_ref()
1930            && *editing_index < entry_ix
1931        {
1932            let backdrop = div()
1933                .id(("backdrop", entry_ix))
1934                .size_full()
1935                .absolute()
1936                .inset_0()
1937                .bg(cx.theme().colors().panel_background)
1938                .opacity(0.8)
1939                .block_mouse_except_scroll()
1940                .on_click(cx.listener(Self::cancel_editing));
1941
1942            div()
1943                .relative()
1944                .child(primary)
1945                .child(backdrop)
1946                .into_any_element()
1947        } else {
1948            primary
1949        }
1950    }
1951
1952    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1953        cx.theme()
1954            .colors()
1955            .element_background
1956            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1957    }
1958
1959    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1960        cx.theme().colors().border.opacity(0.8)
1961    }
1962
1963    fn tool_name_font_size(&self) -> Rems {
1964        rems_from_px(13.)
1965    }
1966
1967    fn render_thinking_block(
1968        &self,
1969        entry_ix: usize,
1970        chunk_ix: usize,
1971        chunk: Entity<Markdown>,
1972        window: &Window,
1973        cx: &Context<Self>,
1974    ) -> AnyElement {
1975        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1976        let card_header_id = SharedString::from("inner-card-header");
1977
1978        let key = (entry_ix, chunk_ix);
1979
1980        let is_open = self.expanded_thinking_blocks.contains(&key);
1981
1982        let scroll_handle = self
1983            .entry_view_state
1984            .read(cx)
1985            .entry(entry_ix)
1986            .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
1987
1988        let thinking_content = {
1989            div()
1990                .id(("thinking-content", chunk_ix))
1991                .when_some(scroll_handle, |this, scroll_handle| {
1992                    this.track_scroll(&scroll_handle)
1993                })
1994                .text_ui_sm(cx)
1995                .overflow_hidden()
1996                .child(
1997                    self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
1998                )
1999        };
2000
2001        v_flex()
2002            .gap_1()
2003            .child(
2004                h_flex()
2005                    .id(header_id)
2006                    .group(&card_header_id)
2007                    .relative()
2008                    .w_full()
2009                    .pr_1()
2010                    .justify_between()
2011                    .child(
2012                        h_flex()
2013                            .h(window.line_height() - px(2.))
2014                            .gap_1p5()
2015                            .overflow_hidden()
2016                            .child(
2017                                Icon::new(IconName::ToolThink)
2018                                    .size(IconSize::Small)
2019                                    .color(Color::Muted),
2020                            )
2021                            .child(
2022                                div()
2023                                    .text_size(self.tool_name_font_size())
2024                                    .text_color(cx.theme().colors().text_muted)
2025                                    .child("Thinking"),
2026                            ),
2027                    )
2028                    .child(
2029                        Disclosure::new(("expand", entry_ix), is_open)
2030                            .opened_icon(IconName::ChevronUp)
2031                            .closed_icon(IconName::ChevronDown)
2032                            .visible_on_hover(&card_header_id)
2033                            .on_click(cx.listener({
2034                                move |this, _event, _window, cx| {
2035                                    if is_open {
2036                                        this.expanded_thinking_blocks.remove(&key);
2037                                    } else {
2038                                        this.expanded_thinking_blocks.insert(key);
2039                                    }
2040                                    cx.notify();
2041                                }
2042                            })),
2043                    )
2044                    .on_click(cx.listener({
2045                        move |this, _event, _window, cx| {
2046                            if is_open {
2047                                this.expanded_thinking_blocks.remove(&key);
2048                            } else {
2049                                this.expanded_thinking_blocks.insert(key);
2050                            }
2051                            cx.notify();
2052                        }
2053                    })),
2054            )
2055            .when(is_open, |this| {
2056                this.child(
2057                    div()
2058                        .ml_1p5()
2059                        .pl_3p5()
2060                        .border_l_1()
2061                        .border_color(self.tool_card_border_color(cx))
2062                        .child(thinking_content),
2063                )
2064            })
2065            .into_any_element()
2066    }
2067
2068    fn render_tool_call(
2069        &self,
2070        entry_ix: usize,
2071        tool_call: &ToolCall,
2072        window: &Window,
2073        cx: &Context<Self>,
2074    ) -> Div {
2075        let has_location = tool_call.locations.len() == 1;
2076        let card_header_id = SharedString::from("inner-tool-call-header");
2077
2078        let tool_icon = if tool_call.kind == acp::ToolKind::Edit && has_location {
2079            FileIcons::get_icon(&tool_call.locations[0].path, cx)
2080                .map(Icon::from_path)
2081                .unwrap_or(Icon::new(IconName::ToolPencil))
2082        } else {
2083            Icon::new(match tool_call.kind {
2084                acp::ToolKind::Read => IconName::ToolSearch,
2085                acp::ToolKind::Edit => IconName::ToolPencil,
2086                acp::ToolKind::Delete => IconName::ToolDeleteFile,
2087                acp::ToolKind::Move => IconName::ArrowRightLeft,
2088                acp::ToolKind::Search => IconName::ToolSearch,
2089                acp::ToolKind::Execute => IconName::ToolTerminal,
2090                acp::ToolKind::Think => IconName::ToolThink,
2091                acp::ToolKind::Fetch => IconName::ToolWeb,
2092                acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
2093                acp::ToolKind::Other => IconName::ToolHammer,
2094            })
2095        }
2096        .size(IconSize::Small)
2097        .color(Color::Muted);
2098
2099        let failed_or_canceled = match &tool_call.status {
2100            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2101            _ => false,
2102        };
2103
2104        let needs_confirmation = matches!(
2105            tool_call.status,
2106            ToolCallStatus::WaitingForConfirmation { .. }
2107        );
2108        let is_edit =
2109            matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2110        let use_card_layout = needs_confirmation || is_edit;
2111
2112        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2113
2114        let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2115
2116        let gradient_overlay = {
2117            div()
2118                .absolute()
2119                .top_0()
2120                .right_0()
2121                .w_12()
2122                .h_full()
2123                .map(|this| {
2124                    if use_card_layout {
2125                        this.bg(linear_gradient(
2126                            90.,
2127                            linear_color_stop(self.tool_card_header_bg(cx), 1.),
2128                            linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2129                        ))
2130                    } else {
2131                        this.bg(linear_gradient(
2132                            90.,
2133                            linear_color_stop(cx.theme().colors().panel_background, 1.),
2134                            linear_color_stop(
2135                                cx.theme().colors().panel_background.opacity(0.2),
2136                                0.,
2137                            ),
2138                        ))
2139                    }
2140                })
2141        };
2142
2143        let tool_output_display =
2144            if is_open {
2145                match &tool_call.status {
2146                    ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2147                        .w_full()
2148                        .children(tool_call.content.iter().enumerate().map(
2149                            |(content_ix, content)| {
2150                                div()
2151                                    .child(self.render_tool_call_content(
2152                                        entry_ix,
2153                                        content,
2154                                        content_ix,
2155                                        tool_call,
2156                                        use_card_layout,
2157                                        window,
2158                                        cx,
2159                                    ))
2160                                    .into_any_element()
2161                            },
2162                        ))
2163                        .child(self.render_permission_buttons(
2164                            tool_call.kind,
2165                            options,
2166                            entry_ix,
2167                            tool_call.id.clone(),
2168                            window,
2169                            cx,
2170                        ))
2171                        .into_any(),
2172                    ToolCallStatus::Pending | ToolCallStatus::InProgress
2173                        if is_edit
2174                            && tool_call.content.is_empty()
2175                            && self.as_native_connection(cx).is_some() =>
2176                    {
2177                        self.render_diff_loading(cx).into_any()
2178                    }
2179                    ToolCallStatus::Pending
2180                    | ToolCallStatus::InProgress
2181                    | ToolCallStatus::Completed
2182                    | ToolCallStatus::Failed
2183                    | ToolCallStatus::Canceled => v_flex()
2184                        .w_full()
2185                        .children(tool_call.content.iter().enumerate().map(
2186                            |(content_ix, content)| {
2187                                div().child(self.render_tool_call_content(
2188                                    entry_ix,
2189                                    content,
2190                                    content_ix,
2191                                    tool_call,
2192                                    use_card_layout,
2193                                    window,
2194                                    cx,
2195                                ))
2196                            },
2197                        ))
2198                        .into_any(),
2199                    ToolCallStatus::Rejected => Empty.into_any(),
2200                }
2201                .into()
2202            } else {
2203                None
2204            };
2205
2206        v_flex()
2207            .map(|this| {
2208                if use_card_layout {
2209                    this.my_1p5()
2210                        .rounded_md()
2211                        .border_1()
2212                        .border_color(self.tool_card_border_color(cx))
2213                        .bg(cx.theme().colors().editor_background)
2214                        .overflow_hidden()
2215                } else {
2216                    this.my_1()
2217                }
2218            })
2219            .map(|this| {
2220                if has_location && !use_card_layout {
2221                    this.ml_4()
2222                } else {
2223                    this.ml_5()
2224                }
2225            })
2226            .mr_5()
2227            .child(
2228                h_flex()
2229                    .group(&card_header_id)
2230                    .relative()
2231                    .w_full()
2232                    .gap_1()
2233                    .justify_between()
2234                    .when(use_card_layout, |this| {
2235                        this.p_0p5()
2236                            .rounded_t(rems_from_px(5.))
2237                            .bg(self.tool_card_header_bg(cx))
2238                    })
2239                    .child(
2240                        h_flex()
2241                            .relative()
2242                            .w_full()
2243                            .h(window.line_height() - px(2.))
2244                            .text_size(self.tool_name_font_size())
2245                            .gap_1p5()
2246                            .when(has_location || use_card_layout, |this| this.px_1())
2247                            .when(has_location, |this| {
2248                                this.cursor(CursorStyle::PointingHand)
2249                                    .rounded(rems_from_px(3.)) // Concentric border radius
2250                                    .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2251                            })
2252                            .overflow_hidden()
2253                            .child(tool_icon)
2254                            .child(if has_location {
2255                                h_flex()
2256                                    .id(("open-tool-call-location", entry_ix))
2257                                    .w_full()
2258                                    .map(|this| {
2259                                        if use_card_layout {
2260                                            this.text_color(cx.theme().colors().text)
2261                                        } else {
2262                                            this.text_color(cx.theme().colors().text_muted)
2263                                        }
2264                                    })
2265                                    .child(self.render_markdown(
2266                                        tool_call.label.clone(),
2267                                        MarkdownStyle {
2268                                            prevent_mouse_interaction: true,
2269                                            ..default_markdown_style(false, true, window, cx)
2270                                        },
2271                                    ))
2272                                    .tooltip(Tooltip::text("Jump to File"))
2273                                    .on_click(cx.listener(move |this, _, window, cx| {
2274                                        this.open_tool_call_location(entry_ix, 0, window, cx);
2275                                    }))
2276                                    .into_any_element()
2277                            } else {
2278                                h_flex()
2279                                    .w_full()
2280                                    .child(self.render_markdown(
2281                                        tool_call.label.clone(),
2282                                        default_markdown_style(false, true, window, cx),
2283                                    ))
2284                                    .into_any()
2285                            })
2286                            .when(!has_location, |this| this.child(gradient_overlay)),
2287                    )
2288                    .when(is_collapsible || failed_or_canceled, |this| {
2289                        this.child(
2290                            h_flex()
2291                                .px_1()
2292                                .gap_px()
2293                                .when(is_collapsible, |this| {
2294                                    this.child(
2295                                    Disclosure::new(("expand", entry_ix), is_open)
2296                                        .opened_icon(IconName::ChevronUp)
2297                                        .closed_icon(IconName::ChevronDown)
2298                                        .visible_on_hover(&card_header_id)
2299                                        .on_click(cx.listener({
2300                                            let id = tool_call.id.clone();
2301                                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2302                                                if is_open {
2303                                                    this.expanded_tool_calls.remove(&id);
2304                                                } else {
2305                                                    this.expanded_tool_calls.insert(id.clone());
2306                                                }
2307                                                cx.notify();
2308                                            }
2309                                        })),
2310                                )
2311                                })
2312                                .when(failed_or_canceled, |this| {
2313                                    this.child(
2314                                        Icon::new(IconName::Close)
2315                                            .color(Color::Error)
2316                                            .size(IconSize::Small),
2317                                    )
2318                                }),
2319                        )
2320                    }),
2321            )
2322            .children(tool_output_display)
2323    }
2324
2325    fn render_tool_call_content(
2326        &self,
2327        entry_ix: usize,
2328        content: &ToolCallContent,
2329        context_ix: usize,
2330        tool_call: &ToolCall,
2331        card_layout: bool,
2332        window: &Window,
2333        cx: &Context<Self>,
2334    ) -> AnyElement {
2335        match content {
2336            ToolCallContent::ContentBlock(content) => {
2337                if let Some(resource_link) = content.resource_link() {
2338                    self.render_resource_link(resource_link, cx)
2339                } else if let Some(markdown) = content.markdown() {
2340                    self.render_markdown_output(
2341                        markdown.clone(),
2342                        tool_call.id.clone(),
2343                        context_ix,
2344                        card_layout,
2345                        window,
2346                        cx,
2347                    )
2348                } else {
2349                    Empty.into_any_element()
2350                }
2351            }
2352            ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2353            ToolCallContent::Terminal(terminal) => {
2354                self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2355            }
2356        }
2357    }
2358
2359    fn render_markdown_output(
2360        &self,
2361        markdown: Entity<Markdown>,
2362        tool_call_id: acp::ToolCallId,
2363        context_ix: usize,
2364        card_layout: bool,
2365        window: &Window,
2366        cx: &Context<Self>,
2367    ) -> AnyElement {
2368        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2369
2370        v_flex()
2371            .mt_1p5()
2372            .gap_2()
2373            .when(!card_layout, |this| {
2374                this.ml(rems(0.4))
2375                    .px_3p5()
2376                    .border_l_1()
2377                    .border_color(self.tool_card_border_color(cx))
2378            })
2379            .when(card_layout, |this| {
2380                this.px_2().pb_2().when(context_ix > 0, |this| {
2381                    this.border_t_1()
2382                        .pt_2()
2383                        .border_color(self.tool_card_border_color(cx))
2384                })
2385            })
2386            .text_xs()
2387            .text_color(cx.theme().colors().text_muted)
2388            .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2389            .when(!card_layout, |this| {
2390                this.child(
2391                    IconButton::new(button_id, IconName::ChevronUp)
2392                        .full_width()
2393                        .style(ButtonStyle::Outlined)
2394                        .icon_color(Color::Muted)
2395                        .on_click(cx.listener({
2396                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2397                                this.expanded_tool_calls.remove(&tool_call_id);
2398                                cx.notify();
2399                            }
2400                        })),
2401                )
2402            })
2403            .into_any_element()
2404    }
2405
2406    fn render_resource_link(
2407        &self,
2408        resource_link: &acp::ResourceLink,
2409        cx: &Context<Self>,
2410    ) -> AnyElement {
2411        let uri: SharedString = resource_link.uri.clone().into();
2412        let is_file = resource_link.uri.strip_prefix("file://");
2413
2414        let label: SharedString = if let Some(abs_path) = is_file {
2415            if let Some(project_path) = self
2416                .project
2417                .read(cx)
2418                .project_path_for_absolute_path(&Path::new(abs_path), cx)
2419                && let Some(worktree) = self
2420                    .project
2421                    .read(cx)
2422                    .worktree_for_id(project_path.worktree_id, cx)
2423            {
2424                worktree
2425                    .read(cx)
2426                    .full_path(&project_path.path)
2427                    .to_string_lossy()
2428                    .to_string()
2429                    .into()
2430            } else {
2431                abs_path.to_string().into()
2432            }
2433        } else {
2434            uri.clone()
2435        };
2436
2437        let button_id = SharedString::from(format!("item-{}", uri));
2438
2439        div()
2440            .ml(rems(0.4))
2441            .pl_2p5()
2442            .border_l_1()
2443            .border_color(self.tool_card_border_color(cx))
2444            .overflow_hidden()
2445            .child(
2446                Button::new(button_id, label)
2447                    .label_size(LabelSize::Small)
2448                    .color(Color::Muted)
2449                    .truncate(true)
2450                    .when(is_file.is_none(), |this| {
2451                        this.icon(IconName::ArrowUpRight)
2452                            .icon_size(IconSize::XSmall)
2453                            .icon_color(Color::Muted)
2454                    })
2455                    .on_click(cx.listener({
2456                        let workspace = self.workspace.clone();
2457                        move |_, _, window, cx: &mut Context<Self>| {
2458                            Self::open_link(uri.clone(), &workspace, window, cx);
2459                        }
2460                    })),
2461            )
2462            .into_any_element()
2463    }
2464
2465    fn render_permission_buttons(
2466        &self,
2467        kind: acp::ToolKind,
2468        options: &[acp::PermissionOption],
2469        entry_ix: usize,
2470        tool_call_id: acp::ToolCallId,
2471        window: &Window,
2472        cx: &Context<Self>,
2473    ) -> Div {
2474        let is_first = self.thread().is_some_and(|thread| {
2475            thread
2476                .read(cx)
2477                .first_tool_awaiting_confirmation()
2478                .is_some_and(|call| call.id == tool_call_id)
2479        });
2480        let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
2481
2482        div()
2483            .p_1()
2484            .border_t_1()
2485            .border_color(self.tool_card_border_color(cx))
2486            .w_full()
2487            .map(|this| {
2488                if kind == acp::ToolKind::SwitchMode {
2489                    this.v_flex()
2490                } else {
2491                    this.h_flex().justify_end().flex_wrap()
2492                }
2493            })
2494            .gap_0p5()
2495            .children(options.iter().map(move |option| {
2496                let option_id = SharedString::from(option.id.0.clone());
2497                Button::new((option_id, entry_ix), option.name.clone())
2498                    .map(|this| {
2499                        let (this, action) = match option.kind {
2500                            acp::PermissionOptionKind::AllowOnce => (
2501                                this.icon(IconName::Check).icon_color(Color::Success),
2502                                Some(&AllowOnce as &dyn Action),
2503                            ),
2504                            acp::PermissionOptionKind::AllowAlways => (
2505                                this.icon(IconName::CheckDouble).icon_color(Color::Success),
2506                                Some(&AllowAlways as &dyn Action),
2507                            ),
2508                            acp::PermissionOptionKind::RejectOnce => (
2509                                this.icon(IconName::Close).icon_color(Color::Error),
2510                                Some(&RejectOnce as &dyn Action),
2511                            ),
2512                            acp::PermissionOptionKind::RejectAlways => {
2513                                (this.icon(IconName::Close).icon_color(Color::Error), None)
2514                            }
2515                        };
2516
2517                        let Some(action) = action else {
2518                            return this;
2519                        };
2520
2521                        if !is_first || seen_kinds.contains(&option.kind) {
2522                            return this;
2523                        }
2524
2525                        seen_kinds.push(option.kind);
2526
2527                        this.key_binding(
2528                            KeyBinding::for_action_in(action, &self.focus_handle, window, cx)
2529                                .map(|kb| kb.size(rems_from_px(10.))),
2530                        )
2531                    })
2532                    .icon_position(IconPosition::Start)
2533                    .icon_size(IconSize::XSmall)
2534                    .label_size(LabelSize::Small)
2535                    .on_click(cx.listener({
2536                        let tool_call_id = tool_call_id.clone();
2537                        let option_id = option.id.clone();
2538                        let option_kind = option.kind;
2539                        move |this, _, window, cx| {
2540                            this.authorize_tool_call(
2541                                tool_call_id.clone(),
2542                                option_id.clone(),
2543                                option_kind,
2544                                window,
2545                                cx,
2546                            );
2547                        }
2548                    }))
2549            }))
2550    }
2551
2552    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2553        let bar = |n: u64, width_class: &str| {
2554            let bg_color = cx.theme().colors().element_active;
2555            let base = h_flex().h_1().rounded_full();
2556
2557            let modified = match width_class {
2558                "w_4_5" => base.w_3_4(),
2559                "w_1_4" => base.w_1_4(),
2560                "w_2_4" => base.w_2_4(),
2561                "w_3_5" => base.w_3_5(),
2562                "w_2_5" => base.w_2_5(),
2563                _ => base.w_1_2(),
2564            };
2565
2566            modified.with_animation(
2567                ElementId::Integer(n),
2568                Animation::new(Duration::from_secs(2)).repeat(),
2569                move |tab, delta| {
2570                    let delta = (delta - 0.15 * n as f32) / 0.7;
2571                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
2572                    let delta = ease_in_out(delta.clamp(0., 1.));
2573                    let delta = 0.1 + 0.9 * delta;
2574
2575                    tab.bg(bg_color.opacity(delta))
2576                },
2577            )
2578        };
2579
2580        v_flex()
2581            .p_3()
2582            .gap_1()
2583            .rounded_b_md()
2584            .bg(cx.theme().colors().editor_background)
2585            .child(bar(0, "w_4_5"))
2586            .child(bar(1, "w_1_4"))
2587            .child(bar(2, "w_2_4"))
2588            .child(bar(3, "w_3_5"))
2589            .child(bar(4, "w_2_5"))
2590            .into_any_element()
2591    }
2592
2593    fn render_diff_editor(
2594        &self,
2595        entry_ix: usize,
2596        diff: &Entity<acp_thread::Diff>,
2597        tool_call: &ToolCall,
2598        cx: &Context<Self>,
2599    ) -> AnyElement {
2600        let tool_progress = matches!(
2601            &tool_call.status,
2602            ToolCallStatus::InProgress | ToolCallStatus::Pending
2603        );
2604
2605        v_flex()
2606            .h_full()
2607            .border_t_1()
2608            .border_color(self.tool_card_border_color(cx))
2609            .child(
2610                if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2611                    && let Some(editor) = entry.editor_for_diff(diff)
2612                    && diff.read(cx).has_revealed_range(cx)
2613                {
2614                    editor.into_any_element()
2615                } else if tool_progress && self.as_native_connection(cx).is_some() {
2616                    self.render_diff_loading(cx)
2617                } else {
2618                    Empty.into_any()
2619                },
2620            )
2621            .into_any()
2622    }
2623
2624    fn render_terminal_tool_call(
2625        &self,
2626        entry_ix: usize,
2627        terminal: &Entity<acp_thread::Terminal>,
2628        tool_call: &ToolCall,
2629        window: &Window,
2630        cx: &Context<Self>,
2631    ) -> AnyElement {
2632        let terminal_data = terminal.read(cx);
2633        let working_dir = terminal_data.working_dir();
2634        let command = terminal_data.command();
2635        let started_at = terminal_data.started_at();
2636
2637        let tool_failed = matches!(
2638            &tool_call.status,
2639            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2640        );
2641
2642        let output = terminal_data.output();
2643        let command_finished = output.is_some();
2644        let truncated_output =
2645            output.is_some_and(|output| output.original_content_len > output.content.len());
2646        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2647
2648        let command_failed = command_finished
2649            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2650
2651        let time_elapsed = if let Some(output) = output {
2652            output.ended_at.duration_since(started_at)
2653        } else {
2654            started_at.elapsed()
2655        };
2656
2657        let header_id =
2658            SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2659        let header_group = SharedString::from(format!(
2660            "terminal-tool-header-group-{}",
2661            terminal.entity_id()
2662        ));
2663        let header_bg = cx
2664            .theme()
2665            .colors()
2666            .element_background
2667            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2668        let border_color = cx.theme().colors().border.opacity(0.6);
2669
2670        let working_dir = working_dir
2671            .as_ref()
2672            .map(|path| format!("{}", path.display()))
2673            .unwrap_or_else(|| "current directory".to_string());
2674
2675        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2676
2677        let header = h_flex()
2678            .id(header_id)
2679            .flex_none()
2680            .gap_1()
2681            .justify_between()
2682            .rounded_t_md()
2683            .child(
2684                div()
2685                    .id(("command-target-path", terminal.entity_id()))
2686                    .w_full()
2687                    .max_w_full()
2688                    .overflow_x_scroll()
2689                    .child(
2690                        Label::new(working_dir)
2691                            .buffer_font(cx)
2692                            .size(LabelSize::XSmall)
2693                            .color(Color::Muted),
2694                    ),
2695            )
2696            .when(!command_finished, |header| {
2697                header
2698                    .gap_1p5()
2699                    .child(
2700                        Button::new(
2701                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2702                            "Stop",
2703                        )
2704                        .icon(IconName::Stop)
2705                        .icon_position(IconPosition::Start)
2706                        .icon_size(IconSize::Small)
2707                        .icon_color(Color::Error)
2708                        .label_size(LabelSize::Small)
2709                        .tooltip(move |window, cx| {
2710                            Tooltip::with_meta(
2711                                "Stop This Command",
2712                                None,
2713                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2714                                window,
2715                                cx,
2716                            )
2717                        })
2718                        .on_click({
2719                            let terminal = terminal.clone();
2720                            cx.listener(move |_this, _event, _window, cx| {
2721                                let inner_terminal = terminal.read(cx).inner().clone();
2722                                inner_terminal.update(cx, |inner_terminal, _cx| {
2723                                    inner_terminal.kill_active_task();
2724                                });
2725                            })
2726                        }),
2727                    )
2728                    .child(Divider::vertical())
2729                    .child(
2730                        Icon::new(IconName::ArrowCircle)
2731                            .size(IconSize::XSmall)
2732                            .color(Color::Info)
2733                            .with_rotate_animation(2)
2734                    )
2735            })
2736            .when(truncated_output, |header| {
2737                let tooltip = if let Some(output) = output {
2738                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2739                       format!("Output exceeded terminal max lines and was \
2740                            truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
2741                    } else {
2742                        format!(
2743                            "Output is {} long, and to avoid unexpected token usage, \
2744                                only {} was sent back to the agent.",
2745                            format_file_size(output.original_content_len as u64, true),
2746                             format_file_size(output.content.len() as u64, true)
2747                        )
2748                    }
2749                } else {
2750                    "Output was truncated".to_string()
2751                };
2752
2753                header.child(
2754                    h_flex()
2755                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
2756                        .gap_1()
2757                        .child(
2758                            Icon::new(IconName::Info)
2759                                .size(IconSize::XSmall)
2760                                .color(Color::Ignored),
2761                        )
2762                        .child(
2763                            Label::new("Truncated")
2764                                .color(Color::Muted)
2765                                .size(LabelSize::XSmall),
2766                        )
2767                        .tooltip(Tooltip::text(tooltip)),
2768                )
2769            })
2770            .when(time_elapsed > Duration::from_secs(10), |header| {
2771                header.child(
2772                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
2773                        .buffer_font(cx)
2774                        .color(Color::Muted)
2775                        .size(LabelSize::XSmall),
2776                )
2777            })
2778            .when(tool_failed || command_failed, |header| {
2779                header.child(
2780                    div()
2781                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2782                        .child(
2783                            Icon::new(IconName::Close)
2784                                .size(IconSize::Small)
2785                                .color(Color::Error),
2786                        )
2787                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
2788                            this.tooltip(Tooltip::text(format!(
2789                                "Exited with code {}",
2790                                status.code().unwrap_or(-1),
2791                            )))
2792                        }),
2793                )
2794            })
2795            .child(
2796                Disclosure::new(
2797                    SharedString::from(format!(
2798                        "terminal-tool-disclosure-{}",
2799                        terminal.entity_id()
2800                    )),
2801                    is_expanded,
2802                )
2803                .opened_icon(IconName::ChevronUp)
2804                .closed_icon(IconName::ChevronDown)
2805                .visible_on_hover(&header_group)
2806                .on_click(cx.listener({
2807                    let id = tool_call.id.clone();
2808                    move |this, _event, _window, _cx| {
2809                        if is_expanded {
2810                            this.expanded_tool_calls.remove(&id);
2811                        } else {
2812                            this.expanded_tool_calls.insert(id.clone());
2813                        }
2814                    }
2815                })),
2816            );
2817
2818        let terminal_view = self
2819            .entry_view_state
2820            .read(cx)
2821            .entry(entry_ix)
2822            .and_then(|entry| entry.terminal(terminal));
2823        let show_output = is_expanded && terminal_view.is_some();
2824
2825        v_flex()
2826            .my_1p5()
2827            .mx_5()
2828            .border_1()
2829            .when(tool_failed || command_failed, |card| card.border_dashed())
2830            .border_color(border_color)
2831            .rounded_md()
2832            .overflow_hidden()
2833            .child(
2834                v_flex()
2835                    .group(&header_group)
2836                    .py_1p5()
2837                    .pr_1p5()
2838                    .pl_2()
2839                    .gap_0p5()
2840                    .bg(header_bg)
2841                    .text_xs()
2842                    .child(header)
2843                    .child(
2844                        MarkdownElement::new(
2845                            command.clone(),
2846                            terminal_command_markdown_style(window, cx),
2847                        )
2848                        .code_block_renderer(
2849                            markdown::CodeBlockRenderer::Default {
2850                                copy_button: false,
2851                                copy_button_on_hover: true,
2852                                border: false,
2853                            },
2854                        ),
2855                    ),
2856            )
2857            .when(show_output, |this| {
2858                this.child(
2859                    div()
2860                        .pt_2()
2861                        .border_t_1()
2862                        .when(tool_failed || command_failed, |card| card.border_dashed())
2863                        .border_color(border_color)
2864                        .bg(cx.theme().colors().editor_background)
2865                        .rounded_b_md()
2866                        .text_ui_sm(cx)
2867                        .h_full()
2868                        .children(terminal_view.map(|terminal_view| {
2869                            if terminal_view
2870                                .read(cx)
2871                                .content_mode(window, cx)
2872                                .is_scrollable()
2873                            {
2874                                div().h_72().child(terminal_view).into_any_element()
2875                            } else {
2876                                terminal_view.into_any_element()
2877                            }
2878                        })),
2879                )
2880            })
2881            .into_any()
2882    }
2883
2884    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2885        let project_context = self
2886            .as_native_thread(cx)?
2887            .read(cx)
2888            .project_context()
2889            .read(cx);
2890
2891        let user_rules_text = if project_context.user_rules.is_empty() {
2892            None
2893        } else if project_context.user_rules.len() == 1 {
2894            let user_rules = &project_context.user_rules[0];
2895
2896            match user_rules.title.as_ref() {
2897                Some(title) => Some(format!("Using \"{title}\" user rule")),
2898                None => Some("Using user rule".into()),
2899            }
2900        } else {
2901            Some(format!(
2902                "Using {} user rules",
2903                project_context.user_rules.len()
2904            ))
2905        };
2906
2907        let first_user_rules_id = project_context
2908            .user_rules
2909            .first()
2910            .map(|user_rules| user_rules.uuid.0);
2911
2912        let rules_files = project_context
2913            .worktrees
2914            .iter()
2915            .filter_map(|worktree| worktree.rules_file.as_ref())
2916            .collect::<Vec<_>>();
2917
2918        let rules_file_text = match rules_files.as_slice() {
2919            &[] => None,
2920            &[rules_file] => Some(format!(
2921                "Using project {:?} file",
2922                rules_file.path_in_worktree
2923            )),
2924            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2925        };
2926
2927        if user_rules_text.is_none() && rules_file_text.is_none() {
2928            return None;
2929        }
2930
2931        let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2932
2933        Some(
2934            h_flex()
2935                .px_2p5()
2936                .child(
2937                    Icon::new(IconName::Attach)
2938                        .size(IconSize::XSmall)
2939                        .color(Color::Disabled),
2940                )
2941                .when_some(user_rules_text, |parent, user_rules_text| {
2942                    parent.child(
2943                        h_flex()
2944                            .id("user-rules")
2945                            .ml_1()
2946                            .mr_1p5()
2947                            .child(
2948                                Label::new(user_rules_text)
2949                                    .size(LabelSize::XSmall)
2950                                    .color(Color::Muted)
2951                                    .truncate(),
2952                            )
2953                            .hover(|s| s.bg(cx.theme().colors().element_hover))
2954                            .tooltip(Tooltip::text("View User Rules"))
2955                            .on_click(move |_event, window, cx| {
2956                                window.dispatch_action(
2957                                    Box::new(OpenRulesLibrary {
2958                                        prompt_to_select: first_user_rules_id,
2959                                    }),
2960                                    cx,
2961                                )
2962                            }),
2963                    )
2964                })
2965                .when(has_both, |this| {
2966                    this.child(
2967                        Label::new("")
2968                            .size(LabelSize::XSmall)
2969                            .color(Color::Disabled),
2970                    )
2971                })
2972                .when_some(rules_file_text, |parent, rules_file_text| {
2973                    parent.child(
2974                        h_flex()
2975                            .id("project-rules")
2976                            .ml_1p5()
2977                            .child(
2978                                Label::new(rules_file_text)
2979                                    .size(LabelSize::XSmall)
2980                                    .color(Color::Muted),
2981                            )
2982                            .hover(|s| s.bg(cx.theme().colors().element_hover))
2983                            .tooltip(Tooltip::text("View Project Rules"))
2984                            .on_click(cx.listener(Self::handle_open_rules)),
2985                    )
2986                })
2987                .into_any(),
2988        )
2989    }
2990
2991    fn render_empty_state_section_header(
2992        &self,
2993        label: impl Into<SharedString>,
2994        action_slot: Option<AnyElement>,
2995        cx: &mut Context<Self>,
2996    ) -> impl IntoElement {
2997        div().pl_1().pr_1p5().child(
2998            h_flex()
2999                .mt_2()
3000                .pl_1p5()
3001                .pb_1()
3002                .w_full()
3003                .justify_between()
3004                .border_b_1()
3005                .border_color(cx.theme().colors().border_variant)
3006                .child(
3007                    Label::new(label.into())
3008                        .size(LabelSize::Small)
3009                        .color(Color::Muted),
3010                )
3011                .children(action_slot),
3012        )
3013    }
3014
3015    fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3016        let render_history = self
3017            .agent
3018            .clone()
3019            .downcast::<agent2::NativeAgentServer>()
3020            .is_some()
3021            && self
3022                .history_store
3023                .update(cx, |history_store, cx| !history_store.is_empty(cx));
3024
3025        v_flex()
3026            .size_full()
3027            .when(render_history, |this| {
3028                let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
3029                    history_store.entries().take(3).collect()
3030                });
3031                this.justify_end().child(
3032                    v_flex()
3033                        .child(
3034                            self.render_empty_state_section_header(
3035                                "Recent",
3036                                Some(
3037                                    Button::new("view-history", "View All")
3038                                        .style(ButtonStyle::Subtle)
3039                                        .label_size(LabelSize::Small)
3040                                        .key_binding(
3041                                            KeyBinding::for_action_in(
3042                                                &OpenHistory,
3043                                                &self.focus_handle(cx),
3044                                                window,
3045                                                cx,
3046                                            )
3047                                            .map(|kb| kb.size(rems_from_px(12.))),
3048                                        )
3049                                        .on_click(move |_event, window, cx| {
3050                                            window.dispatch_action(OpenHistory.boxed_clone(), cx);
3051                                        })
3052                                        .into_any_element(),
3053                                ),
3054                                cx,
3055                            ),
3056                        )
3057                        .child(
3058                            v_flex().p_1().pr_1p5().gap_1().children(
3059                                recent_history
3060                                    .into_iter()
3061                                    .enumerate()
3062                                    .map(|(index, entry)| {
3063                                        // TODO: Add keyboard navigation.
3064                                        let is_hovered =
3065                                            self.hovered_recent_history_item == Some(index);
3066                                        crate::acp::thread_history::AcpHistoryEntryElement::new(
3067                                            entry,
3068                                            cx.entity().downgrade(),
3069                                        )
3070                                        .hovered(is_hovered)
3071                                        .on_hover(cx.listener(
3072                                            move |this, is_hovered, _window, cx| {
3073                                                if *is_hovered {
3074                                                    this.hovered_recent_history_item = Some(index);
3075                                                } else if this.hovered_recent_history_item
3076                                                    == Some(index)
3077                                                {
3078                                                    this.hovered_recent_history_item = None;
3079                                                }
3080                                                cx.notify();
3081                                            },
3082                                        ))
3083                                        .into_any_element()
3084                                    }),
3085                            ),
3086                        ),
3087                )
3088            })
3089            .into_any()
3090    }
3091
3092    fn render_auth_required_state(
3093        &self,
3094        connection: &Rc<dyn AgentConnection>,
3095        description: Option<&Entity<Markdown>>,
3096        configuration_view: Option<&AnyView>,
3097        pending_auth_method: Option<&acp::AuthMethodId>,
3098        window: &mut Window,
3099        cx: &Context<Self>,
3100    ) -> Div {
3101        let show_description =
3102            configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3103
3104        let auth_methods = connection.auth_methods();
3105
3106        v_flex().flex_1().size_full().justify_end().child(
3107            v_flex()
3108                .p_2()
3109                .pr_3()
3110                .w_full()
3111                .gap_1()
3112                .border_t_1()
3113                .border_color(cx.theme().colors().border)
3114                .bg(cx.theme().status().warning.opacity(0.04))
3115                .child(
3116                    h_flex()
3117                        .gap_1p5()
3118                        .child(
3119                            Icon::new(IconName::Warning)
3120                                .color(Color::Warning)
3121                                .size(IconSize::Small),
3122                        )
3123                        .child(Label::new("Authentication Required").size(LabelSize::Small)),
3124                )
3125                .children(description.map(|desc| {
3126                    div().text_ui(cx).child(self.render_markdown(
3127                        desc.clone(),
3128                        default_markdown_style(false, false, window, cx),
3129                    ))
3130                }))
3131                .children(
3132                    configuration_view
3133                        .cloned()
3134                        .map(|view| div().w_full().child(view)),
3135                )
3136                .when(show_description, |el| {
3137                    el.child(
3138                        Label::new(format!(
3139                            "You are not currently authenticated with {}.{}",
3140                            self.agent.name(),
3141                            if auth_methods.len() > 1 {
3142                                " Please choose one of the following options:"
3143                            } else {
3144                                ""
3145                            }
3146                        ))
3147                        .size(LabelSize::Small)
3148                        .color(Color::Muted)
3149                        .mb_1()
3150                        .ml_5(),
3151                    )
3152                })
3153                .when_some(pending_auth_method, |el, _| {
3154                    el.child(
3155                        h_flex()
3156                            .py_4()
3157                            .w_full()
3158                            .justify_center()
3159                            .gap_1()
3160                            .child(
3161                                Icon::new(IconName::ArrowCircle)
3162                                    .size(IconSize::Small)
3163                                    .color(Color::Muted)
3164                                    .with_rotate_animation(2),
3165                            )
3166                            .child(Label::new("Authenticating…").size(LabelSize::Small)),
3167                    )
3168                })
3169                .when(!auth_methods.is_empty(), |this| {
3170                    this.child(
3171                        h_flex()
3172                            .justify_end()
3173                            .flex_wrap()
3174                            .gap_1()
3175                            .when(!show_description, |this| {
3176                                this.border_t_1()
3177                                    .mt_1()
3178                                    .pt_2()
3179                                    .border_color(cx.theme().colors().border.opacity(0.8))
3180                            })
3181                            .children(connection.auth_methods().iter().enumerate().rev().map(
3182                                |(ix, method)| {
3183                                    let (method_id, name) = if self
3184                                        .project
3185                                        .read(cx)
3186                                        .is_via_remote_server()
3187                                        && method.id.0.as_ref() == "oauth-personal"
3188                                        && method.name == "Log in with Google"
3189                                    {
3190                                        ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
3191                                    } else {
3192                                        (method.id.0.clone(), method.name.clone())
3193                                    };
3194
3195                                    Button::new(SharedString::from(method_id.clone()), name)
3196                                        .label_size(LabelSize::Small)
3197                                        .map(|this| {
3198                                            if ix == 0 {
3199                                                this.style(ButtonStyle::Tinted(TintColor::Warning))
3200                                            } else {
3201                                                this.style(ButtonStyle::Outlined)
3202                                            }
3203                                        })
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}