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