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