thread_view.rs

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