thread_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
   3    AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
   4    ToolCallStatus, UserMessageId,
   5};
   6use acp_thread::{AgentConnection, Plan};
   7use action_log::{ActionLog, ActionLogTelemetry};
   8use agent::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore, NativeAgentServer};
   9use agent_client_protocol::{self as acp, PromptCapabilities};
  10use agent_servers::{AgentServer, AgentServerDelegate};
  11use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
  12use anyhow::{Result, anyhow};
  13use arrayvec::ArrayVec;
  14use audio::{Audio, Sound};
  15use buffer_diff::BufferDiff;
  16use client::zed_urls;
  17use cloud_llm_client::PlanV1;
  18use collections::{HashMap, HashSet};
  19use editor::scroll::Autoscroll;
  20use editor::{
  21    Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
  22};
  23use file_icons::FileIcons;
  24use fs::Fs;
  25use futures::FutureExt as _;
  26use gpui::{
  27    Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
  28    CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
  29    ListOffset, ListState, PlatformDisplay, SharedString, StyleRefinement, Subscription, Task,
  30    TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window, WindowHandle, div,
  31    ease_in_out, linear_color_stop, linear_gradient, list, point, pulsating_between,
  32};
  33use language::Buffer;
  34
  35use language_model::LanguageModelRegistry;
  36use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  37use project::{Project, ProjectEntryId};
  38use prompt_store::{PromptId, PromptStore};
  39use rope::Point;
  40use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
  41use std::cell::RefCell;
  42use std::path::Path;
  43use std::sync::Arc;
  44use std::time::Instant;
  45use std::{collections::BTreeMap, rc::Rc, time::Duration};
  46use terminal_view::terminal_panel::TerminalPanel;
  47use text::Anchor;
  48use theme::{AgentFontSize, ThemeSettings};
  49use ui::{
  50    Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
  51    PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
  52};
  53use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  54use workspace::{CollaboratorId, NewTerminal, Workspace};
  55use zed_actions::agent::{Chat, ToggleModelSelector};
  56use zed_actions::assistant::OpenRulesLibrary;
  57
  58use super::entry_view_state::EntryViewState;
  59use crate::acp::AcpModelSelectorPopover;
  60use crate::acp::ModeSelector;
  61use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
  62use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  63use crate::agent_diff::AgentDiff;
  64use crate::profile_selector::{ProfileProvider, ProfileSelector};
  65
  66use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip, UsageCallout};
  67use crate::{
  68    AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ContinueThread, ContinueWithBurnMode,
  69    CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, NewThread, OpenAgentDiff, OpenHistory,
  70    RejectAll, RejectOnce, ToggleBurnMode, ToggleProfileSelector,
  71};
  72
  73#[derive(Copy, Clone, Debug, PartialEq, Eq)]
  74enum ThreadFeedback {
  75    Positive,
  76    Negative,
  77}
  78
  79#[derive(Debug)]
  80enum ThreadError {
  81    PaymentRequired,
  82    ModelRequestLimitReached(cloud_llm_client::Plan),
  83    ToolUseLimitReached,
  84    Refusal,
  85    AuthenticationRequired(SharedString),
  86    Other(SharedString),
  87}
  88
  89impl ThreadError {
  90    fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
  91        if error.is::<language_model::PaymentRequiredError>() {
  92            Self::PaymentRequired
  93        } else if error.is::<language_model::ToolUseLimitReachedError>() {
  94            Self::ToolUseLimitReached
  95        } else if let Some(error) =
  96            error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
  97        {
  98            Self::ModelRequestLimitReached(error.plan)
  99        } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
 100            && acp_error.code == acp::ErrorCode::AuthRequired
 101        {
 102            Self::AuthenticationRequired(acp_error.message.clone().into())
 103        } else {
 104            let string = format!("{:#}", error);
 105            // TODO: we should have Gemini return better errors here.
 106            if agent.clone().downcast::<agent_servers::Gemini>().is_some()
 107                && string.contains("Could not load the default credentials")
 108                || string.contains("API key not valid")
 109                || string.contains("Request had invalid authentication credentials")
 110            {
 111                Self::AuthenticationRequired(string.into())
 112            } else {
 113                Self::Other(string.into())
 114            }
 115        }
 116    }
 117}
 118
 119impl ProfileProvider for Entity<agent::Thread> {
 120    fn profile_id(&self, cx: &App) -> AgentProfileId {
 121        self.read(cx).profile().clone()
 122    }
 123
 124    fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
 125        self.update(cx, |thread, cx| {
 126            // Apply the profile and let the thread swap to its default model.
 127            thread.set_profile(profile_id, cx);
 128        });
 129    }
 130
 131    fn profiles_supported(&self, cx: &App) -> bool {
 132        self.read(cx)
 133            .model()
 134            .is_some_and(|model| model.supports_tools())
 135    }
 136}
 137
 138#[derive(Default)]
 139struct ThreadFeedbackState {
 140    feedback: Option<ThreadFeedback>,
 141    comments_editor: Option<Entity<Editor>>,
 142}
 143
 144impl ThreadFeedbackState {
 145    pub fn submit(
 146        &mut self,
 147        thread: Entity<AcpThread>,
 148        feedback: ThreadFeedback,
 149        window: &mut Window,
 150        cx: &mut App,
 151    ) {
 152        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 153            return;
 154        };
 155
 156        if self.feedback == Some(feedback) {
 157            return;
 158        }
 159
 160        self.feedback = Some(feedback);
 161        match feedback {
 162            ThreadFeedback::Positive => {
 163                self.comments_editor = None;
 164            }
 165            ThreadFeedback::Negative => {
 166                self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
 167            }
 168        }
 169        let session_id = thread.read(cx).session_id().clone();
 170        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 171        let task = telemetry.thread_data(&session_id, cx);
 172        let rating = match feedback {
 173            ThreadFeedback::Positive => "positive",
 174            ThreadFeedback::Negative => "negative",
 175        };
 176        cx.background_spawn(async move {
 177            let thread = task.await?;
 178            telemetry::event!(
 179                "Agent Thread Rated",
 180                agent = agent_telemetry_id,
 181                session_id = session_id,
 182                rating = rating,
 183                thread = thread
 184            );
 185            anyhow::Ok(())
 186        })
 187        .detach_and_log_err(cx);
 188    }
 189
 190    pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
 191        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 192            return;
 193        };
 194
 195        let Some(comments) = self
 196            .comments_editor
 197            .as_ref()
 198            .map(|editor| editor.read(cx).text(cx))
 199            .filter(|text| !text.trim().is_empty())
 200        else {
 201            return;
 202        };
 203
 204        self.comments_editor.take();
 205
 206        let session_id = thread.read(cx).session_id().clone();
 207        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 208        let task = telemetry.thread_data(&session_id, cx);
 209        cx.background_spawn(async move {
 210            let thread = task.await?;
 211            telemetry::event!(
 212                "Agent Thread Feedback Comments",
 213                agent = agent_telemetry_id,
 214                session_id = session_id,
 215                comments = comments,
 216                thread = thread
 217            );
 218            anyhow::Ok(())
 219        })
 220        .detach_and_log_err(cx);
 221    }
 222
 223    pub fn clear(&mut self) {
 224        *self = Self::default()
 225    }
 226
 227    pub fn dismiss_comments(&mut self) {
 228        self.comments_editor.take();
 229    }
 230
 231    fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
 232        let buffer = cx.new(|cx| {
 233            let empty_string = String::new();
 234            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
 235        });
 236
 237        let editor = cx.new(|cx| {
 238            let mut editor = Editor::new(
 239                editor::EditorMode::AutoHeight {
 240                    min_lines: 1,
 241                    max_lines: Some(4),
 242                },
 243                buffer,
 244                None,
 245                window,
 246                cx,
 247            );
 248            editor.set_placeholder_text(
 249                "What went wrong? Share your feedback so we can improve.",
 250                window,
 251                cx,
 252            );
 253            editor
 254        });
 255
 256        editor.read(cx).focus_handle(cx).focus(window);
 257        editor
 258    }
 259}
 260
 261pub struct AcpThreadView {
 262    agent: Rc<dyn AgentServer>,
 263    workspace: WeakEntity<Workspace>,
 264    project: Entity<Project>,
 265    thread_state: ThreadState,
 266    login: Option<task::SpawnInTerminal>,
 267    history_store: Entity<HistoryStore>,
 268    hovered_recent_history_item: Option<usize>,
 269    entry_view_state: Entity<EntryViewState>,
 270    message_editor: Entity<MessageEditor>,
 271    focus_handle: FocusHandle,
 272    model_selector: Option<Entity<AcpModelSelectorPopover>>,
 273    profile_selector: Option<Entity<ProfileSelector>>,
 274    notifications: Vec<WindowHandle<AgentNotification>>,
 275    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 276    thread_retry_status: Option<RetryStatus>,
 277    thread_error: Option<ThreadError>,
 278    thread_error_markdown: Option<Entity<Markdown>>,
 279    thread_feedback: ThreadFeedbackState,
 280    list_state: ListState,
 281    auth_task: Option<Task<()>>,
 282    expanded_tool_calls: HashSet<acp::ToolCallId>,
 283    expanded_thinking_blocks: HashSet<(usize, usize)>,
 284    edits_expanded: bool,
 285    plan_expanded: bool,
 286    editor_expanded: bool,
 287    should_be_following: bool,
 288    editing_message: Option<usize>,
 289    prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
 290    available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
 291    is_loading_contents: bool,
 292    new_server_version_available: Option<SharedString>,
 293    resume_thread_metadata: Option<DbThreadMetadata>,
 294    _cancel_task: Option<Task<()>>,
 295    _subscriptions: [Subscription; 5],
 296    show_codex_windows_warning: bool,
 297    in_flight_prompt: Option<Vec<acp::ContentBlock>>,
 298}
 299
 300enum ThreadState {
 301    Loading(Entity<LoadingView>),
 302    Ready {
 303        thread: Entity<AcpThread>,
 304        title_editor: Option<Entity<Editor>>,
 305        mode_selector: Option<Entity<ModeSelector>>,
 306        _subscriptions: Vec<Subscription>,
 307    },
 308    LoadError(LoadError),
 309    Unauthenticated {
 310        connection: Rc<dyn AgentConnection>,
 311        description: Option<Entity<Markdown>>,
 312        configuration_view: Option<AnyView>,
 313        pending_auth_method: Option<acp::AuthMethodId>,
 314        _subscription: Option<Subscription>,
 315    },
 316}
 317
 318struct LoadingView {
 319    title: SharedString,
 320    _load_task: Task<()>,
 321    _update_title_task: Task<anyhow::Result<()>>,
 322}
 323
 324impl AcpThreadView {
 325    pub fn new(
 326        agent: Rc<dyn AgentServer>,
 327        resume_thread: Option<DbThreadMetadata>,
 328        summarize_thread: Option<DbThreadMetadata>,
 329        workspace: WeakEntity<Workspace>,
 330        project: Entity<Project>,
 331        history_store: Entity<HistoryStore>,
 332        prompt_store: Option<Entity<PromptStore>>,
 333        track_load_event: bool,
 334        window: &mut Window,
 335        cx: &mut Context<Self>,
 336    ) -> Self {
 337        let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
 338        let available_commands = Rc::new(RefCell::new(vec![]));
 339
 340        let placeholder = placeholder_text(agent.name().as_ref(), false);
 341
 342        let message_editor = cx.new(|cx| {
 343            let mut editor = MessageEditor::new(
 344                workspace.clone(),
 345                project.downgrade(),
 346                history_store.clone(),
 347                prompt_store.clone(),
 348                prompt_capabilities.clone(),
 349                available_commands.clone(),
 350                agent.name(),
 351                &placeholder,
 352                editor::EditorMode::AutoHeight {
 353                    min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
 354                    max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
 355                },
 356                window,
 357                cx,
 358            );
 359            if let Some(entry) = summarize_thread {
 360                editor.insert_thread_summary(entry, window, cx);
 361            }
 362            editor
 363        });
 364
 365        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 366
 367        let entry_view_state = cx.new(|_| {
 368            EntryViewState::new(
 369                workspace.clone(),
 370                project.downgrade(),
 371                history_store.clone(),
 372                prompt_store.clone(),
 373                prompt_capabilities.clone(),
 374                available_commands.clone(),
 375                agent.name(),
 376            )
 377        });
 378
 379        let agent_server_store = project.read(cx).agent_server_store().clone();
 380        let subscriptions = [
 381            cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
 382            cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
 383            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 384            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 385            cx.subscribe_in(
 386                &agent_server_store,
 387                window,
 388                Self::handle_agent_servers_updated,
 389            ),
 390        ];
 391
 392        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            .p_2()
4297            .gap_2()
4298            .border_t_1()
4299            .border_color(cx.theme().colors().border)
4300            .bg(editor_bg_color)
4301            .when(self.editor_expanded, |this| {
4302                this.h(vh(0.8, window)).size_full().justify_between()
4303            })
4304            .child(
4305                v_flex()
4306                    .relative()
4307                    .size_full()
4308                    .pt_1()
4309                    .pr_2p5()
4310                    .child(self.message_editor.clone())
4311                    .child(
4312                        h_flex()
4313                            .absolute()
4314                            .top_0()
4315                            .right_0()
4316                            .opacity(0.5)
4317                            .hover(|this| this.opacity(1.0))
4318                            .child(
4319                                IconButton::new("toggle-height", expand_icon)
4320                                    .icon_size(IconSize::Small)
4321                                    .icon_color(Color::Muted)
4322                                    .tooltip({
4323                                        move |_window, cx| {
4324                                            Tooltip::for_action_in(
4325                                                expand_tooltip,
4326                                                &ExpandMessageEditor,
4327                                                &focus_handle,
4328                                                cx,
4329                                            )
4330                                        }
4331                                    })
4332                                    .on_click(cx.listener(|this, _, window, cx| {
4333                                        this.expand_message_editor(
4334                                            &ExpandMessageEditor,
4335                                            window,
4336                                            cx,
4337                                        );
4338                                    })),
4339                            ),
4340                    ),
4341            )
4342            .child(
4343                h_flex()
4344                    .flex_none()
4345                    .flex_wrap()
4346                    .justify_between()
4347                    .child(
4348                        h_flex()
4349                            .gap_0p5()
4350                            .child(self.render_add_context_button(cx))
4351                            .child(self.render_follow_toggle(cx))
4352                            .children(self.render_burn_mode_toggle(cx)),
4353                    )
4354                    .child(
4355                        h_flex()
4356                            .gap_1()
4357                            .children(self.render_token_usage(cx))
4358                            .children(self.profile_selector.clone())
4359                            .children(self.mode_selector().cloned())
4360                            .children(self.model_selector.clone())
4361                            .child(self.render_send_button(cx)),
4362                    ),
4363            )
4364            .when(!enable_editor, |this| this.child(backdrop))
4365            .into_any()
4366    }
4367
4368    pub(crate) fn as_native_connection(
4369        &self,
4370        cx: &App,
4371    ) -> Option<Rc<agent::NativeAgentConnection>> {
4372        let acp_thread = self.thread()?.read(cx);
4373        acp_thread.connection().clone().downcast()
4374    }
4375
4376    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4377        let acp_thread = self.thread()?.read(cx);
4378        self.as_native_connection(cx)?
4379            .thread(acp_thread.session_id(), cx)
4380    }
4381
4382    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4383        self.as_native_thread(cx)
4384            .and_then(|thread| thread.read(cx).model())
4385            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4386    }
4387
4388    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4389        let thread = self.thread()?.read(cx);
4390        let usage = thread.token_usage()?;
4391        let is_generating = thread.status() != ThreadStatus::Idle;
4392
4393        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4394        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4395
4396        Some(
4397            h_flex()
4398                .flex_shrink_0()
4399                .gap_0p5()
4400                .mr_1p5()
4401                .child(
4402                    Label::new(used)
4403                        .size(LabelSize::Small)
4404                        .color(Color::Muted)
4405                        .map(|label| {
4406                            if is_generating {
4407                                label
4408                                    .with_animation(
4409                                        "used-tokens-label",
4410                                        Animation::new(Duration::from_secs(2))
4411                                            .repeat()
4412                                            .with_easing(pulsating_between(0.3, 0.8)),
4413                                        |label, delta| label.alpha(delta),
4414                                    )
4415                                    .into_any()
4416                            } else {
4417                                label.into_any_element()
4418                            }
4419                        }),
4420                )
4421                .child(
4422                    Label::new("/")
4423                        .size(LabelSize::Small)
4424                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4425                )
4426                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4427        )
4428    }
4429
4430    fn toggle_burn_mode(
4431        &mut self,
4432        _: &ToggleBurnMode,
4433        _window: &mut Window,
4434        cx: &mut Context<Self>,
4435    ) {
4436        let Some(thread) = self.as_native_thread(cx) else {
4437            return;
4438        };
4439
4440        thread.update(cx, |thread, cx| {
4441            let current_mode = thread.completion_mode();
4442            thread.set_completion_mode(
4443                match current_mode {
4444                    CompletionMode::Burn => CompletionMode::Normal,
4445                    CompletionMode::Normal => CompletionMode::Burn,
4446                },
4447                cx,
4448            );
4449        });
4450    }
4451
4452    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4453        let Some(thread) = self.thread() else {
4454            return;
4455        };
4456        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4457        let action_log = thread.read(cx).action_log().clone();
4458        action_log.update(cx, |action_log, cx| {
4459            action_log.keep_all_edits(Some(telemetry), cx)
4460        });
4461    }
4462
4463    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4464        let Some(thread) = self.thread() else {
4465            return;
4466        };
4467        let telemetry = ActionLogTelemetry::from(thread.read(cx));
4468        let action_log = thread.read(cx).action_log().clone();
4469        action_log
4470            .update(cx, |action_log, cx| {
4471                action_log.reject_all_edits(Some(telemetry), cx)
4472            })
4473            .detach();
4474    }
4475
4476    fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4477        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4478    }
4479
4480    fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4481        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4482    }
4483
4484    fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4485        self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4486    }
4487
4488    fn authorize_pending_tool_call(
4489        &mut self,
4490        kind: acp::PermissionOptionKind,
4491        window: &mut Window,
4492        cx: &mut Context<Self>,
4493    ) -> Option<()> {
4494        let thread = self.thread()?.read(cx);
4495        let tool_call = thread.first_tool_awaiting_confirmation()?;
4496        let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4497            return None;
4498        };
4499        let option = options.iter().find(|o| o.kind == kind)?;
4500
4501        self.authorize_tool_call(
4502            tool_call.id.clone(),
4503            option.option_id.clone(),
4504            option.kind,
4505            window,
4506            cx,
4507        );
4508
4509        Some(())
4510    }
4511
4512    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4513        let thread = self.as_native_thread(cx)?.read(cx);
4514
4515        if thread
4516            .model()
4517            .is_none_or(|model| !model.supports_burn_mode())
4518        {
4519            return None;
4520        }
4521
4522        let active_completion_mode = thread.completion_mode();
4523        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4524        let icon = if burn_mode_enabled {
4525            IconName::ZedBurnModeOn
4526        } else {
4527            IconName::ZedBurnMode
4528        };
4529
4530        Some(
4531            IconButton::new("burn-mode", icon)
4532                .icon_size(IconSize::Small)
4533                .icon_color(Color::Muted)
4534                .toggle_state(burn_mode_enabled)
4535                .selected_icon_color(Color::Error)
4536                .on_click(cx.listener(|this, _event, window, cx| {
4537                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4538                }))
4539                .tooltip(move |_window, cx| {
4540                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4541                        .into()
4542                })
4543                .into_any_element(),
4544        )
4545    }
4546
4547    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4548        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4549        let is_generating = self
4550            .thread()
4551            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4552
4553        if self.is_loading_contents {
4554            div()
4555                .id("loading-message-content")
4556                .px_1()
4557                .tooltip(Tooltip::text("Loading Added Context…"))
4558                .child(loading_contents_spinner(IconSize::default()))
4559                .into_any_element()
4560        } else if is_generating && is_editor_empty {
4561            IconButton::new("stop-generation", IconName::Stop)
4562                .icon_color(Color::Error)
4563                .style(ButtonStyle::Tinted(ui::TintColor::Error))
4564                .tooltip(move |_window, cx| {
4565                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
4566                })
4567                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4568                .into_any_element()
4569        } else {
4570            let send_btn_tooltip = if is_editor_empty && !is_generating {
4571                "Type to Send"
4572            } else if is_generating {
4573                "Stop and Send Message"
4574            } else {
4575                "Send"
4576            };
4577
4578            IconButton::new("send-message", IconName::Send)
4579                .style(ButtonStyle::Filled)
4580                .map(|this| {
4581                    if is_editor_empty && !is_generating {
4582                        this.disabled(true).icon_color(Color::Muted)
4583                    } else {
4584                        this.icon_color(Color::Accent)
4585                    }
4586                })
4587                .tooltip(move |_window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, cx))
4588                .on_click(cx.listener(|this, _, window, cx| {
4589                    this.send(window, cx);
4590                }))
4591                .into_any_element()
4592        }
4593    }
4594
4595    fn is_following(&self, cx: &App) -> bool {
4596        match self.thread().map(|thread| thread.read(cx).status()) {
4597            Some(ThreadStatus::Generating) => self
4598                .workspace
4599                .read_with(cx, |workspace, _| {
4600                    workspace.is_being_followed(CollaboratorId::Agent)
4601                })
4602                .unwrap_or(false),
4603            _ => self.should_be_following,
4604        }
4605    }
4606
4607    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4608        let following = self.is_following(cx);
4609
4610        self.should_be_following = !following;
4611        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4612            self.workspace
4613                .update(cx, |workspace, cx| {
4614                    if following {
4615                        workspace.unfollow(CollaboratorId::Agent, window, cx);
4616                    } else {
4617                        workspace.follow(CollaboratorId::Agent, window, cx);
4618                    }
4619                })
4620                .ok();
4621        }
4622
4623        telemetry::event!("Follow Agent Selected", following = !following);
4624    }
4625
4626    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4627        let following = self.is_following(cx);
4628
4629        let tooltip_label = if following {
4630            if self.agent.name() == "Zed Agent" {
4631                format!("Stop Following the {}", self.agent.name())
4632            } else {
4633                format!("Stop Following {}", self.agent.name())
4634            }
4635        } else {
4636            if self.agent.name() == "Zed Agent" {
4637                format!("Follow the {}", self.agent.name())
4638            } else {
4639                format!("Follow {}", self.agent.name())
4640            }
4641        };
4642
4643        IconButton::new("follow-agent", IconName::Crosshair)
4644            .icon_size(IconSize::Small)
4645            .icon_color(Color::Muted)
4646            .toggle_state(following)
4647            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4648            .tooltip(move |_window, cx| {
4649                if following {
4650                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4651                } else {
4652                    Tooltip::with_meta(
4653                        tooltip_label.clone(),
4654                        Some(&Follow),
4655                        "Track the agent's location as it reads and edits files.",
4656                        cx,
4657                    )
4658                }
4659            })
4660            .on_click(cx.listener(move |this, _, window, cx| {
4661                this.toggle_following(window, cx);
4662            }))
4663    }
4664
4665    fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4666        let message_editor = self.message_editor.clone();
4667        let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
4668
4669        IconButton::new("add-context", IconName::AtSign)
4670            .icon_size(IconSize::Small)
4671            .icon_color(Color::Muted)
4672            .when(!menu_visible, |this| {
4673                this.tooltip(move |_window, cx| {
4674                    Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
4675                })
4676            })
4677            .on_click(cx.listener(move |_this, _, window, cx| {
4678                let message_editor_clone = message_editor.clone();
4679
4680                window.defer(cx, move |window, cx| {
4681                    message_editor_clone.update(cx, |message_editor, cx| {
4682                        message_editor.trigger_completion_menu(window, cx);
4683                    });
4684                });
4685            }))
4686    }
4687
4688    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4689        let workspace = self.workspace.clone();
4690        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4691            Self::open_link(text, &workspace, window, cx);
4692        })
4693    }
4694
4695    fn open_link(
4696        url: SharedString,
4697        workspace: &WeakEntity<Workspace>,
4698        window: &mut Window,
4699        cx: &mut App,
4700    ) {
4701        let Some(workspace) = workspace.upgrade() else {
4702            cx.open_url(&url);
4703            return;
4704        };
4705
4706        if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
4707        {
4708            workspace.update(cx, |workspace, cx| match mention {
4709                MentionUri::File { abs_path } => {
4710                    let project = workspace.project();
4711                    let Some(path) =
4712                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4713                    else {
4714                        return;
4715                    };
4716
4717                    workspace
4718                        .open_path(path, None, true, window, cx)
4719                        .detach_and_log_err(cx);
4720                }
4721                MentionUri::PastedImage => {}
4722                MentionUri::Directory { abs_path } => {
4723                    let project = workspace.project();
4724                    let Some(entry_id) = project.update(cx, |project, cx| {
4725                        let path = project.find_project_path(abs_path, cx)?;
4726                        project.entry_for_path(&path, cx).map(|entry| entry.id)
4727                    }) else {
4728                        return;
4729                    };
4730
4731                    project.update(cx, |_, cx| {
4732                        cx.emit(project::Event::RevealInProjectPanel(entry_id));
4733                    });
4734                }
4735                MentionUri::Symbol {
4736                    abs_path: path,
4737                    line_range,
4738                    ..
4739                }
4740                | MentionUri::Selection {
4741                    abs_path: Some(path),
4742                    line_range,
4743                } => {
4744                    let project = workspace.project();
4745                    let Some(path) =
4746                        project.update(cx, |project, cx| project.find_project_path(path, cx))
4747                    else {
4748                        return;
4749                    };
4750
4751                    let item = workspace.open_path(path, None, true, window, cx);
4752                    window
4753                        .spawn(cx, async move |cx| {
4754                            let Some(editor) = item.await?.downcast::<Editor>() else {
4755                                return Ok(());
4756                            };
4757                            let range = Point::new(*line_range.start(), 0)
4758                                ..Point::new(*line_range.start(), 0);
4759                            editor
4760                                .update_in(cx, |editor, window, cx| {
4761                                    editor.change_selections(
4762                                        SelectionEffects::scroll(Autoscroll::center()),
4763                                        window,
4764                                        cx,
4765                                        |s| s.select_ranges(vec![range]),
4766                                    );
4767                                })
4768                                .ok();
4769                            anyhow::Ok(())
4770                        })
4771                        .detach_and_log_err(cx);
4772                }
4773                MentionUri::Selection { abs_path: None, .. } => {}
4774                MentionUri::Thread { id, name } => {
4775                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4776                        panel.update(cx, |panel, cx| {
4777                            panel.load_agent_thread(
4778                                DbThreadMetadata {
4779                                    id,
4780                                    title: name.into(),
4781                                    updated_at: Default::default(),
4782                                },
4783                                window,
4784                                cx,
4785                            )
4786                        });
4787                    }
4788                }
4789                MentionUri::TextThread { path, .. } => {
4790                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4791                        panel.update(cx, |panel, cx| {
4792                            panel
4793                                .open_saved_text_thread(path.as_path().into(), window, cx)
4794                                .detach_and_log_err(cx);
4795                        });
4796                    }
4797                }
4798                MentionUri::Rule { id, .. } => {
4799                    let PromptId::User { uuid } = id else {
4800                        return;
4801                    };
4802                    window.dispatch_action(
4803                        Box::new(OpenRulesLibrary {
4804                            prompt_to_select: Some(uuid.0),
4805                        }),
4806                        cx,
4807                    )
4808                }
4809                MentionUri::Fetch { url } => {
4810                    cx.open_url(url.as_str());
4811                }
4812            })
4813        } else {
4814            cx.open_url(&url);
4815        }
4816    }
4817
4818    fn open_tool_call_location(
4819        &self,
4820        entry_ix: usize,
4821        location_ix: usize,
4822        window: &mut Window,
4823        cx: &mut Context<Self>,
4824    ) -> Option<()> {
4825        let (tool_call_location, agent_location) = self
4826            .thread()?
4827            .read(cx)
4828            .entries()
4829            .get(entry_ix)?
4830            .location(location_ix)?;
4831
4832        let project_path = self
4833            .project
4834            .read(cx)
4835            .find_project_path(&tool_call_location.path, cx)?;
4836
4837        let open_task = self
4838            .workspace
4839            .update(cx, |workspace, cx| {
4840                workspace.open_path(project_path, None, true, window, cx)
4841            })
4842            .log_err()?;
4843        window
4844            .spawn(cx, async move |cx| {
4845                let item = open_task.await?;
4846
4847                let Some(active_editor) = item.downcast::<Editor>() else {
4848                    return anyhow::Ok(());
4849                };
4850
4851                active_editor.update_in(cx, |editor, window, cx| {
4852                    let multibuffer = editor.buffer().read(cx);
4853                    let buffer = multibuffer.as_singleton();
4854                    if agent_location.buffer.upgrade() == buffer {
4855                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4856                        let anchor =
4857                            editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
4858                        editor.change_selections(Default::default(), window, cx, |selections| {
4859                            selections.select_anchor_ranges([anchor..anchor]);
4860                        })
4861                    } else {
4862                        let row = tool_call_location.line.unwrap_or_default();
4863                        editor.change_selections(Default::default(), window, cx, |selections| {
4864                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4865                        })
4866                    }
4867                })?;
4868
4869                anyhow::Ok(())
4870            })
4871            .detach_and_log_err(cx);
4872
4873        None
4874    }
4875
4876    pub fn open_thread_as_markdown(
4877        &self,
4878        workspace: Entity<Workspace>,
4879        window: &mut Window,
4880        cx: &mut App,
4881    ) -> Task<Result<()>> {
4882        let markdown_language_task = workspace
4883            .read(cx)
4884            .app_state()
4885            .languages
4886            .language_for_name("Markdown");
4887
4888        let (thread_title, markdown) = if let Some(thread) = self.thread() {
4889            let thread = thread.read(cx);
4890            (thread.title().to_string(), thread.to_markdown(cx))
4891        } else {
4892            return Task::ready(Ok(()));
4893        };
4894
4895        let project = workspace.read(cx).project().clone();
4896        window.spawn(cx, async move |cx| {
4897            let markdown_language = markdown_language_task.await?;
4898
4899            let buffer = project
4900                .update(cx, |project, cx| project.create_buffer(false, cx))?
4901                .await?;
4902
4903            buffer.update(cx, |buffer, cx| {
4904                buffer.set_text(markdown, cx);
4905                buffer.set_language(Some(markdown_language), cx);
4906                buffer.set_capability(language::Capability::ReadWrite, cx);
4907            })?;
4908
4909            workspace.update_in(cx, |workspace, window, cx| {
4910                let buffer = cx
4911                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4912
4913                workspace.add_item_to_active_pane(
4914                    Box::new(cx.new(|cx| {
4915                        let mut editor =
4916                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4917                        editor.set_breadcrumb_header(thread_title);
4918                        editor
4919                    })),
4920                    None,
4921                    true,
4922                    window,
4923                    cx,
4924                );
4925            })?;
4926            anyhow::Ok(())
4927        })
4928    }
4929
4930    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4931        self.list_state.scroll_to(ListOffset::default());
4932        cx.notify();
4933    }
4934
4935    fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
4936        let Some(thread) = self.thread() else {
4937            return;
4938        };
4939
4940        let entries = thread.read(cx).entries();
4941        if entries.is_empty() {
4942            return;
4943        }
4944
4945        // Find the most recent user message and scroll it to the top of the viewport.
4946        // (Fallback: if no user message exists, scroll to the bottom.)
4947        if let Some(ix) = entries
4948            .iter()
4949            .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
4950        {
4951            self.list_state.scroll_to(ListOffset {
4952                item_ix: ix,
4953                offset_in_item: px(0.0),
4954            });
4955            cx.notify();
4956        } else {
4957            self.scroll_to_bottom(cx);
4958        }
4959    }
4960
4961    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4962        if let Some(thread) = self.thread() {
4963            let entry_count = thread.read(cx).entries().len();
4964            self.list_state.reset(entry_count);
4965            cx.notify();
4966        }
4967    }
4968
4969    fn notify_with_sound(
4970        &mut self,
4971        caption: impl Into<SharedString>,
4972        icon: IconName,
4973        window: &mut Window,
4974        cx: &mut Context<Self>,
4975    ) {
4976        self.play_notification_sound(window, cx);
4977        self.show_notification(caption, icon, window, cx);
4978    }
4979
4980    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4981        let settings = AgentSettings::get_global(cx);
4982        if settings.play_sound_when_agent_done && !window.is_window_active() {
4983            Audio::play_sound(Sound::AgentDone, cx);
4984        }
4985    }
4986
4987    fn show_notification(
4988        &mut self,
4989        caption: impl Into<SharedString>,
4990        icon: IconName,
4991        window: &mut Window,
4992        cx: &mut Context<Self>,
4993    ) {
4994        if !self.notifications.is_empty() {
4995            return;
4996        }
4997
4998        let settings = AgentSettings::get_global(cx);
4999
5000        let window_is_inactive = !window.is_window_active();
5001        let panel_is_hidden = self
5002            .workspace
5003            .upgrade()
5004            .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
5005            .unwrap_or(true);
5006
5007        let should_notify = window_is_inactive || panel_is_hidden;
5008
5009        if !should_notify {
5010            return;
5011        }
5012
5013        // TODO: Change this once we have title summarization for external agents.
5014        let title = self.agent.name();
5015
5016        match settings.notify_when_agent_waiting {
5017            NotifyWhenAgentWaiting::PrimaryScreen => {
5018                if let Some(primary) = cx.primary_display() {
5019                    self.pop_up(icon, caption.into(), title, window, primary, cx);
5020                }
5021            }
5022            NotifyWhenAgentWaiting::AllScreens => {
5023                let caption = caption.into();
5024                for screen in cx.displays() {
5025                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
5026                }
5027            }
5028            NotifyWhenAgentWaiting::Never => {
5029                // Don't show anything
5030            }
5031        }
5032    }
5033
5034    fn pop_up(
5035        &mut self,
5036        icon: IconName,
5037        caption: SharedString,
5038        title: SharedString,
5039        window: &mut Window,
5040        screen: Rc<dyn PlatformDisplay>,
5041        cx: &mut Context<Self>,
5042    ) {
5043        let options = AgentNotification::window_options(screen, cx);
5044
5045        let project_name = self.workspace.upgrade().and_then(|workspace| {
5046            workspace
5047                .read(cx)
5048                .project()
5049                .read(cx)
5050                .visible_worktrees(cx)
5051                .next()
5052                .map(|worktree| worktree.read(cx).root_name_str().to_string())
5053        });
5054
5055        if let Some(screen_window) = cx
5056            .open_window(options, |_window, cx| {
5057                cx.new(|_cx| {
5058                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
5059                })
5060            })
5061            .log_err()
5062            && let Some(pop_up) = screen_window.entity(cx).log_err()
5063        {
5064            self.notification_subscriptions
5065                .entry(screen_window)
5066                .or_insert_with(Vec::new)
5067                .push(cx.subscribe_in(&pop_up, window, {
5068                    |this, _, event, window, cx| match event {
5069                        AgentNotificationEvent::Accepted => {
5070                            let handle = window.window_handle();
5071                            cx.activate(true);
5072
5073                            let workspace_handle = this.workspace.clone();
5074
5075                            // If there are multiple Zed windows, activate the correct one.
5076                            cx.defer(move |cx| {
5077                                handle
5078                                    .update(cx, |_view, window, _cx| {
5079                                        window.activate_window();
5080
5081                                        if let Some(workspace) = workspace_handle.upgrade() {
5082                                            workspace.update(_cx, |workspace, cx| {
5083                                                workspace.focus_panel::<AgentPanel>(window, cx);
5084                                            });
5085                                        }
5086                                    })
5087                                    .log_err();
5088                            });
5089
5090                            this.dismiss_notifications(cx);
5091                        }
5092                        AgentNotificationEvent::Dismissed => {
5093                            this.dismiss_notifications(cx);
5094                        }
5095                    }
5096                }));
5097
5098            self.notifications.push(screen_window);
5099
5100            // If the user manually refocuses the original window, dismiss the popup.
5101            self.notification_subscriptions
5102                .entry(screen_window)
5103                .or_insert_with(Vec::new)
5104                .push({
5105                    let pop_up_weak = pop_up.downgrade();
5106
5107                    cx.observe_window_activation(window, move |_, window, cx| {
5108                        if window.is_window_active()
5109                            && let Some(pop_up) = pop_up_weak.upgrade()
5110                        {
5111                            pop_up.update(cx, |_, cx| {
5112                                cx.emit(AgentNotificationEvent::Dismissed);
5113                            });
5114                        }
5115                    })
5116                });
5117        }
5118    }
5119
5120    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
5121        for window in self.notifications.drain(..) {
5122            window
5123                .update(cx, |_, window, _| {
5124                    window.remove_window();
5125                })
5126                .ok();
5127
5128            self.notification_subscriptions.remove(&window);
5129        }
5130    }
5131
5132    fn render_generating(&self, confirmation: bool) -> impl IntoElement {
5133        h_flex()
5134            .id("generating-spinner")
5135            .py_2()
5136            .px(rems_from_px(22.))
5137            .map(|this| {
5138                if confirmation {
5139                    this.gap_2()
5140                        .child(
5141                            h_flex()
5142                                .w_2()
5143                                .child(SpinnerLabel::sand().size(LabelSize::Small)),
5144                        )
5145                        .child(
5146                            LoadingLabel::new("Waiting Confirmation")
5147                                .size(LabelSize::Small)
5148                                .color(Color::Muted),
5149                        )
5150                } else {
5151                    this.child(SpinnerLabel::new().size(LabelSize::Small))
5152                }
5153            })
5154            .into_any_element()
5155    }
5156
5157    fn render_thread_controls(
5158        &self,
5159        thread: &Entity<AcpThread>,
5160        cx: &Context<Self>,
5161    ) -> impl IntoElement {
5162        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
5163        if is_generating {
5164            return self.render_generating(false).into_any_element();
5165        }
5166
5167        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
5168            .shape(ui::IconButtonShape::Square)
5169            .icon_size(IconSize::Small)
5170            .icon_color(Color::Ignored)
5171            .tooltip(Tooltip::text("Open Thread as Markdown"))
5172            .on_click(cx.listener(move |this, _, window, cx| {
5173                if let Some(workspace) = this.workspace.upgrade() {
5174                    this.open_thread_as_markdown(workspace, window, cx)
5175                        .detach_and_log_err(cx);
5176                }
5177            }));
5178
5179        let scroll_to_recent_user_prompt =
5180            IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
5181                .shape(ui::IconButtonShape::Square)
5182                .icon_size(IconSize::Small)
5183                .icon_color(Color::Ignored)
5184                .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
5185                .on_click(cx.listener(move |this, _, _, cx| {
5186                    this.scroll_to_most_recent_user_prompt(cx);
5187                }));
5188
5189        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
5190            .shape(ui::IconButtonShape::Square)
5191            .icon_size(IconSize::Small)
5192            .icon_color(Color::Ignored)
5193            .tooltip(Tooltip::text("Scroll To Top"))
5194            .on_click(cx.listener(move |this, _, _, cx| {
5195                this.scroll_to_top(cx);
5196            }));
5197
5198        let mut container = h_flex()
5199            .w_full()
5200            .py_2()
5201            .px_5()
5202            .gap_px()
5203            .opacity(0.6)
5204            .hover(|s| s.opacity(1.))
5205            .justify_end();
5206
5207        if AgentSettings::get_global(cx).enable_feedback
5208            && self
5209                .thread()
5210                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5211        {
5212            let feedback = self.thread_feedback.feedback;
5213
5214            let tooltip_meta = || {
5215                SharedString::new(
5216                    "Rating the thread sends all of your current conversation to the Zed team.",
5217                )
5218            };
5219
5220            container = container
5221                .child(
5222                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5223                        .shape(ui::IconButtonShape::Square)
5224                        .icon_size(IconSize::Small)
5225                        .icon_color(match feedback {
5226                            Some(ThreadFeedback::Positive) => Color::Accent,
5227                            _ => Color::Ignored,
5228                        })
5229                        .tooltip(move |window, cx| match feedback {
5230                            Some(ThreadFeedback::Positive) => {
5231                                Tooltip::text("Thanks for your feedback!")(window, cx)
5232                            }
5233                            _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
5234                        })
5235                        .on_click(cx.listener(move |this, _, window, cx| {
5236                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5237                        })),
5238                )
5239                .child(
5240                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5241                        .shape(ui::IconButtonShape::Square)
5242                        .icon_size(IconSize::Small)
5243                        .icon_color(match feedback {
5244                            Some(ThreadFeedback::Negative) => Color::Accent,
5245                            _ => Color::Ignored,
5246                        })
5247                        .tooltip(move |window, cx| match feedback {
5248                            Some(ThreadFeedback::Negative) => {
5249                                Tooltip::text(
5250                                    "We appreciate your feedback and will use it to improve in the future.",
5251                                )(window, cx)
5252                            }
5253                            _ => {
5254                                Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
5255                            }
5256                        })
5257                        .on_click(cx.listener(move |this, _, window, cx| {
5258                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5259                        })),
5260                );
5261        }
5262
5263        container
5264            .child(open_as_markdown)
5265            .child(scroll_to_recent_user_prompt)
5266            .child(scroll_to_top)
5267            .into_any_element()
5268    }
5269
5270    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5271        h_flex()
5272            .key_context("AgentFeedbackMessageEditor")
5273            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5274                this.thread_feedback.dismiss_comments();
5275                cx.notify();
5276            }))
5277            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5278                this.submit_feedback_message(cx);
5279            }))
5280            .p_2()
5281            .mb_2()
5282            .mx_5()
5283            .gap_1()
5284            .rounded_md()
5285            .border_1()
5286            .border_color(cx.theme().colors().border)
5287            .bg(cx.theme().colors().editor_background)
5288            .child(div().w_full().child(editor))
5289            .child(
5290                h_flex()
5291                    .child(
5292                        IconButton::new("dismiss-feedback-message", IconName::Close)
5293                            .icon_color(Color::Error)
5294                            .icon_size(IconSize::XSmall)
5295                            .shape(ui::IconButtonShape::Square)
5296                            .on_click(cx.listener(move |this, _, _window, cx| {
5297                                this.thread_feedback.dismiss_comments();
5298                                cx.notify();
5299                            })),
5300                    )
5301                    .child(
5302                        IconButton::new("submit-feedback-message", IconName::Return)
5303                            .icon_size(IconSize::XSmall)
5304                            .shape(ui::IconButtonShape::Square)
5305                            .on_click(cx.listener(move |this, _, _window, cx| {
5306                                this.submit_feedback_message(cx);
5307                            })),
5308                    ),
5309            )
5310    }
5311
5312    fn handle_feedback_click(
5313        &mut self,
5314        feedback: ThreadFeedback,
5315        window: &mut Window,
5316        cx: &mut Context<Self>,
5317    ) {
5318        let Some(thread) = self.thread().cloned() else {
5319            return;
5320        };
5321
5322        self.thread_feedback.submit(thread, feedback, window, cx);
5323        cx.notify();
5324    }
5325
5326    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5327        let Some(thread) = self.thread().cloned() else {
5328            return;
5329        };
5330
5331        self.thread_feedback.submit_comments(thread, cx);
5332        cx.notify();
5333    }
5334
5335    fn render_token_limit_callout(
5336        &self,
5337        line_height: Pixels,
5338        cx: &mut Context<Self>,
5339    ) -> Option<Callout> {
5340        let token_usage = self.thread()?.read(cx).token_usage()?;
5341        let ratio = token_usage.ratio();
5342
5343        let (severity, title) = match ratio {
5344            acp_thread::TokenUsageRatio::Normal => return None,
5345            acp_thread::TokenUsageRatio::Warning => {
5346                (Severity::Warning, "Thread reaching the token limit soon")
5347            }
5348            acp_thread::TokenUsageRatio::Exceeded => {
5349                (Severity::Error, "Thread reached the token limit")
5350            }
5351        };
5352
5353        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5354            thread.read(cx).completion_mode() == CompletionMode::Normal
5355                && thread
5356                    .read(cx)
5357                    .model()
5358                    .is_some_and(|model| model.supports_burn_mode())
5359        });
5360
5361        let description = if burn_mode_available {
5362            "To continue, start a new thread from a summary or turn Burn Mode on."
5363        } else {
5364            "To continue, start a new thread from a summary."
5365        };
5366
5367        Some(
5368            Callout::new()
5369                .severity(severity)
5370                .line_height(line_height)
5371                .title(title)
5372                .description(description)
5373                .actions_slot(
5374                    h_flex()
5375                        .gap_0p5()
5376                        .child(
5377                            Button::new("start-new-thread", "Start New Thread")
5378                                .label_size(LabelSize::Small)
5379                                .on_click(cx.listener(|this, _, window, cx| {
5380                                    let Some(thread) = this.thread() else {
5381                                        return;
5382                                    };
5383                                    let session_id = thread.read(cx).session_id().clone();
5384                                    window.dispatch_action(
5385                                        crate::NewNativeAgentThreadFromSummary {
5386                                            from_session_id: session_id,
5387                                        }
5388                                        .boxed_clone(),
5389                                        cx,
5390                                    );
5391                                })),
5392                        )
5393                        .when(burn_mode_available, |this| {
5394                            this.child(
5395                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5396                                    .icon_size(IconSize::XSmall)
5397                                    .on_click(cx.listener(|this, _event, window, cx| {
5398                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5399                                    })),
5400                            )
5401                        }),
5402                ),
5403        )
5404    }
5405
5406    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5407        if !self.is_using_zed_ai_models(cx) {
5408            return None;
5409        }
5410
5411        let user_store = self.project.read(cx).user_store().read(cx);
5412        if user_store.is_usage_based_billing_enabled() {
5413            return None;
5414        }
5415
5416        let plan = user_store
5417            .plan()
5418            .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5419
5420        let usage = user_store.model_request_usage()?;
5421
5422        Some(
5423            div()
5424                .child(UsageCallout::new(plan, usage))
5425                .line_height(line_height),
5426        )
5427    }
5428
5429    fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5430        self.entry_view_state.update(cx, |entry_view_state, cx| {
5431            entry_view_state.agent_ui_font_size_changed(cx);
5432        });
5433    }
5434
5435    pub(crate) fn insert_dragged_files(
5436        &self,
5437        paths: Vec<project::ProjectPath>,
5438        added_worktrees: Vec<Entity<project::Worktree>>,
5439        window: &mut Window,
5440        cx: &mut Context<Self>,
5441    ) {
5442        self.message_editor.update(cx, |message_editor, cx| {
5443            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5444        })
5445    }
5446
5447    /// Inserts the selected text into the message editor or the message being
5448    /// edited, if any.
5449    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5450        self.active_editor(cx).update(cx, |editor, cx| {
5451            editor.insert_selections(window, cx);
5452        });
5453    }
5454
5455    fn render_thread_retry_status_callout(
5456        &self,
5457        _window: &mut Window,
5458        _cx: &mut Context<Self>,
5459    ) -> Option<Callout> {
5460        let state = self.thread_retry_status.as_ref()?;
5461
5462        let next_attempt_in = state
5463            .duration
5464            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5465        if next_attempt_in.is_zero() {
5466            return None;
5467        }
5468
5469        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5470
5471        let retry_message = if state.max_attempts == 1 {
5472            if next_attempt_in_secs == 1 {
5473                "Retrying. Next attempt in 1 second.".to_string()
5474            } else {
5475                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5476            }
5477        } else if next_attempt_in_secs == 1 {
5478            format!(
5479                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5480                state.attempt, state.max_attempts,
5481            )
5482        } else {
5483            format!(
5484                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5485                state.attempt, state.max_attempts,
5486            )
5487        };
5488
5489        Some(
5490            Callout::new()
5491                .severity(Severity::Warning)
5492                .title(state.last_error.clone())
5493                .description(retry_message),
5494        )
5495    }
5496
5497    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
5498        Callout::new()
5499            .icon(IconName::Warning)
5500            .severity(Severity::Warning)
5501            .title("Codex on Windows")
5502            .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
5503            .actions_slot(
5504                Button::new("open-wsl-modal", "Open in WSL")
5505                    .icon_size(IconSize::Small)
5506                    .icon_color(Color::Muted)
5507                    .on_click(cx.listener({
5508                        move |_, _, _window, cx| {
5509                            #[cfg(windows)]
5510                            _window.dispatch_action(
5511                                zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5512                                cx,
5513                            );
5514                            cx.notify();
5515                        }
5516                    })),
5517            )
5518            .dismiss_action(
5519                IconButton::new("dismiss", IconName::Close)
5520                    .icon_size(IconSize::Small)
5521                    .icon_color(Color::Muted)
5522                    .tooltip(Tooltip::text("Dismiss Warning"))
5523                    .on_click(cx.listener({
5524                        move |this, _, _, cx| {
5525                            this.show_codex_windows_warning = false;
5526                            cx.notify();
5527                        }
5528                    })),
5529            )
5530    }
5531
5532    fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5533        let content = match self.thread_error.as_ref()? {
5534            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5535            ThreadError::Refusal => self.render_refusal_error(cx),
5536            ThreadError::AuthenticationRequired(error) => {
5537                self.render_authentication_required_error(error.clone(), cx)
5538            }
5539            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5540            ThreadError::ModelRequestLimitReached(plan) => {
5541                self.render_model_request_limit_reached_error(*plan, cx)
5542            }
5543            ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5544        };
5545
5546        Some(div().child(content))
5547    }
5548
5549    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5550        v_flex().w_full().justify_end().child(
5551            h_flex()
5552                .p_2()
5553                .pr_3()
5554                .w_full()
5555                .gap_1p5()
5556                .border_t_1()
5557                .border_color(cx.theme().colors().border)
5558                .bg(cx.theme().colors().element_background)
5559                .child(
5560                    h_flex()
5561                        .flex_1()
5562                        .gap_1p5()
5563                        .child(
5564                            Icon::new(IconName::Download)
5565                                .color(Color::Accent)
5566                                .size(IconSize::Small),
5567                        )
5568                        .child(Label::new("New version available").size(LabelSize::Small)),
5569                )
5570                .child(
5571                    Button::new("update-button", format!("Update to v{}", version))
5572                        .label_size(LabelSize::Small)
5573                        .style(ButtonStyle::Tinted(TintColor::Accent))
5574                        .on_click(cx.listener(|this, _, window, cx| {
5575                            this.reset(window, cx);
5576                        })),
5577                ),
5578        )
5579    }
5580
5581    fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
5582        if let Some(thread) = self.as_native_thread(cx) {
5583            Some(thread.read(cx).profile().0.clone())
5584        } else if let Some(mode_selector) = self.mode_selector() {
5585            Some(mode_selector.read(cx).mode().0)
5586        } else {
5587            None
5588        }
5589    }
5590
5591    fn current_model_id(&self, cx: &App) -> Option<String> {
5592        self.model_selector
5593            .as_ref()
5594            .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5595    }
5596
5597    fn current_model_name(&self, cx: &App) -> SharedString {
5598        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5599        // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5600        // This provides better clarity about what refused the request
5601        if self.as_native_connection(cx).is_some() {
5602            self.model_selector
5603                .as_ref()
5604                .and_then(|selector| selector.read(cx).active_model(cx))
5605                .map(|model| model.name.clone())
5606                .unwrap_or_else(|| SharedString::from("The model"))
5607        } else {
5608            // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5609            self.agent.name()
5610        }
5611    }
5612
5613    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5614        let model_or_agent_name = self.current_model_name(cx);
5615        let refusal_message = format!(
5616            "{} 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.",
5617            model_or_agent_name
5618        );
5619
5620        Callout::new()
5621            .severity(Severity::Error)
5622            .title("Request Refused")
5623            .icon(IconName::XCircle)
5624            .description(refusal_message.clone())
5625            .actions_slot(self.create_copy_button(&refusal_message))
5626            .dismiss_action(self.dismiss_error_button(cx))
5627    }
5628
5629    fn render_any_thread_error(
5630        &mut self,
5631        error: SharedString,
5632        window: &mut Window,
5633        cx: &mut Context<'_, Self>,
5634    ) -> Callout {
5635        let can_resume = self
5636            .thread()
5637            .map_or(false, |thread| thread.read(cx).can_resume(cx));
5638
5639        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5640            let thread = thread.read(cx);
5641            let supports_burn_mode = thread
5642                .model()
5643                .map_or(false, |model| model.supports_burn_mode());
5644            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5645        });
5646
5647        let markdown = if let Some(markdown) = &self.thread_error_markdown {
5648            markdown.clone()
5649        } else {
5650            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5651            self.thread_error_markdown = Some(markdown.clone());
5652            markdown
5653        };
5654
5655        let markdown_style = default_markdown_style(false, true, window, cx);
5656        let description = self
5657            .render_markdown(markdown, markdown_style)
5658            .into_any_element();
5659
5660        Callout::new()
5661            .severity(Severity::Error)
5662            .icon(IconName::XCircle)
5663            .title("An Error Happened")
5664            .description_slot(description)
5665            .actions_slot(
5666                h_flex()
5667                    .gap_0p5()
5668                    .when(can_resume && can_enable_burn_mode, |this| {
5669                        this.child(
5670                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5671                                .icon(IconName::ZedBurnMode)
5672                                .icon_position(IconPosition::Start)
5673                                .icon_size(IconSize::Small)
5674                                .label_size(LabelSize::Small)
5675                                .on_click(cx.listener(|this, _, window, cx| {
5676                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5677                                    this.resume_chat(cx);
5678                                })),
5679                        )
5680                    })
5681                    .when(can_resume, |this| {
5682                        this.child(
5683                            IconButton::new("retry", IconName::RotateCw)
5684                                .icon_size(IconSize::Small)
5685                                .tooltip(Tooltip::text("Retry Generation"))
5686                                .on_click(cx.listener(|this, _, _window, cx| {
5687                                    this.resume_chat(cx);
5688                                })),
5689                        )
5690                    })
5691                    .child(self.create_copy_button(error.to_string())),
5692            )
5693            .dismiss_action(self.dismiss_error_button(cx))
5694    }
5695
5696    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5697        const ERROR_MESSAGE: &str =
5698            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5699
5700        Callout::new()
5701            .severity(Severity::Error)
5702            .icon(IconName::XCircle)
5703            .title("Free Usage Exceeded")
5704            .description(ERROR_MESSAGE)
5705            .actions_slot(
5706                h_flex()
5707                    .gap_0p5()
5708                    .child(self.upgrade_button(cx))
5709                    .child(self.create_copy_button(ERROR_MESSAGE)),
5710            )
5711            .dismiss_action(self.dismiss_error_button(cx))
5712    }
5713
5714    fn render_authentication_required_error(
5715        &self,
5716        error: SharedString,
5717        cx: &mut Context<Self>,
5718    ) -> Callout {
5719        Callout::new()
5720            .severity(Severity::Error)
5721            .title("Authentication Required")
5722            .icon(IconName::XCircle)
5723            .description(error.clone())
5724            .actions_slot(
5725                h_flex()
5726                    .gap_0p5()
5727                    .child(self.authenticate_button(cx))
5728                    .child(self.create_copy_button(error)),
5729            )
5730            .dismiss_action(self.dismiss_error_button(cx))
5731    }
5732
5733    fn render_model_request_limit_reached_error(
5734        &self,
5735        plan: cloud_llm_client::Plan,
5736        cx: &mut Context<Self>,
5737    ) -> Callout {
5738        let error_message = match plan {
5739            cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5740                "Upgrade to usage-based billing for more prompts."
5741            }
5742            cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5743            | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5744            cloud_llm_client::Plan::V2(_) => "",
5745        };
5746
5747        Callout::new()
5748            .severity(Severity::Error)
5749            .title("Model Prompt Limit Reached")
5750            .icon(IconName::XCircle)
5751            .description(error_message)
5752            .actions_slot(
5753                h_flex()
5754                    .gap_0p5()
5755                    .child(self.upgrade_button(cx))
5756                    .child(self.create_copy_button(error_message)),
5757            )
5758            .dismiss_action(self.dismiss_error_button(cx))
5759    }
5760
5761    fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5762        let thread = self.as_native_thread(cx)?;
5763        let supports_burn_mode = thread
5764            .read(cx)
5765            .model()
5766            .is_some_and(|model| model.supports_burn_mode());
5767
5768        let focus_handle = self.focus_handle(cx);
5769
5770        Some(
5771            Callout::new()
5772                .icon(IconName::Info)
5773                .title("Consecutive tool use limit reached.")
5774                .actions_slot(
5775                    h_flex()
5776                        .gap_0p5()
5777                        .when(supports_burn_mode, |this| {
5778                            this.child(
5779                                Button::new("continue-burn-mode", "Continue with Burn Mode")
5780                                    .style(ButtonStyle::Filled)
5781                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5782                                    .layer(ElevationIndex::ModalSurface)
5783                                    .label_size(LabelSize::Small)
5784                                    .key_binding(
5785                                        KeyBinding::for_action_in(
5786                                            &ContinueWithBurnMode,
5787                                            &focus_handle,
5788                                            cx,
5789                                        )
5790                                        .map(|kb| kb.size(rems_from_px(10.))),
5791                                    )
5792                                    .tooltip(Tooltip::text(
5793                                        "Enable Burn Mode for unlimited tool use.",
5794                                    ))
5795                                    .on_click({
5796                                        cx.listener(move |this, _, _window, cx| {
5797                                            thread.update(cx, |thread, cx| {
5798                                                thread
5799                                                    .set_completion_mode(CompletionMode::Burn, cx);
5800                                            });
5801                                            this.resume_chat(cx);
5802                                        })
5803                                    }),
5804                            )
5805                        })
5806                        .child(
5807                            Button::new("continue-conversation", "Continue")
5808                                .layer(ElevationIndex::ModalSurface)
5809                                .label_size(LabelSize::Small)
5810                                .key_binding(
5811                                    KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5812                                        .map(|kb| kb.size(rems_from_px(10.))),
5813                                )
5814                                .on_click(cx.listener(|this, _, _window, cx| {
5815                                    this.resume_chat(cx);
5816                                })),
5817                        ),
5818                ),
5819        )
5820    }
5821
5822    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5823        let message = message.into();
5824
5825        IconButton::new("copy", IconName::Copy)
5826            .icon_size(IconSize::Small)
5827            .tooltip(Tooltip::text("Copy Error Message"))
5828            .on_click(move |_, _, cx| {
5829                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5830            })
5831    }
5832
5833    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5834        IconButton::new("dismiss", IconName::Close)
5835            .icon_size(IconSize::Small)
5836            .tooltip(Tooltip::text("Dismiss Error"))
5837            .on_click(cx.listener({
5838                move |this, _, _, cx| {
5839                    this.clear_thread_error(cx);
5840                    cx.notify();
5841                }
5842            }))
5843    }
5844
5845    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5846        Button::new("authenticate", "Authenticate")
5847            .label_size(LabelSize::Small)
5848            .style(ButtonStyle::Filled)
5849            .on_click(cx.listener({
5850                move |this, _, window, cx| {
5851                    let agent = this.agent.clone();
5852                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
5853                        return;
5854                    };
5855
5856                    let connection = thread.read(cx).connection().clone();
5857                    let err = AuthRequired {
5858                        description: None,
5859                        provider_id: None,
5860                    };
5861                    this.clear_thread_error(cx);
5862                    if let Some(message) = this.in_flight_prompt.take() {
5863                        this.message_editor.update(cx, |editor, cx| {
5864                            editor.set_message(message, window, cx);
5865                        });
5866                    }
5867                    let this = cx.weak_entity();
5868                    window.defer(cx, |window, cx| {
5869                        Self::handle_auth_required(this, err, agent, connection, window, cx);
5870                    })
5871                }
5872            }))
5873    }
5874
5875    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5876        let agent = self.agent.clone();
5877        let ThreadState::Ready { thread, .. } = &self.thread_state else {
5878            return;
5879        };
5880
5881        let connection = thread.read(cx).connection().clone();
5882        let err = AuthRequired {
5883            description: None,
5884            provider_id: None,
5885        };
5886        self.clear_thread_error(cx);
5887        let this = cx.weak_entity();
5888        window.defer(cx, |window, cx| {
5889            Self::handle_auth_required(this, err, agent, connection, window, cx);
5890        })
5891    }
5892
5893    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5894        Button::new("upgrade", "Upgrade")
5895            .label_size(LabelSize::Small)
5896            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5897            .on_click(cx.listener({
5898                move |this, _, _, cx| {
5899                    this.clear_thread_error(cx);
5900                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5901                }
5902            }))
5903    }
5904
5905    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5906        let task = match entry {
5907            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5908                history.delete_thread(thread.id.clone(), cx)
5909            }),
5910            HistoryEntry::TextThread(text_thread) => {
5911                self.history_store.update(cx, |history, cx| {
5912                    history.delete_text_thread(text_thread.path.clone(), cx)
5913                })
5914            }
5915        };
5916        task.detach_and_log_err(cx);
5917    }
5918
5919    /// Returns the currently active editor, either for a message that is being
5920    /// edited or the editor for a new message.
5921    fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5922        if let Some(index) = self.editing_message
5923            && let Some(editor) = self
5924                .entry_view_state
5925                .read(cx)
5926                .entry(index)
5927                .and_then(|e| e.message_editor())
5928                .cloned()
5929        {
5930            editor
5931        } else {
5932            self.message_editor.clone()
5933        }
5934    }
5935}
5936
5937fn loading_contents_spinner(size: IconSize) -> AnyElement {
5938    Icon::new(IconName::LoadCircle)
5939        .size(size)
5940        .color(Color::Accent)
5941        .with_rotate_animation(3)
5942        .into_any_element()
5943}
5944
5945fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5946    if agent_name == "Zed Agent" {
5947        format!("Message the {} — @ to include context", agent_name)
5948    } else if has_commands {
5949        format!(
5950            "Message {} — @ to include context, / for commands",
5951            agent_name
5952        )
5953    } else {
5954        format!("Message {} — @ to include context", agent_name)
5955    }
5956}
5957
5958impl Focusable for AcpThreadView {
5959    fn focus_handle(&self, cx: &App) -> FocusHandle {
5960        match self.thread_state {
5961            ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
5962            ThreadState::Loading { .. }
5963            | ThreadState::LoadError(_)
5964            | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
5965        }
5966    }
5967}
5968
5969impl Render for AcpThreadView {
5970    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5971        let has_messages = self.list_state.item_count() > 0;
5972        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5973
5974        v_flex()
5975            .size_full()
5976            .key_context("AcpThread")
5977            .on_action(cx.listener(Self::toggle_burn_mode))
5978            .on_action(cx.listener(Self::keep_all))
5979            .on_action(cx.listener(Self::reject_all))
5980            .on_action(cx.listener(Self::allow_always))
5981            .on_action(cx.listener(Self::allow_once))
5982            .on_action(cx.listener(Self::reject_once))
5983            .track_focus(&self.focus_handle)
5984            .bg(cx.theme().colors().panel_background)
5985            .child(match &self.thread_state {
5986                ThreadState::Unauthenticated {
5987                    connection,
5988                    description,
5989                    configuration_view,
5990                    pending_auth_method,
5991                    ..
5992                } => self
5993                    .render_auth_required_state(
5994                        connection,
5995                        description.as_ref(),
5996                        configuration_view.as_ref(),
5997                        pending_auth_method.as_ref(),
5998                        window,
5999                        cx,
6000                    )
6001                    .into_any(),
6002                ThreadState::Loading { .. } => v_flex()
6003                    .flex_1()
6004                    .child(self.render_recent_history(cx))
6005                    .into_any(),
6006                ThreadState::LoadError(e) => v_flex()
6007                    .flex_1()
6008                    .size_full()
6009                    .items_center()
6010                    .justify_end()
6011                    .child(self.render_load_error(e, window, cx))
6012                    .into_any(),
6013                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
6014                    if has_messages {
6015                        this.child(
6016                            list(
6017                                self.list_state.clone(),
6018                                cx.processor(|this, index: usize, window, cx| {
6019                                    let Some((entry, len)) = this.thread().and_then(|thread| {
6020                                        let entries = &thread.read(cx).entries();
6021                                        Some((entries.get(index)?, entries.len()))
6022                                    }) else {
6023                                        return Empty.into_any();
6024                                    };
6025                                    this.render_entry(index, len, entry, window, cx)
6026                                }),
6027                            )
6028                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
6029                            .flex_grow()
6030                            .into_any(),
6031                        )
6032                        .vertical_scrollbar_for(&self.list_state, window, cx)
6033                        .into_any()
6034                    } else {
6035                        this.child(self.render_recent_history(cx)).into_any()
6036                    }
6037                }),
6038            })
6039            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
6040            // above so that the scrollbar doesn't render behind it. The current setup allows
6041            // the scrollbar to stop exactly at the activity bar start.
6042            .when(has_messages, |this| match &self.thread_state {
6043                ThreadState::Ready { thread, .. } => {
6044                    this.children(self.render_activity_bar(thread, window, cx))
6045                }
6046                _ => this,
6047            })
6048            .children(self.render_thread_retry_status_callout(window, cx))
6049            .when(self.show_codex_windows_warning, |this| {
6050                this.child(self.render_codex_windows_warning(cx))
6051            })
6052            .children(self.render_thread_error(window, cx))
6053            .when_some(
6054                self.new_server_version_available.as_ref().filter(|_| {
6055                    !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
6056                }),
6057                |this, version| this.child(self.render_new_version_callout(&version, cx)),
6058            )
6059            .children(
6060                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
6061                    Some(usage_callout.into_any_element())
6062                } else {
6063                    self.render_token_limit_callout(line_height, cx)
6064                        .map(|token_limit_callout| token_limit_callout.into_any_element())
6065                },
6066            )
6067            .child(self.render_message_editor(window, cx))
6068    }
6069}
6070
6071fn default_markdown_style(
6072    buffer_font: bool,
6073    muted_text: bool,
6074    window: &Window,
6075    cx: &App,
6076) -> MarkdownStyle {
6077    let theme_settings = ThemeSettings::get_global(cx);
6078    let colors = cx.theme().colors();
6079
6080    let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
6081
6082    let mut text_style = window.text_style();
6083    let line_height = buffer_font_size * 1.75;
6084
6085    let font_family = if buffer_font {
6086        theme_settings.buffer_font.family.clone()
6087    } else {
6088        theme_settings.ui_font.family.clone()
6089    };
6090
6091    let font_size = if buffer_font {
6092        theme_settings.agent_buffer_font_size(cx)
6093    } else {
6094        theme_settings.agent_ui_font_size(cx)
6095    };
6096
6097    let text_color = if muted_text {
6098        colors.text_muted
6099    } else {
6100        colors.text
6101    };
6102
6103    text_style.refine(&TextStyleRefinement {
6104        font_family: Some(font_family),
6105        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
6106        font_features: Some(theme_settings.ui_font.features.clone()),
6107        font_size: Some(font_size.into()),
6108        line_height: Some(line_height.into()),
6109        color: Some(text_color),
6110        ..Default::default()
6111    });
6112
6113    MarkdownStyle {
6114        base_text_style: text_style.clone(),
6115        syntax: cx.theme().syntax().clone(),
6116        selection_background_color: colors.element_selection_background,
6117        code_block_overflow_x_scroll: true,
6118        heading_level_styles: Some(HeadingLevelStyles {
6119            h1: Some(TextStyleRefinement {
6120                font_size: Some(rems(1.15).into()),
6121                ..Default::default()
6122            }),
6123            h2: Some(TextStyleRefinement {
6124                font_size: Some(rems(1.1).into()),
6125                ..Default::default()
6126            }),
6127            h3: Some(TextStyleRefinement {
6128                font_size: Some(rems(1.05).into()),
6129                ..Default::default()
6130            }),
6131            h4: Some(TextStyleRefinement {
6132                font_size: Some(rems(1.).into()),
6133                ..Default::default()
6134            }),
6135            h5: Some(TextStyleRefinement {
6136                font_size: Some(rems(0.95).into()),
6137                ..Default::default()
6138            }),
6139            h6: Some(TextStyleRefinement {
6140                font_size: Some(rems(0.875).into()),
6141                ..Default::default()
6142            }),
6143        }),
6144        code_block: StyleRefinement {
6145            padding: EdgesRefinement {
6146                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6147                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6148                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6149                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
6150            },
6151            margin: EdgesRefinement {
6152                top: Some(Length::Definite(px(8.).into())),
6153                left: Some(Length::Definite(px(0.).into())),
6154                right: Some(Length::Definite(px(0.).into())),
6155                bottom: Some(Length::Definite(px(12.).into())),
6156            },
6157            border_style: Some(BorderStyle::Solid),
6158            border_widths: EdgesRefinement {
6159                top: Some(AbsoluteLength::Pixels(px(1.))),
6160                left: Some(AbsoluteLength::Pixels(px(1.))),
6161                right: Some(AbsoluteLength::Pixels(px(1.))),
6162                bottom: Some(AbsoluteLength::Pixels(px(1.))),
6163            },
6164            border_color: Some(colors.border_variant),
6165            background: Some(colors.editor_background.into()),
6166            text: TextStyleRefinement {
6167                font_family: Some(theme_settings.buffer_font.family.clone()),
6168                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6169                font_features: Some(theme_settings.buffer_font.features.clone()),
6170                font_size: Some(buffer_font_size.into()),
6171                ..Default::default()
6172            },
6173            ..Default::default()
6174        },
6175        inline_code: TextStyleRefinement {
6176            font_family: Some(theme_settings.buffer_font.family.clone()),
6177            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6178            font_features: Some(theme_settings.buffer_font.features.clone()),
6179            font_size: Some(buffer_font_size.into()),
6180            background_color: Some(colors.editor_foreground.opacity(0.08)),
6181            ..Default::default()
6182        },
6183        link: TextStyleRefinement {
6184            background_color: Some(colors.editor_foreground.opacity(0.025)),
6185            color: Some(colors.text_accent),
6186            underline: Some(UnderlineStyle {
6187                color: Some(colors.text_accent.opacity(0.5)),
6188                thickness: px(1.),
6189                ..Default::default()
6190            }),
6191            ..Default::default()
6192        },
6193        ..Default::default()
6194    }
6195}
6196
6197fn plan_label_markdown_style(
6198    status: &acp::PlanEntryStatus,
6199    window: &Window,
6200    cx: &App,
6201) -> MarkdownStyle {
6202    let default_md_style = default_markdown_style(false, false, window, cx);
6203
6204    MarkdownStyle {
6205        base_text_style: TextStyle {
6206            color: cx.theme().colors().text_muted,
6207            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
6208                Some(gpui::StrikethroughStyle {
6209                    thickness: px(1.),
6210                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
6211                })
6212            } else {
6213                None
6214            },
6215            ..default_md_style.base_text_style
6216        },
6217        ..default_md_style
6218    }
6219}
6220
6221fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
6222    let default_md_style = default_markdown_style(true, false, window, cx);
6223
6224    MarkdownStyle {
6225        base_text_style: TextStyle {
6226            ..default_md_style.base_text_style
6227        },
6228        selection_background_color: cx.theme().colors().element_selection_background,
6229        ..Default::default()
6230    }
6231}
6232
6233#[cfg(test)]
6234pub(crate) mod tests {
6235    use acp_thread::StubAgentConnection;
6236    use agent_client_protocol::SessionId;
6237    use assistant_text_thread::TextThreadStore;
6238    use editor::MultiBufferOffset;
6239    use fs::FakeFs;
6240    use gpui::{EventEmitter, TestAppContext, VisualTestContext};
6241    use project::Project;
6242    use serde_json::json;
6243    use settings::SettingsStore;
6244    use std::any::Any;
6245    use std::path::Path;
6246    use workspace::Item;
6247
6248    use super::*;
6249
6250    #[gpui::test]
6251    async fn test_drop(cx: &mut TestAppContext) {
6252        init_test(cx);
6253
6254        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6255        let weak_view = thread_view.downgrade();
6256        drop(thread_view);
6257        assert!(!weak_view.is_upgradable());
6258    }
6259
6260    #[gpui::test]
6261    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6262        init_test(cx);
6263
6264        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6265
6266        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6267        message_editor.update_in(cx, |editor, window, cx| {
6268            editor.set_text("Hello", window, cx);
6269        });
6270
6271        cx.deactivate_window();
6272
6273        thread_view.update_in(cx, |thread_view, window, cx| {
6274            thread_view.send(window, cx);
6275        });
6276
6277        cx.run_until_parked();
6278
6279        assert!(
6280            cx.windows()
6281                .iter()
6282                .any(|window| window.downcast::<AgentNotification>().is_some())
6283        );
6284    }
6285
6286    #[gpui::test]
6287    async fn test_notification_for_error(cx: &mut TestAppContext) {
6288        init_test(cx);
6289
6290        let (thread_view, cx) =
6291            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6292
6293        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6294        message_editor.update_in(cx, |editor, window, cx| {
6295            editor.set_text("Hello", window, cx);
6296        });
6297
6298        cx.deactivate_window();
6299
6300        thread_view.update_in(cx, |thread_view, window, cx| {
6301            thread_view.send(window, cx);
6302        });
6303
6304        cx.run_until_parked();
6305
6306        assert!(
6307            cx.windows()
6308                .iter()
6309                .any(|window| window.downcast::<AgentNotification>().is_some())
6310        );
6311    }
6312
6313    #[gpui::test]
6314    async fn test_refusal_handling(cx: &mut TestAppContext) {
6315        init_test(cx);
6316
6317        let (thread_view, cx) =
6318            setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6319
6320        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6321        message_editor.update_in(cx, |editor, window, cx| {
6322            editor.set_text("Do something harmful", window, cx);
6323        });
6324
6325        thread_view.update_in(cx, |thread_view, window, cx| {
6326            thread_view.send(window, cx);
6327        });
6328
6329        cx.run_until_parked();
6330
6331        // Check that the refusal error is set
6332        thread_view.read_with(cx, |thread_view, _cx| {
6333            assert!(
6334                matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6335                "Expected refusal error to be set"
6336            );
6337        });
6338    }
6339
6340    #[gpui::test]
6341    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6342        init_test(cx);
6343
6344        let tool_call_id = acp::ToolCallId::new("1");
6345        let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
6346            .kind(acp::ToolKind::Edit)
6347            .content(vec!["hi".into()]);
6348        let connection =
6349            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6350                tool_call_id,
6351                vec![acp::PermissionOption::new(
6352                    "1",
6353                    "Allow",
6354                    acp::PermissionOptionKind::AllowOnce,
6355                )],
6356            )]));
6357
6358        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6359
6360        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6361
6362        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6363        message_editor.update_in(cx, |editor, window, cx| {
6364            editor.set_text("Hello", window, cx);
6365        });
6366
6367        cx.deactivate_window();
6368
6369        thread_view.update_in(cx, |thread_view, window, cx| {
6370            thread_view.send(window, cx);
6371        });
6372
6373        cx.run_until_parked();
6374
6375        assert!(
6376            cx.windows()
6377                .iter()
6378                .any(|window| window.downcast::<AgentNotification>().is_some())
6379        );
6380    }
6381
6382    #[gpui::test]
6383    async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6384        init_test(cx);
6385
6386        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6387
6388        add_to_workspace(thread_view.clone(), cx);
6389
6390        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6391
6392        message_editor.update_in(cx, |editor, window, cx| {
6393            editor.set_text("Hello", window, cx);
6394        });
6395
6396        // Window is active (don't deactivate), but panel will be hidden
6397        // Note: In the test environment, the panel is not actually added to the dock,
6398        // so is_agent_panel_hidden will return true
6399
6400        thread_view.update_in(cx, |thread_view, window, cx| {
6401            thread_view.send(window, cx);
6402        });
6403
6404        cx.run_until_parked();
6405
6406        // Should show notification because window is active but panel is hidden
6407        assert!(
6408            cx.windows()
6409                .iter()
6410                .any(|window| window.downcast::<AgentNotification>().is_some()),
6411            "Expected notification when panel is hidden"
6412        );
6413    }
6414
6415    #[gpui::test]
6416    async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6417        init_test(cx);
6418
6419        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6420
6421        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6422        message_editor.update_in(cx, |editor, window, cx| {
6423            editor.set_text("Hello", window, cx);
6424        });
6425
6426        // Deactivate window - should show notification regardless of setting
6427        cx.deactivate_window();
6428
6429        thread_view.update_in(cx, |thread_view, window, cx| {
6430            thread_view.send(window, cx);
6431        });
6432
6433        cx.run_until_parked();
6434
6435        // Should still show notification when window is inactive (existing behavior)
6436        assert!(
6437            cx.windows()
6438                .iter()
6439                .any(|window| window.downcast::<AgentNotification>().is_some()),
6440            "Expected notification when window is inactive"
6441        );
6442    }
6443
6444    #[gpui::test]
6445    async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6446        init_test(cx);
6447
6448        // Set notify_when_agent_waiting to Never
6449        cx.update(|cx| {
6450            AgentSettings::override_global(
6451                AgentSettings {
6452                    notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6453                    ..AgentSettings::get_global(cx).clone()
6454                },
6455                cx,
6456            );
6457        });
6458
6459        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6460
6461        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6462        message_editor.update_in(cx, |editor, window, cx| {
6463            editor.set_text("Hello", window, cx);
6464        });
6465
6466        // Window is active
6467
6468        thread_view.update_in(cx, |thread_view, window, cx| {
6469            thread_view.send(window, cx);
6470        });
6471
6472        cx.run_until_parked();
6473
6474        // Should NOT show notification because notify_when_agent_waiting is Never
6475        assert!(
6476            !cx.windows()
6477                .iter()
6478                .any(|window| window.downcast::<AgentNotification>().is_some()),
6479            "Expected no notification when notify_when_agent_waiting is Never"
6480        );
6481    }
6482
6483    #[gpui::test]
6484    async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
6485        init_test(cx);
6486
6487        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6488
6489        let weak_view = thread_view.downgrade();
6490
6491        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6492        message_editor.update_in(cx, |editor, window, cx| {
6493            editor.set_text("Hello", window, cx);
6494        });
6495
6496        cx.deactivate_window();
6497
6498        thread_view.update_in(cx, |thread_view, window, cx| {
6499            thread_view.send(window, cx);
6500        });
6501
6502        cx.run_until_parked();
6503
6504        // Verify notification is shown
6505        assert!(
6506            cx.windows()
6507                .iter()
6508                .any(|window| window.downcast::<AgentNotification>().is_some()),
6509            "Expected notification to be shown"
6510        );
6511
6512        // Drop the thread view (simulating navigation to a new thread)
6513        drop(thread_view);
6514        drop(message_editor);
6515        // Trigger an update to flush effects, which will call release_dropped_entities
6516        cx.update(|_window, _cx| {});
6517        cx.run_until_parked();
6518
6519        // Verify the entity was actually released
6520        assert!(
6521            !weak_view.is_upgradable(),
6522            "Thread view entity should be released after dropping"
6523        );
6524
6525        // The notification should be automatically closed via on_release
6526        assert!(
6527            !cx.windows()
6528                .iter()
6529                .any(|window| window.downcast::<AgentNotification>().is_some()),
6530            "Notification should be closed when thread view is dropped"
6531        );
6532    }
6533
6534    async fn setup_thread_view(
6535        agent: impl AgentServer + 'static,
6536        cx: &mut TestAppContext,
6537    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6538        let fs = FakeFs::new(cx.executor());
6539        let project = Project::test(fs, [], cx).await;
6540        let (workspace, cx) =
6541            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6542
6543        let text_thread_store =
6544            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6545        let history_store =
6546            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6547
6548        let thread_view = cx.update(|window, cx| {
6549            cx.new(|cx| {
6550                AcpThreadView::new(
6551                    Rc::new(agent),
6552                    None,
6553                    None,
6554                    workspace.downgrade(),
6555                    project,
6556                    history_store,
6557                    None,
6558                    false,
6559                    window,
6560                    cx,
6561                )
6562            })
6563        });
6564        cx.run_until_parked();
6565        (thread_view, cx)
6566    }
6567
6568    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6569        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6570
6571        workspace
6572            .update_in(cx, |workspace, window, cx| {
6573                workspace.add_item_to_active_pane(
6574                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6575                    None,
6576                    true,
6577                    window,
6578                    cx,
6579                );
6580            })
6581            .unwrap();
6582    }
6583
6584    struct ThreadViewItem(Entity<AcpThreadView>);
6585
6586    impl Item for ThreadViewItem {
6587        type Event = ();
6588
6589        fn include_in_nav_history() -> bool {
6590            false
6591        }
6592
6593        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6594            "Test".into()
6595        }
6596    }
6597
6598    impl EventEmitter<()> for ThreadViewItem {}
6599
6600    impl Focusable for ThreadViewItem {
6601        fn focus_handle(&self, cx: &App) -> FocusHandle {
6602            self.0.read(cx).focus_handle(cx)
6603        }
6604    }
6605
6606    impl Render for ThreadViewItem {
6607        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6608            self.0.clone().into_any_element()
6609        }
6610    }
6611
6612    struct StubAgentServer<C> {
6613        connection: C,
6614    }
6615
6616    impl<C> StubAgentServer<C> {
6617        fn new(connection: C) -> Self {
6618            Self { connection }
6619        }
6620    }
6621
6622    impl StubAgentServer<StubAgentConnection> {
6623        fn default_response() -> Self {
6624            let conn = StubAgentConnection::new();
6625            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6626                acp::ContentChunk::new("Default response".into()),
6627            )]);
6628            Self::new(conn)
6629        }
6630    }
6631
6632    impl<C> AgentServer for StubAgentServer<C>
6633    where
6634        C: 'static + AgentConnection + Send + Clone,
6635    {
6636        fn logo(&self) -> ui::IconName {
6637            ui::IconName::Ai
6638        }
6639
6640        fn name(&self) -> SharedString {
6641            "Test".into()
6642        }
6643
6644        fn connect(
6645            &self,
6646            _root_dir: Option<&Path>,
6647            _delegate: AgentServerDelegate,
6648            _cx: &mut App,
6649        ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6650            Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6651        }
6652
6653        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6654            self
6655        }
6656    }
6657
6658    #[derive(Clone)]
6659    struct SaboteurAgentConnection;
6660
6661    impl AgentConnection for SaboteurAgentConnection {
6662        fn telemetry_id(&self) -> SharedString {
6663            "saboteur".into()
6664        }
6665
6666        fn new_thread(
6667            self: Rc<Self>,
6668            project: Entity<Project>,
6669            _cwd: &Path,
6670            cx: &mut gpui::App,
6671        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6672            Task::ready(Ok(cx.new(|cx| {
6673                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6674                AcpThread::new(
6675                    "SaboteurAgentConnection",
6676                    self,
6677                    project,
6678                    action_log,
6679                    SessionId::new("test"),
6680                    watch::Receiver::constant(
6681                        acp::PromptCapabilities::new()
6682                            .image(true)
6683                            .audio(true)
6684                            .embedded_context(true),
6685                    ),
6686                    cx,
6687                )
6688            })))
6689        }
6690
6691        fn auth_methods(&self) -> &[acp::AuthMethod] {
6692            &[]
6693        }
6694
6695        fn authenticate(
6696            &self,
6697            _method_id: acp::AuthMethodId,
6698            _cx: &mut App,
6699        ) -> Task<gpui::Result<()>> {
6700            unimplemented!()
6701        }
6702
6703        fn prompt(
6704            &self,
6705            _id: Option<acp_thread::UserMessageId>,
6706            _params: acp::PromptRequest,
6707            _cx: &mut App,
6708        ) -> Task<gpui::Result<acp::PromptResponse>> {
6709            Task::ready(Err(anyhow::anyhow!("Error prompting")))
6710        }
6711
6712        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6713            unimplemented!()
6714        }
6715
6716        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6717            self
6718        }
6719    }
6720
6721    /// Simulates a model which always returns a refusal response
6722    #[derive(Clone)]
6723    struct RefusalAgentConnection;
6724
6725    impl AgentConnection for RefusalAgentConnection {
6726        fn telemetry_id(&self) -> SharedString {
6727            "refusal".into()
6728        }
6729
6730        fn new_thread(
6731            self: Rc<Self>,
6732            project: Entity<Project>,
6733            _cwd: &Path,
6734            cx: &mut gpui::App,
6735        ) -> Task<gpui::Result<Entity<AcpThread>>> {
6736            Task::ready(Ok(cx.new(|cx| {
6737                let action_log = cx.new(|_| ActionLog::new(project.clone()));
6738                AcpThread::new(
6739                    "RefusalAgentConnection",
6740                    self,
6741                    project,
6742                    action_log,
6743                    SessionId::new("test"),
6744                    watch::Receiver::constant(
6745                        acp::PromptCapabilities::new()
6746                            .image(true)
6747                            .audio(true)
6748                            .embedded_context(true),
6749                    ),
6750                    cx,
6751                )
6752            })))
6753        }
6754
6755        fn auth_methods(&self) -> &[acp::AuthMethod] {
6756            &[]
6757        }
6758
6759        fn authenticate(
6760            &self,
6761            _method_id: acp::AuthMethodId,
6762            _cx: &mut App,
6763        ) -> Task<gpui::Result<()>> {
6764            unimplemented!()
6765        }
6766
6767        fn prompt(
6768            &self,
6769            _id: Option<acp_thread::UserMessageId>,
6770            _params: acp::PromptRequest,
6771            _cx: &mut App,
6772        ) -> Task<gpui::Result<acp::PromptResponse>> {
6773            Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
6774        }
6775
6776        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6777            unimplemented!()
6778        }
6779
6780        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6781            self
6782        }
6783    }
6784
6785    pub(crate) fn init_test(cx: &mut TestAppContext) {
6786        cx.update(|cx| {
6787            let settings_store = SettingsStore::test(cx);
6788            cx.set_global(settings_store);
6789            theme::init(theme::LoadThemes::JustBase, cx);
6790            release_channel::init(semver::Version::new(0, 0, 0), cx);
6791            prompt_store::init(cx)
6792        });
6793    }
6794
6795    #[gpui::test]
6796    async fn test_rewind_views(cx: &mut TestAppContext) {
6797        init_test(cx);
6798
6799        let fs = FakeFs::new(cx.executor());
6800        fs.insert_tree(
6801            "/project",
6802            json!({
6803                "test1.txt": "old content 1",
6804                "test2.txt": "old content 2"
6805            }),
6806        )
6807        .await;
6808        let project = Project::test(fs, [Path::new("/project")], cx).await;
6809        let (workspace, cx) =
6810            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6811
6812        let text_thread_store =
6813            cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6814        let history_store =
6815            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6816
6817        let connection = Rc::new(StubAgentConnection::new());
6818        let thread_view = cx.update(|window, cx| {
6819            cx.new(|cx| {
6820                AcpThreadView::new(
6821                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6822                    None,
6823                    None,
6824                    workspace.downgrade(),
6825                    project.clone(),
6826                    history_store.clone(),
6827                    None,
6828                    false,
6829                    window,
6830                    cx,
6831                )
6832            })
6833        });
6834
6835        cx.run_until_parked();
6836
6837        let thread = thread_view
6838            .read_with(cx, |view, _| view.thread().cloned())
6839            .unwrap();
6840
6841        // First user message
6842        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
6843            acp::ToolCall::new("tool1", "Edit file 1")
6844                .kind(acp::ToolKind::Edit)
6845                .status(acp::ToolCallStatus::Completed)
6846                .content(vec![acp::ToolCallContent::Diff(
6847                    acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
6848                )]),
6849        )]);
6850
6851        thread
6852            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6853            .await
6854            .unwrap();
6855        cx.run_until_parked();
6856
6857        thread.read_with(cx, |thread, _| {
6858            assert_eq!(thread.entries().len(), 2);
6859        });
6860
6861        thread_view.read_with(cx, |view, cx| {
6862            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6863                assert!(
6864                    entry_view_state
6865                        .entry(0)
6866                        .unwrap()
6867                        .message_editor()
6868                        .is_some()
6869                );
6870                assert!(entry_view_state.entry(1).unwrap().has_content());
6871            });
6872        });
6873
6874        // Second user message
6875        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
6876            acp::ToolCall::new("tool2", "Edit file 2")
6877                .kind(acp::ToolKind::Edit)
6878                .status(acp::ToolCallStatus::Completed)
6879                .content(vec![acp::ToolCallContent::Diff(
6880                    acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
6881                )]),
6882        )]);
6883
6884        thread
6885            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6886            .await
6887            .unwrap();
6888        cx.run_until_parked();
6889
6890        let second_user_message_id = thread.read_with(cx, |thread, _| {
6891            assert_eq!(thread.entries().len(), 4);
6892            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6893                panic!();
6894            };
6895            user_message.id.clone().unwrap()
6896        });
6897
6898        thread_view.read_with(cx, |view, cx| {
6899            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6900                assert!(
6901                    entry_view_state
6902                        .entry(0)
6903                        .unwrap()
6904                        .message_editor()
6905                        .is_some()
6906                );
6907                assert!(entry_view_state.entry(1).unwrap().has_content());
6908                assert!(
6909                    entry_view_state
6910                        .entry(2)
6911                        .unwrap()
6912                        .message_editor()
6913                        .is_some()
6914                );
6915                assert!(entry_view_state.entry(3).unwrap().has_content());
6916            });
6917        });
6918
6919        // Rewind to first message
6920        thread
6921            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6922            .await
6923            .unwrap();
6924
6925        cx.run_until_parked();
6926
6927        thread.read_with(cx, |thread, _| {
6928            assert_eq!(thread.entries().len(), 2);
6929        });
6930
6931        thread_view.read_with(cx, |view, cx| {
6932            view.entry_view_state.read_with(cx, |entry_view_state, _| {
6933                assert!(
6934                    entry_view_state
6935                        .entry(0)
6936                        .unwrap()
6937                        .message_editor()
6938                        .is_some()
6939                );
6940                assert!(entry_view_state.entry(1).unwrap().has_content());
6941
6942                // Old views should be dropped
6943                assert!(entry_view_state.entry(2).is_none());
6944                assert!(entry_view_state.entry(3).is_none());
6945            });
6946        });
6947    }
6948
6949    #[gpui::test]
6950    async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
6951        init_test(cx);
6952
6953        let connection = StubAgentConnection::new();
6954
6955        // Each user prompt will result in a user message entry plus an agent message entry.
6956        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6957            acp::ContentChunk::new("Response 1".into()),
6958        )]);
6959
6960        let (thread_view, cx) =
6961            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6962
6963        let thread = thread_view
6964            .read_with(cx, |view, _| view.thread().cloned())
6965            .unwrap();
6966
6967        thread
6968            .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
6969            .await
6970            .unwrap();
6971        cx.run_until_parked();
6972
6973        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6974            acp::ContentChunk::new("Response 2".into()),
6975        )]);
6976
6977        thread
6978            .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
6979            .await
6980            .unwrap();
6981        cx.run_until_parked();
6982
6983        // Move somewhere else first so we're not trivially already on the last user prompt.
6984        thread_view.update(cx, |view, cx| {
6985            view.scroll_to_top(cx);
6986        });
6987        cx.run_until_parked();
6988
6989        thread_view.update(cx, |view, cx| {
6990            view.scroll_to_most_recent_user_prompt(cx);
6991            let scroll_top = view.list_state.logical_scroll_top();
6992            // Entries layout is: [User1, Assistant1, User2, Assistant2]
6993            assert_eq!(scroll_top.item_ix, 2);
6994        });
6995    }
6996
6997    #[gpui::test]
6998    async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
6999        cx: &mut TestAppContext,
7000    ) {
7001        init_test(cx);
7002
7003        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7004
7005        // With no entries, scrolling should be a no-op and must not panic.
7006        thread_view.update(cx, |view, cx| {
7007            view.scroll_to_most_recent_user_prompt(cx);
7008            let scroll_top = view.list_state.logical_scroll_top();
7009            assert_eq!(scroll_top.item_ix, 0);
7010        });
7011    }
7012
7013    #[gpui::test]
7014    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
7015        init_test(cx);
7016
7017        let connection = StubAgentConnection::new();
7018
7019        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7020            acp::ContentChunk::new("Response".into()),
7021        )]);
7022
7023        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7024        add_to_workspace(thread_view.clone(), cx);
7025
7026        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7027        message_editor.update_in(cx, |editor, window, cx| {
7028            editor.set_text("Original message to edit", window, cx);
7029        });
7030        thread_view.update_in(cx, |thread_view, window, cx| {
7031            thread_view.send(window, cx);
7032        });
7033
7034        cx.run_until_parked();
7035
7036        let user_message_editor = thread_view.read_with(cx, |view, cx| {
7037            assert_eq!(view.editing_message, None);
7038
7039            view.entry_view_state
7040                .read(cx)
7041                .entry(0)
7042                .unwrap()
7043                .message_editor()
7044                .unwrap()
7045                .clone()
7046        });
7047
7048        // Focus
7049        cx.focus(&user_message_editor);
7050        thread_view.read_with(cx, |view, _cx| {
7051            assert_eq!(view.editing_message, Some(0));
7052        });
7053
7054        // Edit
7055        user_message_editor.update_in(cx, |editor, window, cx| {
7056            editor.set_text("Edited message content", window, cx);
7057        });
7058
7059        // Cancel
7060        user_message_editor.update_in(cx, |_editor, window, cx| {
7061            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
7062        });
7063
7064        thread_view.read_with(cx, |view, _cx| {
7065            assert_eq!(view.editing_message, None);
7066        });
7067
7068        user_message_editor.read_with(cx, |editor, cx| {
7069            assert_eq!(editor.text(cx), "Original message to edit");
7070        });
7071    }
7072
7073    #[gpui::test]
7074    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
7075        init_test(cx);
7076
7077        let connection = StubAgentConnection::new();
7078
7079        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7080        add_to_workspace(thread_view.clone(), cx);
7081
7082        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7083        let mut events = cx.events(&message_editor);
7084        message_editor.update_in(cx, |editor, window, cx| {
7085            editor.set_text("", window, cx);
7086        });
7087
7088        message_editor.update_in(cx, |_editor, window, cx| {
7089            window.dispatch_action(Box::new(Chat), cx);
7090        });
7091        cx.run_until_parked();
7092        // We shouldn't have received any messages
7093        assert!(matches!(
7094            events.try_next(),
7095            Err(futures::channel::mpsc::TryRecvError { .. })
7096        ));
7097    }
7098
7099    #[gpui::test]
7100    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
7101        init_test(cx);
7102
7103        let connection = StubAgentConnection::new();
7104
7105        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7106            acp::ContentChunk::new("Response".into()),
7107        )]);
7108
7109        let (thread_view, cx) =
7110            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7111        add_to_workspace(thread_view.clone(), cx);
7112
7113        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7114        message_editor.update_in(cx, |editor, window, cx| {
7115            editor.set_text("Original message to edit", window, cx);
7116        });
7117        thread_view.update_in(cx, |thread_view, window, cx| {
7118            thread_view.send(window, cx);
7119        });
7120
7121        cx.run_until_parked();
7122
7123        let user_message_editor = thread_view.read_with(cx, |view, cx| {
7124            assert_eq!(view.editing_message, None);
7125            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
7126
7127            view.entry_view_state
7128                .read(cx)
7129                .entry(0)
7130                .unwrap()
7131                .message_editor()
7132                .unwrap()
7133                .clone()
7134        });
7135
7136        // Focus
7137        cx.focus(&user_message_editor);
7138
7139        // Edit
7140        user_message_editor.update_in(cx, |editor, window, cx| {
7141            editor.set_text("Edited message content", window, cx);
7142        });
7143
7144        // Send
7145        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7146            acp::ContentChunk::new("New Response".into()),
7147        )]);
7148
7149        user_message_editor.update_in(cx, |_editor, window, cx| {
7150            window.dispatch_action(Box::new(Chat), cx);
7151        });
7152
7153        cx.run_until_parked();
7154
7155        thread_view.read_with(cx, |view, cx| {
7156            assert_eq!(view.editing_message, None);
7157
7158            let entries = view.thread().unwrap().read(cx).entries();
7159            assert_eq!(entries.len(), 2);
7160            assert_eq!(
7161                entries[0].to_markdown(cx),
7162                "## User\n\nEdited message content\n\n"
7163            );
7164            assert_eq!(
7165                entries[1].to_markdown(cx),
7166                "## Assistant\n\nNew Response\n\n"
7167            );
7168
7169            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
7170                assert!(!state.entry(1).unwrap().has_content());
7171                state.entry(0).unwrap().message_editor().unwrap().clone()
7172            });
7173
7174            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
7175        })
7176    }
7177
7178    #[gpui::test]
7179    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
7180        init_test(cx);
7181
7182        let connection = StubAgentConnection::new();
7183
7184        let (thread_view, cx) =
7185            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7186        add_to_workspace(thread_view.clone(), cx);
7187
7188        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7189        message_editor.update_in(cx, |editor, window, cx| {
7190            editor.set_text("Original message to edit", window, cx);
7191        });
7192        thread_view.update_in(cx, |thread_view, window, cx| {
7193            thread_view.send(window, cx);
7194        });
7195
7196        cx.run_until_parked();
7197
7198        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
7199            let thread = view.thread().unwrap().read(cx);
7200            assert_eq!(thread.entries().len(), 1);
7201
7202            let editor = view
7203                .entry_view_state
7204                .read(cx)
7205                .entry(0)
7206                .unwrap()
7207                .message_editor()
7208                .unwrap()
7209                .clone();
7210
7211            (editor, thread.session_id().clone())
7212        });
7213
7214        // Focus
7215        cx.focus(&user_message_editor);
7216
7217        thread_view.read_with(cx, |view, _cx| {
7218            assert_eq!(view.editing_message, Some(0));
7219        });
7220
7221        // Edit
7222        user_message_editor.update_in(cx, |editor, window, cx| {
7223            editor.set_text("Edited message content", window, cx);
7224        });
7225
7226        thread_view.read_with(cx, |view, _cx| {
7227            assert_eq!(view.editing_message, Some(0));
7228        });
7229
7230        // Finish streaming response
7231        cx.update(|_, cx| {
7232            connection.send_update(
7233                session_id.clone(),
7234                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
7235                cx,
7236            );
7237            connection.end_turn(session_id, acp::StopReason::EndTurn);
7238        });
7239
7240        thread_view.read_with(cx, |view, _cx| {
7241            assert_eq!(view.editing_message, Some(0));
7242        });
7243
7244        cx.run_until_parked();
7245
7246        // Should still be editing
7247        cx.update(|window, cx| {
7248            assert!(user_message_editor.focus_handle(cx).is_focused(window));
7249            assert_eq!(thread_view.read(cx).editing_message, Some(0));
7250            assert_eq!(
7251                user_message_editor.read(cx).text(cx),
7252                "Edited message content"
7253            );
7254        });
7255    }
7256
7257    #[gpui::test]
7258    async fn test_interrupt(cx: &mut TestAppContext) {
7259        init_test(cx);
7260
7261        let connection = StubAgentConnection::new();
7262
7263        let (thread_view, cx) =
7264            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7265        add_to_workspace(thread_view.clone(), cx);
7266
7267        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7268        message_editor.update_in(cx, |editor, window, cx| {
7269            editor.set_text("Message 1", window, cx);
7270        });
7271        thread_view.update_in(cx, |thread_view, window, cx| {
7272            thread_view.send(window, cx);
7273        });
7274
7275        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
7276            let thread = view.thread().unwrap();
7277
7278            (thread.clone(), thread.read(cx).session_id().clone())
7279        });
7280
7281        cx.run_until_parked();
7282
7283        cx.update(|_, cx| {
7284            connection.send_update(
7285                session_id.clone(),
7286                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
7287                    "Message 1 resp".into(),
7288                )),
7289                cx,
7290            );
7291        });
7292
7293        cx.run_until_parked();
7294
7295        thread.read_with(cx, |thread, cx| {
7296            assert_eq!(
7297                thread.to_markdown(cx),
7298                indoc::indoc! {"
7299                    ## User
7300
7301                    Message 1
7302
7303                    ## Assistant
7304
7305                    Message 1 resp
7306
7307                "}
7308            )
7309        });
7310
7311        message_editor.update_in(cx, |editor, window, cx| {
7312            editor.set_text("Message 2", window, cx);
7313        });
7314        thread_view.update_in(cx, |thread_view, window, cx| {
7315            thread_view.send(window, cx);
7316        });
7317
7318        cx.update(|_, cx| {
7319            // Simulate a response sent after beginning to cancel
7320            connection.send_update(
7321                session_id.clone(),
7322                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
7323                cx,
7324            );
7325        });
7326
7327        cx.run_until_parked();
7328
7329        // Last Message 1 response should appear before Message 2
7330        thread.read_with(cx, |thread, cx| {
7331            assert_eq!(
7332                thread.to_markdown(cx),
7333                indoc::indoc! {"
7334                    ## User
7335
7336                    Message 1
7337
7338                    ## Assistant
7339
7340                    Message 1 response
7341
7342                    ## User
7343
7344                    Message 2
7345
7346                "}
7347            )
7348        });
7349
7350        cx.update(|_, cx| {
7351            connection.send_update(
7352                session_id.clone(),
7353                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
7354                    "Message 2 response".into(),
7355                )),
7356                cx,
7357            );
7358            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7359        });
7360
7361        cx.run_until_parked();
7362
7363        thread.read_with(cx, |thread, cx| {
7364            assert_eq!(
7365                thread.to_markdown(cx),
7366                indoc::indoc! {"
7367                    ## User
7368
7369                    Message 1
7370
7371                    ## Assistant
7372
7373                    Message 1 response
7374
7375                    ## User
7376
7377                    Message 2
7378
7379                    ## Assistant
7380
7381                    Message 2 response
7382
7383                "}
7384            )
7385        });
7386    }
7387
7388    #[gpui::test]
7389    async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7390        init_test(cx);
7391
7392        let connection = StubAgentConnection::new();
7393        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7394            acp::ContentChunk::new("Response".into()),
7395        )]);
7396
7397        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7398        add_to_workspace(thread_view.clone(), cx);
7399
7400        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7401        message_editor.update_in(cx, |editor, window, cx| {
7402            editor.set_text("Original message to edit", window, cx)
7403        });
7404        thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7405        cx.run_until_parked();
7406
7407        let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7408            thread_view
7409                .entry_view_state
7410                .read(cx)
7411                .entry(0)
7412                .expect("Should have at least one entry")
7413                .message_editor()
7414                .expect("Should have message editor")
7415                .clone()
7416        });
7417
7418        cx.focus(&user_message_editor);
7419        thread_view.read_with(cx, |thread_view, _cx| {
7420            assert_eq!(thread_view.editing_message, Some(0));
7421        });
7422
7423        // Ensure to edit the focused message before proceeding otherwise, since
7424        // its content is not different from what was sent, focus will be lost.
7425        user_message_editor.update_in(cx, |editor, window, cx| {
7426            editor.set_text("Original message to edit with ", window, cx)
7427        });
7428
7429        // Create a simple buffer with some text so we can create a selection
7430        // that will then be added to the message being edited.
7431        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7432            (thread_view.workspace.clone(), thread_view.project.clone())
7433        });
7434        let buffer = project.update(cx, |project, cx| {
7435            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7436        });
7437
7438        workspace
7439            .update_in(cx, |workspace, window, cx| {
7440                let editor = cx.new(|cx| {
7441                    let mut editor =
7442                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7443
7444                    editor.change_selections(Default::default(), window, cx, |selections| {
7445                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7446                    });
7447
7448                    editor
7449                });
7450                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7451            })
7452            .unwrap();
7453
7454        thread_view.update_in(cx, |thread_view, window, cx| {
7455            assert_eq!(thread_view.editing_message, Some(0));
7456            thread_view.insert_selections(window, cx);
7457        });
7458
7459        user_message_editor.read_with(cx, |editor, cx| {
7460            let text = editor.editor().read(cx).text(cx);
7461            let expected_text = String::from("Original message to edit with selection ");
7462
7463            assert_eq!(text, expected_text);
7464        });
7465    }
7466
7467    #[gpui::test]
7468    async fn test_insert_selections(cx: &mut TestAppContext) {
7469        init_test(cx);
7470
7471        let connection = StubAgentConnection::new();
7472        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7473            acp::ContentChunk::new("Response".into()),
7474        )]);
7475
7476        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7477        add_to_workspace(thread_view.clone(), cx);
7478
7479        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7480        message_editor.update_in(cx, |editor, window, cx| {
7481            editor.set_text("Can you review this snippet ", window, cx)
7482        });
7483
7484        // Create a simple buffer with some text so we can create a selection
7485        // that will then be added to the message being edited.
7486        let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7487            (thread_view.workspace.clone(), thread_view.project.clone())
7488        });
7489        let buffer = project.update(cx, |project, cx| {
7490            project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7491        });
7492
7493        workspace
7494            .update_in(cx, |workspace, window, cx| {
7495                let editor = cx.new(|cx| {
7496                    let mut editor =
7497                        Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7498
7499                    editor.change_selections(Default::default(), window, cx, |selections| {
7500                        selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7501                    });
7502
7503                    editor
7504                });
7505                workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7506            })
7507            .unwrap();
7508
7509        thread_view.update_in(cx, |thread_view, window, cx| {
7510            assert_eq!(thread_view.editing_message, None);
7511            thread_view.insert_selections(window, cx);
7512        });
7513
7514        thread_view.read_with(cx, |thread_view, cx| {
7515            let text = thread_view.message_editor.read(cx).text(cx);
7516            let expected_txt = String::from("Can you review this snippet selection ");
7517
7518            assert_eq!(text, expected_txt);
7519        })
7520    }
7521}