thread_view.rs

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