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