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