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