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