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::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; 3],
 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::settings_changed),
 384            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 385            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 386        ];
 387
 388        Self {
 389            agent: agent.clone(),
 390            workspace: workspace.clone(),
 391            project: project.clone(),
 392            entry_view_state,
 393            thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
 394            message_editor,
 395            model_selector: None,
 396            profile_selector: None,
 397            notifications: Vec::new(),
 398            notification_subscriptions: HashMap::default(),
 399            list_state: list_state.clone(),
 400            scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
 401            thread_retry_status: None,
 402            thread_error: None,
 403            thread_feedback: Default::default(),
 404            auth_task: None,
 405            expanded_tool_calls: HashSet::default(),
 406            expanded_thinking_blocks: HashSet::default(),
 407            editing_message: None,
 408            edits_expanded: false,
 409            plan_expanded: false,
 410            prompt_capabilities,
 411            available_commands,
 412            editor_expanded: false,
 413            should_be_following: false,
 414            history_store,
 415            hovered_recent_history_item: None,
 416            is_loading_contents: false,
 417            _subscriptions: subscriptions,
 418            _cancel_task: None,
 419            focus_handle: cx.focus_handle(),
 420            new_server_version_available: None,
 421        }
 422    }
 423
 424    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 425        self.thread_state = Self::initial_state(
 426            self.agent.clone(),
 427            None,
 428            self.workspace.clone(),
 429            self.project.clone(),
 430            window,
 431            cx,
 432        );
 433        self.new_server_version_available.take();
 434        cx.notify();
 435    }
 436
 437    fn initial_state(
 438        agent: Rc<dyn AgentServer>,
 439        resume_thread: Option<DbThreadMetadata>,
 440        workspace: WeakEntity<Workspace>,
 441        project: Entity<Project>,
 442        window: &mut Window,
 443        cx: &mut Context<Self>,
 444    ) -> ThreadState {
 445        if !project.read(cx).is_local() && agent.clone().downcast::<NativeAgentServer>().is_none() {
 446            return ThreadState::LoadError(LoadError::Other(
 447                "External agents are not yet supported for remote projects.".into(),
 448            ));
 449        }
 450        let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 451        // Pick the first non-single-file worktree for the root directory if there are any,
 452        // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
 453        worktrees.sort_by(|l, r| {
 454            l.read(cx)
 455                .is_single_file()
 456                .cmp(&r.read(cx).is_single_file())
 457        });
 458        let root_dir = worktrees
 459            .into_iter()
 460            .filter_map(|worktree| {
 461                if worktree.read(cx).is_single_file() {
 462                    Some(worktree.read(cx).abs_path().parent()?.into())
 463                } else {
 464                    Some(worktree.read(cx).abs_path())
 465                }
 466            })
 467            .next()
 468            .unwrap_or_else(|| paths::home_dir().as_path().into());
 469        let (status_tx, mut status_rx) = watch::channel("Loading…".into());
 470        let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
 471        let delegate = AgentServerDelegate::new(
 472            project.clone(),
 473            Some(status_tx),
 474            Some(new_version_available_tx),
 475        );
 476
 477        let connect_task = agent.connect(&root_dir, delegate, cx);
 478        let load_task = cx.spawn_in(window, async move |this, cx| {
 479            let connection = match connect_task.await {
 480                Ok(connection) => connection,
 481                Err(err) => {
 482                    this.update_in(cx, |this, window, cx| {
 483                        if err.downcast_ref::<LoadError>().is_some() {
 484                            this.handle_load_error(err, window, cx);
 485                        } else {
 486                            this.handle_thread_error(err, cx);
 487                        }
 488                        cx.notify();
 489                    })
 490                    .log_err();
 491                    return;
 492                }
 493            };
 494
 495            let result = if let Some(native_agent) = connection
 496                .clone()
 497                .downcast::<agent2::NativeAgentConnection>()
 498                && let Some(resume) = resume_thread.clone()
 499            {
 500                cx.update(|_, cx| {
 501                    native_agent
 502                        .0
 503                        .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
 504                })
 505                .log_err()
 506            } else {
 507                cx.update(|_, cx| {
 508                    connection
 509                        .clone()
 510                        .new_thread(project.clone(), &root_dir, cx)
 511                })
 512                .log_err()
 513            };
 514
 515            let Some(result) = result else {
 516                return;
 517            };
 518
 519            let result = match result.await {
 520                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 521                    Ok(err) => {
 522                        cx.update(|window, cx| {
 523                            Self::handle_auth_required(this, err, agent, connection, window, cx)
 524                        })
 525                        .log_err();
 526                        return;
 527                    }
 528                    Err(err) => Err(err),
 529                },
 530                Ok(thread) => Ok(thread),
 531            };
 532
 533            this.update_in(cx, |this, window, cx| {
 534                match result {
 535                    Ok(thread) => {
 536                        let action_log = thread.read(cx).action_log().clone();
 537
 538                        let mut available_commands = thread.read(cx).available_commands();
 539
 540                        if connection
 541                            .auth_methods()
 542                            .iter()
 543                            .any(|method| method.id.0.as_ref() == "claude-login")
 544                        {
 545                            available_commands.push(acp::AvailableCommand {
 546                                name: "login".to_owned(),
 547                                description: "Authenticate".to_owned(),
 548                                input: None,
 549                            });
 550                            available_commands.push(acp::AvailableCommand {
 551                                name: "logout".to_owned(),
 552                                description: "Authenticate".to_owned(),
 553                                input: None,
 554                            });
 555                        }
 556                        this.available_commands.replace(available_commands);
 557
 558                        this.prompt_capabilities
 559                            .set(thread.read(cx).prompt_capabilities());
 560
 561                        let count = thread.read(cx).entries().len();
 562                        this.entry_view_state.update(cx, |view_state, cx| {
 563                            for ix in 0..count {
 564                                view_state.sync_entry(ix, &thread, window, cx);
 565                            }
 566                            this.list_state.splice_focusable(
 567                                0..0,
 568                                (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
 569                            );
 570                        });
 571
 572                        if let Some(resume) = resume_thread {
 573                            this.history_store.update(cx, |history, cx| {
 574                                history.push_recently_opened_entry(
 575                                    HistoryEntryId::AcpThread(resume.id),
 576                                    cx,
 577                                );
 578                            });
 579                        }
 580
 581                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 582
 583                        this.model_selector =
 584                            thread
 585                                .read(cx)
 586                                .connection()
 587                                .model_selector()
 588                                .map(|selector| {
 589                                    cx.new(|cx| {
 590                                        AcpModelSelectorPopover::new(
 591                                            thread.read(cx).session_id().clone(),
 592                                            selector,
 593                                            PopoverMenuHandle::default(),
 594                                            this.focus_handle(cx),
 595                                            window,
 596                                            cx,
 597                                        )
 598                                    })
 599                                });
 600
 601                        let mut subscriptions = vec![
 602                            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 603                            cx.observe(&action_log, |_, _, cx| cx.notify()),
 604                        ];
 605
 606                        let title_editor =
 607                            if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
 608                                let editor = cx.new(|cx| {
 609                                    let mut editor = Editor::single_line(window, cx);
 610                                    editor.set_text(thread.read(cx).title(), window, cx);
 611                                    editor
 612                                });
 613                                subscriptions.push(cx.subscribe_in(
 614                                    &editor,
 615                                    window,
 616                                    Self::handle_title_editor_event,
 617                                ));
 618                                Some(editor)
 619                            } else {
 620                                None
 621                            };
 622                        this.thread_state = ThreadState::Ready {
 623                            thread,
 624                            title_editor,
 625                            _subscriptions: subscriptions,
 626                        };
 627                        this.message_editor.focus_handle(cx).focus(window);
 628
 629                        this.profile_selector = this.as_native_thread(cx).map(|thread| {
 630                            cx.new(|cx| {
 631                                ProfileSelector::new(
 632                                    <dyn Fs>::global(cx),
 633                                    Arc::new(thread.clone()),
 634                                    this.focus_handle(cx),
 635                                    cx,
 636                                )
 637                            })
 638                        });
 639
 640                        cx.notify();
 641                    }
 642                    Err(err) => {
 643                        this.handle_load_error(err, window, cx);
 644                    }
 645                };
 646            })
 647            .log_err();
 648        });
 649
 650        cx.spawn(async move |this, cx| {
 651            while let Ok(new_version) = new_version_available_rx.recv().await {
 652                if let Some(new_version) = new_version {
 653                    this.update(cx, |this, cx| {
 654                        this.new_server_version_available = Some(new_version.into());
 655                        cx.notify();
 656                    })
 657                    .log_err();
 658                }
 659            }
 660        })
 661        .detach();
 662
 663        let loading_view = cx.new(|cx| {
 664            let update_title_task = cx.spawn(async move |this, cx| {
 665                loop {
 666                    let status = status_rx.recv().await?;
 667                    this.update(cx, |this: &mut LoadingView, cx| {
 668                        this.title = status;
 669                        cx.notify();
 670                    })?;
 671                }
 672            });
 673
 674            LoadingView {
 675                title: "Loading…".into(),
 676                _load_task: load_task,
 677                _update_title_task: update_title_task,
 678            }
 679        });
 680
 681        ThreadState::Loading(loading_view)
 682    }
 683
 684    fn handle_auth_required(
 685        this: WeakEntity<Self>,
 686        err: AuthRequired,
 687        agent: Rc<dyn AgentServer>,
 688        connection: Rc<dyn AgentConnection>,
 689        window: &mut Window,
 690        cx: &mut App,
 691    ) {
 692        let agent_name = agent.name();
 693        let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
 694            let registry = LanguageModelRegistry::global(cx);
 695
 696            let sub = window.subscribe(&registry, cx, {
 697                let provider_id = provider_id.clone();
 698                let this = this.clone();
 699                move |_, ev, window, cx| {
 700                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
 701                        && &provider_id == updated_provider_id
 702                        && LanguageModelRegistry::global(cx)
 703                            .read(cx)
 704                            .provider(&provider_id)
 705                            .map_or(false, |provider| provider.is_authenticated(cx))
 706                    {
 707                        this.update(cx, |this, cx| {
 708                            this.reset(window, cx);
 709                        })
 710                        .ok();
 711                    }
 712                }
 713            });
 714
 715            let view = registry.read(cx).provider(&provider_id).map(|provider| {
 716                provider.configuration_view(
 717                    language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
 718                    window,
 719                    cx,
 720                )
 721            });
 722
 723            (view, Some(sub))
 724        } else {
 725            (None, None)
 726        };
 727
 728        this.update(cx, |this, cx| {
 729            this.thread_state = ThreadState::Unauthenticated {
 730                pending_auth_method: None,
 731                connection,
 732                configuration_view,
 733                description: err
 734                    .description
 735                    .clone()
 736                    .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
 737                _subscription: subscription,
 738            };
 739            if this.message_editor.focus_handle(cx).is_focused(window) {
 740                this.focus_handle.focus(window)
 741            }
 742            cx.notify();
 743        })
 744        .ok();
 745    }
 746
 747    fn handle_load_error(
 748        &mut self,
 749        err: anyhow::Error,
 750        window: &mut Window,
 751        cx: &mut Context<Self>,
 752    ) {
 753        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 754            self.thread_state = ThreadState::LoadError(load_err.clone());
 755        } else {
 756            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 757        }
 758        if self.message_editor.focus_handle(cx).is_focused(window) {
 759            self.focus_handle.focus(window)
 760        }
 761        cx.notify();
 762    }
 763
 764    pub fn workspace(&self) -> &WeakEntity<Workspace> {
 765        &self.workspace
 766    }
 767
 768    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 769        match &self.thread_state {
 770            ThreadState::Ready { thread, .. } => Some(thread),
 771            ThreadState::Unauthenticated { .. }
 772            | ThreadState::Loading { .. }
 773            | ThreadState::LoadError { .. } => None,
 774        }
 775    }
 776
 777    pub fn title(&self, cx: &App) -> SharedString {
 778        match &self.thread_state {
 779            ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
 780            ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
 781            ThreadState::LoadError(error) => match error {
 782                LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
 783                LoadError::FailedToInstall(_) => {
 784                    format!("Failed to Install {}", self.agent.name()).into()
 785                }
 786                LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
 787                LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
 788            },
 789        }
 790    }
 791
 792    pub fn title_editor(&self) -> Option<Entity<Editor>> {
 793        if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
 794            title_editor.clone()
 795        } else {
 796            None
 797        }
 798    }
 799
 800    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 801        self.thread_error.take();
 802        self.thread_retry_status.take();
 803
 804        if let Some(thread) = self.thread() {
 805            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 806        }
 807    }
 808
 809    pub fn expand_message_editor(
 810        &mut self,
 811        _: &ExpandMessageEditor,
 812        _window: &mut Window,
 813        cx: &mut Context<Self>,
 814    ) {
 815        self.set_editor_is_expanded(!self.editor_expanded, cx);
 816        cx.notify();
 817    }
 818
 819    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 820        self.editor_expanded = is_expanded;
 821        self.message_editor.update(cx, |editor, cx| {
 822            if is_expanded {
 823                editor.set_mode(
 824                    EditorMode::Full {
 825                        scale_ui_elements_with_buffer_font_size: false,
 826                        show_active_line_background: false,
 827                        sized_by_content: false,
 828                    },
 829                    cx,
 830                )
 831            } else {
 832                editor.set_mode(
 833                    EditorMode::AutoHeight {
 834                        min_lines: MIN_EDITOR_LINES,
 835                        max_lines: Some(MAX_EDITOR_LINES),
 836                    },
 837                    cx,
 838                )
 839            }
 840        });
 841        cx.notify();
 842    }
 843
 844    pub fn handle_title_editor_event(
 845        &mut self,
 846        title_editor: &Entity<Editor>,
 847        event: &EditorEvent,
 848        window: &mut Window,
 849        cx: &mut Context<Self>,
 850    ) {
 851        let Some(thread) = self.thread() else { return };
 852
 853        match event {
 854            EditorEvent::BufferEdited => {
 855                let new_title = title_editor.read(cx).text(cx);
 856                thread.update(cx, |thread, cx| {
 857                    thread
 858                        .set_title(new_title.into(), cx)
 859                        .detach_and_log_err(cx);
 860                })
 861            }
 862            EditorEvent::Blurred => {
 863                if title_editor.read(cx).text(cx).is_empty() {
 864                    title_editor.update(cx, |editor, cx| {
 865                        editor.set_text("New Thread", window, cx);
 866                    });
 867                }
 868            }
 869            _ => {}
 870        }
 871    }
 872
 873    pub fn handle_message_editor_event(
 874        &mut self,
 875        _: &Entity<MessageEditor>,
 876        event: &MessageEditorEvent,
 877        window: &mut Window,
 878        cx: &mut Context<Self>,
 879    ) {
 880        match event {
 881            MessageEditorEvent::Send => self.send(window, cx),
 882            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 883            MessageEditorEvent::Focus => {
 884                self.cancel_editing(&Default::default(), window, cx);
 885            }
 886            MessageEditorEvent::LostFocus => {}
 887        }
 888    }
 889
 890    pub fn handle_entry_view_event(
 891        &mut self,
 892        _: &Entity<EntryViewState>,
 893        event: &EntryViewEvent,
 894        window: &mut Window,
 895        cx: &mut Context<Self>,
 896    ) {
 897        match &event.view_event {
 898            ViewEvent::NewDiff(tool_call_id) => {
 899                if AgentSettings::get_global(cx).expand_edit_card {
 900                    self.expanded_tool_calls.insert(tool_call_id.clone());
 901                }
 902            }
 903            ViewEvent::NewTerminal(tool_call_id) => {
 904                if AgentSettings::get_global(cx).expand_terminal_card {
 905                    self.expanded_tool_calls.insert(tool_call_id.clone());
 906                }
 907            }
 908            ViewEvent::TerminalMovedToBackground(tool_call_id) => {
 909                self.expanded_tool_calls.remove(tool_call_id);
 910            }
 911            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 912                if let Some(thread) = self.thread()
 913                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 914                        thread.read(cx).entries().get(event.entry_index)
 915                    && user_message.id.is_some()
 916                {
 917                    self.editing_message = Some(event.entry_index);
 918                    cx.notify();
 919                }
 920            }
 921            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
 922                if let Some(thread) = self.thread()
 923                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 924                        thread.read(cx).entries().get(event.entry_index)
 925                    && user_message.id.is_some()
 926                {
 927                    if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
 928                        self.editing_message = None;
 929                        cx.notify();
 930                    }
 931                }
 932            }
 933            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 934                self.regenerate(event.entry_index, editor, window, cx);
 935            }
 936            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 937                self.cancel_editing(&Default::default(), window, cx);
 938            }
 939        }
 940    }
 941
 942    fn resume_chat(&mut self, cx: &mut Context<Self>) {
 943        self.thread_error.take();
 944        let Some(thread) = self.thread() else {
 945            return;
 946        };
 947        if !thread.read(cx).can_resume(cx) {
 948            return;
 949        }
 950
 951        let task = thread.update(cx, |thread, cx| thread.resume(cx));
 952        cx.spawn(async move |this, cx| {
 953            let result = task.await;
 954
 955            this.update(cx, |this, cx| {
 956                if let Err(err) = result {
 957                    this.handle_thread_error(err, cx);
 958                }
 959            })
 960        })
 961        .detach();
 962    }
 963
 964    fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 965        let Some(thread) = self.thread() else { return };
 966
 967        if self.is_loading_contents {
 968            return;
 969        }
 970
 971        self.history_store.update(cx, |history, cx| {
 972            history.push_recently_opened_entry(
 973                HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
 974                cx,
 975            );
 976        });
 977
 978        if thread.read(cx).status() != ThreadStatus::Idle {
 979            self.stop_current_and_send_new_message(window, cx);
 980            return;
 981        }
 982
 983        let text = self.message_editor.read(cx).text(cx);
 984        let text = text.trim();
 985        if text == "/login" || text == "/logout" {
 986            let ThreadState::Ready { thread, .. } = &self.thread_state else {
 987                return;
 988            };
 989
 990            let connection = thread.read(cx).connection().clone();
 991            if !connection
 992                .auth_methods()
 993                .iter()
 994                .any(|method| method.id.0.as_ref() == "claude-login")
 995            {
 996                return;
 997            };
 998            let this = cx.weak_entity();
 999            let agent = self.agent.clone();
1000            window.defer(cx, |window, cx| {
1001                Self::handle_auth_required(
1002                    this,
1003                    AuthRequired {
1004                        description: None,
1005                        provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1006                    },
1007                    agent,
1008                    connection,
1009                    window,
1010                    cx,
1011                );
1012            });
1013            cx.notify();
1014            return;
1015        }
1016
1017        let contents = self
1018            .message_editor
1019            .update(cx, |message_editor, cx| message_editor.contents(cx));
1020        self.send_impl(contents, window, cx)
1021    }
1022
1023    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1024        let Some(thread) = self.thread().cloned() else {
1025            return;
1026        };
1027
1028        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1029
1030        let contents = self
1031            .message_editor
1032            .update(cx, |message_editor, cx| message_editor.contents(cx));
1033
1034        cx.spawn_in(window, async move |this, cx| {
1035            cancelled.await;
1036
1037            this.update_in(cx, |this, window, cx| {
1038                this.send_impl(contents, window, cx);
1039            })
1040            .ok();
1041        })
1042        .detach();
1043    }
1044
1045    fn send_impl(
1046        &mut self,
1047        contents: Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
1048        window: &mut Window,
1049        cx: &mut Context<Self>,
1050    ) {
1051        let agent_telemetry_id = self.agent.telemetry_id();
1052
1053        self.thread_error.take();
1054        self.editing_message.take();
1055        self.thread_feedback.clear();
1056
1057        let Some(thread) = self.thread() else {
1058            return;
1059        };
1060        let thread = thread.downgrade();
1061        if self.should_be_following {
1062            self.workspace
1063                .update(cx, |workspace, cx| {
1064                    workspace.follow(CollaboratorId::Agent, window, cx);
1065                })
1066                .ok();
1067        }
1068
1069        self.is_loading_contents = true;
1070        let guard = cx.new(|_| ());
1071        cx.observe_release(&guard, |this, _guard, cx| {
1072            this.is_loading_contents = false;
1073            cx.notify();
1074        })
1075        .detach();
1076
1077        let task = cx.spawn_in(window, async move |this, cx| {
1078            let (contents, tracked_buffers) = contents.await?;
1079
1080            if contents.is_empty() {
1081                return Ok(());
1082            }
1083
1084            this.update_in(cx, |this, window, cx| {
1085                this.set_editor_is_expanded(false, cx);
1086                this.scroll_to_bottom(cx);
1087                this.message_editor.update(cx, |message_editor, cx| {
1088                    message_editor.clear(window, cx);
1089                });
1090            })?;
1091            let send = thread.update(cx, |thread, cx| {
1092                thread.action_log().update(cx, |action_log, cx| {
1093                    for buffer in tracked_buffers {
1094                        action_log.buffer_read(buffer, cx)
1095                    }
1096                });
1097                drop(guard);
1098
1099                telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1100
1101                thread.send(contents, cx)
1102            })?;
1103            send.await
1104        });
1105
1106        cx.spawn(async move |this, cx| {
1107            if let Err(err) = task.await {
1108                this.update(cx, |this, cx| {
1109                    this.handle_thread_error(err, cx);
1110                })
1111                .ok();
1112            } else {
1113                this.update(cx, |this, cx| {
1114                    this.should_be_following = this
1115                        .workspace
1116                        .update(cx, |workspace, _| {
1117                            workspace.is_being_followed(CollaboratorId::Agent)
1118                        })
1119                        .unwrap_or_default();
1120                })
1121                .ok();
1122            }
1123        })
1124        .detach();
1125    }
1126
1127    fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1128        let Some(thread) = self.thread().cloned() else {
1129            return;
1130        };
1131
1132        if let Some(index) = self.editing_message.take()
1133            && let Some(editor) = self
1134                .entry_view_state
1135                .read(cx)
1136                .entry(index)
1137                .and_then(|e| e.message_editor())
1138                .cloned()
1139        {
1140            editor.update(cx, |editor, cx| {
1141                if let Some(user_message) = thread
1142                    .read(cx)
1143                    .entries()
1144                    .get(index)
1145                    .and_then(|e| e.user_message())
1146                {
1147                    editor.set_message(user_message.chunks.clone(), window, cx);
1148                }
1149            })
1150        };
1151        self.focus_handle(cx).focus(window);
1152        cx.notify();
1153    }
1154
1155    fn regenerate(
1156        &mut self,
1157        entry_ix: usize,
1158        message_editor: &Entity<MessageEditor>,
1159        window: &mut Window,
1160        cx: &mut Context<Self>,
1161    ) {
1162        let Some(thread) = self.thread().cloned() else {
1163            return;
1164        };
1165        if self.is_loading_contents {
1166            return;
1167        }
1168
1169        let Some(user_message_id) = thread.update(cx, |thread, _| {
1170            thread.entries().get(entry_ix)?.user_message()?.id.clone()
1171        }) else {
1172            return;
1173        };
1174
1175        let contents = message_editor.update(cx, |message_editor, cx| message_editor.contents(cx));
1176
1177        let task = cx.spawn(async move |_, cx| {
1178            let contents = contents.await?;
1179            thread
1180                .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1181                .await?;
1182            Ok(contents)
1183        });
1184        self.send_impl(task, window, cx);
1185    }
1186
1187    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
1188        if let Some(thread) = self.thread() {
1189            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
1190        }
1191    }
1192
1193    fn open_edited_buffer(
1194        &mut self,
1195        buffer: &Entity<Buffer>,
1196        window: &mut Window,
1197        cx: &mut Context<Self>,
1198    ) {
1199        let Some(thread) = self.thread() else {
1200            return;
1201        };
1202
1203        let Some(diff) =
1204            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1205        else {
1206            return;
1207        };
1208
1209        diff.update(cx, |diff, cx| {
1210            diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1211        })
1212    }
1213
1214    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1215        let Some(thread) = self.as_native_thread(cx) else {
1216            return;
1217        };
1218        let project_context = thread.read(cx).project_context().read(cx);
1219
1220        let project_entry_ids = project_context
1221            .worktrees
1222            .iter()
1223            .flat_map(|worktree| worktree.rules_file.as_ref())
1224            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1225            .collect::<Vec<_>>();
1226
1227        self.workspace
1228            .update(cx, move |workspace, cx| {
1229                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1230                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1231                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1232                let project = workspace.project().read(cx);
1233                let project_paths = project_entry_ids
1234                    .into_iter()
1235                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1236                    .collect::<Vec<_>>();
1237                for project_path in project_paths {
1238                    workspace
1239                        .open_path(project_path, None, true, window, cx)
1240                        .detach_and_log_err(cx);
1241                }
1242            })
1243            .ok();
1244    }
1245
1246    fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1247        self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1248        cx.notify();
1249    }
1250
1251    fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1252        self.thread_error = None;
1253        cx.notify();
1254    }
1255
1256    fn handle_thread_event(
1257        &mut self,
1258        thread: &Entity<AcpThread>,
1259        event: &AcpThreadEvent,
1260        window: &mut Window,
1261        cx: &mut Context<Self>,
1262    ) {
1263        match event {
1264            AcpThreadEvent::NewEntry => {
1265                let len = thread.read(cx).entries().len();
1266                let index = len - 1;
1267                self.entry_view_state.update(cx, |view_state, cx| {
1268                    view_state.sync_entry(index, thread, window, cx);
1269                    self.list_state.splice_focusable(
1270                        index..index,
1271                        [view_state
1272                            .entry(index)
1273                            .and_then(|entry| entry.focus_handle(cx))],
1274                    );
1275                });
1276            }
1277            AcpThreadEvent::EntryUpdated(index) => {
1278                self.entry_view_state.update(cx, |view_state, cx| {
1279                    view_state.sync_entry(*index, thread, window, cx)
1280                });
1281            }
1282            AcpThreadEvent::EntriesRemoved(range) => {
1283                self.entry_view_state
1284                    .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1285                self.list_state.splice(range.clone(), 0);
1286            }
1287            AcpThreadEvent::ToolAuthorizationRequired => {
1288                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1289            }
1290            AcpThreadEvent::Retry(retry) => {
1291                self.thread_retry_status = Some(retry.clone());
1292            }
1293            AcpThreadEvent::Stopped => {
1294                self.thread_retry_status.take();
1295                let used_tools = thread.read(cx).used_tools_since_last_user_message();
1296                self.notify_with_sound(
1297                    if used_tools {
1298                        "Finished running tools"
1299                    } else {
1300                        "New message"
1301                    },
1302                    IconName::ZedAssistant,
1303                    window,
1304                    cx,
1305                );
1306            }
1307            AcpThreadEvent::Refusal => {
1308                self.thread_retry_status.take();
1309                self.thread_error = Some(ThreadError::Refusal);
1310                let model_or_agent_name = self.get_current_model_name(cx);
1311                let notification_message =
1312                    format!("{} refused to respond to this request", model_or_agent_name);
1313                self.notify_with_sound(&notification_message, IconName::Warning, window, cx);
1314            }
1315            AcpThreadEvent::Error => {
1316                self.thread_retry_status.take();
1317                self.notify_with_sound(
1318                    "Agent stopped due to an error",
1319                    IconName::Warning,
1320                    window,
1321                    cx,
1322                );
1323            }
1324            AcpThreadEvent::LoadError(error) => {
1325                self.thread_retry_status.take();
1326                self.thread_state = ThreadState::LoadError(error.clone());
1327                if self.message_editor.focus_handle(cx).is_focused(window) {
1328                    self.focus_handle.focus(window)
1329                }
1330            }
1331            AcpThreadEvent::TitleUpdated => {
1332                let title = thread.read(cx).title();
1333                if let Some(title_editor) = self.title_editor() {
1334                    title_editor.update(cx, |editor, cx| {
1335                        if editor.text(cx) != title {
1336                            editor.set_text(title, window, cx);
1337                        }
1338                    });
1339                }
1340            }
1341            AcpThreadEvent::PromptCapabilitiesUpdated => {
1342                self.prompt_capabilities
1343                    .set(thread.read(cx).prompt_capabilities());
1344            }
1345            AcpThreadEvent::TokenUsageUpdated => {}
1346        }
1347        cx.notify();
1348    }
1349
1350    fn authenticate(
1351        &mut self,
1352        method: acp::AuthMethodId,
1353        window: &mut Window,
1354        cx: &mut Context<Self>,
1355    ) {
1356        let ThreadState::Unauthenticated {
1357            connection,
1358            pending_auth_method,
1359            configuration_view,
1360            ..
1361        } = &mut self.thread_state
1362        else {
1363            return;
1364        };
1365
1366        if method.0.as_ref() == "gemini-api-key" {
1367            let registry = LanguageModelRegistry::global(cx);
1368            let provider = registry
1369                .read(cx)
1370                .provider(&language_model::GOOGLE_PROVIDER_ID)
1371                .unwrap();
1372            if !provider.is_authenticated(cx) {
1373                let this = cx.weak_entity();
1374                let agent = self.agent.clone();
1375                let connection = connection.clone();
1376                window.defer(cx, |window, cx| {
1377                    Self::handle_auth_required(
1378                        this,
1379                        AuthRequired {
1380                            description: Some("GEMINI_API_KEY must be set".to_owned()),
1381                            provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1382                        },
1383                        agent,
1384                        connection,
1385                        window,
1386                        cx,
1387                    );
1388                });
1389                return;
1390            }
1391        } else if method.0.as_ref() == "anthropic-api-key" {
1392            let registry = LanguageModelRegistry::global(cx);
1393            let provider = registry
1394                .read(cx)
1395                .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1396                .unwrap();
1397            let this = cx.weak_entity();
1398            let agent = self.agent.clone();
1399            let connection = connection.clone();
1400            window.defer(cx, move |window, cx| {
1401                if !provider.is_authenticated(cx) {
1402                    Self::handle_auth_required(
1403                        this,
1404                        AuthRequired {
1405                            description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1406                            provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1407                        },
1408                        agent,
1409                        connection,
1410                        window,
1411                        cx,
1412                    );
1413                } else {
1414                    this.update(cx, |this, cx| {
1415                        this.thread_state = Self::initial_state(
1416                            agent,
1417                            None,
1418                            this.workspace.clone(),
1419                            this.project.clone(),
1420                            window,
1421                            cx,
1422                        )
1423                    })
1424                    .ok();
1425                }
1426            });
1427            return;
1428        } else if method.0.as_ref() == "vertex-ai"
1429            && std::env::var("GOOGLE_API_KEY").is_err()
1430            && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1431                || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1432        {
1433            let this = cx.weak_entity();
1434            let agent = self.agent.clone();
1435            let connection = connection.clone();
1436
1437            window.defer(cx, |window, cx| {
1438                    Self::handle_auth_required(
1439                        this,
1440                        AuthRequired {
1441                            description: Some(
1442                                "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1443                                    .to_owned(),
1444                            ),
1445                            provider_id: None,
1446                        },
1447                        agent,
1448                        connection,
1449                        window,
1450                        cx,
1451                    )
1452                });
1453            return;
1454        }
1455
1456        self.thread_error.take();
1457        configuration_view.take();
1458        pending_auth_method.replace(method.clone());
1459        let authenticate = if method.0.as_ref() == "claude-login" {
1460            if let Some(workspace) = self.workspace.upgrade() {
1461                Self::spawn_claude_login(&workspace, window, cx)
1462            } else {
1463                Task::ready(Ok(()))
1464            }
1465        } else {
1466            connection.authenticate(method, cx)
1467        };
1468        cx.notify();
1469        self.auth_task =
1470            Some(cx.spawn_in(window, {
1471                let agent = self.agent.clone();
1472                async move |this, cx| {
1473                    let result = authenticate.await;
1474
1475                    match &result {
1476                        Ok(_) => telemetry::event!(
1477                            "Authenticate Agent Succeeded",
1478                            agent = agent.telemetry_id()
1479                        ),
1480                        Err(_) => {
1481                            telemetry::event!(
1482                                "Authenticate Agent Failed",
1483                                agent = agent.telemetry_id(),
1484                            )
1485                        }
1486                    }
1487
1488                    this.update_in(cx, |this, window, cx| {
1489                        if let Err(err) = result {
1490                            if let ThreadState::Unauthenticated {
1491                                pending_auth_method,
1492                                ..
1493                            } = &mut this.thread_state
1494                            {
1495                                pending_auth_method.take();
1496                            }
1497                            this.handle_thread_error(err, cx);
1498                        } else {
1499                            this.reset(window, cx);
1500                        }
1501                        this.auth_task.take()
1502                    })
1503                    .ok();
1504                }
1505            }));
1506    }
1507
1508    fn spawn_claude_login(
1509        workspace: &Entity<Workspace>,
1510        window: &mut Window,
1511        cx: &mut App,
1512    ) -> Task<Result<()>> {
1513        let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1514            return Task::ready(Ok(()));
1515        };
1516        let project_entity = workspace.read(cx).project();
1517        let project = project_entity.read(cx);
1518        let cwd = project.first_project_directory(cx);
1519        let shell = project.terminal_settings(&cwd, cx).shell.clone();
1520
1521        let delegate = AgentServerDelegate::new(project_entity.clone(), None, None);
1522        let command = ClaudeCode::login_command(delegate, cx);
1523
1524        window.spawn(cx, async move |cx| {
1525            let login_command = command.await?;
1526            let command = login_command
1527                .path
1528                .to_str()
1529                .with_context(|| format!("invalid login command: {:?}", login_command.path))?;
1530            let command = shlex::try_quote(command)?;
1531            let args = login_command
1532                .arguments
1533                .iter()
1534                .map(|arg| {
1535                    Ok(shlex::try_quote(arg)
1536                        .context("Failed to quote argument")?
1537                        .to_string())
1538                })
1539                .collect::<Result<Vec<_>>>()?;
1540
1541            let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1542                terminal_panel.spawn_task(
1543                    &SpawnInTerminal {
1544                        id: task::TaskId("claude-login".into()),
1545                        full_label: "claude /login".to_owned(),
1546                        label: "claude /login".to_owned(),
1547                        command: Some(command.into()),
1548                        args,
1549                        command_label: "claude /login".to_owned(),
1550                        cwd,
1551                        use_new_terminal: true,
1552                        allow_concurrent_runs: true,
1553                        hide: task::HideStrategy::Always,
1554                        shell,
1555                        ..Default::default()
1556                    },
1557                    window,
1558                    cx,
1559                )
1560            })?;
1561
1562            let terminal = terminal.await?;
1563            let mut exit_status = terminal
1564                .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1565                .fuse();
1566
1567            let logged_in = cx
1568                .spawn({
1569                    let terminal = terminal.clone();
1570                    async move |cx| {
1571                        loop {
1572                            cx.background_executor().timer(Duration::from_secs(1)).await;
1573                            let content =
1574                                terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1575                            if content.contains("Login successful") {
1576                                return anyhow::Ok(());
1577                            }
1578                        }
1579                    }
1580                })
1581                .fuse();
1582            futures::pin_mut!(logged_in);
1583            futures::select_biased! {
1584                result = logged_in => {
1585                    if let Err(e) = result {
1586                        log::error!("{e}");
1587                        return Err(anyhow!("exited before logging in"));
1588                    }
1589                }
1590                _ = exit_status => {
1591                    return Err(anyhow!("exited before logging in"));
1592                }
1593            }
1594            terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1595            Ok(())
1596        })
1597    }
1598
1599    fn authorize_tool_call(
1600        &mut self,
1601        tool_call_id: acp::ToolCallId,
1602        option_id: acp::PermissionOptionId,
1603        option_kind: acp::PermissionOptionKind,
1604        window: &mut Window,
1605        cx: &mut Context<Self>,
1606    ) {
1607        let Some(thread) = self.thread() else {
1608            return;
1609        };
1610        thread.update(cx, |thread, cx| {
1611            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1612        });
1613        if self.should_be_following {
1614            self.workspace
1615                .update(cx, |workspace, cx| {
1616                    workspace.follow(CollaboratorId::Agent, window, cx);
1617                })
1618                .ok();
1619        }
1620        cx.notify();
1621    }
1622
1623    fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1624        let Some(thread) = self.thread() else {
1625            return;
1626        };
1627        thread
1628            .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
1629            .detach_and_log_err(cx);
1630        cx.notify();
1631    }
1632
1633    fn render_entry(
1634        &self,
1635        entry_ix: usize,
1636        total_entries: usize,
1637        entry: &AgentThreadEntry,
1638        window: &mut Window,
1639        cx: &Context<Self>,
1640    ) -> AnyElement {
1641        let primary = match &entry {
1642            AgentThreadEntry::UserMessage(message) => {
1643                let Some(editor) = self
1644                    .entry_view_state
1645                    .read(cx)
1646                    .entry(entry_ix)
1647                    .and_then(|entry| entry.message_editor())
1648                    .cloned()
1649                else {
1650                    return Empty.into_any_element();
1651                };
1652
1653                let editing = self.editing_message == Some(entry_ix);
1654                let editor_focus = editor.focus_handle(cx).is_focused(window);
1655                let focus_border = cx.theme().colors().border_focused;
1656
1657                let rules_item = if entry_ix == 0 {
1658                    self.render_rules_item(cx)
1659                } else {
1660                    None
1661                };
1662
1663                let has_checkpoint_button = message
1664                    .checkpoint
1665                    .as_ref()
1666                    .is_some_and(|checkpoint| checkpoint.show);
1667
1668                let agent_name = self.agent.name();
1669
1670                v_flex()
1671                    .id(("user_message", entry_ix))
1672                    .map(|this| {
1673                        if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none()  {
1674                            this.pt(rems_from_px(18.))
1675                        } else if rules_item.is_some() {
1676                            this.pt_3()
1677                        } else {
1678                            this.pt_2()
1679                        }
1680                    })
1681                    .pb_3()
1682                    .px_2()
1683                    .gap_1p5()
1684                    .w_full()
1685                    .children(rules_item)
1686                    .children(message.id.clone().and_then(|message_id| {
1687                        message.checkpoint.as_ref()?.show.then(|| {
1688                            h_flex()
1689                                .px_3()
1690                                .gap_2()
1691                                .child(Divider::horizontal())
1692                                .child(
1693                                    Button::new("restore-checkpoint", "Restore Checkpoint")
1694                                        .icon(IconName::Undo)
1695                                        .icon_size(IconSize::XSmall)
1696                                        .icon_position(IconPosition::Start)
1697                                        .label_size(LabelSize::XSmall)
1698                                        .icon_color(Color::Muted)
1699                                        .color(Color::Muted)
1700                                        .on_click(cx.listener(move |this, _, _window, cx| {
1701                                            this.rewind(&message_id, cx);
1702                                        }))
1703                                )
1704                                .child(Divider::horizontal())
1705                        })
1706                    }))
1707                    .child(
1708                        div()
1709                            .relative()
1710                            .child(
1711                                div()
1712                                    .py_3()
1713                                    .px_2()
1714                                    .rounded_md()
1715                                    .shadow_md()
1716                                    .bg(cx.theme().colors().editor_background)
1717                                    .border_1()
1718                                    .when(editing && !editor_focus, |this| this.border_dashed())
1719                                    .border_color(cx.theme().colors().border)
1720                                    .map(|this|{
1721                                        if editing && editor_focus {
1722                                            this.border_color(focus_border)
1723                                        } else if message.id.is_some() {
1724                                            this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1725                                        } else {
1726                                            this
1727                                        }
1728                                    })
1729                                    .text_xs()
1730                                    .child(editor.clone().into_any_element()),
1731                            )
1732                            .when(editor_focus, |this| {
1733                                let base_container = h_flex()
1734                                    .absolute()
1735                                    .top_neg_3p5()
1736                                    .right_3()
1737                                    .gap_1()
1738                                    .rounded_sm()
1739                                    .border_1()
1740                                    .border_color(cx.theme().colors().border)
1741                                    .bg(cx.theme().colors().editor_background)
1742                                    .overflow_hidden();
1743
1744                                if message.id.is_some() {
1745                                    this.child(
1746                                        base_container
1747                                            .child(
1748                                                IconButton::new("cancel", IconName::Close)
1749                                                    .disabled(self.is_loading_contents)
1750                                                    .icon_color(Color::Error)
1751                                                    .icon_size(IconSize::XSmall)
1752                                                    .on_click(cx.listener(Self::cancel_editing))
1753                                            )
1754                                            .child(
1755                                                if self.is_loading_contents {
1756                                                    div()
1757                                                        .id("loading-edited-message-content")
1758                                                        .tooltip(Tooltip::text("Loading Added Context…"))
1759                                                        .child(loading_contents_spinner(IconSize::XSmall))
1760                                                        .into_any_element()
1761                                                } else {
1762                                                    IconButton::new("regenerate", IconName::Return)
1763                                                        .icon_color(Color::Muted)
1764                                                        .icon_size(IconSize::XSmall)
1765                                                        .tooltip(Tooltip::text(
1766                                                            "Editing will restart the thread from this point."
1767                                                        ))
1768                                                        .on_click(cx.listener({
1769                                                            let editor = editor.clone();
1770                                                            move |this, _, window, cx| {
1771                                                                this.regenerate(
1772                                                                    entry_ix, &editor, window, cx,
1773                                                                );
1774                                                            }
1775                                                        })).into_any_element()
1776                                                }
1777                                            )
1778                                    )
1779                                } else {
1780                                    this.child(
1781                                        base_container
1782                                            .border_dashed()
1783                                            .child(
1784                                                IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1785                                                    .icon_size(IconSize::Small)
1786                                                    .icon_color(Color::Muted)
1787                                                    .style(ButtonStyle::Transparent)
1788                                                    .tooltip(move |_window, cx| {
1789                                                        cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1790                                                            .into()
1791                                                    })
1792                                            )
1793                                    )
1794                                }
1795                            }),
1796                    )
1797                    .into_any()
1798            }
1799            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1800                let is_last = entry_ix + 1 == total_entries;
1801
1802                let style = default_markdown_style(false, false, window, cx);
1803                let message_body = v_flex()
1804                    .w_full()
1805                    .gap_3()
1806                    .children(chunks.iter().enumerate().filter_map(
1807                        |(chunk_ix, chunk)| match chunk {
1808                            AssistantMessageChunk::Message { block } => {
1809                                block.markdown().map(|md| {
1810                                    self.render_markdown(md.clone(), style.clone())
1811                                        .into_any_element()
1812                                })
1813                            }
1814                            AssistantMessageChunk::Thought { block } => {
1815                                block.markdown().map(|md| {
1816                                    self.render_thinking_block(
1817                                        entry_ix,
1818                                        chunk_ix,
1819                                        md.clone(),
1820                                        window,
1821                                        cx,
1822                                    )
1823                                    .into_any_element()
1824                                })
1825                            }
1826                        },
1827                    ))
1828                    .into_any();
1829
1830                v_flex()
1831                    .px_5()
1832                    .py_1p5()
1833                    .when(is_last, |this| this.pb_4())
1834                    .w_full()
1835                    .text_ui(cx)
1836                    .child(message_body)
1837                    .into_any()
1838            }
1839            AgentThreadEntry::ToolCall(tool_call) => {
1840                let has_terminals = tool_call.terminals().next().is_some();
1841
1842                div().w_full().map(|this| {
1843                    if has_terminals {
1844                        this.children(tool_call.terminals().map(|terminal| {
1845                            self.render_terminal_tool_call(
1846                                entry_ix, terminal, tool_call, window, cx,
1847                            )
1848                        }))
1849                    } else {
1850                        this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1851                    }
1852                })
1853            }
1854            .into_any(),
1855        };
1856
1857        let Some(thread) = self.thread() else {
1858            return primary;
1859        };
1860
1861        let primary = if entry_ix == total_entries - 1 {
1862            v_flex()
1863                .w_full()
1864                .child(primary)
1865                .child(self.render_thread_controls(&thread, cx))
1866                .when_some(
1867                    self.thread_feedback.comments_editor.clone(),
1868                    |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
1869                )
1870                .into_any_element()
1871        } else {
1872            primary
1873        };
1874
1875        if let Some(editing_index) = self.editing_message.as_ref()
1876            && *editing_index < entry_ix
1877        {
1878            let backdrop = div()
1879                .id(("backdrop", entry_ix))
1880                .size_full()
1881                .absolute()
1882                .inset_0()
1883                .bg(cx.theme().colors().panel_background)
1884                .opacity(0.8)
1885                .block_mouse_except_scroll()
1886                .on_click(cx.listener(Self::cancel_editing));
1887
1888            div()
1889                .relative()
1890                .child(primary)
1891                .child(backdrop)
1892                .into_any_element()
1893        } else {
1894            primary
1895        }
1896    }
1897
1898    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1899        cx.theme()
1900            .colors()
1901            .element_background
1902            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1903    }
1904
1905    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1906        cx.theme().colors().border.opacity(0.8)
1907    }
1908
1909    fn tool_name_font_size(&self) -> Rems {
1910        rems_from_px(13.)
1911    }
1912
1913    fn render_thinking_block(
1914        &self,
1915        entry_ix: usize,
1916        chunk_ix: usize,
1917        chunk: Entity<Markdown>,
1918        window: &Window,
1919        cx: &Context<Self>,
1920    ) -> AnyElement {
1921        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1922        let card_header_id = SharedString::from("inner-card-header");
1923
1924        let key = (entry_ix, chunk_ix);
1925
1926        let is_open = self.expanded_thinking_blocks.contains(&key);
1927
1928        let scroll_handle = self
1929            .entry_view_state
1930            .read(cx)
1931            .entry(entry_ix)
1932            .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
1933
1934        let thinking_content = {
1935            div()
1936                .id(("thinking-content", chunk_ix))
1937                .when_some(scroll_handle, |this, scroll_handle| {
1938                    this.track_scroll(&scroll_handle)
1939                })
1940                .text_ui_sm(cx)
1941                .overflow_hidden()
1942                .child(
1943                    self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
1944                )
1945        };
1946
1947        v_flex()
1948            .gap_1()
1949            .child(
1950                h_flex()
1951                    .id(header_id)
1952                    .group(&card_header_id)
1953                    .relative()
1954                    .w_full()
1955                    .pr_1()
1956                    .justify_between()
1957                    .child(
1958                        h_flex()
1959                            .h(window.line_height() - px(2.))
1960                            .gap_1p5()
1961                            .overflow_hidden()
1962                            .child(
1963                                Icon::new(IconName::ToolThink)
1964                                    .size(IconSize::Small)
1965                                    .color(Color::Muted),
1966                            )
1967                            .child(
1968                                div()
1969                                    .text_size(self.tool_name_font_size())
1970                                    .text_color(cx.theme().colors().text_muted)
1971                                    .child("Thinking"),
1972                            ),
1973                    )
1974                    .child(
1975                        Disclosure::new(("expand", entry_ix), is_open)
1976                            .opened_icon(IconName::ChevronUp)
1977                            .closed_icon(IconName::ChevronDown)
1978                            .visible_on_hover(&card_header_id)
1979                            .on_click(cx.listener({
1980                                move |this, _event, _window, cx| {
1981                                    if is_open {
1982                                        this.expanded_thinking_blocks.remove(&key);
1983                                    } else {
1984                                        this.expanded_thinking_blocks.insert(key);
1985                                    }
1986                                    cx.notify();
1987                                }
1988                            })),
1989                    )
1990                    .on_click(cx.listener({
1991                        move |this, _event, _window, cx| {
1992                            if is_open {
1993                                this.expanded_thinking_blocks.remove(&key);
1994                            } else {
1995                                this.expanded_thinking_blocks.insert(key);
1996                            }
1997                            cx.notify();
1998                        }
1999                    })),
2000            )
2001            .when(is_open, |this| {
2002                this.child(
2003                    div()
2004                        .ml_1p5()
2005                        .pl_3p5()
2006                        .border_l_1()
2007                        .border_color(self.tool_card_border_color(cx))
2008                        .child(thinking_content),
2009                )
2010            })
2011            .into_any_element()
2012    }
2013
2014    fn render_tool_call(
2015        &self,
2016        entry_ix: usize,
2017        tool_call: &ToolCall,
2018        window: &Window,
2019        cx: &Context<Self>,
2020    ) -> Div {
2021        let card_header_id = SharedString::from("inner-tool-call-header");
2022
2023        let tool_icon =
2024            if tool_call.kind == acp::ToolKind::Edit && tool_call.locations.len() == 1 {
2025                FileIcons::get_icon(&tool_call.locations[0].path, cx)
2026                    .map(Icon::from_path)
2027                    .unwrap_or(Icon::new(IconName::ToolPencil))
2028            } else {
2029                Icon::new(match tool_call.kind {
2030                    acp::ToolKind::Read => IconName::ToolSearch,
2031                    acp::ToolKind::Edit => IconName::ToolPencil,
2032                    acp::ToolKind::Delete => IconName::ToolDeleteFile,
2033                    acp::ToolKind::Move => IconName::ArrowRightLeft,
2034                    acp::ToolKind::Search => IconName::ToolSearch,
2035                    acp::ToolKind::Execute => IconName::ToolTerminal,
2036                    acp::ToolKind::Think => IconName::ToolThink,
2037                    acp::ToolKind::Fetch => IconName::ToolWeb,
2038                    acp::ToolKind::Other => IconName::ToolHammer,
2039                })
2040            }
2041            .size(IconSize::Small)
2042            .color(Color::Muted);
2043
2044        let failed_or_canceled = match &tool_call.status {
2045            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2046            _ => false,
2047        };
2048
2049        let has_location = tool_call.locations.len() == 1;
2050        let needs_confirmation = matches!(
2051            tool_call.status,
2052            ToolCallStatus::WaitingForConfirmation { .. }
2053        );
2054        let is_edit =
2055            matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2056        let use_card_layout = needs_confirmation || is_edit;
2057
2058        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2059
2060        let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2061
2062        let gradient_overlay = {
2063            div()
2064                .absolute()
2065                .top_0()
2066                .right_0()
2067                .w_12()
2068                .h_full()
2069                .map(|this| {
2070                    if use_card_layout {
2071                        this.bg(linear_gradient(
2072                            90.,
2073                            linear_color_stop(self.tool_card_header_bg(cx), 1.),
2074                            linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2075                        ))
2076                    } else {
2077                        this.bg(linear_gradient(
2078                            90.,
2079                            linear_color_stop(cx.theme().colors().panel_background, 1.),
2080                            linear_color_stop(
2081                                cx.theme().colors().panel_background.opacity(0.2),
2082                                0.,
2083                            ),
2084                        ))
2085                    }
2086                })
2087        };
2088
2089        let tool_output_display = if is_open {
2090            match &tool_call.status {
2091                ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2092                    .w_full()
2093                    .children(tool_call.content.iter().map(|content| {
2094                        div()
2095                            .child(self.render_tool_call_content(
2096                                entry_ix,
2097                                content,
2098                                tool_call,
2099                                use_card_layout,
2100                                window,
2101                                cx,
2102                            ))
2103                            .into_any_element()
2104                    }))
2105                    .child(self.render_permission_buttons(
2106                        options,
2107                        entry_ix,
2108                        tool_call.id.clone(),
2109                        cx,
2110                    ))
2111                    .into_any(),
2112                ToolCallStatus::Pending | ToolCallStatus::InProgress
2113                    if is_edit
2114                        && tool_call.content.is_empty()
2115                        && self.as_native_connection(cx).is_some() =>
2116                {
2117                    self.render_diff_loading(cx).into_any()
2118                }
2119                ToolCallStatus::Pending
2120                | ToolCallStatus::InProgress
2121                | ToolCallStatus::Completed
2122                | ToolCallStatus::Failed
2123                | ToolCallStatus::Canceled => v_flex()
2124                    .w_full()
2125                    .children(tool_call.content.iter().map(|content| {
2126                        div().child(self.render_tool_call_content(
2127                            entry_ix,
2128                            content,
2129                            tool_call,
2130                            use_card_layout,
2131                            window,
2132                            cx,
2133                        ))
2134                    }))
2135                    .into_any(),
2136                ToolCallStatus::Rejected => Empty.into_any(),
2137            }
2138            .into()
2139        } else {
2140            None
2141        };
2142
2143        v_flex()
2144            .map(|this| {
2145                if use_card_layout {
2146                    this.my_1p5()
2147                        .rounded_md()
2148                        .border_1()
2149                        .border_color(self.tool_card_border_color(cx))
2150                        .bg(cx.theme().colors().editor_background)
2151                        .overflow_hidden()
2152                } else {
2153                    this.my_1()
2154                }
2155            })
2156            .map(|this| {
2157                if has_location && !use_card_layout {
2158                    this.ml_4()
2159                } else {
2160                    this.ml_5()
2161                }
2162            })
2163            .mr_5()
2164            .child(
2165                h_flex()
2166                    .group(&card_header_id)
2167                    .relative()
2168                    .w_full()
2169                    .gap_1()
2170                    .justify_between()
2171                    .when(use_card_layout, |this| {
2172                        this.p_0p5()
2173                            .rounded_t(rems_from_px(5.))
2174                            .bg(self.tool_card_header_bg(cx))
2175                    })
2176                    .child(
2177                        h_flex()
2178                            .relative()
2179                            .w_full()
2180                            .h(window.line_height() - px(2.))
2181                            .text_size(self.tool_name_font_size())
2182                            .gap_1p5()
2183                            .when(has_location || use_card_layout, |this| this.px_1())
2184                            .when(has_location, |this| {
2185                                this.cursor(CursorStyle::PointingHand)
2186                                    .rounded(rems_from_px(3.)) // Concentric border radius
2187                                    .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2188                            })
2189                            .overflow_hidden()
2190                            .child(tool_icon)
2191                            .child(if has_location {
2192                                let name = tool_call.locations[0]
2193                                    .path
2194                                    .file_name()
2195                                    .unwrap_or_default()
2196                                    .display()
2197                                    .to_string();
2198
2199                                h_flex()
2200                                    .id(("open-tool-call-location", entry_ix))
2201                                    .w_full()
2202                                    .map(|this| {
2203                                        if use_card_layout {
2204                                            this.text_color(cx.theme().colors().text)
2205                                        } else {
2206                                            this.text_color(cx.theme().colors().text_muted)
2207                                        }
2208                                    })
2209                                    .child(name)
2210                                    .tooltip(Tooltip::text("Jump to File"))
2211                                    .on_click(cx.listener(move |this, _, window, cx| {
2212                                        this.open_tool_call_location(entry_ix, 0, window, cx);
2213                                    }))
2214                                    .into_any_element()
2215                            } else {
2216                                h_flex()
2217                                    .w_full()
2218                                    .child(self.render_markdown(
2219                                        tool_call.label.clone(),
2220                                        default_markdown_style(false, true, window, cx),
2221                                    ))
2222                                    .into_any()
2223                            })
2224                            .when(!has_location, |this| this.child(gradient_overlay)),
2225                    )
2226                    .when(is_collapsible || failed_or_canceled, |this| {
2227                        this.child(
2228                            h_flex()
2229                                .px_1()
2230                                .gap_px()
2231                                .when(is_collapsible, |this| {
2232                                    this.child(
2233                                    Disclosure::new(("expand", entry_ix), is_open)
2234                                        .opened_icon(IconName::ChevronUp)
2235                                        .closed_icon(IconName::ChevronDown)
2236                                        .visible_on_hover(&card_header_id)
2237                                        .on_click(cx.listener({
2238                                            let id = tool_call.id.clone();
2239                                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2240                                                if is_open {
2241                                                    this.expanded_tool_calls.remove(&id);
2242                                                } else {
2243                                                    this.expanded_tool_calls.insert(id.clone());
2244                                                }
2245                                                cx.notify();
2246                                            }
2247                                        })),
2248                                )
2249                                })
2250                                .when(failed_or_canceled, |this| {
2251                                    this.child(
2252                                        Icon::new(IconName::Close)
2253                                            .color(Color::Error)
2254                                            .size(IconSize::Small),
2255                                    )
2256                                }),
2257                        )
2258                    }),
2259            )
2260            .children(tool_output_display)
2261    }
2262
2263    fn render_tool_call_content(
2264        &self,
2265        entry_ix: usize,
2266        content: &ToolCallContent,
2267        tool_call: &ToolCall,
2268        card_layout: bool,
2269        window: &Window,
2270        cx: &Context<Self>,
2271    ) -> AnyElement {
2272        match content {
2273            ToolCallContent::ContentBlock(content) => {
2274                if let Some(resource_link) = content.resource_link() {
2275                    self.render_resource_link(resource_link, cx)
2276                } else if let Some(markdown) = content.markdown() {
2277                    self.render_markdown_output(
2278                        markdown.clone(),
2279                        tool_call.id.clone(),
2280                        card_layout,
2281                        window,
2282                        cx,
2283                    )
2284                } else {
2285                    Empty.into_any_element()
2286                }
2287            }
2288            ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2289            ToolCallContent::Terminal(terminal) => {
2290                self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2291            }
2292        }
2293    }
2294
2295    fn render_markdown_output(
2296        &self,
2297        markdown: Entity<Markdown>,
2298        tool_call_id: acp::ToolCallId,
2299        card_layout: bool,
2300        window: &Window,
2301        cx: &Context<Self>,
2302    ) -> AnyElement {
2303        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2304
2305        v_flex()
2306            .mt_1p5()
2307            .gap_2()
2308            .when(!card_layout, |this| {
2309                this.ml(rems(0.4))
2310                    .px_3p5()
2311                    .border_l_1()
2312                    .border_color(self.tool_card_border_color(cx))
2313            })
2314            .when(card_layout, |this| {
2315                this.p_2()
2316                    .border_t_1()
2317                    .border_color(self.tool_card_border_color(cx))
2318            })
2319            .text_sm()
2320            .text_color(cx.theme().colors().text_muted)
2321            .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2322            .when(!card_layout, |this| {
2323                this.child(
2324                    IconButton::new(button_id, IconName::ChevronUp)
2325                        .full_width()
2326                        .style(ButtonStyle::Outlined)
2327                        .icon_color(Color::Muted)
2328                        .on_click(cx.listener({
2329                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2330                                this.expanded_tool_calls.remove(&tool_call_id);
2331                                cx.notify();
2332                            }
2333                        })),
2334                )
2335            })
2336            .into_any_element()
2337    }
2338
2339    fn render_resource_link(
2340        &self,
2341        resource_link: &acp::ResourceLink,
2342        cx: &Context<Self>,
2343    ) -> AnyElement {
2344        let uri: SharedString = resource_link.uri.clone().into();
2345        let is_file = resource_link.uri.strip_prefix("file://");
2346
2347        let label: SharedString = if let Some(abs_path) = is_file {
2348            if let Some(project_path) = self
2349                .project
2350                .read(cx)
2351                .project_path_for_absolute_path(&Path::new(abs_path), cx)
2352                && let Some(worktree) = self
2353                    .project
2354                    .read(cx)
2355                    .worktree_for_id(project_path.worktree_id, cx)
2356            {
2357                worktree
2358                    .read(cx)
2359                    .full_path(&project_path.path)
2360                    .to_string_lossy()
2361                    .to_string()
2362                    .into()
2363            } else {
2364                abs_path.to_string().into()
2365            }
2366        } else {
2367            uri.clone()
2368        };
2369
2370        let button_id = SharedString::from(format!("item-{}", uri));
2371
2372        div()
2373            .ml(rems(0.4))
2374            .pl_2p5()
2375            .border_l_1()
2376            .border_color(self.tool_card_border_color(cx))
2377            .overflow_hidden()
2378            .child(
2379                Button::new(button_id, label)
2380                    .label_size(LabelSize::Small)
2381                    .color(Color::Muted)
2382                    .truncate(true)
2383                    .when(is_file.is_none(), |this| {
2384                        this.icon(IconName::ArrowUpRight)
2385                            .icon_size(IconSize::XSmall)
2386                            .icon_color(Color::Muted)
2387                    })
2388                    .on_click(cx.listener({
2389                        let workspace = self.workspace.clone();
2390                        move |_, _, window, cx: &mut Context<Self>| {
2391                            Self::open_link(uri.clone(), &workspace, window, cx);
2392                        }
2393                    })),
2394            )
2395            .into_any_element()
2396    }
2397
2398    fn render_permission_buttons(
2399        &self,
2400        options: &[acp::PermissionOption],
2401        entry_ix: usize,
2402        tool_call_id: acp::ToolCallId,
2403        cx: &Context<Self>,
2404    ) -> Div {
2405        h_flex()
2406            .py_1()
2407            .pl_2()
2408            .pr_1()
2409            .gap_1()
2410            .justify_between()
2411            .flex_wrap()
2412            .border_t_1()
2413            .border_color(self.tool_card_border_color(cx))
2414            .child(
2415                div()
2416                    .min_w(rems_from_px(145.))
2417                    .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
2418            )
2419            .child(h_flex().gap_0p5().children(options.iter().map(|option| {
2420                let option_id = SharedString::from(option.id.0.clone());
2421                Button::new((option_id, entry_ix), option.name.clone())
2422                    .map(|this| match option.kind {
2423                        acp::PermissionOptionKind::AllowOnce => {
2424                            this.icon(IconName::Check).icon_color(Color::Success)
2425                        }
2426                        acp::PermissionOptionKind::AllowAlways => {
2427                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
2428                        }
2429                        acp::PermissionOptionKind::RejectOnce => {
2430                            this.icon(IconName::Close).icon_color(Color::Error)
2431                        }
2432                        acp::PermissionOptionKind::RejectAlways => {
2433                            this.icon(IconName::Close).icon_color(Color::Error)
2434                        }
2435                    })
2436                    .icon_position(IconPosition::Start)
2437                    .icon_size(IconSize::XSmall)
2438                    .label_size(LabelSize::Small)
2439                    .on_click(cx.listener({
2440                        let tool_call_id = tool_call_id.clone();
2441                        let option_id = option.id.clone();
2442                        let option_kind = option.kind;
2443                        move |this, _, window, cx| {
2444                            this.authorize_tool_call(
2445                                tool_call_id.clone(),
2446                                option_id.clone(),
2447                                option_kind,
2448                                window,
2449                                cx,
2450                            );
2451                        }
2452                    }))
2453            })))
2454    }
2455
2456    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2457        let bar = |n: u64, width_class: &str| {
2458            let bg_color = cx.theme().colors().element_active;
2459            let base = h_flex().h_1().rounded_full();
2460
2461            let modified = match width_class {
2462                "w_4_5" => base.w_3_4(),
2463                "w_1_4" => base.w_1_4(),
2464                "w_2_4" => base.w_2_4(),
2465                "w_3_5" => base.w_3_5(),
2466                "w_2_5" => base.w_2_5(),
2467                _ => base.w_1_2(),
2468            };
2469
2470            modified.with_animation(
2471                ElementId::Integer(n),
2472                Animation::new(Duration::from_secs(2)).repeat(),
2473                move |tab, delta| {
2474                    let delta = (delta - 0.15 * n as f32) / 0.7;
2475                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
2476                    let delta = ease_in_out(delta.clamp(0., 1.));
2477                    let delta = 0.1 + 0.9 * delta;
2478
2479                    tab.bg(bg_color.opacity(delta))
2480                },
2481            )
2482        };
2483
2484        v_flex()
2485            .p_3()
2486            .gap_1()
2487            .rounded_b_md()
2488            .bg(cx.theme().colors().editor_background)
2489            .child(bar(0, "w_4_5"))
2490            .child(bar(1, "w_1_4"))
2491            .child(bar(2, "w_2_4"))
2492            .child(bar(3, "w_3_5"))
2493            .child(bar(4, "w_2_5"))
2494            .into_any_element()
2495    }
2496
2497    fn render_diff_editor(
2498        &self,
2499        entry_ix: usize,
2500        diff: &Entity<acp_thread::Diff>,
2501        tool_call: &ToolCall,
2502        cx: &Context<Self>,
2503    ) -> AnyElement {
2504        let tool_progress = matches!(
2505            &tool_call.status,
2506            ToolCallStatus::InProgress | ToolCallStatus::Pending
2507        );
2508
2509        v_flex()
2510            .h_full()
2511            .border_t_1()
2512            .border_color(self.tool_card_border_color(cx))
2513            .child(
2514                if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2515                    && let Some(editor) = entry.editor_for_diff(diff)
2516                    && diff.read(cx).has_revealed_range(cx)
2517                {
2518                    editor.into_any_element()
2519                } else if tool_progress && self.as_native_connection(cx).is_some() {
2520                    self.render_diff_loading(cx)
2521                } else {
2522                    Empty.into_any()
2523                },
2524            )
2525            .into_any()
2526    }
2527
2528    fn render_terminal_tool_call(
2529        &self,
2530        entry_ix: usize,
2531        terminal: &Entity<acp_thread::Terminal>,
2532        tool_call: &ToolCall,
2533        window: &Window,
2534        cx: &Context<Self>,
2535    ) -> AnyElement {
2536        let terminal_data = terminal.read(cx);
2537        let working_dir = terminal_data.working_dir();
2538        let command = terminal_data.command();
2539        let started_at = terminal_data.started_at();
2540
2541        let tool_failed = matches!(
2542            &tool_call.status,
2543            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2544        );
2545
2546        let output = terminal_data.output();
2547        let command_finished = output.is_some();
2548        let truncated_output =
2549            output.is_some_and(|output| output.original_content_len > output.content.len());
2550        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2551
2552        let command_failed = command_finished
2553            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2554
2555        let time_elapsed = if let Some(output) = output {
2556            output.ended_at.duration_since(started_at)
2557        } else {
2558            started_at.elapsed()
2559        };
2560
2561        let header_id =
2562            SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2563        let header_group = SharedString::from(format!(
2564            "terminal-tool-header-group-{}",
2565            terminal.entity_id()
2566        ));
2567        let header_bg = cx
2568            .theme()
2569            .colors()
2570            .element_background
2571            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2572        let border_color = cx.theme().colors().border.opacity(0.6);
2573
2574        let working_dir = working_dir
2575            .as_ref()
2576            .map(|path| format!("{}", path.display()))
2577            .unwrap_or_else(|| "current directory".to_string());
2578
2579        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2580
2581        let header = h_flex()
2582            .id(header_id)
2583            .flex_none()
2584            .gap_1()
2585            .justify_between()
2586            .rounded_t_md()
2587            .child(
2588                div()
2589                    .id(("command-target-path", terminal.entity_id()))
2590                    .w_full()
2591                    .max_w_full()
2592                    .overflow_x_scroll()
2593                    .child(
2594                        Label::new(working_dir)
2595                            .buffer_font(cx)
2596                            .size(LabelSize::XSmall)
2597                            .color(Color::Muted),
2598                    ),
2599            )
2600            .when(!command_finished, |header| {
2601                header
2602                    .gap_1p5()
2603                    .child(
2604                        Button::new(
2605                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2606                            "Stop",
2607                        )
2608                        .icon(IconName::Stop)
2609                        .icon_position(IconPosition::Start)
2610                        .icon_size(IconSize::Small)
2611                        .icon_color(Color::Error)
2612                        .label_size(LabelSize::Small)
2613                        .tooltip(move |window, cx| {
2614                            Tooltip::with_meta(
2615                                "Stop This Command",
2616                                None,
2617                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2618                                window,
2619                                cx,
2620                            )
2621                        })
2622                        .on_click({
2623                            let terminal = terminal.clone();
2624                            cx.listener(move |_this, _event, _window, cx| {
2625                                let inner_terminal = terminal.read(cx).inner().clone();
2626                                inner_terminal.update(cx, |inner_terminal, _cx| {
2627                                    inner_terminal.kill_active_task();
2628                                });
2629                            })
2630                        }),
2631                    )
2632                    .child(Divider::vertical())
2633                    .child(
2634                        Icon::new(IconName::ArrowCircle)
2635                            .size(IconSize::XSmall)
2636                            .color(Color::Info)
2637                            .with_rotate_animation(2)
2638                    )
2639            })
2640            .child(
2641                Disclosure::new(
2642                    SharedString::from(format!(
2643                        "terminal-tool-disclosure-{}",
2644                        terminal.entity_id()
2645                    )),
2646                    is_expanded,
2647                )
2648                .opened_icon(IconName::ChevronUp)
2649                .closed_icon(IconName::ChevronDown)
2650                .visible_on_hover(&header_group)
2651                .on_click(cx.listener({
2652                    let id = tool_call.id.clone();
2653                    move |this, _event, _window, _cx| {
2654                        if is_expanded {
2655                            this.expanded_tool_calls.remove(&id);
2656                        } else {
2657                            this.expanded_tool_calls.insert(id.clone());
2658                        }
2659                    }
2660                })),
2661            )
2662            .when(truncated_output, |header| {
2663                let tooltip = if let Some(output) = output {
2664                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2665                       format!("Output exceeded terminal max lines and was \
2666                            truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
2667                    } else {
2668                        format!(
2669                            "Output is {} long, and to avoid unexpected token usage, \
2670                                only {} was sent back to the agent.",
2671                            format_file_size(output.original_content_len as u64, true),
2672                             format_file_size(output.content.len() as u64, true)
2673                        )
2674                    }
2675                } else {
2676                    "Output was truncated".to_string()
2677                };
2678
2679                header.child(
2680                    h_flex()
2681                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
2682                        .gap_1()
2683                        .child(
2684                            Icon::new(IconName::Info)
2685                                .size(IconSize::XSmall)
2686                                .color(Color::Ignored),
2687                        )
2688                        .child(
2689                            Label::new("Truncated")
2690                                .color(Color::Muted)
2691                                .size(LabelSize::XSmall),
2692                        )
2693                        .tooltip(Tooltip::text(tooltip)),
2694                )
2695            })
2696            .when(time_elapsed > Duration::from_secs(10), |header| {
2697                header.child(
2698                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
2699                        .buffer_font(cx)
2700                        .color(Color::Muted)
2701                        .size(LabelSize::XSmall),
2702                )
2703            })
2704            .when(tool_failed || command_failed, |header| {
2705                header.child(
2706                    div()
2707                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2708                        .child(
2709                            Icon::new(IconName::Close)
2710                                .size(IconSize::Small)
2711                                .color(Color::Error),
2712                        )
2713                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
2714                            this.tooltip(Tooltip::text(format!(
2715                                "Exited with code {}",
2716                                status.code().unwrap_or(-1),
2717                            )))
2718                        }),
2719                )
2720            });
2721
2722        let terminal_view = self
2723            .entry_view_state
2724            .read(cx)
2725            .entry(entry_ix)
2726            .and_then(|entry| entry.terminal(terminal));
2727        let show_output = is_expanded && terminal_view.is_some();
2728
2729        v_flex()
2730            .my_1p5()
2731            .mx_5()
2732            .border_1()
2733            .when(tool_failed || command_failed, |card| card.border_dashed())
2734            .border_color(border_color)
2735            .rounded_md()
2736            .overflow_hidden()
2737            .child(
2738                v_flex()
2739                    .group(&header_group)
2740                    .py_1p5()
2741                    .pr_1p5()
2742                    .pl_2()
2743                    .gap_0p5()
2744                    .bg(header_bg)
2745                    .text_xs()
2746                    .child(header)
2747                    .child(
2748                        MarkdownElement::new(
2749                            command.clone(),
2750                            terminal_command_markdown_style(window, cx),
2751                        )
2752                        .code_block_renderer(
2753                            markdown::CodeBlockRenderer::Default {
2754                                copy_button: false,
2755                                copy_button_on_hover: true,
2756                                border: false,
2757                            },
2758                        ),
2759                    ),
2760            )
2761            .when(show_output, |this| {
2762                this.child(
2763                    div()
2764                        .pt_2()
2765                        .border_t_1()
2766                        .when(tool_failed || command_failed, |card| card.border_dashed())
2767                        .border_color(border_color)
2768                        .bg(cx.theme().colors().editor_background)
2769                        .rounded_b_md()
2770                        .text_ui_sm(cx)
2771                        .h_full()
2772                        .children(terminal_view.map(|terminal_view| {
2773                            if terminal_view
2774                                .read(cx)
2775                                .content_mode(window, cx)
2776                                .is_scrollable()
2777                            {
2778                                div().h_72().child(terminal_view).into_any_element()
2779                            } else {
2780                                terminal_view.into_any_element()
2781                            }
2782                        })),
2783                )
2784            })
2785            .into_any()
2786    }
2787
2788    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2789        let project_context = self
2790            .as_native_thread(cx)?
2791            .read(cx)
2792            .project_context()
2793            .read(cx);
2794
2795        let user_rules_text = if project_context.user_rules.is_empty() {
2796            None
2797        } else if project_context.user_rules.len() == 1 {
2798            let user_rules = &project_context.user_rules[0];
2799
2800            match user_rules.title.as_ref() {
2801                Some(title) => Some(format!("Using \"{title}\" user rule")),
2802                None => Some("Using user rule".into()),
2803            }
2804        } else {
2805            Some(format!(
2806                "Using {} user rules",
2807                project_context.user_rules.len()
2808            ))
2809        };
2810
2811        let first_user_rules_id = project_context
2812            .user_rules
2813            .first()
2814            .map(|user_rules| user_rules.uuid.0);
2815
2816        let rules_files = project_context
2817            .worktrees
2818            .iter()
2819            .filter_map(|worktree| worktree.rules_file.as_ref())
2820            .collect::<Vec<_>>();
2821
2822        let rules_file_text = match rules_files.as_slice() {
2823            &[] => None,
2824            &[rules_file] => Some(format!(
2825                "Using project {:?} file",
2826                rules_file.path_in_worktree
2827            )),
2828            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2829        };
2830
2831        if user_rules_text.is_none() && rules_file_text.is_none() {
2832            return None;
2833        }
2834
2835        let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2836
2837        Some(
2838            h_flex()
2839                .px_2p5()
2840                .child(
2841                    Icon::new(IconName::Attach)
2842                        .size(IconSize::XSmall)
2843                        .color(Color::Disabled),
2844                )
2845                .when_some(user_rules_text, |parent, user_rules_text| {
2846                    parent.child(
2847                        h_flex()
2848                            .id("user-rules")
2849                            .ml_1()
2850                            .mr_1p5()
2851                            .child(
2852                                Label::new(user_rules_text)
2853                                    .size(LabelSize::XSmall)
2854                                    .color(Color::Muted)
2855                                    .truncate(),
2856                            )
2857                            .hover(|s| s.bg(cx.theme().colors().element_hover))
2858                            .tooltip(Tooltip::text("View User Rules"))
2859                            .on_click(move |_event, window, cx| {
2860                                window.dispatch_action(
2861                                    Box::new(OpenRulesLibrary {
2862                                        prompt_to_select: first_user_rules_id,
2863                                    }),
2864                                    cx,
2865                                )
2866                            }),
2867                    )
2868                })
2869                .when(has_both, |this| {
2870                    this.child(
2871                        Label::new("")
2872                            .size(LabelSize::XSmall)
2873                            .color(Color::Disabled),
2874                    )
2875                })
2876                .when_some(rules_file_text, |parent, rules_file_text| {
2877                    parent.child(
2878                        h_flex()
2879                            .id("project-rules")
2880                            .ml_1p5()
2881                            .child(
2882                                Label::new(rules_file_text)
2883                                    .size(LabelSize::XSmall)
2884                                    .color(Color::Muted),
2885                            )
2886                            .hover(|s| s.bg(cx.theme().colors().element_hover))
2887                            .tooltip(Tooltip::text("View Project Rules"))
2888                            .on_click(cx.listener(Self::handle_open_rules)),
2889                    )
2890                })
2891                .into_any(),
2892        )
2893    }
2894
2895    fn render_empty_state_section_header(
2896        &self,
2897        label: impl Into<SharedString>,
2898        action_slot: Option<AnyElement>,
2899        cx: &mut Context<Self>,
2900    ) -> impl IntoElement {
2901        div().pl_1().pr_1p5().child(
2902            h_flex()
2903                .mt_2()
2904                .pl_1p5()
2905                .pb_1()
2906                .w_full()
2907                .justify_between()
2908                .border_b_1()
2909                .border_color(cx.theme().colors().border_variant)
2910                .child(
2911                    Label::new(label.into())
2912                        .size(LabelSize::Small)
2913                        .color(Color::Muted),
2914                )
2915                .children(action_slot),
2916        )
2917    }
2918
2919    fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2920        let render_history = self
2921            .agent
2922            .clone()
2923            .downcast::<agent2::NativeAgentServer>()
2924            .is_some()
2925            && self
2926                .history_store
2927                .update(cx, |history_store, cx| !history_store.is_empty(cx));
2928
2929        v_flex()
2930            .size_full()
2931            .when(render_history, |this| {
2932                let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
2933                    history_store.entries().take(3).collect()
2934                });
2935                this.justify_end().child(
2936                    v_flex()
2937                        .child(
2938                            self.render_empty_state_section_header(
2939                                "Recent",
2940                                Some(
2941                                    Button::new("view-history", "View All")
2942                                        .style(ButtonStyle::Subtle)
2943                                        .label_size(LabelSize::Small)
2944                                        .key_binding(
2945                                            KeyBinding::for_action_in(
2946                                                &OpenHistory,
2947                                                &self.focus_handle(cx),
2948                                                window,
2949                                                cx,
2950                                            )
2951                                            .map(|kb| kb.size(rems_from_px(12.))),
2952                                        )
2953                                        .on_click(move |_event, window, cx| {
2954                                            window.dispatch_action(OpenHistory.boxed_clone(), cx);
2955                                        })
2956                                        .into_any_element(),
2957                                ),
2958                                cx,
2959                            ),
2960                        )
2961                        .child(
2962                            v_flex().p_1().pr_1p5().gap_1().children(
2963                                recent_history
2964                                    .into_iter()
2965                                    .enumerate()
2966                                    .map(|(index, entry)| {
2967                                        // TODO: Add keyboard navigation.
2968                                        let is_hovered =
2969                                            self.hovered_recent_history_item == Some(index);
2970                                        crate::acp::thread_history::AcpHistoryEntryElement::new(
2971                                            entry,
2972                                            cx.entity().downgrade(),
2973                                        )
2974                                        .hovered(is_hovered)
2975                                        .on_hover(cx.listener(
2976                                            move |this, is_hovered, _window, cx| {
2977                                                if *is_hovered {
2978                                                    this.hovered_recent_history_item = Some(index);
2979                                                } else if this.hovered_recent_history_item
2980                                                    == Some(index)
2981                                                {
2982                                                    this.hovered_recent_history_item = None;
2983                                                }
2984                                                cx.notify();
2985                                            },
2986                                        ))
2987                                        .into_any_element()
2988                                    }),
2989                            ),
2990                        ),
2991                )
2992            })
2993            .into_any()
2994    }
2995
2996    fn render_auth_required_state(
2997        &self,
2998        connection: &Rc<dyn AgentConnection>,
2999        description: Option<&Entity<Markdown>>,
3000        configuration_view: Option<&AnyView>,
3001        pending_auth_method: Option<&acp::AuthMethodId>,
3002        window: &mut Window,
3003        cx: &Context<Self>,
3004    ) -> Div {
3005        let show_description =
3006            configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3007
3008        v_flex().flex_1().size_full().justify_end().child(
3009            v_flex()
3010                .p_2()
3011                .pr_3()
3012                .w_full()
3013                .gap_1()
3014                .border_t_1()
3015                .border_color(cx.theme().colors().border)
3016                .bg(cx.theme().status().warning.opacity(0.04))
3017                .child(
3018                    h_flex()
3019                        .gap_1p5()
3020                        .child(
3021                            Icon::new(IconName::Warning)
3022                                .color(Color::Warning)
3023                                .size(IconSize::Small),
3024                        )
3025                        .child(Label::new("Authentication Required").size(LabelSize::Small)),
3026                )
3027                .children(description.map(|desc| {
3028                    div().text_ui(cx).child(self.render_markdown(
3029                        desc.clone(),
3030                        default_markdown_style(false, false, window, cx),
3031                    ))
3032                }))
3033                .children(
3034                    configuration_view
3035                        .cloned()
3036                        .map(|view| div().w_full().child(view)),
3037                )
3038                .when(
3039                    show_description,
3040                    |el| {
3041                        el.child(
3042                            Label::new(format!(
3043                                "You are not currently authenticated with {}. Please choose one of the following options:",
3044                                self.agent.name()
3045                            ))
3046                            .size(LabelSize::Small)
3047                            .color(Color::Muted)
3048                            .mb_1()
3049                            .ml_5(),
3050                        )
3051                    },
3052                )
3053                .when_some(pending_auth_method, |el, _| {
3054                    el.child(
3055                        h_flex()
3056                            .py_4()
3057                            .w_full()
3058                            .justify_center()
3059                            .gap_1()
3060                            .child(
3061                                Icon::new(IconName::ArrowCircle)
3062                                    .size(IconSize::Small)
3063                                    .color(Color::Muted)
3064                                    .with_rotate_animation(2)
3065                            )
3066                            .child(Label::new("Authenticating…").size(LabelSize::Small)),
3067                    )
3068                })
3069                .when(!connection.auth_methods().is_empty(), |this| {
3070                    this.child(
3071                        h_flex()
3072                            .justify_end()
3073                            .flex_wrap()
3074                            .gap_1()
3075                            .when(!show_description, |this| {
3076                                this.border_t_1()
3077                                    .mt_1()
3078                                    .pt_2()
3079                                    .border_color(cx.theme().colors().border.opacity(0.8))
3080                            })
3081                            .children(
3082                                connection
3083                                    .auth_methods()
3084                                    .iter()
3085                                    .enumerate()
3086                                    .rev()
3087                                    .map(|(ix, method)| {
3088                                        Button::new(
3089                                            SharedString::from(method.id.0.clone()),
3090                                            method.name.clone(),
3091                                        )
3092                                        .when(ix == 0, |el| {
3093                                            el.style(ButtonStyle::Tinted(ui::TintColor::Warning))
3094                                        })
3095                                        .label_size(LabelSize::Small)
3096                                        .on_click({
3097                                            let method_id = method.id.clone();
3098                                            cx.listener(move |this, _, window, cx| {
3099                                                telemetry::event!(
3100                                                    "Authenticate Agent Started",
3101                                                    agent = this.agent.telemetry_id(),
3102                                                    method = method_id
3103                                                );
3104
3105                                                this.authenticate(method_id.clone(), window, cx)
3106                                            })
3107                                        })
3108                                    }),
3109                            ),
3110                    )
3111                })
3112
3113        )
3114    }
3115
3116    fn render_load_error(
3117        &self,
3118        e: &LoadError,
3119        window: &mut Window,
3120        cx: &mut Context<Self>,
3121    ) -> AnyElement {
3122        let (title, message, action_slot): (_, SharedString, _) = match e {
3123            LoadError::Unsupported {
3124                command: path,
3125                current_version,
3126                minimum_version,
3127            } => {
3128                return self.render_unsupported(path, current_version, minimum_version, window, cx);
3129            }
3130            LoadError::FailedToInstall(msg) => (
3131                "Failed to Install",
3132                msg.into(),
3133                Some(self.create_copy_button(msg.to_string()).into_any_element()),
3134            ),
3135            LoadError::Exited { status } => (
3136                "Failed to Launch",
3137                format!("Server exited with status {status}").into(),
3138                None,
3139            ),
3140            LoadError::Other(msg) => (
3141                "Failed to Launch",
3142                msg.into(),
3143                Some(self.create_copy_button(msg.to_string()).into_any_element()),
3144            ),
3145        };
3146
3147        Callout::new()
3148            .severity(Severity::Error)
3149            .icon(IconName::XCircleFilled)
3150            .title(title)
3151            .description(message)
3152            .actions_slot(div().children(action_slot))
3153            .into_any_element()
3154    }
3155
3156    fn render_unsupported(
3157        &self,
3158        path: &SharedString,
3159        version: &SharedString,
3160        minimum_version: &SharedString,
3161        _window: &mut Window,
3162        cx: &mut Context<Self>,
3163    ) -> AnyElement {
3164        let (heading_label, description_label) = (
3165            format!("Upgrade {} to work with Zed", self.agent.name()),
3166            if version.is_empty() {
3167                format!(
3168                    "Currently using {}, which does not report a valid --version",
3169                    path,
3170                )
3171            } else {
3172                format!(
3173                    "Currently using {}, which is only version {} (need at least {minimum_version})",
3174                    path, version
3175                )
3176            },
3177        );
3178
3179        v_flex()
3180            .w_full()
3181            .p_3p5()
3182            .gap_2p5()
3183            .border_t_1()
3184            .border_color(cx.theme().colors().border)
3185            .bg(linear_gradient(
3186                180.,
3187                linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3188                linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3189            ))
3190            .child(
3191                v_flex().gap_0p5().child(Label::new(heading_label)).child(
3192                    Label::new(description_label)
3193                        .size(LabelSize::Small)
3194                        .color(Color::Muted),
3195                ),
3196            )
3197            .into_any_element()
3198    }
3199
3200    fn render_activity_bar(
3201        &self,
3202        thread_entity: &Entity<AcpThread>,
3203        window: &mut Window,
3204        cx: &Context<Self>,
3205    ) -> Option<AnyElement> {
3206        let thread = thread_entity.read(cx);
3207        let action_log = thread.action_log();
3208        let changed_buffers = action_log.read(cx).changed_buffers(cx);
3209        let plan = thread.plan();
3210
3211        if changed_buffers.is_empty() && plan.is_empty() {
3212            return None;
3213        }
3214
3215        let editor_bg_color = cx.theme().colors().editor_background;
3216        let active_color = cx.theme().colors().element_selected;
3217        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
3218
3219        // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3220        // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3221        // be, which blocks you from being able to accept or reject edits. This switches the
3222        // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3223        // block you from using the panel.
3224        let pending_edits = false;
3225
3226        v_flex()
3227            .mt_1()
3228            .mx_2()
3229            .bg(bg_edit_files_disclosure)
3230            .border_1()
3231            .border_b_0()
3232            .border_color(cx.theme().colors().border)
3233            .rounded_t_md()
3234            .shadow(vec![gpui::BoxShadow {
3235                color: gpui::black().opacity(0.15),
3236                offset: point(px(1.), px(-1.)),
3237                blur_radius: px(3.),
3238                spread_radius: px(0.),
3239            }])
3240            .when(!plan.is_empty(), |this| {
3241                this.child(self.render_plan_summary(plan, window, cx))
3242                    .when(self.plan_expanded, |parent| {
3243                        parent.child(self.render_plan_entries(plan, window, cx))
3244                    })
3245            })
3246            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3247                this.child(Divider::horizontal().color(DividerColor::Border))
3248            })
3249            .when(!changed_buffers.is_empty(), |this| {
3250                this.child(self.render_edits_summary(
3251                    &changed_buffers,
3252                    self.edits_expanded,
3253                    pending_edits,
3254                    window,
3255                    cx,
3256                ))
3257                .when(self.edits_expanded, |parent| {
3258                    parent.child(self.render_edited_files(
3259                        action_log,
3260                        &changed_buffers,
3261                        pending_edits,
3262                        cx,
3263                    ))
3264                })
3265            })
3266            .into_any()
3267            .into()
3268    }
3269
3270    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3271        let stats = plan.stats();
3272
3273        let title = if let Some(entry) = stats.in_progress_entry
3274            && !self.plan_expanded
3275        {
3276            h_flex()
3277                .w_full()
3278                .cursor_default()
3279                .gap_1()
3280                .text_xs()
3281                .text_color(cx.theme().colors().text_muted)
3282                .justify_between()
3283                .child(
3284                    h_flex()
3285                        .gap_1()
3286                        .child(
3287                            Label::new("Current:")
3288                                .size(LabelSize::Small)
3289                                .color(Color::Muted),
3290                        )
3291                        .child(MarkdownElement::new(
3292                            entry.content.clone(),
3293                            plan_label_markdown_style(&entry.status, window, cx),
3294                        )),
3295                )
3296                .when(stats.pending > 0, |this| {
3297                    this.child(
3298                        Label::new(format!("{} left", stats.pending))
3299                            .size(LabelSize::Small)
3300                            .color(Color::Muted)
3301                            .mr_1(),
3302                    )
3303                })
3304        } else {
3305            let status_label = if stats.pending == 0 {
3306                "All Done".to_string()
3307            } else if stats.completed == 0 {
3308                format!("{} Tasks", plan.entries.len())
3309            } else {
3310                format!("{}/{}", stats.completed, plan.entries.len())
3311            };
3312
3313            h_flex()
3314                .w_full()
3315                .gap_1()
3316                .justify_between()
3317                .child(
3318                    Label::new("Plan")
3319                        .size(LabelSize::Small)
3320                        .color(Color::Muted),
3321                )
3322                .child(
3323                    Label::new(status_label)
3324                        .size(LabelSize::Small)
3325                        .color(Color::Muted)
3326                        .mr_1(),
3327                )
3328        };
3329
3330        h_flex()
3331            .p_1()
3332            .justify_between()
3333            .when(self.plan_expanded, |this| {
3334                this.border_b_1().border_color(cx.theme().colors().border)
3335            })
3336            .child(
3337                h_flex()
3338                    .id("plan_summary")
3339                    .w_full()
3340                    .gap_1()
3341                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3342                    .child(title)
3343                    .on_click(cx.listener(|this, _, _, cx| {
3344                        this.plan_expanded = !this.plan_expanded;
3345                        cx.notify();
3346                    })),
3347            )
3348    }
3349
3350    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3351        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3352            let element = h_flex()
3353                .py_1()
3354                .px_2()
3355                .gap_2()
3356                .justify_between()
3357                .bg(cx.theme().colors().editor_background)
3358                .when(index < plan.entries.len() - 1, |parent| {
3359                    parent.border_color(cx.theme().colors().border).border_b_1()
3360                })
3361                .child(
3362                    h_flex()
3363                        .id(("plan_entry", index))
3364                        .gap_1p5()
3365                        .max_w_full()
3366                        .overflow_x_scroll()
3367                        .text_xs()
3368                        .text_color(cx.theme().colors().text_muted)
3369                        .child(match entry.status {
3370                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3371                                .size(IconSize::Small)
3372                                .color(Color::Muted)
3373                                .into_any_element(),
3374                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3375                                .size(IconSize::Small)
3376                                .color(Color::Accent)
3377                                .with_rotate_animation(2)
3378                                .into_any_element(),
3379                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3380                                .size(IconSize::Small)
3381                                .color(Color::Success)
3382                                .into_any_element(),
3383                        })
3384                        .child(MarkdownElement::new(
3385                            entry.content.clone(),
3386                            plan_label_markdown_style(&entry.status, window, cx),
3387                        )),
3388                );
3389
3390            Some(element)
3391        }))
3392    }
3393
3394    fn render_edits_summary(
3395        &self,
3396        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3397        expanded: bool,
3398        pending_edits: bool,
3399        window: &mut Window,
3400        cx: &Context<Self>,
3401    ) -> Div {
3402        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3403
3404        let focus_handle = self.focus_handle(cx);
3405
3406        h_flex()
3407            .p_1()
3408            .justify_between()
3409            .flex_wrap()
3410            .when(expanded, |this| {
3411                this.border_b_1().border_color(cx.theme().colors().border)
3412            })
3413            .child(
3414                h_flex()
3415                    .id("edits-container")
3416                    .gap_1()
3417                    .child(Disclosure::new("edits-disclosure", expanded))
3418                    .map(|this| {
3419                        if pending_edits {
3420                            this.child(
3421                                Label::new(format!(
3422                                    "Editing {} {}",
3423                                    changed_buffers.len(),
3424                                    if changed_buffers.len() == 1 {
3425                                        "file"
3426                                    } else {
3427                                        "files"
3428                                    }
3429                                ))
3430                                .color(Color::Muted)
3431                                .size(LabelSize::Small)
3432                                .with_animation(
3433                                    "edit-label",
3434                                    Animation::new(Duration::from_secs(2))
3435                                        .repeat()
3436                                        .with_easing(pulsating_between(0.3, 0.7)),
3437                                    |label, delta| label.alpha(delta),
3438                                ),
3439                            )
3440                        } else {
3441                            this.child(
3442                                Label::new("Edits")
3443                                    .size(LabelSize::Small)
3444                                    .color(Color::Muted),
3445                            )
3446                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
3447                            .child(
3448                                Label::new(format!(
3449                                    "{} {}",
3450                                    changed_buffers.len(),
3451                                    if changed_buffers.len() == 1 {
3452                                        "file"
3453                                    } else {
3454                                        "files"
3455                                    }
3456                                ))
3457                                .size(LabelSize::Small)
3458                                .color(Color::Muted),
3459                            )
3460                        }
3461                    })
3462                    .on_click(cx.listener(|this, _, _, cx| {
3463                        this.edits_expanded = !this.edits_expanded;
3464                        cx.notify();
3465                    })),
3466            )
3467            .child(
3468                h_flex()
3469                    .gap_1()
3470                    .child(
3471                        IconButton::new("review-changes", IconName::ListTodo)
3472                            .icon_size(IconSize::Small)
3473                            .tooltip({
3474                                let focus_handle = focus_handle.clone();
3475                                move |window, cx| {
3476                                    Tooltip::for_action_in(
3477                                        "Review Changes",
3478                                        &OpenAgentDiff,
3479                                        &focus_handle,
3480                                        window,
3481                                        cx,
3482                                    )
3483                                }
3484                            })
3485                            .on_click(cx.listener(|_, _, window, cx| {
3486                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3487                            })),
3488                    )
3489                    .child(Divider::vertical().color(DividerColor::Border))
3490                    .child(
3491                        Button::new("reject-all-changes", "Reject All")
3492                            .label_size(LabelSize::Small)
3493                            .disabled(pending_edits)
3494                            .when(pending_edits, |this| {
3495                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3496                            })
3497                            .key_binding(
3498                                KeyBinding::for_action_in(
3499                                    &RejectAll,
3500                                    &focus_handle.clone(),
3501                                    window,
3502                                    cx,
3503                                )
3504                                .map(|kb| kb.size(rems_from_px(10.))),
3505                            )
3506                            .on_click(cx.listener(move |this, _, window, cx| {
3507                                this.reject_all(&RejectAll, window, cx);
3508                            })),
3509                    )
3510                    .child(
3511                        Button::new("keep-all-changes", "Keep All")
3512                            .label_size(LabelSize::Small)
3513                            .disabled(pending_edits)
3514                            .when(pending_edits, |this| {
3515                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3516                            })
3517                            .key_binding(
3518                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3519                                    .map(|kb| kb.size(rems_from_px(10.))),
3520                            )
3521                            .on_click(cx.listener(move |this, _, window, cx| {
3522                                this.keep_all(&KeepAll, window, cx);
3523                            })),
3524                    ),
3525            )
3526    }
3527
3528    fn render_edited_files(
3529        &self,
3530        action_log: &Entity<ActionLog>,
3531        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3532        pending_edits: bool,
3533        cx: &Context<Self>,
3534    ) -> Div {
3535        let editor_bg_color = cx.theme().colors().editor_background;
3536
3537        v_flex().children(changed_buffers.iter().enumerate().flat_map(
3538            |(index, (buffer, _diff))| {
3539                let file = buffer.read(cx).file()?;
3540                let path = file.path();
3541
3542                let file_path = path.parent().and_then(|parent| {
3543                    let parent_str = parent.to_string_lossy();
3544
3545                    if parent_str.is_empty() {
3546                        None
3547                    } else {
3548                        Some(
3549                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3550                                .color(Color::Muted)
3551                                .size(LabelSize::XSmall)
3552                                .buffer_font(cx),
3553                        )
3554                    }
3555                });
3556
3557                let file_name = path.file_name().map(|name| {
3558                    Label::new(name.to_string_lossy().to_string())
3559                        .size(LabelSize::XSmall)
3560                        .buffer_font(cx)
3561                });
3562
3563                let file_icon = FileIcons::get_icon(path, cx)
3564                    .map(Icon::from_path)
3565                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3566                    .unwrap_or_else(|| {
3567                        Icon::new(IconName::File)
3568                            .color(Color::Muted)
3569                            .size(IconSize::Small)
3570                    });
3571
3572                let overlay_gradient = linear_gradient(
3573                    90.,
3574                    linear_color_stop(editor_bg_color, 1.),
3575                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3576                );
3577
3578                let element = h_flex()
3579                    .group("edited-code")
3580                    .id(("file-container", index))
3581                    .py_1()
3582                    .pl_2()
3583                    .pr_1()
3584                    .gap_2()
3585                    .justify_between()
3586                    .bg(editor_bg_color)
3587                    .when(index < changed_buffers.len() - 1, |parent| {
3588                        parent.border_color(cx.theme().colors().border).border_b_1()
3589                    })
3590                    .child(
3591                        h_flex()
3592                            .relative()
3593                            .id(("file-name", index))
3594                            .pr_8()
3595                            .gap_1p5()
3596                            .max_w_full()
3597                            .overflow_x_scroll()
3598                            .child(file_icon)
3599                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3600                            .child(
3601                                div()
3602                                    .absolute()
3603                                    .h_full()
3604                                    .w_12()
3605                                    .top_0()
3606                                    .bottom_0()
3607                                    .right_0()
3608                                    .bg(overlay_gradient),
3609                            )
3610                            .on_click({
3611                                let buffer = buffer.clone();
3612                                cx.listener(move |this, _, window, cx| {
3613                                    this.open_edited_buffer(&buffer, window, cx);
3614                                })
3615                            }),
3616                    )
3617                    .child(
3618                        h_flex()
3619                            .gap_1()
3620                            .visible_on_hover("edited-code")
3621                            .child(
3622                                Button::new("review", "Review")
3623                                    .label_size(LabelSize::Small)
3624                                    .on_click({
3625                                        let buffer = buffer.clone();
3626                                        cx.listener(move |this, _, window, cx| {
3627                                            this.open_edited_buffer(&buffer, window, cx);
3628                                        })
3629                                    }),
3630                            )
3631                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3632                            .child(
3633                                Button::new("reject-file", "Reject")
3634                                    .label_size(LabelSize::Small)
3635                                    .disabled(pending_edits)
3636                                    .on_click({
3637                                        let buffer = buffer.clone();
3638                                        let action_log = action_log.clone();
3639                                        move |_, _, cx| {
3640                                            action_log.update(cx, |action_log, cx| {
3641                                                action_log
3642                                                    .reject_edits_in_ranges(
3643                                                        buffer.clone(),
3644                                                        vec![Anchor::MIN..Anchor::MAX],
3645                                                        cx,
3646                                                    )
3647                                                    .detach_and_log_err(cx);
3648                                            })
3649                                        }
3650                                    }),
3651                            )
3652                            .child(
3653                                Button::new("keep-file", "Keep")
3654                                    .label_size(LabelSize::Small)
3655                                    .disabled(pending_edits)
3656                                    .on_click({
3657                                        let buffer = buffer.clone();
3658                                        let action_log = action_log.clone();
3659                                        move |_, _, cx| {
3660                                            action_log.update(cx, |action_log, cx| {
3661                                                action_log.keep_edits_in_range(
3662                                                    buffer.clone(),
3663                                                    Anchor::MIN..Anchor::MAX,
3664                                                    cx,
3665                                                );
3666                                            })
3667                                        }
3668                                    }),
3669                            ),
3670                    );
3671
3672                Some(element)
3673            },
3674        ))
3675    }
3676
3677    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3678        let focus_handle = self.message_editor.focus_handle(cx);
3679        let editor_bg_color = cx.theme().colors().editor_background;
3680        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3681            (IconName::Minimize, "Minimize Message Editor")
3682        } else {
3683            (IconName::Maximize, "Expand Message Editor")
3684        };
3685
3686        let backdrop = div()
3687            .size_full()
3688            .absolute()
3689            .inset_0()
3690            .bg(cx.theme().colors().panel_background)
3691            .opacity(0.8)
3692            .block_mouse_except_scroll();
3693
3694        let enable_editor = match self.thread_state {
3695            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3696            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3697        };
3698
3699        v_flex()
3700            .on_action(cx.listener(Self::expand_message_editor))
3701            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3702                if let Some(profile_selector) = this.profile_selector.as_ref() {
3703                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3704                }
3705            }))
3706            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3707                if let Some(model_selector) = this.model_selector.as_ref() {
3708                    model_selector
3709                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3710                }
3711            }))
3712            .p_2()
3713            .gap_2()
3714            .border_t_1()
3715            .border_color(cx.theme().colors().border)
3716            .bg(editor_bg_color)
3717            .when(self.editor_expanded, |this| {
3718                this.h(vh(0.8, window)).size_full().justify_between()
3719            })
3720            .child(
3721                v_flex()
3722                    .relative()
3723                    .size_full()
3724                    .pt_1()
3725                    .pr_2p5()
3726                    .child(self.message_editor.clone())
3727                    .child(
3728                        h_flex()
3729                            .absolute()
3730                            .top_0()
3731                            .right_0()
3732                            .opacity(0.5)
3733                            .hover(|this| this.opacity(1.0))
3734                            .child(
3735                                IconButton::new("toggle-height", expand_icon)
3736                                    .icon_size(IconSize::Small)
3737                                    .icon_color(Color::Muted)
3738                                    .tooltip({
3739                                        move |window, cx| {
3740                                            Tooltip::for_action_in(
3741                                                expand_tooltip,
3742                                                &ExpandMessageEditor,
3743                                                &focus_handle,
3744                                                window,
3745                                                cx,
3746                                            )
3747                                        }
3748                                    })
3749                                    .on_click(cx.listener(|_, _, window, cx| {
3750                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3751                                    })),
3752                            ),
3753                    ),
3754            )
3755            .child(
3756                h_flex()
3757                    .flex_none()
3758                    .flex_wrap()
3759                    .justify_between()
3760                    .child(
3761                        h_flex()
3762                            .child(self.render_follow_toggle(cx))
3763                            .children(self.render_burn_mode_toggle(cx)),
3764                    )
3765                    .child(
3766                        h_flex()
3767                            .gap_1()
3768                            .children(self.render_token_usage(cx))
3769                            .children(self.profile_selector.clone())
3770                            .children(self.model_selector.clone())
3771                            .child(self.render_send_button(cx)),
3772                    ),
3773            )
3774            .when(!enable_editor, |this| this.child(backdrop))
3775            .into_any()
3776    }
3777
3778    pub(crate) fn as_native_connection(
3779        &self,
3780        cx: &App,
3781    ) -> Option<Rc<agent2::NativeAgentConnection>> {
3782        let acp_thread = self.thread()?.read(cx);
3783        acp_thread.connection().clone().downcast()
3784    }
3785
3786    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3787        let acp_thread = self.thread()?.read(cx);
3788        self.as_native_connection(cx)?
3789            .thread(acp_thread.session_id(), cx)
3790    }
3791
3792    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3793        self.as_native_thread(cx)
3794            .and_then(|thread| thread.read(cx).model())
3795            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3796    }
3797
3798    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3799        let thread = self.thread()?.read(cx);
3800        let usage = thread.token_usage()?;
3801        let is_generating = thread.status() != ThreadStatus::Idle;
3802
3803        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3804        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3805
3806        Some(
3807            h_flex()
3808                .flex_shrink_0()
3809                .gap_0p5()
3810                .mr_1p5()
3811                .child(
3812                    Label::new(used)
3813                        .size(LabelSize::Small)
3814                        .color(Color::Muted)
3815                        .map(|label| {
3816                            if is_generating {
3817                                label
3818                                    .with_animation(
3819                                        "used-tokens-label",
3820                                        Animation::new(Duration::from_secs(2))
3821                                            .repeat()
3822                                            .with_easing(pulsating_between(0.3, 0.8)),
3823                                        |label, delta| label.alpha(delta),
3824                                    )
3825                                    .into_any()
3826                            } else {
3827                                label.into_any_element()
3828                            }
3829                        }),
3830                )
3831                .child(
3832                    Label::new("/")
3833                        .size(LabelSize::Small)
3834                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3835                )
3836                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3837        )
3838    }
3839
3840    fn toggle_burn_mode(
3841        &mut self,
3842        _: &ToggleBurnMode,
3843        _window: &mut Window,
3844        cx: &mut Context<Self>,
3845    ) {
3846        let Some(thread) = self.as_native_thread(cx) else {
3847            return;
3848        };
3849
3850        thread.update(cx, |thread, cx| {
3851            let current_mode = thread.completion_mode();
3852            thread.set_completion_mode(
3853                match current_mode {
3854                    CompletionMode::Burn => CompletionMode::Normal,
3855                    CompletionMode::Normal => CompletionMode::Burn,
3856                },
3857                cx,
3858            );
3859        });
3860    }
3861
3862    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3863        let Some(thread) = self.thread() else {
3864            return;
3865        };
3866        let action_log = thread.read(cx).action_log().clone();
3867        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3868    }
3869
3870    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3871        let Some(thread) = self.thread() else {
3872            return;
3873        };
3874        let action_log = thread.read(cx).action_log().clone();
3875        action_log
3876            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3877            .detach();
3878    }
3879
3880    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3881        let thread = self.as_native_thread(cx)?.read(cx);
3882
3883        if thread
3884            .model()
3885            .is_none_or(|model| !model.supports_burn_mode())
3886        {
3887            return None;
3888        }
3889
3890        let active_completion_mode = thread.completion_mode();
3891        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3892        let icon = if burn_mode_enabled {
3893            IconName::ZedBurnModeOn
3894        } else {
3895            IconName::ZedBurnMode
3896        };
3897
3898        Some(
3899            IconButton::new("burn-mode", icon)
3900                .icon_size(IconSize::Small)
3901                .icon_color(Color::Muted)
3902                .toggle_state(burn_mode_enabled)
3903                .selected_icon_color(Color::Error)
3904                .on_click(cx.listener(|this, _event, window, cx| {
3905                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3906                }))
3907                .tooltip(move |_window, cx| {
3908                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3909                        .into()
3910                })
3911                .into_any_element(),
3912        )
3913    }
3914
3915    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3916        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3917        let is_generating = self
3918            .thread()
3919            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3920
3921        if self.is_loading_contents {
3922            div()
3923                .id("loading-message-content")
3924                .px_1()
3925                .tooltip(Tooltip::text("Loading Added Context…"))
3926                .child(loading_contents_spinner(IconSize::default()))
3927                .into_any_element()
3928        } else if is_generating && is_editor_empty {
3929            IconButton::new("stop-generation", IconName::Stop)
3930                .icon_color(Color::Error)
3931                .style(ButtonStyle::Tinted(ui::TintColor::Error))
3932                .tooltip(move |window, cx| {
3933                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3934                })
3935                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3936                .into_any_element()
3937        } else {
3938            let send_btn_tooltip = if is_editor_empty && !is_generating {
3939                "Type to Send"
3940            } else if is_generating {
3941                "Stop and Send Message"
3942            } else {
3943                "Send"
3944            };
3945
3946            IconButton::new("send-message", IconName::Send)
3947                .style(ButtonStyle::Filled)
3948                .map(|this| {
3949                    if is_editor_empty && !is_generating {
3950                        this.disabled(true).icon_color(Color::Muted)
3951                    } else {
3952                        this.icon_color(Color::Accent)
3953                    }
3954                })
3955                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3956                .on_click(cx.listener(|this, _, window, cx| {
3957                    this.send(window, cx);
3958                }))
3959                .into_any_element()
3960        }
3961    }
3962
3963    fn is_following(&self, cx: &App) -> bool {
3964        match self.thread().map(|thread| thread.read(cx).status()) {
3965            Some(ThreadStatus::Generating) => self
3966                .workspace
3967                .read_with(cx, |workspace, _| {
3968                    workspace.is_being_followed(CollaboratorId::Agent)
3969                })
3970                .unwrap_or(false),
3971            _ => self.should_be_following,
3972        }
3973    }
3974
3975    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3976        let following = self.is_following(cx);
3977
3978        self.should_be_following = !following;
3979        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3980            self.workspace
3981                .update(cx, |workspace, cx| {
3982                    if following {
3983                        workspace.unfollow(CollaboratorId::Agent, window, cx);
3984                    } else {
3985                        workspace.follow(CollaboratorId::Agent, window, cx);
3986                    }
3987                })
3988                .ok();
3989        }
3990
3991        telemetry::event!("Follow Agent Selected", following = !following);
3992    }
3993
3994    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3995        let following = self.is_following(cx);
3996
3997        let tooltip_label = if following {
3998            if self.agent.name() == "Zed Agent" {
3999                format!("Stop Following the {}", self.agent.name())
4000            } else {
4001                format!("Stop Following {}", self.agent.name())
4002            }
4003        } else {
4004            if self.agent.name() == "Zed Agent" {
4005                format!("Follow the {}", self.agent.name())
4006            } else {
4007                format!("Follow {}", self.agent.name())
4008            }
4009        };
4010
4011        IconButton::new("follow-agent", IconName::Crosshair)
4012            .icon_size(IconSize::Small)
4013            .icon_color(Color::Muted)
4014            .toggle_state(following)
4015            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4016            .tooltip(move |window, cx| {
4017                if following {
4018                    Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4019                } else {
4020                    Tooltip::with_meta(
4021                        tooltip_label.clone(),
4022                        Some(&Follow),
4023                        "Track the agent's location as it reads and edits files.",
4024                        window,
4025                        cx,
4026                    )
4027                }
4028            })
4029            .on_click(cx.listener(move |this, _, window, cx| {
4030                this.toggle_following(window, cx);
4031            }))
4032    }
4033
4034    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4035        let workspace = self.workspace.clone();
4036        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4037            Self::open_link(text, &workspace, window, cx);
4038        })
4039    }
4040
4041    fn open_link(
4042        url: SharedString,
4043        workspace: &WeakEntity<Workspace>,
4044        window: &mut Window,
4045        cx: &mut App,
4046    ) {
4047        let Some(workspace) = workspace.upgrade() else {
4048            cx.open_url(&url);
4049            return;
4050        };
4051
4052        if let Some(mention) = MentionUri::parse(&url).log_err() {
4053            workspace.update(cx, |workspace, cx| match mention {
4054                MentionUri::File { abs_path } => {
4055                    let project = workspace.project();
4056                    let Some(path) =
4057                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4058                    else {
4059                        return;
4060                    };
4061
4062                    workspace
4063                        .open_path(path, None, true, window, cx)
4064                        .detach_and_log_err(cx);
4065                }
4066                MentionUri::PastedImage => {}
4067                MentionUri::Directory { abs_path } => {
4068                    let project = workspace.project();
4069                    let Some(entry) = project.update(cx, |project, cx| {
4070                        let path = project.find_project_path(abs_path, cx)?;
4071                        project.entry_for_path(&path, cx)
4072                    }) else {
4073                        return;
4074                    };
4075
4076                    project.update(cx, |_, cx| {
4077                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
4078                    });
4079                }
4080                MentionUri::Symbol {
4081                    abs_path: path,
4082                    line_range,
4083                    ..
4084                }
4085                | MentionUri::Selection {
4086                    abs_path: Some(path),
4087                    line_range,
4088                } => {
4089                    let project = workspace.project();
4090                    let Some((path, _)) = project.update(cx, |project, cx| {
4091                        let path = project.find_project_path(path, cx)?;
4092                        let entry = project.entry_for_path(&path, cx)?;
4093                        Some((path, entry))
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), 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 settings_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.settings_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                    vec![],
5749                    cx,
5750                )
5751            })))
5752        }
5753
5754        fn auth_methods(&self) -> &[acp::AuthMethod] {
5755            &[]
5756        }
5757
5758        fn authenticate(
5759            &self,
5760            _method_id: acp::AuthMethodId,
5761            _cx: &mut App,
5762        ) -> Task<gpui::Result<()>> {
5763            unimplemented!()
5764        }
5765
5766        fn prompt(
5767            &self,
5768            _id: Option<acp_thread::UserMessageId>,
5769            _params: acp::PromptRequest,
5770            _cx: &mut App,
5771        ) -> Task<gpui::Result<acp::PromptResponse>> {
5772            Task::ready(Err(anyhow::anyhow!("Error prompting")))
5773        }
5774
5775        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5776            unimplemented!()
5777        }
5778
5779        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5780            self
5781        }
5782    }
5783
5784    /// Simulates a model which always returns a refusal response
5785    #[derive(Clone)]
5786    struct RefusalAgentConnection;
5787
5788    impl AgentConnection for RefusalAgentConnection {
5789        fn new_thread(
5790            self: Rc<Self>,
5791            project: Entity<Project>,
5792            _cwd: &Path,
5793            cx: &mut gpui::App,
5794        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5795            Task::ready(Ok(cx.new(|cx| {
5796                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5797                AcpThread::new(
5798                    "RefusalAgentConnection",
5799                    self,
5800                    project,
5801                    action_log,
5802                    SessionId("test".into()),
5803                    watch::Receiver::constant(acp::PromptCapabilities {
5804                        image: true,
5805                        audio: true,
5806                        embedded_context: true,
5807                    }),
5808                    Vec::new(),
5809                    cx,
5810                )
5811            })))
5812        }
5813
5814        fn auth_methods(&self) -> &[acp::AuthMethod] {
5815            &[]
5816        }
5817
5818        fn authenticate(
5819            &self,
5820            _method_id: acp::AuthMethodId,
5821            _cx: &mut App,
5822        ) -> Task<gpui::Result<()>> {
5823            unimplemented!()
5824        }
5825
5826        fn prompt(
5827            &self,
5828            _id: Option<acp_thread::UserMessageId>,
5829            _params: acp::PromptRequest,
5830            _cx: &mut App,
5831        ) -> Task<gpui::Result<acp::PromptResponse>> {
5832            Task::ready(Ok(acp::PromptResponse {
5833                stop_reason: acp::StopReason::Refusal,
5834            }))
5835        }
5836
5837        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5838            unimplemented!()
5839        }
5840
5841        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5842            self
5843        }
5844    }
5845
5846    pub(crate) fn init_test(cx: &mut TestAppContext) {
5847        cx.update(|cx| {
5848            let settings_store = SettingsStore::test(cx);
5849            cx.set_global(settings_store);
5850            language::init(cx);
5851            Project::init_settings(cx);
5852            AgentSettings::register(cx);
5853            workspace::init_settings(cx);
5854            ThemeSettings::register(cx);
5855            release_channel::init(SemanticVersion::default(), cx);
5856            EditorSettings::register(cx);
5857            prompt_store::init(cx)
5858        });
5859    }
5860
5861    #[gpui::test]
5862    async fn test_rewind_views(cx: &mut TestAppContext) {
5863        init_test(cx);
5864
5865        let fs = FakeFs::new(cx.executor());
5866        fs.insert_tree(
5867            "/project",
5868            json!({
5869                "test1.txt": "old content 1",
5870                "test2.txt": "old content 2"
5871            }),
5872        )
5873        .await;
5874        let project = Project::test(fs, [Path::new("/project")], cx).await;
5875        let (workspace, cx) =
5876            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5877
5878        let context_store =
5879            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5880        let history_store =
5881            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5882
5883        let connection = Rc::new(StubAgentConnection::new());
5884        let thread_view = cx.update(|window, cx| {
5885            cx.new(|cx| {
5886                AcpThreadView::new(
5887                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5888                    None,
5889                    None,
5890                    workspace.downgrade(),
5891                    project.clone(),
5892                    history_store.clone(),
5893                    None,
5894                    window,
5895                    cx,
5896                )
5897            })
5898        });
5899
5900        cx.run_until_parked();
5901
5902        let thread = thread_view
5903            .read_with(cx, |view, _| view.thread().cloned())
5904            .unwrap();
5905
5906        // First user message
5907        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5908            id: acp::ToolCallId("tool1".into()),
5909            title: "Edit file 1".into(),
5910            kind: acp::ToolKind::Edit,
5911            status: acp::ToolCallStatus::Completed,
5912            content: vec![acp::ToolCallContent::Diff {
5913                diff: acp::Diff {
5914                    path: "/project/test1.txt".into(),
5915                    old_text: Some("old content 1".into()),
5916                    new_text: "new content 1".into(),
5917                },
5918            }],
5919            locations: vec![],
5920            raw_input: None,
5921            raw_output: None,
5922        })]);
5923
5924        thread
5925            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5926            .await
5927            .unwrap();
5928        cx.run_until_parked();
5929
5930        thread.read_with(cx, |thread, _| {
5931            assert_eq!(thread.entries().len(), 2);
5932        });
5933
5934        thread_view.read_with(cx, |view, cx| {
5935            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5936                assert!(
5937                    entry_view_state
5938                        .entry(0)
5939                        .unwrap()
5940                        .message_editor()
5941                        .is_some()
5942                );
5943                assert!(entry_view_state.entry(1).unwrap().has_content());
5944            });
5945        });
5946
5947        // Second user message
5948        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5949            id: acp::ToolCallId("tool2".into()),
5950            title: "Edit file 2".into(),
5951            kind: acp::ToolKind::Edit,
5952            status: acp::ToolCallStatus::Completed,
5953            content: vec![acp::ToolCallContent::Diff {
5954                diff: acp::Diff {
5955                    path: "/project/test2.txt".into(),
5956                    old_text: Some("old content 2".into()),
5957                    new_text: "new content 2".into(),
5958                },
5959            }],
5960            locations: vec![],
5961            raw_input: None,
5962            raw_output: None,
5963        })]);
5964
5965        thread
5966            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5967            .await
5968            .unwrap();
5969        cx.run_until_parked();
5970
5971        let second_user_message_id = thread.read_with(cx, |thread, _| {
5972            assert_eq!(thread.entries().len(), 4);
5973            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5974                panic!();
5975            };
5976            user_message.id.clone().unwrap()
5977        });
5978
5979        thread_view.read_with(cx, |view, cx| {
5980            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5981                assert!(
5982                    entry_view_state
5983                        .entry(0)
5984                        .unwrap()
5985                        .message_editor()
5986                        .is_some()
5987                );
5988                assert!(entry_view_state.entry(1).unwrap().has_content());
5989                assert!(
5990                    entry_view_state
5991                        .entry(2)
5992                        .unwrap()
5993                        .message_editor()
5994                        .is_some()
5995                );
5996                assert!(entry_view_state.entry(3).unwrap().has_content());
5997            });
5998        });
5999
6000        // Rewind to first message
6001        thread
6002            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6003            .await
6004            .unwrap();
6005
6006        cx.run_until_parked();
6007
6008        thread.read_with(cx, |thread, _| {
6009            assert_eq!(thread.entries().len(), 2);
6010        });
6011
6012        thread_view.read_with(cx, |view, cx| {
6013            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6014                assert!(
6015                    entry_view_state
6016                        .entry(0)
6017                        .unwrap()
6018                        .message_editor()
6019                        .is_some()
6020                );
6021                assert!(entry_view_state.entry(1).unwrap().has_content());
6022
6023                // Old views should be dropped
6024                assert!(entry_view_state.entry(2).is_none());
6025                assert!(entry_view_state.entry(3).is_none());
6026            });
6027        });
6028    }
6029
6030    #[gpui::test]
6031    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6032        init_test(cx);
6033
6034        let connection = StubAgentConnection::new();
6035
6036        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6037            content: acp::ContentBlock::Text(acp::TextContent {
6038                text: "Response".into(),
6039                annotations: None,
6040            }),
6041        }]);
6042
6043        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6044        add_to_workspace(thread_view.clone(), cx);
6045
6046        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6047        message_editor.update_in(cx, |editor, window, cx| {
6048            editor.set_text("Original message to edit", window, cx);
6049        });
6050        thread_view.update_in(cx, |thread_view, window, cx| {
6051            thread_view.send(window, cx);
6052        });
6053
6054        cx.run_until_parked();
6055
6056        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6057            assert_eq!(view.editing_message, None);
6058
6059            view.entry_view_state
6060                .read(cx)
6061                .entry(0)
6062                .unwrap()
6063                .message_editor()
6064                .unwrap()
6065                .clone()
6066        });
6067
6068        // Focus
6069        cx.focus(&user_message_editor);
6070        thread_view.read_with(cx, |view, _cx| {
6071            assert_eq!(view.editing_message, Some(0));
6072        });
6073
6074        // Edit
6075        user_message_editor.update_in(cx, |editor, window, cx| {
6076            editor.set_text("Edited message content", window, cx);
6077        });
6078
6079        // Cancel
6080        user_message_editor.update_in(cx, |_editor, window, cx| {
6081            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6082        });
6083
6084        thread_view.read_with(cx, |view, _cx| {
6085            assert_eq!(view.editing_message, None);
6086        });
6087
6088        user_message_editor.read_with(cx, |editor, cx| {
6089            assert_eq!(editor.text(cx), "Original message to edit");
6090        });
6091    }
6092
6093    #[gpui::test]
6094    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6095        init_test(cx);
6096
6097        let connection = StubAgentConnection::new();
6098
6099        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6100        add_to_workspace(thread_view.clone(), cx);
6101
6102        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6103        let mut events = cx.events(&message_editor);
6104        message_editor.update_in(cx, |editor, window, cx| {
6105            editor.set_text("", window, cx);
6106        });
6107
6108        message_editor.update_in(cx, |_editor, window, cx| {
6109            window.dispatch_action(Box::new(Chat), cx);
6110        });
6111        cx.run_until_parked();
6112        // We shouldn't have received any messages
6113        assert!(matches!(
6114            events.try_next(),
6115            Err(futures::channel::mpsc::TryRecvError { .. })
6116        ));
6117    }
6118
6119    #[gpui::test]
6120    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6121        init_test(cx);
6122
6123        let connection = StubAgentConnection::new();
6124
6125        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6126            content: acp::ContentBlock::Text(acp::TextContent {
6127                text: "Response".into(),
6128                annotations: None,
6129            }),
6130        }]);
6131
6132        let (thread_view, cx) =
6133            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6134        add_to_workspace(thread_view.clone(), cx);
6135
6136        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6137        message_editor.update_in(cx, |editor, window, cx| {
6138            editor.set_text("Original message to edit", window, cx);
6139        });
6140        thread_view.update_in(cx, |thread_view, window, cx| {
6141            thread_view.send(window, cx);
6142        });
6143
6144        cx.run_until_parked();
6145
6146        let user_message_editor = thread_view.read_with(cx, |view, cx| {
6147            assert_eq!(view.editing_message, None);
6148            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6149
6150            view.entry_view_state
6151                .read(cx)
6152                .entry(0)
6153                .unwrap()
6154                .message_editor()
6155                .unwrap()
6156                .clone()
6157        });
6158
6159        // Focus
6160        cx.focus(&user_message_editor);
6161
6162        // Edit
6163        user_message_editor.update_in(cx, |editor, window, cx| {
6164            editor.set_text("Edited message content", window, cx);
6165        });
6166
6167        // Send
6168        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6169            content: acp::ContentBlock::Text(acp::TextContent {
6170                text: "New Response".into(),
6171                annotations: None,
6172            }),
6173        }]);
6174
6175        user_message_editor.update_in(cx, |_editor, window, cx| {
6176            window.dispatch_action(Box::new(Chat), cx);
6177        });
6178
6179        cx.run_until_parked();
6180
6181        thread_view.read_with(cx, |view, cx| {
6182            assert_eq!(view.editing_message, None);
6183
6184            let entries = view.thread().unwrap().read(cx).entries();
6185            assert_eq!(entries.len(), 2);
6186            assert_eq!(
6187                entries[0].to_markdown(cx),
6188                "## User\n\nEdited message content\n\n"
6189            );
6190            assert_eq!(
6191                entries[1].to_markdown(cx),
6192                "## Assistant\n\nNew Response\n\n"
6193            );
6194
6195            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6196                assert!(!state.entry(1).unwrap().has_content());
6197                state.entry(0).unwrap().message_editor().unwrap().clone()
6198            });
6199
6200            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6201        })
6202    }
6203
6204    #[gpui::test]
6205    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6206        init_test(cx);
6207
6208        let connection = StubAgentConnection::new();
6209
6210        let (thread_view, cx) =
6211            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6212        add_to_workspace(thread_view.clone(), cx);
6213
6214        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6215        message_editor.update_in(cx, |editor, window, cx| {
6216            editor.set_text("Original message to edit", window, cx);
6217        });
6218        thread_view.update_in(cx, |thread_view, window, cx| {
6219            thread_view.send(window, cx);
6220        });
6221
6222        cx.run_until_parked();
6223
6224        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6225            let thread = view.thread().unwrap().read(cx);
6226            assert_eq!(thread.entries().len(), 1);
6227
6228            let editor = view
6229                .entry_view_state
6230                .read(cx)
6231                .entry(0)
6232                .unwrap()
6233                .message_editor()
6234                .unwrap()
6235                .clone();
6236
6237            (editor, thread.session_id().clone())
6238        });
6239
6240        // Focus
6241        cx.focus(&user_message_editor);
6242
6243        thread_view.read_with(cx, |view, _cx| {
6244            assert_eq!(view.editing_message, Some(0));
6245        });
6246
6247        // Edit
6248        user_message_editor.update_in(cx, |editor, window, cx| {
6249            editor.set_text("Edited message content", window, cx);
6250        });
6251
6252        thread_view.read_with(cx, |view, _cx| {
6253            assert_eq!(view.editing_message, Some(0));
6254        });
6255
6256        // Finish streaming response
6257        cx.update(|_, cx| {
6258            connection.send_update(
6259                session_id.clone(),
6260                acp::SessionUpdate::AgentMessageChunk {
6261                    content: acp::ContentBlock::Text(acp::TextContent {
6262                        text: "Response".into(),
6263                        annotations: None,
6264                    }),
6265                },
6266                cx,
6267            );
6268            connection.end_turn(session_id, acp::StopReason::EndTurn);
6269        });
6270
6271        thread_view.read_with(cx, |view, _cx| {
6272            assert_eq!(view.editing_message, Some(0));
6273        });
6274
6275        cx.run_until_parked();
6276
6277        // Should still be editing
6278        cx.update(|window, cx| {
6279            assert!(user_message_editor.focus_handle(cx).is_focused(window));
6280            assert_eq!(thread_view.read(cx).editing_message, Some(0));
6281            assert_eq!(
6282                user_message_editor.read(cx).text(cx),
6283                "Edited message content"
6284            );
6285        });
6286    }
6287
6288    #[gpui::test]
6289    async fn test_interrupt(cx: &mut TestAppContext) {
6290        init_test(cx);
6291
6292        let connection = StubAgentConnection::new();
6293
6294        let (thread_view, cx) =
6295            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6296        add_to_workspace(thread_view.clone(), cx);
6297
6298        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6299        message_editor.update_in(cx, |editor, window, cx| {
6300            editor.set_text("Message 1", window, cx);
6301        });
6302        thread_view.update_in(cx, |thread_view, window, cx| {
6303            thread_view.send(window, cx);
6304        });
6305
6306        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6307            let thread = view.thread().unwrap();
6308
6309            (thread.clone(), thread.read(cx).session_id().clone())
6310        });
6311
6312        cx.run_until_parked();
6313
6314        cx.update(|_, cx| {
6315            connection.send_update(
6316                session_id.clone(),
6317                acp::SessionUpdate::AgentMessageChunk {
6318                    content: "Message 1 resp".into(),
6319                },
6320                cx,
6321            );
6322        });
6323
6324        cx.run_until_parked();
6325
6326        thread.read_with(cx, |thread, cx| {
6327            assert_eq!(
6328                thread.to_markdown(cx),
6329                indoc::indoc! {"
6330                    ## User
6331
6332                    Message 1
6333
6334                    ## Assistant
6335
6336                    Message 1 resp
6337
6338                "}
6339            )
6340        });
6341
6342        message_editor.update_in(cx, |editor, window, cx| {
6343            editor.set_text("Message 2", window, cx);
6344        });
6345        thread_view.update_in(cx, |thread_view, window, cx| {
6346            thread_view.send(window, cx);
6347        });
6348
6349        cx.update(|_, cx| {
6350            // Simulate a response sent after beginning to cancel
6351            connection.send_update(
6352                session_id.clone(),
6353                acp::SessionUpdate::AgentMessageChunk {
6354                    content: "onse".into(),
6355                },
6356                cx,
6357            );
6358        });
6359
6360        cx.run_until_parked();
6361
6362        // Last Message 1 response should appear before Message 2
6363        thread.read_with(cx, |thread, cx| {
6364            assert_eq!(
6365                thread.to_markdown(cx),
6366                indoc::indoc! {"
6367                    ## User
6368
6369                    Message 1
6370
6371                    ## Assistant
6372
6373                    Message 1 response
6374
6375                    ## User
6376
6377                    Message 2
6378
6379                "}
6380            )
6381        });
6382
6383        cx.update(|_, cx| {
6384            connection.send_update(
6385                session_id.clone(),
6386                acp::SessionUpdate::AgentMessageChunk {
6387                    content: "Message 2 response".into(),
6388                },
6389                cx,
6390            );
6391            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6392        });
6393
6394        cx.run_until_parked();
6395
6396        thread.read_with(cx, |thread, cx| {
6397            assert_eq!(
6398                thread.to_markdown(cx),
6399                indoc::indoc! {"
6400                    ## User
6401
6402                    Message 1
6403
6404                    ## Assistant
6405
6406                    Message 1 response
6407
6408                    ## User
6409
6410                    Message 2
6411
6412                    ## Assistant
6413
6414                    Message 2 response
6415
6416                "}
6417            )
6418        });
6419    }
6420}