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