thread_view.rs

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