thread_view.rs

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