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