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