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