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