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