thread_view.rs

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