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