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