thread_view.rs

   1use crate::{
   2    DEFAULT_THREAD_TITLE, SelectPermissionGranularity,
   3    agent_configuration::configure_context_server_modal::default_markdown_style,
   4};
   5use std::cell::RefCell;
   6
   7use acp_thread::{ContentBlock, PlanEntry};
   8use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
   9use editor::actions::OpenExcerpts;
  10use feature_flags::AcpBetaFeatureFlag;
  11
  12use crate::message_editor::SharedSessionCapabilities;
  13
  14use gpui::{Corner, List};
  15use heapless::Vec as ArrayVec;
  16use language_model::{LanguageModelEffortLevel, Speed};
  17use settings::update_settings_file;
  18use ui::{ButtonLike, SpinnerLabel, SpinnerVariant, SplitButton, SplitButtonStyle, Tab};
  19use workspace::SERIALIZATION_THROTTLE_TIME;
  20
  21use super::*;
  22
  23#[derive(Default)]
  24struct ThreadFeedbackState {
  25    feedback: Option<ThreadFeedback>,
  26    comments_editor: Option<Entity<Editor>>,
  27}
  28
  29impl ThreadFeedbackState {
  30    pub fn submit(
  31        &mut self,
  32        thread: Entity<AcpThread>,
  33        feedback: ThreadFeedback,
  34        window: &mut Window,
  35        cx: &mut App,
  36    ) {
  37        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
  38            return;
  39        };
  40
  41        let project = thread.read(cx).project().read(cx);
  42        let client = project.client();
  43        let user_store = project.user_store();
  44        let organization = user_store.read(cx).current_organization();
  45
  46        if self.feedback == Some(feedback) {
  47            return;
  48        }
  49
  50        self.feedback = Some(feedback);
  51        match feedback {
  52            ThreadFeedback::Positive => {
  53                self.comments_editor = None;
  54            }
  55            ThreadFeedback::Negative => {
  56                self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
  57            }
  58        }
  59        let session_id = thread.read(cx).session_id().clone();
  60        let parent_session_id = thread.read(cx).parent_session_id().cloned();
  61        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
  62        let task = telemetry.thread_data(&session_id, cx);
  63        let rating = match feedback {
  64            ThreadFeedback::Positive => "positive",
  65            ThreadFeedback::Negative => "negative",
  66        };
  67        cx.background_spawn(async move {
  68            let thread = task.await?;
  69
  70            client
  71                .cloud_client()
  72                .submit_agent_feedback(SubmitAgentThreadFeedbackBody {
  73                    organization_id: organization.map(|organization| organization.id.clone()),
  74                    agent: agent_telemetry_id.to_string(),
  75                    session_id: session_id.to_string(),
  76                    parent_session_id: parent_session_id.map(|id| id.to_string()),
  77                    rating: rating.to_string(),
  78                    thread,
  79                })
  80                .await?;
  81
  82            anyhow::Ok(())
  83        })
  84        .detach_and_log_err(cx);
  85    }
  86
  87    pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
  88        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
  89            return;
  90        };
  91
  92        let Some(comments) = self
  93            .comments_editor
  94            .as_ref()
  95            .map(|editor| editor.read(cx).text(cx))
  96            .filter(|text| !text.trim().is_empty())
  97        else {
  98            return;
  99        };
 100
 101        self.comments_editor.take();
 102
 103        let project = thread.read(cx).project().read(cx);
 104        let client = project.client();
 105        let user_store = project.user_store();
 106        let organization = user_store.read(cx).current_organization();
 107
 108        let session_id = thread.read(cx).session_id().clone();
 109        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 110        let task = telemetry.thread_data(&session_id, cx);
 111        cx.background_spawn(async move {
 112            let thread = task.await?;
 113
 114            client
 115                .cloud_client()
 116                .submit_agent_feedback_comments(SubmitAgentThreadFeedbackCommentsBody {
 117                    organization_id: organization.map(|organization| organization.id.clone()),
 118                    agent: agent_telemetry_id.to_string(),
 119                    session_id: session_id.to_string(),
 120                    comments,
 121                    thread,
 122                })
 123                .await?;
 124
 125            anyhow::Ok(())
 126        })
 127        .detach_and_log_err(cx);
 128    }
 129
 130    pub fn clear(&mut self) {
 131        *self = Self::default()
 132    }
 133
 134    pub fn dismiss_comments(&mut self) {
 135        self.comments_editor.take();
 136    }
 137
 138    fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
 139        let buffer = cx.new(|cx| {
 140            let empty_string = String::new();
 141            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
 142        });
 143
 144        let editor = cx.new(|cx| {
 145            let mut editor = Editor::new(
 146                editor::EditorMode::AutoHeight {
 147                    min_lines: 1,
 148                    max_lines: Some(4),
 149                },
 150                buffer,
 151                None,
 152                window,
 153                cx,
 154            );
 155            editor.set_placeholder_text(
 156                "What went wrong? Share your feedback so we can improve.",
 157                window,
 158                cx,
 159            );
 160            editor
 161        });
 162
 163        editor.read(cx).focus_handle(cx).focus(window, cx);
 164        editor
 165    }
 166}
 167
 168struct GeneratingSpinner {
 169    variant: SpinnerVariant,
 170}
 171
 172impl GeneratingSpinner {
 173    fn new(variant: SpinnerVariant) -> Self {
 174        Self { variant }
 175    }
 176}
 177
 178impl Render for GeneratingSpinner {
 179    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 180        SpinnerLabel::with_variant(self.variant).size(LabelSize::Small)
 181    }
 182}
 183
 184#[derive(IntoElement)]
 185struct GeneratingSpinnerElement {
 186    variant: SpinnerVariant,
 187}
 188
 189impl GeneratingSpinnerElement {
 190    fn new(variant: SpinnerVariant) -> Self {
 191        Self { variant }
 192    }
 193}
 194
 195impl RenderOnce for GeneratingSpinnerElement {
 196    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
 197        let id = match self.variant {
 198            SpinnerVariant::Dots => "generating-spinner-view",
 199            SpinnerVariant::Sand => "confirmation-spinner-view",
 200            _ => "spinner-view",
 201        };
 202        window.with_id(id, |window| {
 203            window.use_state(cx, |_, _| GeneratingSpinner::new(self.variant))
 204        })
 205    }
 206}
 207
 208pub enum AcpThreadViewEvent {
 209    MessageSentOrQueued,
 210}
 211
 212impl EventEmitter<AcpThreadViewEvent> for ThreadView {}
 213
 214/// Tracks the user's permission dropdown selection state for a specific tool call.
 215///
 216/// Default (no entry in the map) means the last dropdown choice is selected,
 217/// which is typically "Only this time".
 218#[derive(Clone)]
 219pub(crate) enum PermissionSelection {
 220    /// A specific choice from the dropdown (e.g., "Always for terminal", "Only this time").
 221    /// The index corresponds to the position in the `choices` list from `PermissionOptions`.
 222    Choice(usize),
 223    /// "Select options…" mode where individual command patterns can be toggled.
 224    /// Contains the indices of checked patterns in the `patterns` list.
 225    /// All patterns start checked when this mode is first activated.
 226    SelectedPatterns(Vec<usize>),
 227}
 228
 229impl PermissionSelection {
 230    /// Returns the choice index if a specific dropdown choice is selected,
 231    /// or `None` if in per-command pattern mode.
 232    pub(crate) fn choice_index(&self) -> Option<usize> {
 233        match self {
 234            Self::Choice(index) => Some(*index),
 235            Self::SelectedPatterns(_) => None,
 236        }
 237    }
 238
 239    fn is_pattern_checked(&self, index: usize) -> bool {
 240        match self {
 241            Self::SelectedPatterns(checked) => checked.contains(&index),
 242            _ => false,
 243        }
 244    }
 245
 246    fn has_any_checked_patterns(&self) -> bool {
 247        match self {
 248            Self::SelectedPatterns(checked) => !checked.is_empty(),
 249            _ => false,
 250        }
 251    }
 252
 253    fn toggle_pattern(&mut self, index: usize) {
 254        if let Self::SelectedPatterns(checked) = self {
 255            if let Some(pos) = checked.iter().position(|&i| i == index) {
 256                checked.swap_remove(pos);
 257            } else {
 258                checked.push(index);
 259            }
 260        }
 261    }
 262}
 263
 264pub struct ThreadView {
 265    pub session_id: acp::SessionId,
 266    pub parent_session_id: Option<acp::SessionId>,
 267    pub thread: Entity<AcpThread>,
 268    pub(crate) conversation: Entity<super::Conversation>,
 269    pub server_view: WeakEntity<ConversationView>,
 270    pub agent_icon: IconName,
 271    pub agent_icon_from_external_svg: Option<SharedString>,
 272    pub agent_id: AgentId,
 273    pub focus_handle: FocusHandle,
 274    pub workspace: WeakEntity<Workspace>,
 275    pub entry_view_state: Entity<EntryViewState>,
 276    pub title_editor: Entity<Editor>,
 277    pub config_options_view: Option<Entity<ConfigOptionsView>>,
 278    pub mode_selector: Option<Entity<ModeSelector>>,
 279    pub model_selector: Option<Entity<ModelSelectorPopover>>,
 280    pub profile_selector: Option<Entity<ProfileSelector>>,
 281    pub permission_dropdown_handle: PopoverMenuHandle<ContextMenu>,
 282    pub thread_retry_status: Option<RetryStatus>,
 283    pub(super) thread_error: Option<ThreadError>,
 284    pub thread_error_markdown: Option<Entity<Markdown>>,
 285    pub token_limit_callout_dismissed: bool,
 286    pub last_token_limit_telemetry: Option<acp_thread::TokenUsageRatio>,
 287    thread_feedback: ThreadFeedbackState,
 288    pub list_state: ListState,
 289    pub session_capabilities: SharedSessionCapabilities,
 290    /// Tracks which tool calls have their content/output expanded.
 291    /// Used for showing/hiding tool call results, terminal output, etc.
 292    pub expanded_tool_calls: HashSet<agent_client_protocol::ToolCallId>,
 293    pub expanded_tool_call_raw_inputs: HashSet<agent_client_protocol::ToolCallId>,
 294    pub expanded_thinking_blocks: HashSet<(usize, usize)>,
 295    auto_expanded_thinking_block: Option<(usize, usize)>,
 296    user_toggled_thinking_blocks: HashSet<(usize, usize)>,
 297    pub subagent_scroll_handles: RefCell<HashMap<acp::SessionId, ScrollHandle>>,
 298    pub edits_expanded: bool,
 299    pub plan_expanded: bool,
 300    pub queue_expanded: bool,
 301    pub editor_expanded: bool,
 302    pub should_be_following: bool,
 303    pub editing_message: Option<usize>,
 304    pub local_queued_messages: Vec<QueuedMessage>,
 305    pub queued_message_editors: Vec<Entity<MessageEditor>>,
 306    pub queued_message_editor_subscriptions: Vec<Subscription>,
 307    pub last_synced_queue_length: usize,
 308    pub turn_fields: TurnFields,
 309    pub discarded_partial_edits: HashSet<agent_client_protocol::ToolCallId>,
 310    pub is_loading_contents: bool,
 311    pub new_server_version_available: Option<SharedString>,
 312    pub resumed_without_history: bool,
 313    pub(crate) permission_selections:
 314        HashMap<agent_client_protocol::ToolCallId, PermissionSelection>,
 315    pub resume_thread_metadata: Option<AgentSessionInfo>,
 316    pub _cancel_task: Option<Task<()>>,
 317    _save_task: Option<Task<()>>,
 318    _draft_resolve_task: Option<Task<()>>,
 319    pub skip_queue_processing_count: usize,
 320    pub user_interrupted_generation: bool,
 321    pub can_fast_track_queue: bool,
 322    pub hovered_edited_file_buttons: Option<usize>,
 323    pub in_flight_prompt: Option<Vec<acp::ContentBlock>>,
 324    pub _subscriptions: Vec<Subscription>,
 325    pub message_editor: Entity<MessageEditor>,
 326    pub add_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 327    pub thinking_effort_menu_handle: PopoverMenuHandle<ContextMenu>,
 328    pub project: WeakEntity<Project>,
 329    pub recent_history_entries: Vec<AgentSessionInfo>,
 330    pub hovered_recent_history_item: Option<usize>,
 331    pub show_external_source_prompt_warning: bool,
 332    pub show_codex_windows_warning: bool,
 333    pub multi_root_callout_dismissed: bool,
 334    pub generating_indicator_in_list: bool,
 335    pub history: Option<Entity<ThreadHistory>>,
 336    pub _history_subscription: Option<Subscription>,
 337}
 338impl Focusable for ThreadView {
 339    fn focus_handle(&self, cx: &App) -> FocusHandle {
 340        if self.parent_session_id.is_some() {
 341            self.focus_handle.clone()
 342        } else {
 343            self.active_editor(cx).focus_handle(cx)
 344        }
 345    }
 346}
 347
 348#[derive(Default)]
 349pub struct TurnFields {
 350    pub _turn_timer_task: Option<Task<()>>,
 351    pub last_turn_duration: Option<Duration>,
 352    pub last_turn_tokens: Option<u64>,
 353    pub turn_generation: usize,
 354    pub turn_started_at: Option<Instant>,
 355    pub turn_tokens: Option<u64>,
 356}
 357
 358impl ThreadView {
 359    pub(crate) fn new(
 360        thread: Entity<AcpThread>,
 361        conversation: Entity<super::Conversation>,
 362        server_view: WeakEntity<ConversationView>,
 363        agent_icon: IconName,
 364        agent_icon_from_external_svg: Option<SharedString>,
 365        agent_id: AgentId,
 366        agent_display_name: SharedString,
 367        workspace: WeakEntity<Workspace>,
 368        entry_view_state: Entity<EntryViewState>,
 369        config_options_view: Option<Entity<ConfigOptionsView>>,
 370        mode_selector: Option<Entity<ModeSelector>>,
 371        model_selector: Option<Entity<ModelSelectorPopover>>,
 372        profile_selector: Option<Entity<ProfileSelector>>,
 373        list_state: ListState,
 374        session_capabilities: SharedSessionCapabilities,
 375        resumed_without_history: bool,
 376        project: WeakEntity<Project>,
 377        thread_store: Option<Entity<ThreadStore>>,
 378        history: Option<Entity<ThreadHistory>>,
 379        prompt_store: Option<Entity<PromptStore>>,
 380        initial_content: Option<AgentInitialContent>,
 381        mut subscriptions: Vec<Subscription>,
 382        window: &mut Window,
 383        cx: &mut Context<Self>,
 384    ) -> Self {
 385        let session_id = thread.read(cx).session_id().clone();
 386        let parent_session_id = thread.read(cx).parent_session_id().cloned();
 387
 388        let has_commands = !session_capabilities.read().available_commands().is_empty();
 389        let placeholder = placeholder_text(agent_display_name.as_ref(), has_commands);
 390
 391        let history_subscription = history.as_ref().map(|h| {
 392            cx.observe(h, |this, history, cx| {
 393                this.update_recent_history_from_cache(&history, cx);
 394            })
 395        });
 396
 397        let mut should_auto_submit = false;
 398        let mut show_external_source_prompt_warning = false;
 399
 400        let message_editor = cx.new(|cx| {
 401            let mut editor = MessageEditor::new(
 402                workspace.clone(),
 403                project.clone(),
 404                thread_store,
 405                history.as_ref().map(|h| h.downgrade()),
 406                prompt_store,
 407                session_capabilities.clone(),
 408                agent_id.clone(),
 409                &placeholder,
 410                editor::EditorMode::AutoHeight {
 411                    min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
 412                    max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
 413                },
 414                window,
 415                cx,
 416            );
 417            if let Some(content) = initial_content {
 418                match content {
 419                    AgentInitialContent::ThreadSummary { session_id, title } => {
 420                        editor.insert_thread_summary(session_id, title, window, cx);
 421                    }
 422                    AgentInitialContent::ContentBlock {
 423                        blocks,
 424                        auto_submit,
 425                    } => {
 426                        should_auto_submit = auto_submit;
 427                        editor.set_message(blocks, window, cx);
 428                    }
 429                    AgentInitialContent::FromExternalSource(prompt) => {
 430                        show_external_source_prompt_warning = true;
 431                        // SECURITY: Be explicit about not auto submitting prompt from external source.
 432                        should_auto_submit = false;
 433                        editor.set_message(
 434                            vec![acp::ContentBlock::Text(acp::TextContent::new(
 435                                prompt.into_string(),
 436                            ))],
 437                            window,
 438                            cx,
 439                        );
 440                    }
 441                }
 442            } else if let Some(draft) = thread.read(cx).draft_prompt() {
 443                editor.set_message(draft.to_vec(), window, cx);
 444            }
 445            editor
 446        });
 447
 448        let show_codex_windows_warning = cfg!(windows)
 449            && project.upgrade().is_some_and(|p| p.read(cx).is_local())
 450            && agent_id.as_ref() == "Codex";
 451
 452        let title_editor = {
 453            let can_edit = thread.update(cx, |thread, cx| thread.can_set_title(cx));
 454            let editor = cx.new(|cx| {
 455                let mut editor = Editor::single_line(window, cx);
 456                if let Some(title) = thread.read(cx).title() {
 457                    editor.set_text(title, window, cx);
 458                } else {
 459                    editor.set_text(DEFAULT_THREAD_TITLE, window, cx);
 460                }
 461                editor.set_read_only(!can_edit);
 462                editor
 463            });
 464            subscriptions.push(cx.subscribe_in(&editor, window, Self::handle_title_editor_event));
 465            editor
 466        };
 467
 468        subscriptions.push(cx.subscribe_in(
 469            &entry_view_state,
 470            window,
 471            Self::handle_entry_view_event,
 472        ));
 473
 474        subscriptions.push(cx.subscribe_in(
 475            &message_editor,
 476            window,
 477            Self::handle_message_editor_event,
 478        ));
 479
 480        subscriptions.push(cx.observe(&message_editor, |this, editor, cx| {
 481            let is_empty = editor.read(cx).text(cx).is_empty();
 482            let draft_contents_task = if is_empty {
 483                None
 484            } else {
 485                Some(editor.update(cx, |editor, cx| editor.draft_contents(cx)))
 486            };
 487            this._draft_resolve_task = Some(cx.spawn(async move |this, cx| {
 488                let draft = if let Some(task) = draft_contents_task {
 489                    let blocks = task.await.ok().filter(|b| !b.is_empty());
 490                    blocks
 491                } else {
 492                    None
 493                };
 494                this.update(cx, |this, cx| {
 495                    this.thread.update(cx, |thread, _cx| {
 496                        thread.set_draft_prompt(draft);
 497                    });
 498                    this.schedule_save(cx);
 499                })
 500                .ok();
 501            }));
 502        }));
 503
 504        let recent_history_entries = history
 505            .as_ref()
 506            .map(|h| h.read(cx).get_recent_sessions(3))
 507            .unwrap_or_default();
 508
 509        let mut this = Self {
 510            session_id,
 511            parent_session_id,
 512            focus_handle: cx.focus_handle(),
 513            thread,
 514            conversation,
 515            server_view,
 516            agent_icon,
 517            agent_icon_from_external_svg,
 518            agent_id,
 519            workspace,
 520            entry_view_state,
 521            title_editor,
 522            config_options_view,
 523            mode_selector,
 524            model_selector,
 525            profile_selector,
 526            list_state,
 527            session_capabilities,
 528            resumed_without_history,
 529            _subscriptions: subscriptions,
 530            permission_dropdown_handle: PopoverMenuHandle::default(),
 531            thread_retry_status: None,
 532            thread_error: None,
 533            thread_error_markdown: None,
 534            token_limit_callout_dismissed: false,
 535            last_token_limit_telemetry: None,
 536            thread_feedback: Default::default(),
 537            expanded_tool_calls: HashSet::default(),
 538            expanded_tool_call_raw_inputs: HashSet::default(),
 539            expanded_thinking_blocks: HashSet::default(),
 540            auto_expanded_thinking_block: None,
 541            user_toggled_thinking_blocks: HashSet::default(),
 542            subagent_scroll_handles: RefCell::new(HashMap::default()),
 543            edits_expanded: false,
 544            plan_expanded: false,
 545            queue_expanded: true,
 546            editor_expanded: false,
 547            should_be_following: false,
 548            editing_message: None,
 549            local_queued_messages: Vec::new(),
 550            queued_message_editors: Vec::new(),
 551            queued_message_editor_subscriptions: Vec::new(),
 552            last_synced_queue_length: 0,
 553            turn_fields: TurnFields::default(),
 554            discarded_partial_edits: HashSet::default(),
 555            is_loading_contents: false,
 556            new_server_version_available: None,
 557            permission_selections: HashMap::default(),
 558            resume_thread_metadata: None,
 559            _cancel_task: None,
 560            _save_task: None,
 561            _draft_resolve_task: None,
 562            skip_queue_processing_count: 0,
 563            user_interrupted_generation: false,
 564            can_fast_track_queue: false,
 565            hovered_edited_file_buttons: None,
 566            in_flight_prompt: None,
 567            message_editor,
 568            add_context_menu_handle: PopoverMenuHandle::default(),
 569            thinking_effort_menu_handle: PopoverMenuHandle::default(),
 570            project,
 571            recent_history_entries,
 572            hovered_recent_history_item: None,
 573            show_external_source_prompt_warning,
 574            history,
 575            _history_subscription: history_subscription,
 576            show_codex_windows_warning,
 577            multi_root_callout_dismissed: false,
 578            generating_indicator_in_list: false,
 579        };
 580
 581        this.sync_generating_indicator(cx);
 582        this.sync_editor_mode_for_empty_state(cx);
 583        let list_state_for_scroll = this.list_state.clone();
 584        let thread_view = cx.entity().downgrade();
 585
 586        this.list_state
 587            .set_scroll_handler(move |_event, _window, cx| {
 588                let list_state = list_state_for_scroll.clone();
 589                let thread_view = thread_view.clone();
 590                // N.B. We must defer because the scroll handler is called while the
 591                // ListState's RefCell is mutably borrowed. Reading logical_scroll_top()
 592                // directly would panic from a double borrow.
 593                cx.defer(move |cx| {
 594                    let scroll_top = list_state.logical_scroll_top();
 595                    let _ = thread_view.update(cx, |this, cx| {
 596                        if let Some(thread) = this.as_native_thread(cx) {
 597                            thread.update(cx, |thread, _cx| {
 598                                thread.set_ui_scroll_position(Some(scroll_top));
 599                            });
 600                        }
 601                        this.schedule_save(cx);
 602                    });
 603                });
 604            });
 605
 606        if should_auto_submit {
 607            this.send(window, cx);
 608        }
 609        this
 610    }
 611
 612    /// Schedule a throttled save of the thread state (draft prompt, scroll position, etc.).
 613    /// Multiple calls within `SERIALIZATION_THROTTLE_TIME` are coalesced into a single save.
 614    fn schedule_save(&mut self, cx: &mut Context<Self>) {
 615        self._save_task = Some(cx.spawn(async move |this, cx| {
 616            cx.background_executor()
 617                .timer(SERIALIZATION_THROTTLE_TIME)
 618                .await;
 619            this.update(cx, |this, cx| {
 620                if let Some(thread) = this.as_native_thread(cx) {
 621                    thread.update(cx, |_thread, cx| cx.notify());
 622                }
 623            })
 624            .ok();
 625        }));
 626    }
 627
 628    pub fn handle_message_editor_event(
 629        &mut self,
 630        _editor: &Entity<MessageEditor>,
 631        event: &MessageEditorEvent,
 632        window: &mut Window,
 633        cx: &mut Context<Self>,
 634    ) {
 635        match event {
 636            MessageEditorEvent::Send => self.send(window, cx),
 637            MessageEditorEvent::SendImmediately => self.interrupt_and_send(window, cx),
 638            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 639            MessageEditorEvent::Focus => {
 640                self.cancel_editing(&Default::default(), window, cx);
 641            }
 642            MessageEditorEvent::LostFocus => {}
 643            MessageEditorEvent::InputAttempted { .. } => {}
 644        }
 645    }
 646
 647    pub fn is_draft(&self, cx: &App) -> bool {
 648        self.thread.read(cx).entries().is_empty()
 649    }
 650
 651    pub(crate) fn as_native_connection(
 652        &self,
 653        cx: &App,
 654    ) -> Option<Rc<agent::NativeAgentConnection>> {
 655        let acp_thread = self.thread.read(cx);
 656        acp_thread.connection().clone().downcast()
 657    }
 658
 659    pub fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
 660        let acp_thread = self.thread.read(cx);
 661        self.as_native_connection(cx)?
 662            .thread(acp_thread.session_id(), cx)
 663    }
 664
 665    /// Resolves the message editor's contents into content blocks. For profiles
 666    /// that do not enable any tools, directory mentions are expanded to inline
 667    /// file contents since the agent can't read files on its own.
 668    fn resolve_message_contents(
 669        &self,
 670        message_editor: &Entity<MessageEditor>,
 671        cx: &mut App,
 672    ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
 673        let expand = self.as_native_thread(cx).is_some_and(|thread| {
 674            let thread = thread.read(cx);
 675            AgentSettings::get_global(cx)
 676                .profiles
 677                .get(thread.profile())
 678                .is_some_and(|profile| profile.tools.is_empty())
 679        });
 680        message_editor.update(cx, |message_editor, cx| message_editor.contents(expand, cx))
 681    }
 682
 683    pub fn current_model_id(&self, cx: &App) -> Option<String> {
 684        let selector = self.model_selector.as_ref()?;
 685        let model = selector.read(cx).active_model(cx)?;
 686        Some(model.id.to_string())
 687    }
 688
 689    pub fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
 690        if let Some(thread) = self.as_native_thread(cx) {
 691            Some(thread.read(cx).profile().0.clone())
 692        } else {
 693            let mode_selector = self.mode_selector.as_ref()?;
 694            Some(mode_selector.read(cx).mode().0)
 695        }
 696    }
 697
 698    fn is_subagent(&self) -> bool {
 699        self.parent_session_id.is_some()
 700    }
 701
 702    /// Returns the currently active editor, either for a message that is being
 703    /// edited or the editor for a new message.
 704    pub(crate) fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
 705        if let Some(index) = self.editing_message
 706            && let Some(editor) = self
 707                .entry_view_state
 708                .read(cx)
 709                .entry(index)
 710                .and_then(|entry| entry.message_editor())
 711                .cloned()
 712        {
 713            editor
 714        } else {
 715            self.message_editor.clone()
 716        }
 717    }
 718
 719    pub fn has_queued_messages(&self) -> bool {
 720        !self.local_queued_messages.is_empty()
 721    }
 722
 723    pub fn is_imported_thread(&self, cx: &App) -> bool {
 724        let Some(thread) = self.as_native_thread(cx) else {
 725            return false;
 726        };
 727        thread.read(cx).is_imported()
 728    }
 729
 730    // events
 731
 732    pub fn handle_entry_view_event(
 733        &mut self,
 734        _: &Entity<EntryViewState>,
 735        event: &EntryViewEvent,
 736        window: &mut Window,
 737        cx: &mut Context<Self>,
 738    ) {
 739        match &event.view_event {
 740            ViewEvent::NewDiff(tool_call_id) => {
 741                if AgentSettings::get_global(cx).expand_edit_card {
 742                    self.expanded_tool_calls.insert(tool_call_id.clone());
 743                }
 744            }
 745            ViewEvent::NewTerminal(tool_call_id) => {
 746                if AgentSettings::get_global(cx).expand_terminal_card {
 747                    self.expanded_tool_calls.insert(tool_call_id.clone());
 748                }
 749            }
 750            ViewEvent::TerminalMovedToBackground(tool_call_id) => {
 751                self.expanded_tool_calls.remove(tool_call_id);
 752            }
 753            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 754                if let Some(AgentThreadEntry::UserMessage(user_message)) =
 755                    self.thread.read(cx).entries().get(event.entry_index)
 756                    && self.thread.read(cx).supports_truncate(cx)
 757                    && user_message.id.is_some()
 758                    && !self.is_subagent()
 759                {
 760                    self.editing_message = Some(event.entry_index);
 761                    cx.notify();
 762                }
 763            }
 764            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
 765                if let Some(AgentThreadEntry::UserMessage(user_message)) =
 766                    self.thread.read(cx).entries().get(event.entry_index)
 767                    && self.thread.read(cx).supports_truncate(cx)
 768                    && user_message.id.is_some()
 769                    && !self.is_subagent()
 770                {
 771                    if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
 772                        self.editing_message = None;
 773                        cx.notify();
 774                    }
 775                }
 776            }
 777            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
 778            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 779                if !self.is_subagent() {
 780                    self.regenerate(event.entry_index, editor.clone(), window, cx);
 781                }
 782            }
 783            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 784                self.cancel_editing(&Default::default(), window, cx);
 785            }
 786            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::InputAttempted { .. }) => {}
 787            ViewEvent::OpenDiffLocation {
 788                path,
 789                position,
 790                split,
 791            } => {
 792                self.open_diff_location(path, *position, *split, window, cx);
 793            }
 794        }
 795    }
 796
 797    fn open_diff_location(
 798        &self,
 799        path: &str,
 800        position: Point,
 801        split: bool,
 802        window: &mut Window,
 803        cx: &mut Context<Self>,
 804    ) {
 805        let Some(project) = self.project.upgrade() else {
 806            return;
 807        };
 808        let Some(project_path) = project.read(cx).find_project_path(path, cx) else {
 809            return;
 810        };
 811
 812        let open_task = if split {
 813            self.workspace
 814                .update(cx, |workspace, cx| {
 815                    workspace.split_path(project_path, window, cx)
 816                })
 817                .log_err()
 818        } else {
 819            self.workspace
 820                .update(cx, |workspace, cx| {
 821                    workspace.open_path(project_path, None, true, window, cx)
 822                })
 823                .log_err()
 824        };
 825
 826        let Some(open_task) = open_task else {
 827            return;
 828        };
 829
 830        window
 831            .spawn(cx, async move |cx| {
 832                let item = open_task.await?;
 833                let Some(editor) = item.downcast::<Editor>() else {
 834                    return anyhow::Ok(());
 835                };
 836                editor.update_in(cx, |editor, window, cx| {
 837                    editor.change_selections(
 838                        SelectionEffects::scroll(Autoscroll::center()),
 839                        window,
 840                        cx,
 841                        |selections| {
 842                            selections.select_ranges([position..position]);
 843                        },
 844                    );
 845                })?;
 846                anyhow::Ok(())
 847            })
 848            .detach_and_log_err(cx);
 849    }
 850
 851    // turns
 852
 853    pub fn start_turn(&mut self, cx: &mut Context<Self>) -> usize {
 854        self.turn_fields.turn_generation += 1;
 855        let generation = self.turn_fields.turn_generation;
 856        self.turn_fields.turn_started_at = Some(Instant::now());
 857        self.turn_fields.last_turn_duration = None;
 858        self.turn_fields.last_turn_tokens = None;
 859        self.turn_fields.turn_tokens = Some(0);
 860        self.turn_fields._turn_timer_task = Some(cx.spawn(async move |this, cx| {
 861            loop {
 862                cx.background_executor().timer(Duration::from_secs(1)).await;
 863                if this.update(cx, |_, cx| cx.notify()).is_err() {
 864                    break;
 865                }
 866            }
 867        }));
 868        generation
 869    }
 870
 871    pub fn stop_turn(&mut self, generation: usize, _cx: &mut Context<Self>) {
 872        if self.turn_fields.turn_generation != generation {
 873            return;
 874        }
 875        self.turn_fields.last_turn_duration = self
 876            .turn_fields
 877            .turn_started_at
 878            .take()
 879            .map(|started| started.elapsed());
 880        self.turn_fields.last_turn_tokens = self.turn_fields.turn_tokens.take();
 881        self.turn_fields._turn_timer_task = None;
 882    }
 883
 884    pub fn update_turn_tokens(&mut self, cx: &App) {
 885        if let Some(usage) = self.thread.read(cx).token_usage() {
 886            if let Some(tokens) = &mut self.turn_fields.turn_tokens {
 887                *tokens += usage.output_tokens;
 888            }
 889        }
 890    }
 891
 892    // sending
 893
 894    fn clear_external_source_prompt_warning(&mut self, cx: &mut Context<Self>) {
 895        if self.show_external_source_prompt_warning {
 896            self.show_external_source_prompt_warning = false;
 897            cx.notify();
 898        }
 899    }
 900
 901    pub fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 902        let thread = &self.thread;
 903
 904        if self.is_loading_contents {
 905            return;
 906        }
 907
 908        let message_editor = self.message_editor.clone();
 909
 910        let is_editor_empty = message_editor.read(cx).is_empty(cx);
 911        let is_generating = thread.read(cx).status() != ThreadStatus::Idle;
 912
 913        let has_queued = self.has_queued_messages();
 914        if is_editor_empty && self.can_fast_track_queue && has_queued {
 915            self.can_fast_track_queue = false;
 916            cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
 917            self.send_queued_message_at_index(0, true, window, cx);
 918            return;
 919        }
 920
 921        if is_editor_empty {
 922            return;
 923        }
 924
 925        if is_generating {
 926            cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
 927            self.queue_message(message_editor, window, cx);
 928            return;
 929        }
 930
 931        let text = message_editor.read(cx).text(cx);
 932        let text = text.trim();
 933        if text == "/login" || text == "/logout" {
 934            let connection = thread.read(cx).connection().clone();
 935            let can_login = !connection.auth_methods().is_empty();
 936            // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
 937            let logout_supported = text == "/logout"
 938                && self
 939                    .session_capabilities
 940                    .read()
 941                    .available_commands()
 942                    .iter()
 943                    .any(|command| command.name == "logout");
 944            if can_login && !logout_supported {
 945                message_editor.update(cx, |editor, cx| editor.clear(window, cx));
 946                self.clear_external_source_prompt_warning(cx);
 947
 948                let connection = self.thread.read(cx).connection().clone();
 949                window.defer(cx, {
 950                    let agent_id = self.agent_id.clone();
 951                    let server_view = self.server_view.clone();
 952                    move |window, cx| {
 953                        ConversationView::handle_auth_required(
 954                            server_view.clone(),
 955                            AuthRequired::new(),
 956                            agent_id,
 957                            connection,
 958                            window,
 959                            cx,
 960                        );
 961                    }
 962                });
 963                cx.notify();
 964                return;
 965            }
 966        }
 967
 968        cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
 969        self.send_impl(message_editor, window, cx)
 970    }
 971
 972    pub fn send_impl(
 973        &mut self,
 974        message_editor: Entity<MessageEditor>,
 975        window: &mut Window,
 976        cx: &mut Context<Self>,
 977    ) {
 978        let contents = self.resolve_message_contents(&message_editor, cx);
 979
 980        self.thread_error.take();
 981        self.thread_feedback.clear();
 982        self.editing_message.take();
 983
 984        if self.should_be_following {
 985            self.workspace
 986                .update(cx, |workspace, cx| {
 987                    workspace.follow(CollaboratorId::Agent, window, cx);
 988                })
 989                .ok();
 990        }
 991
 992        let contents_task = cx.spawn_in(window, async move |_this, cx| {
 993            let (contents, tracked_buffers) = contents.await?;
 994
 995            if contents.is_empty() {
 996                return Ok(None);
 997            }
 998
 999            let _ = cx.update(|window, cx| {
1000                message_editor.update(cx, |message_editor, cx| {
1001                    message_editor.clear(window, cx);
1002                });
1003            });
1004
1005            Ok(Some((contents, tracked_buffers)))
1006        });
1007
1008        self.send_content(contents_task, window, cx);
1009    }
1010
1011    pub fn send_content(
1012        &mut self,
1013        contents_task: Task<anyhow::Result<Option<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>>,
1014        window: &mut Window,
1015        cx: &mut Context<Self>,
1016    ) {
1017        let session_id = self.thread.read(cx).session_id().clone();
1018        let parent_session_id = self.thread.read(cx).parent_session_id().cloned();
1019        let agent_telemetry_id = self.thread.read(cx).connection().telemetry_id();
1020        let is_first_message = self.thread.read(cx).entries().is_empty();
1021        let thread = self.thread.downgrade();
1022
1023        self.is_loading_contents = true;
1024
1025        let model_id = self.current_model_id(cx);
1026        let mode_id = self.current_mode_id(cx);
1027        let guard = cx.new(|_| ());
1028        cx.observe_release(&guard, |this, _guard, cx| {
1029            this.is_loading_contents = false;
1030            cx.notify();
1031        })
1032        .detach();
1033
1034        let task = cx.spawn_in(window, async move |this, cx| {
1035            let Some((contents, tracked_buffers)) = contents_task.await? else {
1036                return Ok(());
1037            };
1038
1039            let generation = this.update(cx, |this, cx| {
1040                this.clear_external_source_prompt_warning(cx);
1041                let generation = this.start_turn(cx);
1042                this.in_flight_prompt = Some(contents.clone());
1043                generation
1044            })?;
1045
1046            this.update_in(cx, |this, _window, cx| {
1047                this.set_editor_is_expanded(false, cx);
1048            })?;
1049
1050            let _ = this.update(cx, |this, cx| {
1051                this.list_state.scroll_to_end();
1052                cx.notify();
1053            });
1054
1055            let _stop_turn = defer({
1056                let this = this.clone();
1057                let mut cx = cx.clone();
1058                move || {
1059                    this.update(&mut cx, |this, cx| {
1060                        this.stop_turn(generation, cx);
1061                        cx.notify();
1062                    })
1063                    .ok();
1064                }
1065            });
1066            if is_first_message && thread.read_with(cx, |thread, _cx| thread.title().is_none())? {
1067                let text: String = contents
1068                    .iter()
1069                    .filter_map(|block| match block {
1070                        acp::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
1071                        acp::ContentBlock::ResourceLink(resource_link) => {
1072                            Some(format!("@{}", resource_link.name))
1073                        }
1074                        _ => None,
1075                    })
1076                    .collect::<Vec<_>>()
1077                    .join(" ");
1078                let text = text.lines().next().unwrap_or("").trim();
1079                if !text.is_empty() {
1080                    let title: SharedString = util::truncate_and_trailoff(text, 200).into();
1081                    thread.update(cx, |thread, cx| {
1082                        thread.set_provisional_title(title, cx);
1083                    })?;
1084                }
1085            }
1086
1087            let turn_start_time = Instant::now();
1088            let send = thread.update(cx, |thread, cx| {
1089                thread.action_log().update(cx, |action_log, cx| {
1090                    for buffer in tracked_buffers {
1091                        action_log.buffer_read(buffer, cx)
1092                    }
1093                });
1094                drop(guard);
1095
1096                telemetry::event!(
1097                    "Agent Message Sent",
1098                    agent = agent_telemetry_id,
1099                    session = session_id,
1100                    parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),
1101                    model = model_id,
1102                    mode = mode_id
1103                );
1104
1105                thread.send(contents, cx)
1106            })?;
1107
1108            let _ = this.update(cx, |this, cx| {
1109                this.sync_generating_indicator(cx);
1110                cx.notify();
1111            });
1112
1113            let res = send.await;
1114            let turn_time_ms = turn_start_time.elapsed().as_millis();
1115            drop(_stop_turn);
1116            let status = if res.is_ok() {
1117                let _ = this.update(cx, |this, _| this.in_flight_prompt.take());
1118                "success"
1119            } else {
1120                "failure"
1121            };
1122            telemetry::event!(
1123                "Agent Turn Completed",
1124                agent = agent_telemetry_id,
1125                session = session_id,
1126                parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),
1127                model = model_id,
1128                mode = mode_id,
1129                status,
1130                turn_time_ms,
1131            );
1132            res.map(|_| ())
1133        });
1134
1135        cx.spawn(async move |this, cx| {
1136            if let Err(err) = task.await {
1137                this.update(cx, |this, cx| {
1138                    this.handle_thread_error(err, cx);
1139                })
1140                .ok();
1141            } else {
1142                this.update(cx, |this, cx| {
1143                    let should_be_following = this
1144                        .workspace
1145                        .update(cx, |workspace, _| {
1146                            workspace.is_being_followed(CollaboratorId::Agent)
1147                        })
1148                        .unwrap_or_default();
1149                    this.should_be_following = should_be_following;
1150                })
1151                .ok();
1152            }
1153        })
1154        .detach();
1155    }
1156
1157    pub fn interrupt_and_send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1158        let thread = &self.thread;
1159
1160        if self.is_loading_contents {
1161            return;
1162        }
1163
1164        let message_editor = self.message_editor.clone();
1165        if thread.read(cx).status() == ThreadStatus::Idle {
1166            self.send_impl(message_editor, window, cx);
1167            return;
1168        }
1169
1170        self.stop_current_and_send_new_message(message_editor, window, cx);
1171    }
1172
1173    fn stop_current_and_send_new_message(
1174        &mut self,
1175        message_editor: Entity<MessageEditor>,
1176        window: &mut Window,
1177        cx: &mut Context<Self>,
1178    ) {
1179        let thread = self.thread.clone();
1180        self.skip_queue_processing_count = 0;
1181        self.user_interrupted_generation = true;
1182
1183        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1184
1185        cx.spawn_in(window, async move |this, cx| {
1186            cancelled.await;
1187
1188            this.update_in(cx, |this, window, cx| {
1189                this.send_impl(message_editor, window, cx);
1190            })
1191            .ok();
1192        })
1193        .detach();
1194    }
1195
1196    pub(crate) fn handle_thread_error(
1197        &mut self,
1198        error: impl Into<ThreadError>,
1199        cx: &mut Context<Self>,
1200    ) {
1201        let error = error.into();
1202        self.emit_thread_error_telemetry(&error, cx);
1203        self.thread_error = Some(error);
1204        cx.notify();
1205    }
1206
1207    fn emit_thread_error_telemetry(&self, error: &ThreadError, cx: &mut Context<Self>) {
1208        let (error_kind, acp_error_code, message): (&str, Option<SharedString>, SharedString) =
1209            match error {
1210                ThreadError::PaymentRequired => (
1211                    "payment_required",
1212                    None,
1213                    "You reached your free usage limit. Upgrade to Zed Pro for more prompts."
1214                        .into(),
1215                ),
1216                ThreadError::Refusal => {
1217                    let model_or_agent_name = self.current_model_name(cx);
1218                    let message = format!(
1219                        "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
1220                        model_or_agent_name
1221                    );
1222                    ("refusal", None, message.into())
1223                }
1224                ThreadError::AuthenticationRequired(message) => {
1225                    ("authentication_required", None, message.clone())
1226                }
1227                ThreadError::RateLimitExceeded { provider } => (
1228                    "rate_limit_exceeded",
1229                    None,
1230                    format!("{provider}'s rate limit was reached.").into(),
1231                ),
1232                ThreadError::ServerOverloaded { provider } => (
1233                    "server_overloaded",
1234                    None,
1235                    format!("{provider}'s servers are temporarily unavailable.").into(),
1236                ),
1237                ThreadError::PromptTooLarge => (
1238                    "prompt_too_large",
1239                    None,
1240                    "Context too large for the model's context window.".into(),
1241                ),
1242                ThreadError::NoApiKey { provider } => (
1243                    "no_api_key",
1244                    None,
1245                    format!("No API key configured for {provider}.").into(),
1246                ),
1247                ThreadError::StreamError { provider } => (
1248                    "stream_error",
1249                    None,
1250                    format!("Connection to {provider}'s API was interrupted.").into(),
1251                ),
1252                ThreadError::InvalidApiKey { provider } => (
1253                    "invalid_api_key",
1254                    None,
1255                    format!("Invalid or expired API key for {provider}.").into(),
1256                ),
1257                ThreadError::PermissionDenied { provider } => (
1258                    "permission_denied",
1259                    None,
1260                    format!(
1261                        "{provider}'s API rejected the request due to insufficient permissions."
1262                    )
1263                    .into(),
1264                ),
1265                ThreadError::RequestFailed => (
1266                    "request_failed",
1267                    None,
1268                    "Request could not be completed after multiple attempts.".into(),
1269                ),
1270                ThreadError::MaxOutputTokens => (
1271                    "max_output_tokens",
1272                    None,
1273                    "Model reached its maximum output length.".into(),
1274                ),
1275                ThreadError::NoModelSelected => {
1276                    ("no_model_selected", None, "No model selected.".into())
1277                }
1278                ThreadError::ApiError { provider } => (
1279                    "api_error",
1280                    None,
1281                    format!("{provider}'s API returned an unexpected error.").into(),
1282                ),
1283                ThreadError::Other {
1284                    acp_error_code,
1285                    message,
1286                } => ("other", acp_error_code.clone(), message.clone()),
1287            };
1288
1289        let agent_telemetry_id = self.thread.read(cx).connection().telemetry_id();
1290        let session_id = self.thread.read(cx).session_id().clone();
1291        let parent_session_id = self
1292            .thread
1293            .read(cx)
1294            .parent_session_id()
1295            .map(|id| id.to_string());
1296
1297        telemetry::event!(
1298            "Agent Panel Error Shown",
1299            agent = agent_telemetry_id,
1300            session_id = session_id,
1301            parent_session_id = parent_session_id,
1302            kind = error_kind,
1303            acp_error_code = acp_error_code,
1304            message = message,
1305        );
1306    }
1307
1308    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
1309        self.thread_retry_status.take();
1310        self.thread_error.take();
1311        self.user_interrupted_generation = true;
1312        self._cancel_task = Some(self.thread.update(cx, |thread, cx| thread.cancel(cx)));
1313        self.sync_generating_indicator(cx);
1314        cx.notify();
1315    }
1316
1317    pub fn retry_generation(&mut self, cx: &mut Context<Self>) {
1318        self.thread_error.take();
1319
1320        let thread = &self.thread;
1321        if !thread.read(cx).can_retry(cx) {
1322            return;
1323        }
1324
1325        let task = thread.update(cx, |thread, cx| thread.retry(cx));
1326        self.sync_generating_indicator(cx);
1327        cx.notify();
1328        cx.spawn(async move |this, cx| {
1329            let result = task.await;
1330
1331            this.update(cx, |this, cx| {
1332                if let Err(err) = result {
1333                    this.handle_thread_error(err, cx);
1334                }
1335            })
1336        })
1337        .detach();
1338    }
1339
1340    pub fn regenerate(
1341        &mut self,
1342        entry_ix: usize,
1343        message_editor: Entity<MessageEditor>,
1344        window: &mut Window,
1345        cx: &mut Context<Self>,
1346    ) {
1347        if self.is_loading_contents {
1348            return;
1349        }
1350        let thread = self.thread.clone();
1351
1352        let Some(user_message_id) = thread.update(cx, |thread, _| {
1353            thread.entries().get(entry_ix)?.user_message()?.id.clone()
1354        }) else {
1355            return;
1356        };
1357
1358        cx.spawn_in(window, async move |this, cx| {
1359            // Check if there are any edits from prompts before the one being regenerated.
1360            //
1361            // If there are, we keep/accept them since we're not regenerating the prompt that created them.
1362            //
1363            // If editing the prompt that generated the edits, they are auto-rejected
1364            // through the `rewind` function in the `acp_thread`.
1365            let has_earlier_edits = thread.read_with(cx, |thread, _| {
1366                thread
1367                    .entries()
1368                    .iter()
1369                    .take(entry_ix)
1370                    .any(|entry| entry.diffs().next().is_some())
1371            });
1372
1373            if has_earlier_edits {
1374                thread.update(cx, |thread, cx| {
1375                    thread.action_log().update(cx, |action_log, cx| {
1376                        action_log.keep_all_edits(None, cx);
1377                    });
1378                });
1379            }
1380
1381            thread
1382                .update(cx, |thread, cx| thread.rewind(user_message_id, cx))
1383                .await?;
1384            this.update_in(cx, |thread, window, cx| {
1385                thread.send_impl(message_editor, window, cx);
1386                thread.focus_handle(cx).focus(window, cx);
1387            })?;
1388            anyhow::Ok(())
1389        })
1390        .detach_and_log_err(cx);
1391    }
1392
1393    // message queueing
1394
1395    fn queue_message(
1396        &mut self,
1397        message_editor: Entity<MessageEditor>,
1398        window: &mut Window,
1399        cx: &mut Context<Self>,
1400    ) {
1401        let is_idle = self.thread.read(cx).status() == acp_thread::ThreadStatus::Idle;
1402
1403        if is_idle {
1404            self.send_impl(message_editor, window, cx);
1405            return;
1406        }
1407
1408        let contents = self.resolve_message_contents(&message_editor, cx);
1409
1410        cx.spawn_in(window, async move |this, cx| {
1411            let (content, tracked_buffers) = contents.await?;
1412
1413            if content.is_empty() {
1414                return Ok::<(), anyhow::Error>(());
1415            }
1416
1417            this.update_in(cx, |this, window, cx| {
1418                this.add_to_queue(content, tracked_buffers, cx);
1419                this.can_fast_track_queue = true;
1420                message_editor.update(cx, |message_editor, cx| {
1421                    message_editor.clear(window, cx);
1422                });
1423                cx.notify();
1424            })?;
1425            Ok(())
1426        })
1427        .detach_and_log_err(cx);
1428    }
1429
1430    pub fn add_to_queue(
1431        &mut self,
1432        content: Vec<acp::ContentBlock>,
1433        tracked_buffers: Vec<Entity<Buffer>>,
1434        cx: &mut Context<Self>,
1435    ) {
1436        self.local_queued_messages.push(QueuedMessage {
1437            content,
1438            tracked_buffers,
1439        });
1440        self.sync_queue_flag_to_native_thread(cx);
1441    }
1442
1443    pub fn remove_from_queue(
1444        &mut self,
1445        index: usize,
1446        cx: &mut Context<Self>,
1447    ) -> Option<QueuedMessage> {
1448        if index < self.local_queued_messages.len() {
1449            let removed = self.local_queued_messages.remove(index);
1450            self.sync_queue_flag_to_native_thread(cx);
1451            Some(removed)
1452        } else {
1453            None
1454        }
1455    }
1456
1457    pub fn sync_queue_flag_to_native_thread(&self, cx: &mut Context<Self>) {
1458        if let Some(native_thread) = self.as_native_thread(cx) {
1459            let has_queued = self.has_queued_messages();
1460            native_thread.update(cx, |thread, _| {
1461                thread.set_has_queued_message(has_queued);
1462            });
1463        }
1464    }
1465
1466    pub fn send_queued_message_at_index(
1467        &mut self,
1468        index: usize,
1469        is_send_now: bool,
1470        window: &mut Window,
1471        cx: &mut Context<Self>,
1472    ) {
1473        let Some(queued) = self.remove_from_queue(index, cx) else {
1474            return;
1475        };
1476
1477        self.message_editor.focus_handle(cx).focus(window, cx);
1478
1479        let content = queued.content;
1480        let tracked_buffers = queued.tracked_buffers;
1481
1482        // Only increment skip count for "Send Now" operations (out-of-order sends)
1483        // Normal auto-processing from the Stopped handler doesn't need to skip.
1484        // We only skip the Stopped event from the cancelled generation, NOT the
1485        // Stopped event from the newly sent message (which should trigger queue processing).
1486        if is_send_now {
1487            let is_generating =
1488                self.thread.read(cx).status() == acp_thread::ThreadStatus::Generating;
1489            self.skip_queue_processing_count += if is_generating { 1 } else { 0 };
1490        }
1491
1492        let cancelled = self.thread.update(cx, |thread, cx| thread.cancel(cx));
1493
1494        let workspace = self.workspace.clone();
1495
1496        let should_be_following = self.should_be_following;
1497        let contents_task = cx.spawn_in(window, async move |_this, cx| {
1498            cancelled.await;
1499            if should_be_following {
1500                workspace
1501                    .update_in(cx, |workspace, window, cx| {
1502                        workspace.follow(CollaboratorId::Agent, window, cx);
1503                    })
1504                    .ok();
1505            }
1506
1507            Ok(Some((content, tracked_buffers)))
1508        });
1509
1510        self.send_content(contents_task, window, cx);
1511    }
1512
1513    pub fn move_queued_message_to_main_editor(
1514        &mut self,
1515        index: usize,
1516        inserted_text: Option<&str>,
1517        cursor_offset: Option<usize>,
1518        window: &mut Window,
1519        cx: &mut Context<Self>,
1520    ) -> bool {
1521        let Some(queued_message) = self.remove_from_queue(index, cx) else {
1522            return false;
1523        };
1524        let queued_content = queued_message.content;
1525        let message_editor = self.message_editor.clone();
1526        let inserted_text = inserted_text.map(ToOwned::to_owned);
1527
1528        window.focus(&message_editor.focus_handle(cx), cx);
1529
1530        if message_editor.read(cx).is_empty(cx) {
1531            message_editor.update(cx, |editor, cx| {
1532                editor.set_message(queued_content, window, cx);
1533                if let Some(offset) = cursor_offset {
1534                    editor.set_cursor_offset(offset, window, cx);
1535                }
1536                if let Some(inserted_text) = inserted_text.as_deref() {
1537                    editor.insert_text(inserted_text, window, cx);
1538                }
1539            });
1540            cx.notify();
1541            return true;
1542        }
1543
1544        // Adjust cursor offset accounting for existing content
1545        let existing_len = message_editor.read(cx).text(cx).len();
1546        let separator = "\n\n";
1547
1548        message_editor.update(cx, |editor, cx| {
1549            editor.append_message(queued_content, Some(separator), window, cx);
1550            if let Some(offset) = cursor_offset {
1551                let adjusted_offset = existing_len + separator.len() + offset;
1552                editor.set_cursor_offset(adjusted_offset, window, cx);
1553            }
1554            if let Some(inserted_text) = inserted_text.as_deref() {
1555                editor.insert_text(inserted_text, window, cx);
1556            }
1557        });
1558
1559        cx.notify();
1560        true
1561    }
1562
1563    // editor methods
1564
1565    pub fn expand_message_editor(
1566        &mut self,
1567        _: &ExpandMessageEditor,
1568        _window: &mut Window,
1569        cx: &mut Context<Self>,
1570    ) {
1571        if self.list_state.item_count() == 0 {
1572            return;
1573        }
1574        self.set_editor_is_expanded(!self.editor_expanded, cx);
1575        cx.stop_propagation();
1576        cx.notify();
1577    }
1578
1579    pub fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
1580        self.editor_expanded = is_expanded;
1581        self.message_editor.update(cx, |editor, cx| {
1582            if is_expanded {
1583                editor.set_mode(
1584                    EditorMode::Full {
1585                        scale_ui_elements_with_buffer_font_size: false,
1586                        show_active_line_background: false,
1587                        sizing_behavior: SizingBehavior::ExcludeOverscrollMargin,
1588                    },
1589                    cx,
1590                )
1591            } else {
1592                let agent_settings = AgentSettings::get_global(cx);
1593                editor.set_mode(
1594                    EditorMode::AutoHeight {
1595                        min_lines: agent_settings.message_editor_min_lines,
1596                        max_lines: Some(agent_settings.set_message_editor_max_lines()),
1597                    },
1598                    cx,
1599                )
1600            }
1601        });
1602        cx.notify();
1603    }
1604
1605    pub fn handle_title_editor_event(
1606        &mut self,
1607        title_editor: &Entity<Editor>,
1608        event: &EditorEvent,
1609        window: &mut Window,
1610        cx: &mut Context<Self>,
1611    ) {
1612        let thread = &self.thread;
1613
1614        match event {
1615            EditorEvent::BufferEdited => {
1616                // We only want to set the title if the user has actively edited
1617                // it. If the title editor is not focused, we programmatically
1618                // changed the text, so we don't want to set the title again.
1619                if !title_editor.read(cx).is_focused(window) {
1620                    return;
1621                }
1622
1623                let new_title = title_editor.read(cx).text(cx);
1624                thread.update(cx, |thread, cx| {
1625                    thread
1626                        .set_title(new_title.into(), cx)
1627                        .detach_and_log_err(cx);
1628                })
1629            }
1630            EditorEvent::Blurred => {
1631                if title_editor.read(cx).text(cx).is_empty() {
1632                    title_editor.update(cx, |editor, cx| {
1633                        editor.set_text(DEFAULT_THREAD_TITLE, window, cx);
1634                    });
1635                }
1636            }
1637            _ => {}
1638        }
1639    }
1640
1641    pub fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1642        if let Some(index) = self.editing_message.take()
1643            && let Some(editor) = &self
1644                .entry_view_state
1645                .read(cx)
1646                .entry(index)
1647                .and_then(|e| e.message_editor())
1648                .cloned()
1649        {
1650            editor.update(cx, |editor, cx| {
1651                if let Some(user_message) = self
1652                    .thread
1653                    .read(cx)
1654                    .entries()
1655                    .get(index)
1656                    .and_then(|e| e.user_message())
1657                {
1658                    editor.set_message(user_message.chunks.clone(), window, cx);
1659                }
1660            })
1661        };
1662        self.message_editor.focus_handle(cx).focus(window, cx);
1663        cx.notify();
1664    }
1665
1666    pub fn authorize_tool_call(
1667        &mut self,
1668        session_id: acp::SessionId,
1669        tool_call_id: acp::ToolCallId,
1670        outcome: SelectedPermissionOutcome,
1671        window: &mut Window,
1672        cx: &mut Context<Self>,
1673    ) {
1674        self.conversation.update(cx, |conversation, cx| {
1675            conversation.authorize_tool_call(session_id, tool_call_id, outcome, cx);
1676        });
1677        if self.should_be_following {
1678            self.workspace
1679                .update(cx, |workspace, cx| {
1680                    workspace.follow(CollaboratorId::Agent, window, cx);
1681                })
1682                .ok();
1683        }
1684        cx.notify();
1685    }
1686
1687    pub fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
1688        self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
1689    }
1690
1691    pub fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
1692        self.authorize_pending_with_granularity(true, window, cx);
1693    }
1694
1695    pub fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
1696        self.authorize_pending_with_granularity(false, window, cx);
1697    }
1698
1699    pub fn authorize_pending_tool_call(
1700        &mut self,
1701        kind: acp::PermissionOptionKind,
1702        window: &mut Window,
1703        cx: &mut Context<Self>,
1704    ) -> Option<()> {
1705        let session_id = self.thread.read(cx).session_id().clone();
1706        self.conversation.update(cx, |conversation, cx| {
1707            conversation.authorize_pending_tool_call(&session_id, kind, cx)
1708        })?;
1709        if self.should_be_following {
1710            self.workspace
1711                .update(cx, |workspace, cx| {
1712                    workspace.follow(CollaboratorId::Agent, window, cx);
1713                })
1714                .ok();
1715        }
1716        cx.notify();
1717        Some(())
1718    }
1719
1720    fn is_waiting_for_confirmation(entry: &AgentThreadEntry) -> bool {
1721        if let AgentThreadEntry::ToolCall(tool_call) = entry {
1722            matches!(
1723                tool_call.status,
1724                ToolCallStatus::WaitingForConfirmation { .. }
1725            )
1726        } else {
1727            false
1728        }
1729    }
1730
1731    fn handle_authorize_tool_call(
1732        &mut self,
1733        action: &AuthorizeToolCall,
1734        window: &mut Window,
1735        cx: &mut Context<Self>,
1736    ) {
1737        let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1738        let option_id = acp::PermissionOptionId::new(action.option_id.clone());
1739        let option_kind = match action.option_kind.as_str() {
1740            "AllowOnce" => acp::PermissionOptionKind::AllowOnce,
1741            "AllowAlways" => acp::PermissionOptionKind::AllowAlways,
1742            "RejectOnce" => acp::PermissionOptionKind::RejectOnce,
1743            "RejectAlways" => acp::PermissionOptionKind::RejectAlways,
1744            _ => acp::PermissionOptionKind::AllowOnce,
1745        };
1746
1747        let session_id = self.thread.read(cx).session_id().clone();
1748        self.authorize_tool_call(
1749            session_id,
1750            tool_call_id,
1751            SelectedPermissionOutcome::new(option_id, option_kind),
1752            window,
1753            cx,
1754        );
1755    }
1756
1757    pub fn handle_select_permission_granularity(
1758        &mut self,
1759        action: &SelectPermissionGranularity,
1760        _window: &mut Window,
1761        cx: &mut Context<Self>,
1762    ) {
1763        let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1764        self.permission_selections
1765            .insert(tool_call_id, PermissionSelection::Choice(action.index));
1766
1767        cx.notify();
1768    }
1769
1770    pub fn handle_toggle_command_pattern(
1771        &mut self,
1772        action: &crate::ToggleCommandPattern,
1773        _window: &mut Window,
1774        cx: &mut Context<Self>,
1775    ) {
1776        let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1777
1778        match self.permission_selections.get_mut(&tool_call_id) {
1779            Some(PermissionSelection::SelectedPatterns(checked)) => {
1780                // Already in pattern mode — toggle the individual pattern.
1781                if let Some(pos) = checked.iter().position(|&i| i == action.pattern_index) {
1782                    checked.swap_remove(pos);
1783                } else {
1784                    checked.push(action.pattern_index);
1785                }
1786            }
1787            _ => {
1788                // First click: activate "Select options" with all patterns checked.
1789                let thread = self.thread.read(cx);
1790                let pattern_count = thread
1791                    .entries()
1792                    .iter()
1793                    .find_map(|entry| {
1794                        if let AgentThreadEntry::ToolCall(call) = entry {
1795                            if call.id == tool_call_id {
1796                                if let ToolCallStatus::WaitingForConfirmation { options, .. } =
1797                                    &call.status
1798                                {
1799                                    if let PermissionOptions::DropdownWithPatterns {
1800                                        patterns,
1801                                        ..
1802                                    } = options
1803                                    {
1804                                        return Some(patterns.len());
1805                                    }
1806                                }
1807                            }
1808                        }
1809                        None
1810                    })
1811                    .unwrap_or(0);
1812                self.permission_selections.insert(
1813                    tool_call_id,
1814                    PermissionSelection::SelectedPatterns((0..pattern_count).collect()),
1815                );
1816            }
1817        }
1818        cx.notify();
1819    }
1820
1821    fn authorize_pending_with_granularity(
1822        &mut self,
1823        is_allow: bool,
1824        window: &mut Window,
1825        cx: &mut Context<Self>,
1826    ) -> Option<()> {
1827        let session_id = self.thread.read(cx).session_id().clone();
1828        let (returned_session_id, tool_call_id, options) = self
1829            .conversation
1830            .read(cx)
1831            .pending_tool_call(&session_id, cx)?;
1832        let options = options.clone();
1833        self.authorize_with_granularity(
1834            returned_session_id,
1835            tool_call_id,
1836            &options,
1837            is_allow,
1838            window,
1839            cx,
1840        )
1841    }
1842
1843    fn authorize_with_granularity(
1844        &mut self,
1845        session_id: acp::SessionId,
1846        tool_call_id: acp::ToolCallId,
1847        options: &PermissionOptions,
1848        is_allow: bool,
1849        window: &mut Window,
1850        cx: &mut Context<Self>,
1851    ) -> Option<()> {
1852        let choices = match options {
1853            PermissionOptions::Dropdown(choices) => choices.as_slice(),
1854            PermissionOptions::DropdownWithPatterns { choices, .. } => choices.as_slice(),
1855            _ => {
1856                let kind = if is_allow {
1857                    acp::PermissionOptionKind::AllowOnce
1858                } else {
1859                    acp::PermissionOptionKind::RejectOnce
1860                };
1861                return self.authorize_pending_tool_call(kind, window, cx);
1862            }
1863        };
1864
1865        let selection = self.permission_selections.get(&tool_call_id);
1866
1867        // When in per-command pattern mode, use the checked patterns.
1868        if let Some(PermissionSelection::SelectedPatterns(checked)) = selection {
1869            if let Some(outcome) = options.build_outcome_for_checked_patterns(checked, is_allow) {
1870                self.authorize_tool_call(session_id, tool_call_id, outcome, window, cx);
1871                return Some(());
1872            }
1873        }
1874
1875        // Use the selected granularity choice ("Always for terminal" or "Only this time")
1876        let selected_index = selection
1877            .and_then(|s| s.choice_index())
1878            .unwrap_or_else(|| choices.len().saturating_sub(1));
1879
1880        let selected_choice = choices.get(selected_index).or(choices.last())?;
1881        let outcome = selected_choice.build_outcome(is_allow);
1882
1883        self.authorize_tool_call(session_id, tool_call_id, outcome, window, cx);
1884
1885        Some(())
1886    }
1887
1888    // edits
1889
1890    pub fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
1891        let thread = &self.thread;
1892        let telemetry = ActionLogTelemetry::from(thread.read(cx));
1893        let action_log = thread.read(cx).action_log().clone();
1894        action_log.update(cx, |action_log, cx| {
1895            action_log.keep_all_edits(Some(telemetry), cx)
1896        });
1897    }
1898
1899    pub fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
1900        let thread = &self.thread;
1901        let telemetry = ActionLogTelemetry::from(thread.read(cx));
1902        let action_log = thread.read(cx).action_log().clone();
1903        let has_changes = action_log.read(cx).changed_buffers(cx).len() > 0;
1904
1905        action_log
1906            .update(cx, |action_log, cx| {
1907                action_log.reject_all_edits(Some(telemetry), cx)
1908            })
1909            .detach();
1910
1911        if has_changes {
1912            if let Some(workspace) = self.workspace.upgrade() {
1913                workspace.update(cx, |workspace, cx| {
1914                    crate::ui::show_undo_reject_toast(workspace, action_log, cx);
1915                });
1916            }
1917        }
1918    }
1919
1920    pub fn undo_last_reject(
1921        &mut self,
1922        _: &UndoLastReject,
1923        _window: &mut Window,
1924        cx: &mut Context<Self>,
1925    ) {
1926        let thread = &self.thread;
1927        let action_log = thread.read(cx).action_log().clone();
1928        action_log
1929            .update(cx, |action_log, cx| action_log.undo_last_reject(cx))
1930            .detach()
1931    }
1932
1933    pub fn open_edited_buffer(
1934        &mut self,
1935        buffer: &Entity<Buffer>,
1936        window: &mut Window,
1937        cx: &mut Context<Self>,
1938    ) {
1939        let thread = &self.thread;
1940
1941        let Some(diff) =
1942            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1943        else {
1944            return;
1945        };
1946
1947        diff.update(cx, |diff, cx| {
1948            diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1949        })
1950    }
1951
1952    // thread stuff
1953
1954    fn share_thread(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1955        let Some((thread, project)) = self.as_native_thread(cx).zip(self.project.upgrade()) else {
1956            return;
1957        };
1958
1959        let client = project.read(cx).client();
1960        let workspace = self.workspace.clone();
1961        let session_id = thread.read(cx).id().to_string();
1962
1963        let load_task = thread.read(cx).to_db(cx);
1964
1965        cx.spawn(async move |_this, cx| {
1966            let db_thread = load_task.await;
1967
1968            let shared_thread = SharedThread::from_db_thread(&db_thread);
1969            let thread_data = shared_thread.to_bytes()?;
1970            let title = shared_thread.title.to_string();
1971
1972            client
1973                .request(proto::ShareAgentThread {
1974                    session_id: session_id.clone(),
1975                    title,
1976                    thread_data,
1977                })
1978                .await?;
1979
1980            let share_url = client::zed_urls::shared_agent_thread_url(&session_id);
1981
1982            cx.update(|cx| {
1983                if let Some(workspace) = workspace.upgrade() {
1984                    workspace.update(cx, |workspace, cx| {
1985                        struct ThreadSharedToast;
1986                        workspace.show_toast(
1987                            Toast::new(
1988                                NotificationId::unique::<ThreadSharedToast>(),
1989                                "Thread shared!",
1990                            )
1991                            .on_click(
1992                                "Copy URL",
1993                                move |_window, cx| {
1994                                    cx.write_to_clipboard(ClipboardItem::new_string(
1995                                        share_url.clone(),
1996                                    ));
1997                                },
1998                            ),
1999                            cx,
2000                        );
2001                    });
2002                }
2003            });
2004
2005            anyhow::Ok(())
2006        })
2007        .detach_and_log_err(cx);
2008    }
2009
2010    pub fn sync_thread(
2011        &mut self,
2012        project: Entity<Project>,
2013        server_view: Entity<ConversationView>,
2014        window: &mut Window,
2015        cx: &mut Context<Self>,
2016    ) {
2017        if !self.is_imported_thread(cx) {
2018            return;
2019        }
2020
2021        let Some(session_list) = self
2022            .as_native_connection(cx)
2023            .and_then(|connection| connection.session_list(cx))
2024            .and_then(|list| list.downcast::<NativeAgentSessionList>())
2025        else {
2026            return;
2027        };
2028        let thread_store = session_list.thread_store().clone();
2029
2030        let client = project.read(cx).client();
2031        let session_id = self.thread.read(cx).session_id().clone();
2032        cx.spawn_in(window, async move |this, cx| {
2033            let response = client
2034                .request(proto::GetSharedAgentThread {
2035                    session_id: session_id.to_string(),
2036                })
2037                .await?;
2038
2039            let shared_thread = SharedThread::from_bytes(&response.thread_data)?;
2040
2041            let db_thread = shared_thread.to_db_thread();
2042
2043            thread_store
2044                .update(&mut cx.clone(), |store, cx| {
2045                    store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
2046                })
2047                .await?;
2048
2049            server_view.update_in(cx, |server_view, window, cx| server_view.reset(window, cx))?;
2050
2051            this.update_in(cx, |this, _window, cx| {
2052                if let Some(workspace) = this.workspace.upgrade() {
2053                    workspace.update(cx, |workspace, cx| {
2054                        struct ThreadSyncedToast;
2055                        workspace.show_toast(
2056                            Toast::new(
2057                                NotificationId::unique::<ThreadSyncedToast>(),
2058                                "Thread synced with latest version",
2059                            )
2060                            .autohide(),
2061                            cx,
2062                        );
2063                    });
2064                }
2065            })?;
2066
2067            anyhow::Ok(())
2068        })
2069        .detach_and_log_err(cx);
2070    }
2071
2072    pub fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
2073        self.thread
2074            .update(cx, |thread, cx| {
2075                thread.restore_checkpoint(message_id.clone(), cx)
2076            })
2077            .detach_and_log_err(cx);
2078    }
2079
2080    pub fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
2081        self.thread_error = None;
2082        self.thread_error_markdown = None;
2083        self.token_limit_callout_dismissed = true;
2084        cx.notify();
2085    }
2086
2087    fn is_following(&self, cx: &App) -> bool {
2088        match self.thread.read(cx).status() {
2089            ThreadStatus::Generating => self
2090                .workspace
2091                .read_with(cx, |workspace, _| {
2092                    workspace.is_being_followed(CollaboratorId::Agent)
2093                })
2094                .unwrap_or(false),
2095            _ => self.should_be_following,
2096        }
2097    }
2098
2099    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2100        let following = self.is_following(cx);
2101
2102        self.should_be_following = !following;
2103        if self.thread.read(cx).status() == ThreadStatus::Generating {
2104            self.workspace
2105                .update(cx, |workspace, cx| {
2106                    if following {
2107                        workspace.unfollow(CollaboratorId::Agent, window, cx);
2108                    } else {
2109                        workspace.follow(CollaboratorId::Agent, window, cx);
2110                    }
2111                })
2112                .ok();
2113        }
2114
2115        telemetry::event!("Follow Agent Selected", following = !following);
2116    }
2117
2118    // other
2119
2120    pub fn render_thread_retry_status_callout(&self) -> Option<Callout> {
2121        let state = self.thread_retry_status.as_ref()?;
2122
2123        let next_attempt_in = state
2124            .duration
2125            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
2126        if next_attempt_in.is_zero() {
2127            return None;
2128        }
2129
2130        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
2131
2132        let retry_message = if state.max_attempts == 1 {
2133            if next_attempt_in_secs == 1 {
2134                "Retrying. Next attempt in 1 second.".to_string()
2135            } else {
2136                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
2137            }
2138        } else if next_attempt_in_secs == 1 {
2139            format!(
2140                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
2141                state.attempt, state.max_attempts,
2142            )
2143        } else {
2144            format!(
2145                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
2146                state.attempt, state.max_attempts,
2147            )
2148        };
2149
2150        Some(
2151            Callout::new()
2152                .icon(IconName::Warning)
2153                .severity(Severity::Warning)
2154                .title(state.last_error.clone())
2155                .description(retry_message),
2156        )
2157    }
2158
2159    pub fn handle_open_rules(
2160        &mut self,
2161        _: &ClickEvent,
2162        window: &mut Window,
2163        cx: &mut Context<Self>,
2164    ) {
2165        let Some(thread) = self.as_native_thread(cx) else {
2166            return;
2167        };
2168        let project_context = thread.read(cx).project_context().read(cx);
2169
2170        let project_entry_ids = project_context
2171            .worktrees
2172            .iter()
2173            .flat_map(|worktree| worktree.rules_file.as_ref())
2174            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
2175            .collect::<Vec<_>>();
2176
2177        self.workspace
2178            .update(cx, move |workspace, cx| {
2179                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
2180                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
2181                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
2182                let project = workspace.project().read(cx);
2183                let project_paths = project_entry_ids
2184                    .into_iter()
2185                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
2186                    .collect::<Vec<_>>();
2187                for project_path in project_paths {
2188                    workspace
2189                        .open_path(project_path, None, true, window, cx)
2190                        .detach_and_log_err(cx);
2191                }
2192            })
2193            .ok();
2194    }
2195
2196    fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
2197        let editor_bg_color = cx.theme().colors().editor_background;
2198        let active_color = cx.theme().colors().element_selected;
2199        editor_bg_color.blend(active_color.opacity(0.3))
2200    }
2201
2202    pub fn render_activity_bar(
2203        &self,
2204        window: &mut Window,
2205        cx: &Context<Self>,
2206    ) -> Option<AnyElement> {
2207        let thread = self.thread.read(cx);
2208        let action_log = thread.action_log();
2209        let telemetry = ActionLogTelemetry::from(thread);
2210        let changed_buffers = action_log.read(cx).changed_buffers(cx);
2211        let plan = thread.plan();
2212        let queue_is_empty = !self.has_queued_messages();
2213
2214        let subagents_awaiting_permission = self.render_subagents_awaiting_permission(cx);
2215        let has_subagents_awaiting = subagents_awaiting_permission.is_some();
2216
2217        if changed_buffers.is_empty()
2218            && plan.is_empty()
2219            && queue_is_empty
2220            && !has_subagents_awaiting
2221        {
2222            return None;
2223        }
2224
2225        // Temporarily always enable ACP edit controls. This is temporary, to lessen the
2226        // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
2227        // be, which blocks you from being able to accept or reject edits. This switches the
2228        // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
2229        // block you from using the panel.
2230        let pending_edits = false;
2231
2232        let plan_expanded = self.plan_expanded;
2233        let edits_expanded = self.edits_expanded;
2234        let queue_expanded = self.queue_expanded;
2235
2236        let max_content_width = AgentSettings::get_global(cx).max_content_width;
2237
2238        h_flex()
2239            .w_full()
2240            .justify_center()
2241            .child(
2242                v_flex()
2243                    .flex_basis(max_content_width)
2244                    .flex_shrink()
2245                    .flex_grow_0()
2246                    .mx_2()
2247                    .bg(self.activity_bar_bg(cx))
2248                    .border_1()
2249                    .border_b_0()
2250                    .border_color(cx.theme().colors().border)
2251                    .rounded_t_md()
2252                    .shadow(vec![gpui::BoxShadow {
2253                        color: gpui::black().opacity(0.12),
2254                        offset: point(px(1.), px(-1.)),
2255                        blur_radius: px(2.),
2256                        spread_radius: px(0.),
2257                    }])
2258                    .when_some(subagents_awaiting_permission, |this, element| {
2259                        this.child(element)
2260                    })
2261                    .when(
2262                        has_subagents_awaiting
2263                            && (!plan.is_empty() || !changed_buffers.is_empty() || !queue_is_empty),
2264                        |this| this.child(Divider::horizontal().color(DividerColor::Border)),
2265                    )
2266                    .when(!plan.is_empty(), |this| {
2267                        this.child(self.render_plan_summary(plan, window, cx))
2268                            .when(plan_expanded, |parent| {
2269                                parent.child(self.render_plan_entries(plan, window, cx))
2270                            })
2271                    })
2272                    .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2273                        this.child(Divider::horizontal().color(DividerColor::Border))
2274                    })
2275                    .when(
2276                        !changed_buffers.is_empty() && thread.parent_session_id().is_none(),
2277                        |this| {
2278                            this.child(self.render_edits_summary(
2279                                &changed_buffers,
2280                                edits_expanded,
2281                                pending_edits,
2282                                cx,
2283                            ))
2284                            .when(edits_expanded, |parent| {
2285                                parent.child(self.render_edited_files(
2286                                    action_log,
2287                                    telemetry.clone(),
2288                                    &changed_buffers,
2289                                    pending_edits,
2290                                    cx,
2291                                ))
2292                            })
2293                        },
2294                    )
2295                    .when(!queue_is_empty, |this| {
2296                        this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
2297                            this.child(Divider::horizontal().color(DividerColor::Border))
2298                        })
2299                        .child(self.render_message_queue_summary(window, cx))
2300                        .when(queue_expanded, |parent| {
2301                            parent.child(self.render_message_queue_entries(window, cx))
2302                        })
2303                    }),
2304            )
2305            .into_any()
2306            .into()
2307    }
2308
2309    fn render_edited_files(
2310        &self,
2311        action_log: &Entity<ActionLog>,
2312        telemetry: ActionLogTelemetry,
2313        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2314        pending_edits: bool,
2315        cx: &Context<Self>,
2316    ) -> impl IntoElement {
2317        let editor_bg_color = cx.theme().colors().editor_background;
2318
2319        // Sort edited files alphabetically for consistency with Git diff view
2320        let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
2321        sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
2322            let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
2323            let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
2324            path_a.cmp(&path_b)
2325        });
2326
2327        v_flex()
2328            .id("edited_files_list")
2329            .max_h_40()
2330            .overflow_y_scroll()
2331            .children(
2332                sorted_buffers
2333                    .into_iter()
2334                    .enumerate()
2335                    .flat_map(|(index, (buffer, diff))| {
2336                        let file = buffer.read(cx).file()?;
2337                        let path = file.path();
2338                        let path_style = file.path_style(cx);
2339                        let separator = file.path_style(cx).primary_separator();
2340
2341                        let file_path = path.parent().and_then(|parent| {
2342                            if parent.is_empty() {
2343                                None
2344                            } else {
2345                                Some(
2346                                    Label::new(format!(
2347                                        "{}{separator}",
2348                                        parent.display(path_style)
2349                                    ))
2350                                    .color(Color::Muted)
2351                                    .size(LabelSize::XSmall)
2352                                    .buffer_font(cx),
2353                                )
2354                            }
2355                        });
2356
2357                        let file_name = path.file_name().map(|name| {
2358                            Label::new(name.to_string())
2359                                .size(LabelSize::XSmall)
2360                                .buffer_font(cx)
2361                                .ml_1()
2362                        });
2363
2364                        let full_path = path.display(path_style).to_string();
2365
2366                        let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
2367                            .map(Icon::from_path)
2368                            .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2369                            .unwrap_or_else(|| {
2370                                Icon::new(IconName::File)
2371                                    .color(Color::Muted)
2372                                    .size(IconSize::Small)
2373                            });
2374
2375                        let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
2376
2377                        let buttons = self.render_edited_files_buttons(
2378                            index,
2379                            buffer,
2380                            action_log,
2381                            &telemetry,
2382                            pending_edits,
2383                            editor_bg_color,
2384                            cx,
2385                        );
2386
2387                        let element = h_flex()
2388                            .group("edited-code")
2389                            .id(("file-container", index))
2390                            .relative()
2391                            .min_w_0()
2392                            .p_1p5()
2393                            .gap_2()
2394                            .justify_between()
2395                            .bg(editor_bg_color)
2396                            .when(index < changed_buffers.len() - 1, |parent| {
2397                                parent.border_color(cx.theme().colors().border).border_b_1()
2398                            })
2399                            .child(
2400                                h_flex()
2401                                    .id(("file-name-path", index))
2402                                    .cursor_pointer()
2403                                    .pr_0p5()
2404                                    .gap_0p5()
2405                                    .rounded_xs()
2406                                    .child(file_icon)
2407                                    .children(file_name)
2408                                    .children(file_path)
2409                                    .child(
2410                                        DiffStat::new(
2411                                            "file",
2412                                            file_stats.lines_added as usize,
2413                                            file_stats.lines_removed as usize,
2414                                        )
2415                                        .label_size(LabelSize::XSmall),
2416                                    )
2417                                    .hover(|s| s.bg(cx.theme().colors().element_hover))
2418                                    .tooltip({
2419                                        move |_, cx| {
2420                                            Tooltip::with_meta(
2421                                                "Go to File",
2422                                                None,
2423                                                full_path.clone(),
2424                                                cx,
2425                                            )
2426                                        }
2427                                    })
2428                                    .on_click({
2429                                        let buffer = buffer.clone();
2430                                        cx.listener(move |this, _, window, cx| {
2431                                            this.open_edited_buffer(&buffer, window, cx);
2432                                        })
2433                                    }),
2434                            )
2435                            .child(buttons);
2436
2437                        Some(element)
2438                    }),
2439            )
2440            .into_any_element()
2441    }
2442
2443    fn render_edited_files_buttons(
2444        &self,
2445        index: usize,
2446        buffer: &Entity<Buffer>,
2447        action_log: &Entity<ActionLog>,
2448        telemetry: &ActionLogTelemetry,
2449        pending_edits: bool,
2450        editor_bg_color: Hsla,
2451        cx: &Context<Self>,
2452    ) -> impl IntoElement {
2453        h_flex()
2454            .id("edited-buttons-container")
2455            .visible_on_hover("edited-code")
2456            .absolute()
2457            .right_0()
2458            .px_1()
2459            .gap_1()
2460            .bg(editor_bg_color)
2461            .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
2462                if *is_hovered {
2463                    this.hovered_edited_file_buttons = Some(index);
2464                } else if this.hovered_edited_file_buttons == Some(index) {
2465                    this.hovered_edited_file_buttons = None;
2466                }
2467                cx.notify();
2468            }))
2469            .child(
2470                Button::new("review", "Review")
2471                    .label_size(LabelSize::Small)
2472                    .on_click({
2473                        let buffer = buffer.clone();
2474                        cx.listener(move |this, _, window, cx| {
2475                            this.open_edited_buffer(&buffer, window, cx);
2476                        })
2477                    }),
2478            )
2479            .child(
2480                Button::new(("reject-file", index), "Reject")
2481                    .label_size(LabelSize::Small)
2482                    .disabled(pending_edits)
2483                    .on_click({
2484                        let buffer = buffer.clone();
2485                        let action_log = action_log.clone();
2486                        let telemetry = telemetry.clone();
2487                        move |_, _, cx| {
2488                            action_log.update(cx, |action_log, cx| {
2489                                action_log
2490                                    .reject_edits_in_ranges(
2491                                        buffer.clone(),
2492                                        vec![Anchor::min_max_range_for_buffer(
2493                                            buffer.read(cx).remote_id(),
2494                                        )],
2495                                        Some(telemetry.clone()),
2496                                        cx,
2497                                    )
2498                                    .0
2499                                    .detach_and_log_err(cx);
2500                            })
2501                        }
2502                    }),
2503            )
2504            .child(
2505                Button::new(("keep-file", index), "Keep")
2506                    .label_size(LabelSize::Small)
2507                    .disabled(pending_edits)
2508                    .on_click({
2509                        let buffer = buffer.clone();
2510                        let action_log = action_log.clone();
2511                        let telemetry = telemetry.clone();
2512                        move |_, _, cx| {
2513                            action_log.update(cx, |action_log, cx| {
2514                                action_log.keep_edits_in_range(
2515                                    buffer.clone(),
2516                                    Anchor::min_max_range_for_buffer(buffer.read(cx).remote_id()),
2517                                    Some(telemetry.clone()),
2518                                    cx,
2519                                );
2520                            })
2521                        }
2522                    }),
2523            )
2524    }
2525
2526    fn collect_subagent_items_for_sessions(
2527        entries: &[AgentThreadEntry],
2528        awaiting_session_ids: &[acp::SessionId],
2529        cx: &App,
2530    ) -> Vec<(SharedString, usize)> {
2531        let tool_calls_by_session: HashMap<_, _> = entries
2532            .iter()
2533            .enumerate()
2534            .filter_map(|(entry_ix, entry)| {
2535                let AgentThreadEntry::ToolCall(tool_call) = entry else {
2536                    return None;
2537                };
2538                let info = tool_call.subagent_session_info.as_ref()?;
2539                let summary_text = tool_call.label.read(cx).source().to_string();
2540                let subagent_summary = if summary_text.is_empty() {
2541                    SharedString::from("Subagent")
2542                } else {
2543                    SharedString::from(summary_text)
2544                };
2545                Some((info.session_id.clone(), (subagent_summary, entry_ix)))
2546            })
2547            .collect();
2548
2549        awaiting_session_ids
2550            .iter()
2551            .filter_map(|session_id| tool_calls_by_session.get(session_id).cloned())
2552            .collect()
2553    }
2554
2555    fn render_subagents_awaiting_permission(&self, cx: &Context<Self>) -> Option<AnyElement> {
2556        let awaiting = self.conversation.read(cx).subagents_awaiting_permission(cx);
2557
2558        if awaiting.is_empty() {
2559            return None;
2560        }
2561
2562        let awaiting_session_ids: Vec<_> = awaiting
2563            .iter()
2564            .map(|(session_id, _)| session_id.clone())
2565            .collect();
2566
2567        let thread = self.thread.read(cx);
2568        let entries = thread.entries();
2569        let subagent_items =
2570            Self::collect_subagent_items_for_sessions(entries, &awaiting_session_ids, cx);
2571
2572        if subagent_items.is_empty() {
2573            return None;
2574        }
2575
2576        let item_count = subagent_items.len();
2577
2578        Some(
2579            v_flex()
2580                .child(
2581                    h_flex()
2582                        .py_1()
2583                        .px_2()
2584                        .w_full()
2585                        .gap_1()
2586                        .border_b_1()
2587                        .border_color(cx.theme().colors().border)
2588                        .child(
2589                            Label::new("Subagents Awaiting Permission:")
2590                                .size(LabelSize::Small)
2591                                .color(Color::Muted),
2592                        )
2593                        .child(Label::new(item_count.to_string()).size(LabelSize::Small)),
2594                )
2595                .child(
2596                    v_flex().children(subagent_items.into_iter().enumerate().map(
2597                        |(ix, (label, entry_ix))| {
2598                            let is_last = ix == item_count - 1;
2599                            let group = format!("group-{}", entry_ix);
2600
2601                            h_flex()
2602                                .cursor_pointer()
2603                                .id(format!("subagent-permission-{}", entry_ix))
2604                                .group(&group)
2605                                .p_1()
2606                                .pl_2()
2607                                .min_w_0()
2608                                .w_full()
2609                                .gap_1()
2610                                .justify_between()
2611                                .bg(cx.theme().colors().editor_background)
2612                                .hover(|s| s.bg(cx.theme().colors().element_hover))
2613                                .when(!is_last, |this| {
2614                                    this.border_b_1().border_color(cx.theme().colors().border)
2615                                })
2616                                .child(
2617                                    h_flex()
2618                                        .gap_1p5()
2619                                        .child(
2620                                            Icon::new(IconName::Circle)
2621                                                .size(IconSize::XSmall)
2622                                                .color(Color::Warning),
2623                                        )
2624                                        .child(
2625                                            Label::new(label)
2626                                                .size(LabelSize::Small)
2627                                                .color(Color::Muted)
2628                                                .truncate(),
2629                                        ),
2630                                )
2631                                .child(
2632                                    div().visible_on_hover(&group).child(
2633                                        Label::new("Scroll to Subagent")
2634                                            .size(LabelSize::Small)
2635                                            .color(Color::Muted)
2636                                            .truncate(),
2637                                    ),
2638                                )
2639                                .on_click(cx.listener(move |this, _, _, cx| {
2640                                    this.list_state.scroll_to(ListOffset {
2641                                        item_ix: entry_ix,
2642                                        offset_in_item: px(0.0),
2643                                    });
2644                                    cx.notify();
2645                                }))
2646                        },
2647                    )),
2648                )
2649                .into_any(),
2650        )
2651    }
2652
2653    fn render_message_queue_summary(
2654        &self,
2655        _window: &mut Window,
2656        cx: &Context<Self>,
2657    ) -> impl IntoElement {
2658        let queue_count = self.local_queued_messages.len();
2659        let title: SharedString = if queue_count == 1 {
2660            "1 Queued Message".into()
2661        } else {
2662            format!("{} Queued Messages", queue_count).into()
2663        };
2664
2665        h_flex()
2666            .p_1()
2667            .w_full()
2668            .gap_1()
2669            .justify_between()
2670            .when(self.queue_expanded, |this| {
2671                this.border_b_1().border_color(cx.theme().colors().border)
2672            })
2673            .child(
2674                h_flex()
2675                    .id("queue_summary")
2676                    .gap_1()
2677                    .child(Disclosure::new("queue_disclosure", self.queue_expanded))
2678                    .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
2679                    .on_click(cx.listener(|this, _, _, cx| {
2680                        this.queue_expanded = !this.queue_expanded;
2681                        cx.notify();
2682                    })),
2683            )
2684            .child(
2685                Button::new("clear_queue", "Clear All")
2686                    .label_size(LabelSize::Small)
2687                    .key_binding(
2688                        KeyBinding::for_action(&ClearMessageQueue, cx)
2689                            .map(|kb| kb.size(rems_from_px(12.))),
2690                    )
2691                    .on_click(cx.listener(|this, _, _, cx| {
2692                        this.clear_queue(cx);
2693                        this.can_fast_track_queue = false;
2694                        cx.notify();
2695                    })),
2696            )
2697            .into_any_element()
2698    }
2699
2700    fn clear_queue(&mut self, cx: &mut Context<Self>) {
2701        self.local_queued_messages.clear();
2702        self.sync_queue_flag_to_native_thread(cx);
2703    }
2704
2705    fn render_plan_summary(
2706        &self,
2707        plan: &Plan,
2708        window: &mut Window,
2709        cx: &Context<Self>,
2710    ) -> impl IntoElement {
2711        let plan_expanded = self.plan_expanded;
2712        let stats = plan.stats();
2713
2714        let title = if let Some(entry) = stats.in_progress_entry
2715            && !plan_expanded
2716        {
2717            h_flex()
2718                .cursor_default()
2719                .relative()
2720                .w_full()
2721                .gap_1()
2722                .truncate()
2723                .child(
2724                    Label::new("Current:")
2725                        .size(LabelSize::Small)
2726                        .color(Color::Muted),
2727                )
2728                .child(
2729                    div()
2730                        .text_xs()
2731                        .text_color(cx.theme().colors().text_muted)
2732                        .line_clamp(1)
2733                        .child(MarkdownElement::new(
2734                            entry.content.clone(),
2735                            plan_label_markdown_style(&entry.status, window, cx),
2736                        )),
2737                )
2738                .when(stats.pending > 0, |this| {
2739                    this.child(
2740                        h_flex()
2741                            .absolute()
2742                            .top_0()
2743                            .right_0()
2744                            .h_full()
2745                            .child(div().min_w_8().h_full().bg(linear_gradient(
2746                                90.,
2747                                linear_color_stop(self.activity_bar_bg(cx), 1.),
2748                                linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
2749                            )))
2750                            .child(
2751                                div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
2752                                    Label::new(format!("{} left", stats.pending))
2753                                        .size(LabelSize::Small)
2754                                        .color(Color::Muted),
2755                                ),
2756                            ),
2757                    )
2758                })
2759        } else {
2760            let status_label = if stats.pending == 0 {
2761                "All Done".to_string()
2762            } else if stats.completed == 0 {
2763                format!("{} Tasks", plan.entries.len())
2764            } else {
2765                format!("{}/{}", stats.completed, plan.entries.len())
2766            };
2767
2768            h_flex()
2769                .w_full()
2770                .gap_1()
2771                .justify_between()
2772                .child(
2773                    Label::new("Plan")
2774                        .size(LabelSize::Small)
2775                        .color(Color::Muted),
2776                )
2777                .child(
2778                    Label::new(status_label)
2779                        .size(LabelSize::Small)
2780                        .color(Color::Muted)
2781                        .mr_1(),
2782                )
2783        };
2784
2785        h_flex()
2786            .id("plan_summary")
2787            .p_1()
2788            .w_full()
2789            .gap_1()
2790            .when(plan_expanded, |this| {
2791                this.border_b_1().border_color(cx.theme().colors().border)
2792            })
2793            .child(Disclosure::new("plan_disclosure", plan_expanded))
2794            .child(title.flex_1())
2795            .child(
2796                IconButton::new("dismiss-plan", IconName::Close)
2797                    .icon_size(IconSize::XSmall)
2798                    .shape(ui::IconButtonShape::Square)
2799                    .tooltip(Tooltip::text("Clear plan"))
2800                    .on_click(cx.listener(|this, _, _, cx| {
2801                        this.thread.update(cx, |thread, cx| thread.clear_plan(cx));
2802                        cx.stop_propagation();
2803                    })),
2804            )
2805            .on_click(cx.listener(|this, _, _, cx| {
2806                this.plan_expanded = !this.plan_expanded;
2807                cx.notify();
2808            }))
2809            .into_any_element()
2810    }
2811
2812    fn render_plan_entries(
2813        &self,
2814        plan: &Plan,
2815        window: &mut Window,
2816        cx: &Context<Self>,
2817    ) -> impl IntoElement {
2818        v_flex()
2819            .id("plan_items_list")
2820            .max_h_40()
2821            .overflow_y_scroll()
2822            .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2823                let element = h_flex()
2824                    .py_1()
2825                    .px_2()
2826                    .gap_2()
2827                    .justify_between()
2828                    .bg(cx.theme().colors().editor_background)
2829                    .when(index < plan.entries.len() - 1, |parent| {
2830                        parent.border_color(cx.theme().colors().border).border_b_1()
2831                    })
2832                    .child(
2833                        h_flex()
2834                            .id(("plan_entry", index))
2835                            .gap_1p5()
2836                            .max_w_full()
2837                            .overflow_x_scroll()
2838                            .text_xs()
2839                            .text_color(cx.theme().colors().text_muted)
2840                            .child(match entry.status {
2841                                acp::PlanEntryStatus::InProgress => {
2842                                    Icon::new(IconName::TodoProgress)
2843                                        .size(IconSize::Small)
2844                                        .color(Color::Accent)
2845                                        .with_rotate_animation(2)
2846                                        .into_any_element()
2847                                }
2848                                acp::PlanEntryStatus::Completed => {
2849                                    Icon::new(IconName::TodoComplete)
2850                                        .size(IconSize::Small)
2851                                        .color(Color::Success)
2852                                        .into_any_element()
2853                                }
2854                                acp::PlanEntryStatus::Pending | _ => {
2855                                    Icon::new(IconName::TodoPending)
2856                                        .size(IconSize::Small)
2857                                        .color(Color::Muted)
2858                                        .into_any_element()
2859                                }
2860                            })
2861                            .child(MarkdownElement::new(
2862                                entry.content.clone(),
2863                                plan_label_markdown_style(&entry.status, window, cx),
2864                            )),
2865                    );
2866
2867                Some(element)
2868            }))
2869            .into_any_element()
2870    }
2871
2872    fn render_completed_plan(
2873        &self,
2874        entries: &[PlanEntry],
2875        window: &Window,
2876        cx: &Context<Self>,
2877    ) -> AnyElement {
2878        v_flex()
2879            .px_5()
2880            .py_1p5()
2881            .w_full()
2882            .child(
2883                v_flex()
2884                    .w_full()
2885                    .rounded_md()
2886                    .border_1()
2887                    .border_color(self.tool_card_border_color(cx))
2888                    .child(
2889                        h_flex()
2890                            .px_2()
2891                            .py_1()
2892                            .gap_1()
2893                            .bg(self.tool_card_header_bg(cx))
2894                            .border_b_1()
2895                            .border_color(self.tool_card_border_color(cx))
2896                            .child(
2897                                Label::new("Completed Plan")
2898                                    .size(LabelSize::Small)
2899                                    .color(Color::Muted),
2900                            )
2901                            .child(
2902                                Label::new(format!(
2903                                    "{} {}",
2904                                    entries.len(),
2905                                    if entries.len() == 1 { "step" } else { "steps" }
2906                                ))
2907                                .size(LabelSize::Small)
2908                                .color(Color::Muted),
2909                            ),
2910                    )
2911                    .child(
2912                        v_flex().children(entries.iter().enumerate().map(|(index, entry)| {
2913                            h_flex()
2914                                .py_1()
2915                                .px_2()
2916                                .gap_1p5()
2917                                .when(index < entries.len() - 1, |this| {
2918                                    this.border_b_1().border_color(cx.theme().colors().border)
2919                                })
2920                                .child(
2921                                    Icon::new(IconName::TodoComplete)
2922                                        .size(IconSize::Small)
2923                                        .color(Color::Success),
2924                                )
2925                                .child(
2926                                    div()
2927                                        .max_w_full()
2928                                        .overflow_x_hidden()
2929                                        .text_xs()
2930                                        .text_color(cx.theme().colors().text_muted)
2931                                        .child(MarkdownElement::new(
2932                                            entry.content.clone(),
2933                                            default_markdown_style(window, cx),
2934                                        )),
2935                                )
2936                        })),
2937                    ),
2938            )
2939            .into_any()
2940    }
2941
2942    fn render_edits_summary(
2943        &self,
2944        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2945        expanded: bool,
2946        pending_edits: bool,
2947        cx: &Context<Self>,
2948    ) -> Div {
2949        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2950
2951        let focus_handle = self.focus_handle(cx);
2952
2953        h_flex()
2954            .p_1()
2955            .justify_between()
2956            .flex_wrap()
2957            .when(expanded, |this| {
2958                this.border_b_1().border_color(cx.theme().colors().border)
2959            })
2960            .child(
2961                h_flex()
2962                    .id("edits-container")
2963                    .cursor_pointer()
2964                    .gap_1()
2965                    .child(Disclosure::new("edits-disclosure", expanded))
2966                    .map(|this| {
2967                        if pending_edits {
2968                            this.child(
2969                                Label::new(format!(
2970                                    "Editing {} {}",
2971                                    changed_buffers.len(),
2972                                    if changed_buffers.len() == 1 {
2973                                        "file"
2974                                    } else {
2975                                        "files"
2976                                    }
2977                                ))
2978                                .color(Color::Muted)
2979                                .size(LabelSize::Small)
2980                                .with_animation(
2981                                    "edit-label",
2982                                    Animation::new(Duration::from_secs(2))
2983                                        .repeat()
2984                                        .with_easing(pulsating_between(0.3, 0.7)),
2985                                    |label, delta| label.alpha(delta),
2986                                ),
2987                            )
2988                        } else {
2989                            let stats = DiffStats::all_files(changed_buffers, cx);
2990                            let dot_divider = || {
2991                                Label::new("")
2992                                    .size(LabelSize::XSmall)
2993                                    .color(Color::Disabled)
2994                            };
2995
2996                            this.child(
2997                                Label::new("Edits")
2998                                    .size(LabelSize::Small)
2999                                    .color(Color::Muted),
3000                            )
3001                            .child(dot_divider())
3002                            .child(
3003                                Label::new(format!(
3004                                    "{} {}",
3005                                    changed_buffers.len(),
3006                                    if changed_buffers.len() == 1 {
3007                                        "file"
3008                                    } else {
3009                                        "files"
3010                                    }
3011                                ))
3012                                .size(LabelSize::Small)
3013                                .color(Color::Muted),
3014                            )
3015                            .child(dot_divider())
3016                            .child(DiffStat::new(
3017                                "total",
3018                                stats.lines_added as usize,
3019                                stats.lines_removed as usize,
3020                            ))
3021                        }
3022                    })
3023                    .on_click(cx.listener(|this, _, _, cx| {
3024                        this.edits_expanded = !this.edits_expanded;
3025                        cx.notify();
3026                    })),
3027            )
3028            .child(
3029                h_flex()
3030                    .gap_1()
3031                    .child(
3032                        IconButton::new("review-changes", IconName::ListTodo)
3033                            .icon_size(IconSize::Small)
3034                            .tooltip({
3035                                let focus_handle = focus_handle.clone();
3036                                move |_window, cx| {
3037                                    Tooltip::for_action_in(
3038                                        "Review Changes",
3039                                        &OpenAgentDiff,
3040                                        &focus_handle,
3041                                        cx,
3042                                    )
3043                                }
3044                            })
3045                            .on_click(cx.listener(|_, _, window, cx| {
3046                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3047                            })),
3048                    )
3049                    .child(Divider::vertical().color(DividerColor::Border))
3050                    .child(
3051                        Button::new("reject-all-changes", "Reject All")
3052                            .label_size(LabelSize::Small)
3053                            .disabled(pending_edits)
3054                            .when(pending_edits, |this| {
3055                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3056                            })
3057                            .key_binding(
3058                                KeyBinding::for_action_in(&RejectAll, &focus_handle.clone(), cx)
3059                                    .map(|kb| kb.size(rems_from_px(12.))),
3060                            )
3061                            .on_click(cx.listener(move |this, _, window, cx| {
3062                                this.reject_all(&RejectAll, window, cx);
3063                            })),
3064                    )
3065                    .child(
3066                        Button::new("keep-all-changes", "Keep All")
3067                            .label_size(LabelSize::Small)
3068                            .disabled(pending_edits)
3069                            .when(pending_edits, |this| {
3070                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3071                            })
3072                            .key_binding(
3073                                KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
3074                                    .map(|kb| kb.size(rems_from_px(12.))),
3075                            )
3076                            .on_click(cx.listener(move |this, _, window, cx| {
3077                                this.keep_all(&KeepAll, window, cx);
3078                            })),
3079                    ),
3080            )
3081    }
3082
3083    fn is_subagent_canceled_or_failed(&self, cx: &App) -> bool {
3084        let Some(parent_session_id) = self.parent_session_id.as_ref() else {
3085            return false;
3086        };
3087
3088        let my_session_id = self.thread.read(cx).session_id().clone();
3089
3090        self.server_view
3091            .upgrade()
3092            .and_then(|sv| sv.read(cx).thread_view(parent_session_id, cx))
3093            .is_some_and(|parent_view| {
3094                parent_view
3095                    .read(cx)
3096                    .thread
3097                    .read(cx)
3098                    .tool_call_for_subagent(&my_session_id)
3099                    .is_some_and(|tc| {
3100                        matches!(
3101                            tc.status,
3102                            ToolCallStatus::Canceled
3103                                | ToolCallStatus::Failed
3104                                | ToolCallStatus::Rejected
3105                        )
3106                    })
3107            })
3108    }
3109
3110    pub(crate) fn render_subagent_titlebar(&mut self, cx: &mut Context<Self>) -> Option<Div> {
3111        if self.parent_session_id.is_none() {
3112            return None;
3113        }
3114        let parent_session_id = self.thread.read(cx).parent_session_id()?.clone();
3115
3116        let server_view = self.server_view.clone();
3117        let thread = self.thread.clone();
3118        let is_done = thread.read(cx).status() == ThreadStatus::Idle;
3119        let is_canceled_or_failed = self.is_subagent_canceled_or_failed(cx);
3120
3121        let max_content_width = AgentSettings::get_global(cx).max_content_width;
3122
3123        Some(
3124            h_flex()
3125                .w_full()
3126                .h(Tab::container_height(cx))
3127                .border_b_1()
3128                .when(is_done && is_canceled_or_failed, |this| {
3129                    this.border_dashed()
3130                })
3131                .border_color(cx.theme().colors().border)
3132                .bg(cx.theme().colors().editor_background.opacity(0.2))
3133                .child(
3134                    h_flex()
3135                        .size_full()
3136                        .max_w(max_content_width)
3137                        .mx_auto()
3138                        .pl_2()
3139                        .pr_1()
3140                        .flex_shrink_0()
3141                        .justify_between()
3142                        .gap_1()
3143                        .child(
3144                            h_flex()
3145                                .flex_1()
3146                                .gap_2()
3147                                .child(
3148                                    Icon::new(IconName::ForwardArrowUp)
3149                                        .size(IconSize::Small)
3150                                        .color(Color::Muted),
3151                                )
3152                                .child(self.title_editor.clone())
3153                                .when(is_done && is_canceled_or_failed, |this| {
3154                                    this.child(Icon::new(IconName::Close).color(Color::Error))
3155                                })
3156                                .when(is_done && !is_canceled_or_failed, |this| {
3157                                    this.child(Icon::new(IconName::Check).color(Color::Success))
3158                                }),
3159                        )
3160                        .child(
3161                            h_flex()
3162                                .gap_0p5()
3163                                .when(!is_done, |this| {
3164                                    this.child(
3165                                        IconButton::new("stop_subagent", IconName::Stop)
3166                                            .icon_size(IconSize::Small)
3167                                            .icon_color(Color::Error)
3168                                            .tooltip(Tooltip::text("Stop Subagent"))
3169                                            .on_click(move |_, _, cx| {
3170                                                thread.update(cx, |thread, cx| {
3171                                                    thread.cancel(cx).detach();
3172                                                });
3173                                            }),
3174                                    )
3175                                })
3176                                .child(
3177                                    IconButton::new("minimize_subagent", IconName::Dash)
3178                                        .icon_size(IconSize::Small)
3179                                        .tooltip(Tooltip::text("Minimize Subagent"))
3180                                        .on_click(move |_, window, cx| {
3181                                            let _ = server_view.update(cx, |server_view, cx| {
3182                                                server_view.navigate_to_thread(
3183                                                    parent_session_id.clone(),
3184                                                    window,
3185                                                    cx,
3186                                                );
3187                                            });
3188                                        }),
3189                                ),
3190                        ),
3191                ),
3192        )
3193    }
3194
3195    pub(crate) fn render_message_editor(
3196        &mut self,
3197        window: &mut Window,
3198        cx: &mut Context<Self>,
3199    ) -> AnyElement {
3200        if self.is_subagent() {
3201            return div().into_any_element();
3202        }
3203
3204        let focus_handle = self.message_editor.focus_handle(cx);
3205        let editor_bg_color = cx.theme().colors().editor_background;
3206
3207        let editor_expanded = self.editor_expanded;
3208        let (expand_icon, expand_tooltip) = if editor_expanded {
3209            (IconName::Minimize, "Minimize Message Editor")
3210        } else {
3211            (IconName::Maximize, "Expand Message Editor")
3212        };
3213
3214        let max_content_width = AgentSettings::get_global(cx).max_content_width;
3215        let has_messages = self.list_state.item_count() > 0;
3216        let fills_container = !has_messages || editor_expanded;
3217
3218        h_flex()
3219            .p_2()
3220            .bg(editor_bg_color)
3221            .justify_center()
3222            .map(|this| {
3223                if has_messages {
3224                    this.on_action(cx.listener(Self::expand_message_editor))
3225                        .border_t_1()
3226                        .border_color(cx.theme().colors().border)
3227                        .when(editor_expanded, |this| this.h(vh(0.8, window)))
3228                } else {
3229                    this.flex_1().size_full()
3230                }
3231            })
3232            .child(
3233                v_flex()
3234                    .flex_basis(max_content_width)
3235                    .flex_shrink()
3236                    .flex_grow_0()
3237                    .when(fills_container, |this| this.h_full())
3238                    .justify_between()
3239                    .gap_2()
3240                    .child(
3241                        v_flex()
3242                            .relative()
3243                            .w_full()
3244                            .min_h_0()
3245                            .when(fills_container, |this| this.flex_1())
3246                            .pt_1()
3247                            .pr_2p5()
3248                            .child(self.message_editor.clone())
3249                            .when(has_messages, |this| {
3250                                this.child(
3251                                    h_flex()
3252                                        .absolute()
3253                                        .top_0()
3254                                        .right_0()
3255                                        .opacity(0.5)
3256                                        .hover(|s| s.opacity(1.0))
3257                                        .child(
3258                                            IconButton::new("toggle-height", expand_icon)
3259                                                .icon_size(IconSize::Small)
3260                                                .icon_color(Color::Muted)
3261                                                .tooltip({
3262                                                    move |_window, cx| {
3263                                                        Tooltip::for_action_in(
3264                                                            expand_tooltip,
3265                                                            &ExpandMessageEditor,
3266                                                            &focus_handle,
3267                                                            cx,
3268                                                        )
3269                                                    }
3270                                                })
3271                                                .on_click(cx.listener(|this, _, window, cx| {
3272                                                    this.expand_message_editor(
3273                                                        &ExpandMessageEditor,
3274                                                        window,
3275                                                        cx,
3276                                                    );
3277                                                })),
3278                                        ),
3279                                )
3280                            }),
3281                    )
3282                    .child(
3283                        h_flex()
3284                            .w_full()
3285                            .flex_none()
3286                            .flex_wrap()
3287                            .justify_between()
3288                            .child(
3289                                h_flex()
3290                                    .gap_0p5()
3291                                    .child(self.render_add_context_button(cx))
3292                                    .child(self.render_follow_toggle(cx))
3293                                    .children(self.render_fast_mode_control(cx))
3294                                    .children(self.render_thinking_control(cx)),
3295                            )
3296                            .child(
3297                                h_flex()
3298                                    .gap_1()
3299                                    .children(self.render_token_usage(cx))
3300                                    .children(self.profile_selector.clone())
3301                                    .map(|this| match self.config_options_view.clone() {
3302                                        Some(config_view) => this.child(config_view),
3303                                        None => this
3304                                            .children(self.mode_selector.clone())
3305                                            .children(self.model_selector.clone()),
3306                                    })
3307                                    .child(self.render_send_button(cx)),
3308                            ),
3309                    ),
3310            )
3311            .into_any()
3312    }
3313
3314    fn render_message_queue_entries(
3315        &self,
3316        _window: &mut Window,
3317        cx: &Context<Self>,
3318    ) -> impl IntoElement {
3319        let message_editor = self.message_editor.read(cx);
3320        let focus_handle = message_editor.focus_handle(cx);
3321
3322        let queued_message_editors = &self.queued_message_editors;
3323        let queue_len = queued_message_editors.len();
3324        let can_fast_track = self.can_fast_track_queue && queue_len > 0;
3325
3326        v_flex()
3327            .id("message_queue_list")
3328            .max_h_40()
3329            .overflow_y_scroll()
3330            .children(
3331                queued_message_editors
3332                    .iter()
3333                    .enumerate()
3334                    .map(|(index, editor)| {
3335                        let is_next = index == 0;
3336                        let (icon_color, tooltip_text) = if is_next {
3337                            (Color::Accent, "Next in Queue")
3338                        } else {
3339                            (Color::Muted, "In Queue")
3340                        };
3341
3342                        let editor_focused = editor.focus_handle(cx).is_focused(_window);
3343                        let keybinding_size = rems_from_px(12.);
3344
3345                        h_flex()
3346                            .group("queue_entry")
3347                            .w_full()
3348                            .p_1p5()
3349                            .gap_1()
3350                            .bg(cx.theme().colors().editor_background)
3351                            .when(index < queue_len - 1, |this| {
3352                                this.border_b_1()
3353                                    .border_color(cx.theme().colors().border_variant)
3354                            })
3355                            .child(
3356                                div()
3357                                    .id("next_in_queue")
3358                                    .child(
3359                                        Icon::new(IconName::Circle)
3360                                            .size(IconSize::Small)
3361                                            .color(icon_color),
3362                                    )
3363                                    .tooltip(Tooltip::text(tooltip_text)),
3364                            )
3365                            .child(editor.clone())
3366                            .child(if editor_focused {
3367                                h_flex()
3368                                    .gap_1()
3369                                    .min_w(rems_from_px(150.))
3370                                    .justify_end()
3371                                    .child(
3372                                        IconButton::new(("edit", index), IconName::Pencil)
3373                                            .icon_size(IconSize::Small)
3374                                            .tooltip(|_window, cx| {
3375                                                Tooltip::with_meta(
3376                                                    "Edit Queued Message",
3377                                                    None,
3378                                                    "Type anything to edit",
3379                                                    cx,
3380                                                )
3381                                            })
3382                                            .on_click(cx.listener(move |this, _, window, cx| {
3383                                                this.move_queued_message_to_main_editor(
3384                                                    index, None, None, window, cx,
3385                                                );
3386                                            })),
3387                                    )
3388                                    .child(
3389                                        Button::new(("send_now_focused", index), "Send Now")
3390                                            .label_size(LabelSize::Small)
3391                                            .style(ButtonStyle::Outlined)
3392                                            .key_binding(
3393                                                KeyBinding::for_action_in(
3394                                                    &SendImmediately,
3395                                                    &editor.focus_handle(cx),
3396                                                    cx,
3397                                                )
3398                                                .map(|kb| kb.size(keybinding_size)),
3399                                            )
3400                                            .on_click(cx.listener(move |this, _, window, cx| {
3401                                                this.send_queued_message_at_index(
3402                                                    index, true, window, cx,
3403                                                );
3404                                            })),
3405                                    )
3406                            } else {
3407                                h_flex()
3408                                    .when(!is_next, |this| this.visible_on_hover("queue_entry"))
3409                                    .gap_1()
3410                                    .min_w(rems_from_px(150.))
3411                                    .justify_end()
3412                                    .child(
3413                                        IconButton::new(("delete", index), IconName::Trash)
3414                                            .icon_size(IconSize::Small)
3415                                            .tooltip({
3416                                                let focus_handle = focus_handle.clone();
3417                                                move |_window, cx| {
3418                                                    if is_next {
3419                                                        Tooltip::for_action_in(
3420                                                            "Remove Message from Queue",
3421                                                            &RemoveFirstQueuedMessage,
3422                                                            &focus_handle,
3423                                                            cx,
3424                                                        )
3425                                                    } else {
3426                                                        Tooltip::simple(
3427                                                            "Remove Message from Queue",
3428                                                            cx,
3429                                                        )
3430                                                    }
3431                                                }
3432                                            })
3433                                            .on_click(cx.listener(move |this, _, _, cx| {
3434                                                this.remove_from_queue(index, cx);
3435                                                cx.notify();
3436                                            })),
3437                                    )
3438                                    .child(
3439                                        IconButton::new(("edit", index), IconName::Pencil)
3440                                            .icon_size(IconSize::Small)
3441                                            .tooltip({
3442                                                let focus_handle = focus_handle.clone();
3443                                                move |_window, cx| {
3444                                                    if is_next {
3445                                                        Tooltip::for_action_in(
3446                                                            "Edit",
3447                                                            &EditFirstQueuedMessage,
3448                                                            &focus_handle,
3449                                                            cx,
3450                                                        )
3451                                                    } else {
3452                                                        Tooltip::simple("Edit", cx)
3453                                                    }
3454                                                }
3455                                            })
3456                                            .on_click(cx.listener(move |this, _, window, cx| {
3457                                                this.move_queued_message_to_main_editor(
3458                                                    index, None, None, window, cx,
3459                                                );
3460                                            })),
3461                                    )
3462                                    .child(
3463                                        Button::new(("send_now", index), "Send Now")
3464                                            .label_size(LabelSize::Small)
3465                                            .when(is_next, |this| this.style(ButtonStyle::Outlined))
3466                                            .when(is_next && message_editor.is_empty(cx), |this| {
3467                                                let action: Box<dyn gpui::Action> =
3468                                                    if can_fast_track {
3469                                                        Box::new(Chat)
3470                                                    } else {
3471                                                        Box::new(SendNextQueuedMessage)
3472                                                    };
3473
3474                                                this.key_binding(
3475                                                    KeyBinding::for_action_in(
3476                                                        action.as_ref(),
3477                                                        &focus_handle.clone(),
3478                                                        cx,
3479                                                    )
3480                                                    .map(|kb| kb.size(keybinding_size)),
3481                                                )
3482                                            })
3483                                            .on_click(cx.listener(move |this, _, window, cx| {
3484                                                this.send_queued_message_at_index(
3485                                                    index, true, window, cx,
3486                                                );
3487                                            })),
3488                                    )
3489                            })
3490                    }),
3491            )
3492            .into_any_element()
3493    }
3494
3495    fn supports_split_token_display(&self, cx: &App) -> bool {
3496        self.as_native_thread(cx)
3497            .and_then(|thread| thread.read(cx).model())
3498            .is_some_and(|model| model.supports_split_token_display())
3499    }
3500
3501    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3502        let thread = self.thread.read(cx);
3503        let usage = thread.token_usage()?;
3504        let show_split = self.supports_split_token_display(cx);
3505
3506        let cost_label = if cx.has_flag::<AcpBetaFeatureFlag>() {
3507            thread.cost().map(|cost| {
3508                let precision = if cost.amount > 0.0 && cost.amount < 0.01 {
3509                    4
3510                } else {
3511                    2
3512                };
3513                format!("{:.prec$} {}", cost.amount, cost.currency, prec = precision)
3514            })
3515        } else {
3516            None
3517        };
3518
3519        let progress_color = |ratio: f32| -> Hsla {
3520            if ratio >= 0.85 {
3521                cx.theme().status().warning
3522            } else {
3523                cx.theme().colors().text_muted
3524            }
3525        };
3526
3527        let used = crate::humanize_token_count(usage.used_tokens);
3528        let max = crate::humanize_token_count(usage.max_tokens);
3529        let input_tokens_label = crate::humanize_token_count(usage.input_tokens);
3530        let output_tokens_label = crate::humanize_token_count(usage.output_tokens);
3531
3532        let progress_ratio = if usage.max_tokens > 0 {
3533            usage.used_tokens as f32 / usage.max_tokens as f32
3534        } else {
3535            0.0
3536        };
3537
3538        let ring_size = px(16.0);
3539        let stroke_width = px(2.);
3540
3541        let percentage = format!("{}%", (progress_ratio * 100.0).round() as u32);
3542
3543        let tooltip_separator_color = Color::Custom(cx.theme().colors().text_disabled.opacity(0.6));
3544
3545        let (user_rules_count, first_user_rules_id, project_rules_count, project_entry_ids) = self
3546            .as_native_thread(cx)
3547            .map(|thread| {
3548                let project_context = thread.read(cx).project_context().read(cx);
3549                let user_rules_count = project_context.user_rules.len();
3550                let first_user_rules_id = project_context.user_rules.first().map(|r| r.uuid.0);
3551                let project_entry_ids = project_context
3552                    .worktrees
3553                    .iter()
3554                    .filter_map(|wt| wt.rules_file.as_ref())
3555                    .map(|rf| ProjectEntryId::from_usize(rf.project_entry_id))
3556                    .collect::<Vec<_>>();
3557                let project_rules_count = project_entry_ids.len();
3558                (
3559                    user_rules_count,
3560                    first_user_rules_id,
3561                    project_rules_count,
3562                    project_entry_ids,
3563                )
3564            })
3565            .unwrap_or_default();
3566
3567        let workspace = self.workspace.clone();
3568
3569        let max_output_tokens = self
3570            .as_native_thread(cx)
3571            .and_then(|thread| thread.read(cx).model())
3572            .and_then(|model| model.max_output_tokens())
3573            .unwrap_or(0);
3574        let input_max_label =
3575            crate::humanize_token_count(usage.max_tokens.saturating_sub(max_output_tokens));
3576        let output_max_label = crate::humanize_token_count(max_output_tokens);
3577
3578        let build_tooltip = {
3579            move |_window: &mut Window, cx: &mut App| {
3580                let percentage = percentage.clone();
3581                let used = used.clone();
3582                let max = max.clone();
3583                let input_tokens_label = input_tokens_label.clone();
3584                let output_tokens_label = output_tokens_label.clone();
3585                let input_max_label = input_max_label.clone();
3586                let output_max_label = output_max_label.clone();
3587                let project_entry_ids = project_entry_ids.clone();
3588                let workspace = workspace.clone();
3589                let cost_label = cost_label.clone();
3590                cx.new(move |_cx| TokenUsageTooltip {
3591                    percentage,
3592                    used,
3593                    max,
3594                    input_tokens: input_tokens_label,
3595                    output_tokens: output_tokens_label,
3596                    input_max: input_max_label,
3597                    output_max: output_max_label,
3598                    show_split,
3599                    cost_label,
3600                    separator_color: tooltip_separator_color,
3601                    user_rules_count,
3602                    first_user_rules_id,
3603                    project_rules_count,
3604                    project_entry_ids,
3605                    workspace,
3606                })
3607                .into()
3608            }
3609        };
3610
3611        if show_split {
3612            let input_max_raw = usage.max_tokens.saturating_sub(max_output_tokens);
3613            let output_max_raw = max_output_tokens;
3614
3615            let input_ratio = if input_max_raw > 0 {
3616                usage.input_tokens as f32 / input_max_raw as f32
3617            } else {
3618                0.0
3619            };
3620            let output_ratio = if output_max_raw > 0 {
3621                usage.output_tokens as f32 / output_max_raw as f32
3622            } else {
3623                0.0
3624            };
3625
3626            Some(
3627                h_flex()
3628                    .id("split_token_usage")
3629                    .flex_shrink_0()
3630                    .gap_1p5()
3631                    .mr_1()
3632                    .child(
3633                        h_flex()
3634                            .gap_0p5()
3635                            .child(
3636                                Icon::new(IconName::ArrowUp)
3637                                    .size(IconSize::XSmall)
3638                                    .color(Color::Muted),
3639                            )
3640                            .child(
3641                                CircularProgress::new(
3642                                    usage.input_tokens as f32,
3643                                    input_max_raw as f32,
3644                                    ring_size,
3645                                    cx,
3646                                )
3647                                .stroke_width(stroke_width)
3648                                .progress_color(progress_color(input_ratio)),
3649                            ),
3650                    )
3651                    .child(
3652                        h_flex()
3653                            .gap_0p5()
3654                            .child(
3655                                Icon::new(IconName::ArrowDown)
3656                                    .size(IconSize::XSmall)
3657                                    .color(Color::Muted),
3658                            )
3659                            .child(
3660                                CircularProgress::new(
3661                                    usage.output_tokens as f32,
3662                                    output_max_raw as f32,
3663                                    ring_size,
3664                                    cx,
3665                                )
3666                                .stroke_width(stroke_width)
3667                                .progress_color(progress_color(output_ratio)),
3668                            ),
3669                    )
3670                    .hoverable_tooltip(build_tooltip)
3671                    .into_any_element(),
3672            )
3673        } else {
3674            Some(
3675                h_flex()
3676                    .id("circular_progress_tokens")
3677                    .mt_px()
3678                    .mr_1()
3679                    .child(
3680                        CircularProgress::new(
3681                            usage.used_tokens as f32,
3682                            usage.max_tokens as f32,
3683                            ring_size,
3684                            cx,
3685                        )
3686                        .stroke_width(stroke_width)
3687                        .progress_color(progress_color(progress_ratio)),
3688                    )
3689                    .hoverable_tooltip(build_tooltip)
3690                    .into_any_element(),
3691            )
3692        }
3693    }
3694
3695    fn fast_mode_available(&self, cx: &Context<Self>) -> bool {
3696        if !cx.is_staff() {
3697            return false;
3698        }
3699        self.as_native_thread(cx)
3700            .and_then(|thread| thread.read(cx).model())
3701            .map(|model| model.supports_fast_mode())
3702            .unwrap_or(false)
3703    }
3704
3705    fn render_fast_mode_control(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3706        if !self.fast_mode_available(cx) {
3707            return None;
3708        }
3709
3710        let thread = self.as_native_thread(cx)?.read(cx);
3711
3712        let (tooltip_label, color, icon) = if matches!(thread.speed(), Some(Speed::Fast)) {
3713            ("Disable Fast Mode", Color::Muted, IconName::FastForward)
3714        } else {
3715            (
3716                "Enable Fast Mode",
3717                Color::Custom(cx.theme().colors().icon_disabled.opacity(0.8)),
3718                IconName::FastForwardOff,
3719            )
3720        };
3721
3722        let focus_handle = self.message_editor.focus_handle(cx);
3723
3724        Some(
3725            IconButton::new("fast-mode", icon)
3726                .icon_size(IconSize::Small)
3727                .icon_color(color)
3728                .tooltip(move |_, cx| {
3729                    Tooltip::for_action_in(tooltip_label, &ToggleFastMode, &focus_handle, cx)
3730                })
3731                .on_click(cx.listener(move |this, _, _window, cx| {
3732                    this.toggle_fast_mode(cx);
3733                }))
3734                .into_any_element(),
3735        )
3736    }
3737
3738    fn render_thinking_control(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3739        let thread = self.as_native_thread(cx)?.read(cx);
3740        let model = thread.model()?;
3741
3742        let supports_thinking = model.supports_thinking();
3743        if !supports_thinking {
3744            return None;
3745        }
3746
3747        let thinking = thread.thinking_enabled();
3748
3749        let (tooltip_label, icon, color) = if thinking {
3750            (
3751                "Disable Thinking Mode",
3752                IconName::ThinkingMode,
3753                Color::Muted,
3754            )
3755        } else {
3756            (
3757                "Enable Thinking Mode",
3758                IconName::ThinkingModeOff,
3759                Color::Custom(cx.theme().colors().icon_disabled.opacity(0.8)),
3760            )
3761        };
3762
3763        let focus_handle = self.message_editor.focus_handle(cx);
3764
3765        let thinking_toggle = IconButton::new("thinking-mode", icon)
3766            .icon_size(IconSize::Small)
3767            .icon_color(color)
3768            .tooltip(move |_, cx| {
3769                Tooltip::for_action_in(tooltip_label, &ToggleThinkingMode, &focus_handle, cx)
3770            })
3771            .on_click(cx.listener(move |this, _, _window, cx| {
3772                if let Some(thread) = this.as_native_thread(cx) {
3773                    thread.update(cx, |thread, cx| {
3774                        let enable_thinking = !thread.thinking_enabled();
3775                        thread.set_thinking_enabled(enable_thinking, cx);
3776
3777                        let fs = thread.project().read(cx).fs().clone();
3778                        update_settings_file(fs, cx, move |settings, _| {
3779                            if let Some(agent) = settings.agent.as_mut()
3780                                && let Some(default_model) = agent.default_model.as_mut()
3781                            {
3782                                default_model.enable_thinking = enable_thinking;
3783                            }
3784                        });
3785                    });
3786                }
3787            }));
3788
3789        if model.supported_effort_levels().is_empty() {
3790            return Some(thinking_toggle.into_any_element());
3791        }
3792
3793        if !model.supported_effort_levels().is_empty() && !thinking {
3794            return Some(thinking_toggle.into_any_element());
3795        }
3796
3797        let left_btn = thinking_toggle;
3798        let right_btn = self.render_effort_selector(
3799            model.supported_effort_levels(),
3800            thread.thinking_effort().cloned(),
3801            cx,
3802        );
3803
3804        Some(
3805            SplitButton::new(left_btn, right_btn.into_any_element())
3806                .style(SplitButtonStyle::Transparent)
3807                .into_any_element(),
3808        )
3809    }
3810
3811    fn render_effort_selector(
3812        &self,
3813        supported_effort_levels: Vec<LanguageModelEffortLevel>,
3814        selected_effort: Option<String>,
3815        cx: &Context<Self>,
3816    ) -> impl IntoElement {
3817        let weak_self = cx.weak_entity();
3818
3819        let default_effort_level = supported_effort_levels
3820            .iter()
3821            .find(|effort_level| effort_level.is_default)
3822            .cloned();
3823
3824        let selected = selected_effort.and_then(|effort| {
3825            supported_effort_levels
3826                .iter()
3827                .find(|level| level.value == effort)
3828                .cloned()
3829        });
3830
3831        let label = selected
3832            .clone()
3833            .or(default_effort_level)
3834            .map_or("Select Effort".into(), |effort| effort.name);
3835
3836        let (label_color, icon) = if self.thinking_effort_menu_handle.is_deployed() {
3837            (Color::Accent, IconName::ChevronUp)
3838        } else {
3839            (Color::Muted, IconName::ChevronDown)
3840        };
3841
3842        let focus_handle = self.message_editor.focus_handle(cx);
3843        let show_cycle_row = supported_effort_levels.len() > 1;
3844
3845        let tooltip = Tooltip::element({
3846            move |_, cx| {
3847                let mut content = v_flex().gap_1().child(
3848                    h_flex()
3849                        .gap_2()
3850                        .justify_between()
3851                        .child(Label::new("Change Thinking Effort"))
3852                        .child(KeyBinding::for_action_in(
3853                            &ToggleThinkingEffortMenu,
3854                            &focus_handle,
3855                            cx,
3856                        )),
3857                );
3858
3859                if show_cycle_row {
3860                    content = content.child(
3861                        h_flex()
3862                            .pt_1()
3863                            .gap_2()
3864                            .justify_between()
3865                            .border_t_1()
3866                            .border_color(cx.theme().colors().border_variant)
3867                            .child(Label::new("Cycle Thinking Effort"))
3868                            .child(KeyBinding::for_action_in(
3869                                &CycleThinkingEffort,
3870                                &focus_handle,
3871                                cx,
3872                            )),
3873                    );
3874                }
3875
3876                content.into_any_element()
3877            }
3878        });
3879
3880        PopoverMenu::new("effort-selector")
3881            .trigger_with_tooltip(
3882                ButtonLike::new_rounded_right("effort-selector-trigger")
3883                    .selected_style(ButtonStyle::Tinted(TintColor::Accent))
3884                    .child(Label::new(label).size(LabelSize::Small).color(label_color))
3885                    .child(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted)),
3886                tooltip,
3887            )
3888            .menu(move |window, cx| {
3889                Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
3890                    menu = menu.header("Change Thinking Effort");
3891
3892                    for effort_level in supported_effort_levels.clone() {
3893                        let is_selected = selected
3894                            .as_ref()
3895                            .is_some_and(|selected| selected.value == effort_level.value);
3896                        let entry = ContextMenuEntry::new(effort_level.name)
3897                            .toggleable(IconPosition::End, is_selected);
3898
3899                        menu.push_item(entry.handler({
3900                            let effort = effort_level.value.clone();
3901                            let weak_self = weak_self.clone();
3902                            move |_window, cx| {
3903                                let effort = effort.clone();
3904                                weak_self
3905                                    .update(cx, |this, cx| {
3906                                        if let Some(thread) = this.as_native_thread(cx) {
3907                                            thread.update(cx, |thread, cx| {
3908                                                thread.set_thinking_effort(
3909                                                    Some(effort.to_string()),
3910                                                    cx,
3911                                                );
3912
3913                                                let fs = thread.project().read(cx).fs().clone();
3914                                                update_settings_file(fs, cx, move |settings, _| {
3915                                                    if let Some(agent) = settings.agent.as_mut()
3916                                                        && let Some(default_model) =
3917                                                            agent.default_model.as_mut()
3918                                                    {
3919                                                        default_model.effort =
3920                                                            Some(effort.to_string());
3921                                                    }
3922                                                });
3923                                            });
3924                                        }
3925                                    })
3926                                    .ok();
3927                            }
3928                        }));
3929                    }
3930
3931                    menu
3932                }))
3933            })
3934            .with_handle(self.thinking_effort_menu_handle.clone())
3935            .offset(gpui::Point {
3936                x: px(0.0),
3937                y: px(-2.0),
3938            })
3939            .anchor(Corner::BottomLeft)
3940    }
3941
3942    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3943        let message_editor = self.message_editor.read(cx);
3944        let is_editor_empty = message_editor.is_empty(cx);
3945        let focus_handle = message_editor.focus_handle(cx);
3946
3947        let is_generating = self.thread.read(cx).status() != ThreadStatus::Idle;
3948
3949        if self.is_loading_contents {
3950            div()
3951                .id("loading-message-content")
3952                .px_1()
3953                .tooltip(Tooltip::text("Loading Added Context…"))
3954                .child(loading_contents_spinner(IconSize::default()))
3955                .into_any_element()
3956        } else if is_generating && is_editor_empty {
3957            IconButton::new("stop-generation", IconName::Stop)
3958                .icon_color(Color::Error)
3959                .style(ButtonStyle::Tinted(TintColor::Error))
3960                .tooltip(move |_window, cx| {
3961                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
3962                })
3963                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3964                .into_any_element()
3965        } else {
3966            let send_icon = if is_generating {
3967                IconName::QueueMessage
3968            } else {
3969                IconName::Send
3970            };
3971            IconButton::new("send-message", send_icon)
3972                .style(ButtonStyle::Filled)
3973                .map(|this| {
3974                    if is_editor_empty && !is_generating {
3975                        this.disabled(true).icon_color(Color::Muted)
3976                    } else {
3977                        this.icon_color(Color::Accent)
3978                    }
3979                })
3980                .tooltip(move |_window, cx| {
3981                    if is_editor_empty && !is_generating {
3982                        Tooltip::for_action("Type to Send", &Chat, cx)
3983                    } else if is_generating {
3984                        let focus_handle = focus_handle.clone();
3985
3986                        Tooltip::element(move |_window, cx| {
3987                            v_flex()
3988                                .gap_1()
3989                                .child(
3990                                    h_flex()
3991                                        .gap_2()
3992                                        .justify_between()
3993                                        .child(Label::new("Queue and Send"))
3994                                        .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
3995                                )
3996                                .child(
3997                                    h_flex()
3998                                        .pt_1()
3999                                        .gap_2()
4000                                        .justify_between()
4001                                        .border_t_1()
4002                                        .border_color(cx.theme().colors().border_variant)
4003                                        .child(Label::new("Send Immediately"))
4004                                        .child(KeyBinding::for_action_in(
4005                                            &SendImmediately,
4006                                            &focus_handle,
4007                                            cx,
4008                                        )),
4009                                )
4010                                .into_any_element()
4011                        })(_window, cx)
4012                    } else {
4013                        Tooltip::for_action("Send Message", &Chat, cx)
4014                    }
4015                })
4016                .on_click(cx.listener(|this, _, window, cx| {
4017                    this.send(window, cx);
4018                }))
4019                .into_any_element()
4020        }
4021    }
4022
4023    fn render_add_context_button(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
4024        let focus_handle = self.message_editor.focus_handle(cx);
4025        let weak_self = cx.weak_entity();
4026
4027        PopoverMenu::new("add-context-menu")
4028            .trigger_with_tooltip(
4029                IconButton::new("add-context", IconName::Plus)
4030                    .icon_size(IconSize::Small)
4031                    .icon_color(Color::Muted),
4032                {
4033                    move |_window, cx| {
4034                        Tooltip::for_action_in(
4035                            "Add Context",
4036                            &OpenAddContextMenu,
4037                            &focus_handle,
4038                            cx,
4039                        )
4040                    }
4041                },
4042            )
4043            .anchor(Corner::BottomLeft)
4044            .with_handle(self.add_context_menu_handle.clone())
4045            .offset(gpui::Point {
4046                x: px(0.0),
4047                y: px(-2.0),
4048            })
4049            .menu(move |window, cx| {
4050                weak_self
4051                    .update(cx, |this, cx| this.build_add_context_menu(window, cx))
4052                    .ok()
4053            })
4054    }
4055
4056    fn build_add_context_menu(
4057        &self,
4058        window: &mut Window,
4059        cx: &mut Context<Self>,
4060    ) -> Entity<ContextMenu> {
4061        let message_editor = self.message_editor.clone();
4062        let workspace = self.workspace.clone();
4063        let session_capabilities = self.session_capabilities.read();
4064        let supports_images = session_capabilities.supports_images();
4065        let supports_embedded_context = session_capabilities.supports_embedded_context();
4066
4067        let has_editor_selection = workspace
4068            .upgrade()
4069            .and_then(|ws| {
4070                ws.read(cx)
4071                    .active_item(cx)
4072                    .and_then(|item| item.downcast::<Editor>())
4073            })
4074            .is_some_and(|editor| {
4075                editor.update(cx, |editor, cx| {
4076                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
4077                })
4078            });
4079
4080        let has_terminal_selection = workspace
4081            .upgrade()
4082            .and_then(|ws| ws.read(cx).panel::<TerminalPanel>(cx))
4083            .is_some_and(|panel| !panel.read(cx).terminal_selections(cx).is_empty());
4084
4085        let has_selection = has_editor_selection || has_terminal_selection;
4086
4087        ContextMenu::build(window, cx, move |menu, _window, _cx| {
4088            menu.key_context("AddContextMenu")
4089                .header("Context")
4090                .item(
4091                    ContextMenuEntry::new("Files & Directories")
4092                        .icon(IconName::File)
4093                        .icon_color(Color::Muted)
4094                        .icon_size(IconSize::XSmall)
4095                        .handler({
4096                            let message_editor = message_editor.clone();
4097                            move |window, cx| {
4098                                message_editor.focus_handle(cx).focus(window, cx);
4099                                message_editor.update(cx, |editor, cx| {
4100                                    editor.insert_context_type("file", window, cx);
4101                                });
4102                            }
4103                        }),
4104                )
4105                .item(
4106                    ContextMenuEntry::new("Symbols")
4107                        .icon(IconName::Code)
4108                        .icon_color(Color::Muted)
4109                        .icon_size(IconSize::XSmall)
4110                        .handler({
4111                            let message_editor = message_editor.clone();
4112                            move |window, cx| {
4113                                message_editor.focus_handle(cx).focus(window, cx);
4114                                message_editor.update(cx, |editor, cx| {
4115                                    editor.insert_context_type("symbol", window, cx);
4116                                });
4117                            }
4118                        }),
4119                )
4120                .item(
4121                    ContextMenuEntry::new("Threads")
4122                        .icon(IconName::Thread)
4123                        .icon_color(Color::Muted)
4124                        .icon_size(IconSize::XSmall)
4125                        .handler({
4126                            let message_editor = message_editor.clone();
4127                            move |window, cx| {
4128                                message_editor.focus_handle(cx).focus(window, cx);
4129                                message_editor.update(cx, |editor, cx| {
4130                                    editor.insert_context_type("thread", window, cx);
4131                                });
4132                            }
4133                        }),
4134                )
4135                .item(
4136                    ContextMenuEntry::new("Rules")
4137                        .icon(IconName::Reader)
4138                        .icon_color(Color::Muted)
4139                        .icon_size(IconSize::XSmall)
4140                        .handler({
4141                            let message_editor = message_editor.clone();
4142                            move |window, cx| {
4143                                message_editor.focus_handle(cx).focus(window, cx);
4144                                message_editor.update(cx, |editor, cx| {
4145                                    editor.insert_context_type("rule", window, cx);
4146                                });
4147                            }
4148                        }),
4149                )
4150                .item(
4151                    ContextMenuEntry::new("Image")
4152                        .icon(IconName::Image)
4153                        .icon_color(Color::Muted)
4154                        .icon_size(IconSize::XSmall)
4155                        .disabled(!supports_images)
4156                        .handler({
4157                            let message_editor = message_editor.clone();
4158                            move |window, cx| {
4159                                message_editor.focus_handle(cx).focus(window, cx);
4160                                message_editor.update(cx, |editor, cx| {
4161                                    editor.add_images_from_picker(window, cx);
4162                                });
4163                            }
4164                        }),
4165                )
4166                .item(
4167                    ContextMenuEntry::new("Selection")
4168                        .icon(IconName::CursorIBeam)
4169                        .icon_color(Color::Muted)
4170                        .icon_size(IconSize::XSmall)
4171                        .disabled(!has_selection)
4172                        .handler({
4173                            move |window, cx| {
4174                                window.dispatch_action(
4175                                    zed_actions::agent::AddSelectionToThread.boxed_clone(),
4176                                    cx,
4177                                );
4178                            }
4179                        }),
4180                )
4181                .item(
4182                    ContextMenuEntry::new("Branch Diff")
4183                        .icon(IconName::GitBranch)
4184                        .icon_color(Color::Muted)
4185                        .icon_size(IconSize::XSmall)
4186                        .disabled(!supports_embedded_context)
4187                        .handler({
4188                            move |window, cx| {
4189                                message_editor.update(cx, |editor, cx| {
4190                                    editor.insert_branch_diff_crease(window, cx);
4191                                });
4192                            }
4193                        }),
4194                )
4195        })
4196    }
4197
4198    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4199        let following = self.is_following(cx);
4200
4201        let tooltip_label = if following {
4202            if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
4203                format!("Stop Following the {}", self.agent_id)
4204            } else {
4205                format!("Stop Following {}", self.agent_id)
4206            }
4207        } else {
4208            if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
4209                format!("Follow the {}", self.agent_id)
4210            } else {
4211                format!("Follow {}", self.agent_id)
4212            }
4213        };
4214
4215        IconButton::new("follow-agent", IconName::Crosshair)
4216            .icon_size(IconSize::Small)
4217            .icon_color(Color::Muted)
4218            .toggle_state(following)
4219            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4220            .tooltip(move |_window, cx| {
4221                if following {
4222                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4223                } else {
4224                    Tooltip::with_meta(
4225                        tooltip_label.clone(),
4226                        Some(&Follow),
4227                        "Track the agent's location as it reads and edits files.",
4228                        cx,
4229                    )
4230                }
4231            })
4232            .on_click(cx.listener(move |this, _, window, cx| {
4233                this.toggle_following(window, cx);
4234            }))
4235    }
4236}
4237
4238struct TokenUsageTooltip {
4239    percentage: String,
4240    used: String,
4241    max: String,
4242    input_tokens: String,
4243    output_tokens: String,
4244    input_max: String,
4245    output_max: String,
4246    show_split: bool,
4247    cost_label: Option<String>,
4248    separator_color: Color,
4249    user_rules_count: usize,
4250    first_user_rules_id: Option<uuid::Uuid>,
4251    project_rules_count: usize,
4252    project_entry_ids: Vec<ProjectEntryId>,
4253    workspace: WeakEntity<Workspace>,
4254}
4255
4256impl Render for TokenUsageTooltip {
4257    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4258        let separator_color = self.separator_color;
4259        let percentage = self.percentage.clone();
4260        let used = self.used.clone();
4261        let max = self.max.clone();
4262        let input_tokens = self.input_tokens.clone();
4263        let output_tokens = self.output_tokens.clone();
4264        let input_max = self.input_max.clone();
4265        let output_max = self.output_max.clone();
4266        let show_split = self.show_split;
4267        let cost_label = self.cost_label.clone();
4268        let user_rules_count = self.user_rules_count;
4269        let first_user_rules_id = self.first_user_rules_id;
4270        let project_rules_count = self.project_rules_count;
4271        let project_entry_ids = self.project_entry_ids.clone();
4272        let workspace = self.workspace.clone();
4273
4274        ui::tooltip_container(cx, move |container, cx| {
4275            container
4276                .min_w_40()
4277                .child(
4278                    Label::new("Context")
4279                        .color(Color::Muted)
4280                        .size(LabelSize::Small),
4281                )
4282                .when(!show_split, |this| {
4283                    this.child(
4284                        h_flex()
4285                            .gap_0p5()
4286                            .child(Label::new(percentage.clone()))
4287                            .child(Label::new("\u{2022}").color(separator_color).mx_1())
4288                            .child(Label::new(used.clone()))
4289                            .child(Label::new("/").color(separator_color))
4290                            .child(Label::new(max.clone()).color(Color::Muted)),
4291                    )
4292                })
4293                .when(show_split, |this| {
4294                    this.child(
4295                        v_flex()
4296                            .gap_0p5()
4297                            .child(
4298                                h_flex()
4299                                    .gap_0p5()
4300                                    .child(Label::new("Input:").color(Color::Muted).mr_0p5())
4301                                    .child(Label::new(input_tokens))
4302                                    .child(Label::new("/").color(separator_color))
4303                                    .child(Label::new(input_max).color(Color::Muted)),
4304                            )
4305                            .child(
4306                                h_flex()
4307                                    .gap_0p5()
4308                                    .child(Label::new("Output:").color(Color::Muted).mr_0p5())
4309                                    .child(Label::new(output_tokens))
4310                                    .child(Label::new("/").color(separator_color))
4311                                    .child(Label::new(output_max).color(Color::Muted)),
4312                            ),
4313                    )
4314                })
4315                .when_some(cost_label, |this, cost_label| {
4316                    this.child(
4317                        v_flex()
4318                            .mt_1p5()
4319                            .pt_1p5()
4320                            .gap_0p5()
4321                            .border_t_1()
4322                            .border_color(cx.theme().colors().border_variant)
4323                            .child(
4324                                Label::new("Cost")
4325                                    .color(Color::Muted)
4326                                    .size(LabelSize::Small),
4327                            )
4328                            .child(Label::new(cost_label)),
4329                    )
4330                })
4331                .when(
4332                    user_rules_count > 0 || project_rules_count > 0,
4333                    move |this| {
4334                        this.child(
4335                            v_flex()
4336                                .mt_1p5()
4337                                .pt_1p5()
4338                                .pb_0p5()
4339                                .gap_0p5()
4340                                .border_t_1()
4341                                .border_color(cx.theme().colors().border_variant)
4342                                .child(
4343                                    Label::new("Rules")
4344                                        .color(Color::Muted)
4345                                        .size(LabelSize::Small),
4346                                )
4347                                .child(
4348                                    v_flex()
4349                                        .mx_neg_1()
4350                                        .when(user_rules_count > 0, move |this| {
4351                                            this.child(
4352                                                Button::new(
4353                                                    "open-user-rules",
4354                                                    format!("{} user rules", user_rules_count),
4355                                                )
4356                                                .end_icon(
4357                                                    Icon::new(IconName::ArrowUpRight)
4358                                                        .color(Color::Muted)
4359                                                        .size(IconSize::XSmall),
4360                                                )
4361                                                .on_click(move |_, window, cx| {
4362                                                    window.dispatch_action(
4363                                                        Box::new(OpenRulesLibrary {
4364                                                            prompt_to_select: first_user_rules_id,
4365                                                        }),
4366                                                        cx,
4367                                                    );
4368                                                }),
4369                                            )
4370                                        })
4371                                        .when(project_rules_count > 0, move |this| {
4372                                            let workspace = workspace.clone();
4373                                            let project_entry_ids = project_entry_ids.clone();
4374                                            this.child(
4375                                                Button::new(
4376                                                    "open-project-rules",
4377                                                    format!(
4378                                                        "{} project rules",
4379                                                        project_rules_count
4380                                                    ),
4381                                                )
4382                                                .end_icon(
4383                                                    Icon::new(IconName::ArrowUpRight)
4384                                                        .color(Color::Muted)
4385                                                        .size(IconSize::XSmall),
4386                                                )
4387                                                .on_click(move |_, window, cx| {
4388                                                    let _ =
4389                                                        workspace.update(cx, |workspace, cx| {
4390                                                            let project =
4391                                                                workspace.project().read(cx);
4392                                                            let paths = project_entry_ids
4393                                                                .iter()
4394                                                                .flat_map(|id| {
4395                                                                    project.path_for_entry(*id, cx)
4396                                                                })
4397                                                                .collect::<Vec<_>>();
4398                                                            for path in paths {
4399                                                                workspace
4400                                                                    .open_path(
4401                                                                        path, None, true, window,
4402                                                                        cx,
4403                                                                    )
4404                                                                    .detach_and_log_err(cx);
4405                                                            }
4406                                                        });
4407                                                }),
4408                                            )
4409                                        }),
4410                                ),
4411                        )
4412                    },
4413                )
4414        })
4415    }
4416}
4417
4418impl ThreadView {
4419    fn render_entries(&mut self, cx: &mut Context<Self>) -> List {
4420        let max_content_width = AgentSettings::get_global(cx).max_content_width;
4421        let centered_container = move |content: AnyElement| {
4422            h_flex()
4423                .w_full()
4424                .justify_center()
4425                .child(div().max_w(max_content_width).w_full().child(content))
4426        };
4427
4428        list(
4429            self.list_state.clone(),
4430            cx.processor(move |this, index: usize, window, cx| {
4431                let entries = this.thread.read(cx).entries();
4432                if let Some(entry) = entries.get(index) {
4433                    let rendered = this.render_entry(index, entries.len(), entry, window, cx);
4434                    centered_container(rendered.into_any_element()).into_any_element()
4435                } else if this.generating_indicator_in_list {
4436                    let confirmation = entries
4437                        .last()
4438                        .is_some_and(|entry| Self::is_waiting_for_confirmation(entry));
4439                    let rendered = this.render_generating(confirmation, cx);
4440                    centered_container(rendered.into_any_element()).into_any_element()
4441                } else {
4442                    Empty.into_any()
4443                }
4444            }),
4445        )
4446        .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4447        .flex_grow()
4448    }
4449
4450    fn render_entry(
4451        &self,
4452        entry_ix: usize,
4453        total_entries: usize,
4454        entry: &AgentThreadEntry,
4455        window: &Window,
4456        cx: &Context<Self>,
4457    ) -> AnyElement {
4458        let is_indented = entry.is_indented();
4459        let is_first_indented = is_indented
4460            && self
4461                .thread
4462                .read(cx)
4463                .entries()
4464                .get(entry_ix.saturating_sub(1))
4465                .is_none_or(|entry| !entry.is_indented());
4466
4467        let primary = match &entry {
4468            AgentThreadEntry::UserMessage(message) => {
4469                let Some(editor) = self
4470                    .entry_view_state
4471                    .read(cx)
4472                    .entry(entry_ix)
4473                    .and_then(|entry| entry.message_editor())
4474                    .cloned()
4475                else {
4476                    return Empty.into_any_element();
4477                };
4478
4479                let editing = self.editing_message == Some(entry_ix);
4480                let editor_focus = editor.focus_handle(cx).is_focused(window);
4481                let focus_border = cx.theme().colors().border_focused;
4482
4483                let has_checkpoint_button = message
4484                    .checkpoint
4485                    .as_ref()
4486                    .is_some_and(|checkpoint| checkpoint.show);
4487
4488                let is_subagent = self.is_subagent();
4489                let can_rewind = self.thread.read(cx).supports_truncate(cx);
4490                let is_editable = can_rewind && message.id.is_some() && !is_subagent;
4491                let agent_name = if is_subagent {
4492                    "subagents".into()
4493                } else {
4494                    self.agent_id.clone()
4495                };
4496
4497                v_flex()
4498                    .id(("user_message", entry_ix))
4499                    .map(|this| {
4500                        if is_first_indented {
4501                            this.pt_0p5()
4502                        } else {
4503                            this.pt_2()
4504                        }
4505                    })
4506                    .pb_3()
4507                    .px_2()
4508                    .gap_1p5()
4509                    .w_full()
4510                    .when(is_editable && has_checkpoint_button, |this| {
4511                        this.children(message.id.clone().map(|message_id| {
4512                            h_flex()
4513                                .px_3()
4514                                .gap_2()
4515                                .child(Divider::horizontal())
4516                                .child(
4517                                    Button::new("restore-checkpoint", "Restore Checkpoint")
4518                                        .start_icon(Icon::new(IconName::Undo).size(IconSize::XSmall).color(Color::Muted))
4519                                        .label_size(LabelSize::XSmall)
4520                                        .color(Color::Muted)
4521                                        .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
4522                                        .on_click(cx.listener(move |this, _, _window, cx| {
4523                                            this.restore_checkpoint(&message_id, cx);
4524                                        }))
4525                                )
4526                                .child(Divider::horizontal())
4527                        }))
4528                    })
4529                    .child(
4530                        div()
4531                            .relative()
4532                            .child(
4533                                div()
4534                                    .py_3()
4535                                    .px_2()
4536                                    .rounded_md()
4537                                    .bg(cx.theme().colors().editor_background)
4538                                    .border_1()
4539                                    .when(is_indented, |this| {
4540                                        this.py_2().px_2().shadow_sm()
4541                                    })
4542                                    .border_color(cx.theme().colors().border)
4543                                    .map(|this| {
4544                                        if !is_editable {
4545                                            if is_subagent {
4546                                                return this.border_dashed();
4547                                            }
4548                                            return this;
4549                                        }
4550                                        if editing && editor_focus {
4551                                            return this.border_color(focus_border);
4552                                        }
4553                                        if editing && !editor_focus {
4554                                            return this.border_dashed()
4555                                        }
4556                                        this.shadow_md().hover(|s| {
4557                                            s.border_color(focus_border.opacity(0.8))
4558                                        })
4559                                    })
4560                                    .text_xs()
4561                                    .child(editor.clone().into_any_element())
4562                            )
4563                            .when(editor_focus, |this| {
4564                                let base_container = h_flex()
4565                                    .absolute()
4566                                    .top_neg_3p5()
4567                                    .right_3()
4568                                    .gap_1()
4569                                    .rounded_sm()
4570                                    .border_1()
4571                                    .border_color(cx.theme().colors().border)
4572                                    .bg(cx.theme().colors().editor_background)
4573                                    .overflow_hidden();
4574
4575                                let is_loading_contents = self.is_loading_contents;
4576                                if is_editable {
4577                                    this.child(
4578                                        base_container
4579                                            .child(
4580                                                IconButton::new("cancel", IconName::Close)
4581                                                    .disabled(is_loading_contents)
4582                                                    .icon_color(Color::Error)
4583                                                    .icon_size(IconSize::XSmall)
4584                                                    .on_click(cx.listener(Self::cancel_editing))
4585                                            )
4586                                            .child(
4587                                                if is_loading_contents {
4588                                                    div()
4589                                                        .id("loading-edited-message-content")
4590                                                        .tooltip(Tooltip::text("Loading Added Context…"))
4591                                                        .child(loading_contents_spinner(IconSize::XSmall))
4592                                                        .into_any_element()
4593                                                } else {
4594                                                    IconButton::new("regenerate", IconName::Return)
4595                                                        .icon_color(Color::Muted)
4596                                                        .icon_size(IconSize::XSmall)
4597                                                        .tooltip(Tooltip::text(
4598                                                            "Editing will restart the thread from this point."
4599                                                        ))
4600                                                        .on_click(cx.listener({
4601                                                            let editor = editor.clone();
4602                                                            move |this, _, window, cx| {
4603                                                                this.regenerate(
4604                                                                    entry_ix, editor.clone(), window, cx,
4605                                                                );
4606                                                            }
4607                                                        })).into_any_element()
4608                                                }
4609                                            )
4610                                    )
4611                                } else {
4612                                    this.child(
4613                                        base_container
4614                                            .border_dashed()
4615                                            .child(IconButton::new("non_editable", IconName::PencilUnavailable)
4616                                                .icon_size(IconSize::Small)
4617                                                .icon_color(Color::Muted)
4618                                                .style(ButtonStyle::Transparent)
4619                                                .tooltip(Tooltip::element({
4620                                                    let agent_name = agent_name.clone();
4621                                                    move |_, _| {
4622                                                        v_flex()
4623                                                            .gap_1()
4624                                                            .child(Label::new("Unavailable Editing"))
4625                                                            .child(
4626                                                                div().max_w_64().child(
4627                                                                    Label::new(format!(
4628                                                                        "Editing previous messages is not available for {} yet.",
4629                                                                        agent_name
4630                                                                    ))
4631                                                                    .size(LabelSize::Small)
4632                                                                    .color(Color::Muted),
4633                                                                ),
4634                                                            )
4635                                                            .into_any_element()
4636                                                    }
4637                                                }))),
4638                                    )
4639                                }
4640                            }),
4641                    )
4642                    .into_any()
4643            }
4644            AgentThreadEntry::AssistantMessage(AssistantMessage {
4645                chunks,
4646                indented: _,
4647                is_subagent_output: _,
4648            }) => {
4649                let mut is_blank = true;
4650                let is_last = entry_ix + 1 == total_entries;
4651
4652                let style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
4653                let message_body = v_flex()
4654                    .w_full()
4655                    .gap_3()
4656                    .children(chunks.iter().enumerate().filter_map(
4657                        |(chunk_ix, chunk)| match chunk {
4658                            AssistantMessageChunk::Message { block } => {
4659                                block.markdown().and_then(|md| {
4660                                    let this_is_blank = md.read(cx).source().trim().is_empty();
4661                                    is_blank = is_blank && this_is_blank;
4662                                    if this_is_blank {
4663                                        return None;
4664                                    }
4665
4666                                    Some(
4667                                        self.render_markdown(md.clone(), style.clone())
4668                                            .into_any_element(),
4669                                    )
4670                                })
4671                            }
4672                            AssistantMessageChunk::Thought { block } => {
4673                                block.markdown().and_then(|md| {
4674                                    let this_is_blank = md.read(cx).source().trim().is_empty();
4675                                    is_blank = is_blank && this_is_blank;
4676                                    if this_is_blank {
4677                                        return None;
4678                                    }
4679                                    Some(
4680                                        self.render_thinking_block(
4681                                            entry_ix,
4682                                            chunk_ix,
4683                                            md.clone(),
4684                                            window,
4685                                            cx,
4686                                        )
4687                                        .into_any_element(),
4688                                    )
4689                                })
4690                            }
4691                        },
4692                    ))
4693                    .into_any();
4694
4695                if is_blank {
4696                    Empty.into_any()
4697                } else {
4698                    v_flex()
4699                        .px_5()
4700                        .py_1p5()
4701                        .when(is_last, |this| this.pb_4())
4702                        .w_full()
4703                        .text_ui(cx)
4704                        .child(self.render_message_context_menu(entry_ix, message_body, cx))
4705                        .when_some(
4706                            self.entry_view_state
4707                                .read(cx)
4708                                .entry(entry_ix)
4709                                .and_then(|entry| entry.focus_handle(cx)),
4710                            |this, handle| this.track_focus(&handle),
4711                        )
4712                        .into_any()
4713                }
4714            }
4715            AgentThreadEntry::ToolCall(tool_call) => self
4716                .render_any_tool_call(
4717                    self.thread.read(cx).session_id(),
4718                    entry_ix,
4719                    tool_call,
4720                    &self.focus_handle(cx),
4721                    false,
4722                    window,
4723                    cx,
4724                )
4725                .into_any(),
4726            AgentThreadEntry::CompletedPlan(entries) => {
4727                self.render_completed_plan(entries, window, cx)
4728            }
4729        };
4730
4731        let is_subagent_output = self.is_subagent()
4732            && matches!(entry, AgentThreadEntry::AssistantMessage(msg) if msg.is_subagent_output);
4733
4734        let primary = if is_subagent_output {
4735            v_flex()
4736                .w_full()
4737                .child(
4738                    h_flex()
4739                        .id("subagent_output")
4740                        .px_5()
4741                        .py_1()
4742                        .gap_2()
4743                        .child(Divider::horizontal())
4744                        .child(
4745                            h_flex()
4746                                .gap_1()
4747                                .child(
4748                                    Icon::new(IconName::ForwardArrowUp)
4749                                        .color(Color::Muted)
4750                                        .size(IconSize::Small),
4751                                )
4752                                .child(
4753                                    Label::new("Subagent Output")
4754                                        .size(LabelSize::Custom(self.tool_name_font_size()))
4755                                        .color(Color::Muted),
4756                                ),
4757                        )
4758                        .child(Divider::horizontal())
4759                        .tooltip(Tooltip::text("Everything below this line was sent as output from this subagent to the main agent.")),
4760                )
4761                .child(primary)
4762                .into_any_element()
4763        } else {
4764            primary
4765        };
4766
4767        let thread = self.thread.clone();
4768
4769        let primary = if is_indented {
4770            let line_top = if is_first_indented {
4771                rems_from_px(-12.0)
4772            } else {
4773                rems_from_px(0.0)
4774            };
4775
4776            div()
4777                .relative()
4778                .w_full()
4779                .pl_5()
4780                .bg(cx.theme().colors().panel_background.opacity(0.2))
4781                .child(
4782                    div()
4783                        .absolute()
4784                        .left(rems_from_px(18.0))
4785                        .top(line_top)
4786                        .bottom_0()
4787                        .w_px()
4788                        .bg(cx.theme().colors().border.opacity(0.6)),
4789                )
4790                .child(primary)
4791                .into_any_element()
4792        } else {
4793            primary
4794        };
4795
4796        let needs_confirmation = Self::is_waiting_for_confirmation(entry);
4797
4798        let comments_editor = self.thread_feedback.comments_editor.clone();
4799
4800        let primary = if entry_ix + 1 == total_entries {
4801            v_flex()
4802                .w_full()
4803                .child(primary)
4804                .when(!needs_confirmation, |this| {
4805                    this.child(self.render_thread_controls(&thread, cx))
4806                })
4807                .when_some(comments_editor, |this, editor| {
4808                    this.child(Self::render_feedback_feedback_editor(editor, cx))
4809                })
4810                .into_any_element()
4811        } else {
4812            primary
4813        };
4814
4815        if let Some(editing_index) = self.editing_message
4816            && editing_index < entry_ix
4817        {
4818            let is_subagent = self.is_subagent();
4819
4820            let backdrop = div()
4821                .id(("backdrop", entry_ix))
4822                .size_full()
4823                .absolute()
4824                .inset_0()
4825                .bg(cx.theme().colors().panel_background)
4826                .opacity(0.8)
4827                .block_mouse_except_scroll()
4828                .on_click(cx.listener(Self::cancel_editing));
4829
4830            div()
4831                .relative()
4832                .child(primary)
4833                .when(!is_subagent, |this| this.child(backdrop))
4834                .into_any_element()
4835        } else {
4836            primary
4837        }
4838    }
4839
4840    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4841        h_flex()
4842            .key_context("AgentFeedbackMessageEditor")
4843            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4844                this.thread_feedback.dismiss_comments();
4845                cx.notify();
4846            }))
4847            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4848                this.submit_feedback_message(cx);
4849            }))
4850            .p_2()
4851            .mb_2()
4852            .mx_5()
4853            .gap_1()
4854            .rounded_md()
4855            .border_1()
4856            .border_color(cx.theme().colors().border)
4857            .bg(cx.theme().colors().editor_background)
4858            .child(div().w_full().child(editor))
4859            .child(
4860                h_flex()
4861                    .child(
4862                        IconButton::new("dismiss-feedback-message", IconName::Close)
4863                            .icon_color(Color::Error)
4864                            .icon_size(IconSize::XSmall)
4865                            .shape(ui::IconButtonShape::Square)
4866                            .on_click(cx.listener(move |this, _, _window, cx| {
4867                                this.thread_feedback.dismiss_comments();
4868                                cx.notify();
4869                            })),
4870                    )
4871                    .child(
4872                        IconButton::new("submit-feedback-message", IconName::Return)
4873                            .icon_size(IconSize::XSmall)
4874                            .shape(ui::IconButtonShape::Square)
4875                            .on_click(cx.listener(move |this, _, _window, cx| {
4876                                this.submit_feedback_message(cx);
4877                            })),
4878                    ),
4879            )
4880    }
4881
4882    fn render_thread_controls(
4883        &self,
4884        thread: &Entity<AcpThread>,
4885        cx: &Context<Self>,
4886    ) -> impl IntoElement {
4887        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4888        if is_generating {
4889            return Empty.into_any_element();
4890        }
4891
4892        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4893            .shape(ui::IconButtonShape::Square)
4894            .icon_size(IconSize::Small)
4895            .icon_color(Color::Ignored)
4896            .tooltip(Tooltip::text("Open Thread as Markdown"))
4897            .on_click(cx.listener(move |this, _, window, cx| {
4898                if let Some(workspace) = this.workspace.upgrade() {
4899                    this.open_thread_as_markdown(workspace, window, cx)
4900                        .detach_and_log_err(cx);
4901                }
4902            }));
4903
4904        let scroll_to_recent_user_prompt =
4905            IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
4906                .shape(ui::IconButtonShape::Square)
4907                .icon_size(IconSize::Small)
4908                .icon_color(Color::Ignored)
4909                .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
4910                .on_click(cx.listener(move |this, _, _, cx| {
4911                    this.scroll_to_most_recent_user_prompt(cx);
4912                }));
4913
4914        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4915            .shape(ui::IconButtonShape::Square)
4916            .icon_size(IconSize::Small)
4917            .icon_color(Color::Ignored)
4918            .tooltip(Tooltip::text("Scroll To Top"))
4919            .on_click(cx.listener(move |this, _, _, cx| {
4920                this.scroll_to_top(cx);
4921            }));
4922
4923        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
4924        let last_turn_clock = show_stats
4925            .then(|| {
4926                self.turn_fields
4927                    .last_turn_duration
4928                    .filter(|&duration| duration > STOPWATCH_THRESHOLD)
4929                    .map(|duration| {
4930                        Label::new(duration_alt_display(duration))
4931                            .size(LabelSize::Small)
4932                            .color(Color::Muted)
4933                    })
4934            })
4935            .flatten();
4936
4937        let last_turn_tokens_label = last_turn_clock
4938            .is_some()
4939            .then(|| {
4940                self.turn_fields
4941                    .last_turn_tokens
4942                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4943                    .map(|tokens| {
4944                        Label::new(format!("{} tokens", crate::humanize_token_count(tokens)))
4945                            .size(LabelSize::Small)
4946                            .color(Color::Muted)
4947                    })
4948            })
4949            .flatten();
4950
4951        let mut container = h_flex()
4952            .w_full()
4953            .py_2()
4954            .px_5()
4955            .gap_px()
4956            .opacity(0.6)
4957            .hover(|s| s.opacity(1.))
4958            .justify_end()
4959            .when(
4960                last_turn_tokens_label.is_some() || last_turn_clock.is_some(),
4961                |this| {
4962                    this.child(
4963                        h_flex()
4964                            .gap_1()
4965                            .px_1()
4966                            .when_some(last_turn_tokens_label, |this, label| this.child(label))
4967                            .when_some(last_turn_clock, |this, label| this.child(label)),
4968                    )
4969                },
4970            );
4971
4972        let enable_thread_feedback = util::maybe!({
4973            let project = thread.read(cx).project().read(cx);
4974            let user_store = project.user_store();
4975            if let Some(configuration) = user_store.read(cx).current_organization_configuration() {
4976                if !configuration.is_agent_thread_feedback_enabled {
4977                    return false;
4978                }
4979            }
4980
4981            AgentSettings::get_global(cx).enable_feedback
4982                && self.thread.read(cx).connection().telemetry().is_some()
4983        });
4984
4985        if enable_thread_feedback {
4986            let feedback = self.thread_feedback.feedback;
4987
4988            let tooltip_meta = || {
4989                SharedString::new(
4990                    "Rating the thread sends all of your current conversation to the Zed team.",
4991                )
4992            };
4993
4994            container = container
4995                    .child(
4996                        IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4997                            .shape(ui::IconButtonShape::Square)
4998                            .icon_size(IconSize::Small)
4999                            .icon_color(match feedback {
5000                                Some(ThreadFeedback::Positive) => Color::Accent,
5001                                _ => Color::Ignored,
5002                            })
5003                            .tooltip(move |window, cx| match feedback {
5004                                Some(ThreadFeedback::Positive) => {
5005                                    Tooltip::text("Thanks for your feedback!")(window, cx)
5006                                }
5007                                _ => {
5008                                    Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx)
5009                                }
5010                            })
5011                            .on_click(cx.listener(move |this, _, window, cx| {
5012                                this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5013                            })),
5014                    )
5015                    .child(
5016                        IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5017                            .shape(ui::IconButtonShape::Square)
5018                            .icon_size(IconSize::Small)
5019                            .icon_color(match feedback {
5020                                Some(ThreadFeedback::Negative) => Color::Accent,
5021                                _ => Color::Ignored,
5022                            })
5023                            .tooltip(move |window, cx| match feedback {
5024                                Some(ThreadFeedback::Negative) => {
5025                                    Tooltip::text(
5026                                    "We appreciate your feedback and will use it to improve in the future.",
5027                                )(window, cx)
5028                                }
5029                                _ => {
5030                                    Tooltip::with_meta(
5031                                        "Not Helpful Response",
5032                                        None,
5033                                        tooltip_meta(),
5034                                        cx,
5035                                    )
5036                                }
5037                            })
5038                            .on_click(cx.listener(move |this, _, window, cx| {
5039                                this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5040                            })),
5041                    );
5042        }
5043
5044        if let Some(project) = self.project.upgrade()
5045            && let Some(server_view) = self.server_view.upgrade()
5046            && cx.has_flag::<AgentSharingFeatureFlag>()
5047            && project.read(cx).client().status().borrow().is_connected()
5048        {
5049            let button = if self.is_imported_thread(cx) {
5050                IconButton::new("sync-thread", IconName::ArrowCircle)
5051                    .shape(ui::IconButtonShape::Square)
5052                    .icon_size(IconSize::Small)
5053                    .icon_color(Color::Ignored)
5054                    .tooltip(Tooltip::text("Sync with source thread"))
5055                    .on_click(cx.listener(move |this, _, window, cx| {
5056                        this.sync_thread(project.clone(), server_view.clone(), window, cx);
5057                    }))
5058            } else {
5059                IconButton::new("share-thread", IconName::ArrowUpRight)
5060                    .shape(ui::IconButtonShape::Square)
5061                    .icon_size(IconSize::Small)
5062                    .icon_color(Color::Ignored)
5063                    .tooltip(Tooltip::text("Share Thread"))
5064                    .on_click(cx.listener(move |this, _, window, cx| {
5065                        this.share_thread(window, cx);
5066                    }))
5067            };
5068
5069            container = container.child(button);
5070        }
5071
5072        container
5073            .child(open_as_markdown)
5074            .child(scroll_to_recent_user_prompt)
5075            .child(scroll_to_top)
5076            .into_any_element()
5077    }
5078
5079    pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
5080        let entries = self.thread.read(cx).entries();
5081        if entries.is_empty() {
5082            return;
5083        }
5084
5085        // Find the most recent user message and scroll it to the top of the viewport.
5086        // (Fallback: if no user message exists, scroll to the bottom.)
5087        if let Some(ix) = entries
5088            .iter()
5089            .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
5090        {
5091            self.list_state.scroll_to(ListOffset {
5092                item_ix: ix,
5093                offset_in_item: px(0.0),
5094            });
5095            cx.notify();
5096        } else {
5097            self.scroll_to_end(cx);
5098        }
5099    }
5100
5101    pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
5102        self.list_state.scroll_to_end();
5103        cx.notify();
5104    }
5105
5106    fn handle_feedback_click(
5107        &mut self,
5108        feedback: ThreadFeedback,
5109        window: &mut Window,
5110        cx: &mut Context<Self>,
5111    ) {
5112        self.thread_feedback
5113            .submit(self.thread.clone(), feedback, window, cx);
5114        cx.notify();
5115    }
5116
5117    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5118        let thread = self.thread.clone();
5119        self.thread_feedback.submit_comments(thread, cx);
5120        cx.notify();
5121    }
5122
5123    pub(crate) fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
5124        self.list_state.scroll_to(ListOffset::default());
5125        cx.notify();
5126    }
5127
5128    fn scroll_output_page_up(
5129        &mut self,
5130        _: &ScrollOutputPageUp,
5131        _window: &mut Window,
5132        cx: &mut Context<Self>,
5133    ) {
5134        let page_height = self.list_state.viewport_bounds().size.height;
5135        self.list_state.scroll_by(-page_height * 0.9);
5136        cx.notify();
5137    }
5138
5139    fn scroll_output_page_down(
5140        &mut self,
5141        _: &ScrollOutputPageDown,
5142        _window: &mut Window,
5143        cx: &mut Context<Self>,
5144    ) {
5145        let page_height = self.list_state.viewport_bounds().size.height;
5146        self.list_state.scroll_by(page_height * 0.9);
5147        cx.notify();
5148    }
5149
5150    fn scroll_output_line_up(
5151        &mut self,
5152        _: &ScrollOutputLineUp,
5153        window: &mut Window,
5154        cx: &mut Context<Self>,
5155    ) {
5156        self.list_state.scroll_by(-window.line_height() * 3.);
5157        cx.notify();
5158    }
5159
5160    fn scroll_output_line_down(
5161        &mut self,
5162        _: &ScrollOutputLineDown,
5163        window: &mut Window,
5164        cx: &mut Context<Self>,
5165    ) {
5166        self.list_state.scroll_by(window.line_height() * 3.);
5167        cx.notify();
5168    }
5169
5170    fn scroll_output_to_top(
5171        &mut self,
5172        _: &ScrollOutputToTop,
5173        _window: &mut Window,
5174        cx: &mut Context<Self>,
5175    ) {
5176        self.scroll_to_top(cx);
5177    }
5178
5179    fn scroll_output_to_bottom(
5180        &mut self,
5181        _: &ScrollOutputToBottom,
5182        _window: &mut Window,
5183        cx: &mut Context<Self>,
5184    ) {
5185        self.scroll_to_end(cx);
5186    }
5187
5188    fn scroll_output_to_previous_message(
5189        &mut self,
5190        _: &ScrollOutputToPreviousMessage,
5191        _window: &mut Window,
5192        cx: &mut Context<Self>,
5193    ) {
5194        let entries = self.thread.read(cx).entries();
5195        let current_ix = self.list_state.logical_scroll_top().item_ix;
5196        if let Some(target_ix) = (0..current_ix)
5197            .rev()
5198            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5199        {
5200            self.list_state.scroll_to(ListOffset {
5201                item_ix: target_ix,
5202                offset_in_item: px(0.),
5203            });
5204            cx.notify();
5205        }
5206    }
5207
5208    fn scroll_output_to_next_message(
5209        &mut self,
5210        _: &ScrollOutputToNextMessage,
5211        _window: &mut Window,
5212        cx: &mut Context<Self>,
5213    ) {
5214        let entries = self.thread.read(cx).entries();
5215        let current_ix = self.list_state.logical_scroll_top().item_ix;
5216        if let Some(target_ix) = (current_ix + 1..entries.len())
5217            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5218        {
5219            self.list_state.scroll_to(ListOffset {
5220                item_ix: target_ix,
5221                offset_in_item: px(0.),
5222            });
5223            cx.notify();
5224        }
5225    }
5226
5227    pub fn open_thread_as_markdown(
5228        &self,
5229        workspace: Entity<Workspace>,
5230        window: &mut Window,
5231        cx: &mut App,
5232    ) -> Task<Result<()>> {
5233        let markdown_language_task = workspace
5234            .read(cx)
5235            .app_state()
5236            .languages
5237            .language_for_name("Markdown");
5238
5239        let thread = self.thread.read(cx);
5240        let thread_title = thread
5241            .title()
5242            .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into())
5243            .to_string();
5244        let markdown = thread.to_markdown(cx);
5245
5246        let project = workspace.read(cx).project().clone();
5247        window.spawn(cx, async move |cx| {
5248            let markdown_language = markdown_language_task.await?;
5249
5250            let buffer = project
5251                .update(cx, |project, cx| {
5252                    project.create_buffer(Some(markdown_language), false, cx)
5253                })
5254                .await?;
5255
5256            buffer.update(cx, |buffer, cx| {
5257                buffer.set_text(markdown, cx);
5258                buffer.set_capability(language::Capability::ReadWrite, cx);
5259            });
5260
5261            workspace.update_in(cx, |workspace, window, cx| {
5262                let buffer = cx
5263                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5264
5265                workspace.add_item_to_active_pane(
5266                    Box::new(cx.new(|cx| {
5267                        let mut editor =
5268                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5269                        editor.set_breadcrumb_header(thread_title);
5270                        editor.disable_mouse_wheel_zoom();
5271                        editor
5272                    })),
5273                    None,
5274                    true,
5275                    window,
5276                    cx,
5277                );
5278            })?;
5279            anyhow::Ok(())
5280        })
5281    }
5282
5283    pub(crate) fn sync_editor_mode_for_empty_state(&mut self, cx: &mut Context<Self>) {
5284        let has_messages = self.list_state.item_count() > 0;
5285        let v2_empty_state = !has_messages;
5286
5287        let mode = if v2_empty_state {
5288            EditorMode::Full {
5289                scale_ui_elements_with_buffer_font_size: false,
5290                show_active_line_background: false,
5291                sizing_behavior: SizingBehavior::Default,
5292            }
5293        } else {
5294            EditorMode::AutoHeight {
5295                min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
5296                max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
5297            }
5298        };
5299        self.message_editor.update(cx, |editor, cx| {
5300            editor.set_mode(mode, cx);
5301        });
5302    }
5303
5304    /// Ensures the list item count includes (or excludes) an extra item for the generating indicator
5305    pub(crate) fn sync_generating_indicator(&mut self, cx: &App) {
5306        let is_generating = matches!(self.thread.read(cx).status(), ThreadStatus::Generating);
5307
5308        if is_generating && !self.generating_indicator_in_list {
5309            let entries_count = self.thread.read(cx).entries().len();
5310            self.list_state.splice(entries_count..entries_count, 1);
5311            self.generating_indicator_in_list = true;
5312        } else if !is_generating && self.generating_indicator_in_list {
5313            let entries_count = self.thread.read(cx).entries().len();
5314            self.list_state.splice(entries_count..entries_count + 1, 0);
5315            self.generating_indicator_in_list = false;
5316        }
5317    }
5318
5319    fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
5320        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
5321        let elapsed_label = show_stats
5322            .then(|| {
5323                self.turn_fields.turn_started_at.and_then(|started_at| {
5324                    let elapsed = started_at.elapsed();
5325                    (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
5326                })
5327            })
5328            .flatten();
5329
5330        let is_blocked_on_terminal_command =
5331            !confirmation && self.is_blocked_on_terminal_command(cx);
5332        let is_waiting = confirmation || self.thread.read(cx).has_in_progress_tool_calls();
5333
5334        let turn_tokens_label = elapsed_label
5335            .is_some()
5336            .then(|| {
5337                self.turn_fields
5338                    .turn_tokens
5339                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
5340                    .map(|tokens| crate::humanize_token_count(tokens))
5341            })
5342            .flatten();
5343
5344        let arrow_icon = if is_waiting {
5345            IconName::ArrowUp
5346        } else {
5347            IconName::ArrowDown
5348        };
5349
5350        h_flex()
5351            .id("generating-spinner")
5352            .py_2()
5353            .px(rems_from_px(22.))
5354            .gap_2()
5355            .map(|this| {
5356                if confirmation {
5357                    this.child(
5358                        h_flex()
5359                            .w_2()
5360                            .justify_center()
5361                            .child(GeneratingSpinnerElement::new(SpinnerVariant::Sand)),
5362                    )
5363                    .child(
5364                        div().min_w(rems(8.)).child(
5365                            LoadingLabel::new("Awaiting Confirmation")
5366                                .size(LabelSize::Small)
5367                                .color(Color::Muted),
5368                        ),
5369                    )
5370                } else if is_blocked_on_terminal_command {
5371                    this
5372                } else {
5373                    this.child(
5374                        h_flex()
5375                            .w_2()
5376                            .justify_center()
5377                            .child(GeneratingSpinnerElement::new(SpinnerVariant::Dots)),
5378                    )
5379                }
5380            })
5381            .when_some(elapsed_label, |this, elapsed| {
5382                this.child(
5383                    Label::new(elapsed)
5384                        .size(LabelSize::Small)
5385                        .color(Color::Muted),
5386                )
5387            })
5388            .when_some(turn_tokens_label, |this, tokens| {
5389                this.child(
5390                    h_flex()
5391                        .gap_0p5()
5392                        .child(
5393                            Icon::new(arrow_icon)
5394                                .size(IconSize::XSmall)
5395                                .color(Color::Muted),
5396                        )
5397                        .child(
5398                            Label::new(format!("{} tokens", tokens))
5399                                .size(LabelSize::Small)
5400                                .color(Color::Muted),
5401                        ),
5402                )
5403            })
5404            .into_any_element()
5405    }
5406
5407    pub(crate) fn auto_expand_streaming_thought(&mut self, cx: &mut Context<Self>) {
5408        let thinking_display = AgentSettings::get_global(cx).thinking_display;
5409
5410        if !matches!(
5411            thinking_display,
5412            ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
5413        ) {
5414            return;
5415        }
5416
5417        let key = {
5418            let thread = self.thread.read(cx);
5419            if thread.status() != ThreadStatus::Generating {
5420                return;
5421            }
5422            let entries = thread.entries();
5423            let last_ix = entries.len().saturating_sub(1);
5424            match entries.get(last_ix) {
5425                Some(AgentThreadEntry::AssistantMessage(msg)) => match msg.chunks.last() {
5426                    Some(AssistantMessageChunk::Thought { .. }) => {
5427                        Some((last_ix, msg.chunks.len() - 1))
5428                    }
5429                    _ => None,
5430                },
5431                _ => None,
5432            }
5433        };
5434
5435        if let Some(key) = key {
5436            if self.auto_expanded_thinking_block != Some(key) {
5437                self.auto_expanded_thinking_block = Some(key);
5438                self.expanded_thinking_blocks.insert(key);
5439                cx.notify();
5440            }
5441        } else if self.auto_expanded_thinking_block.is_some() {
5442            if thinking_display == ThinkingBlockDisplay::Auto {
5443                if let Some(key) = self.auto_expanded_thinking_block {
5444                    if !self.user_toggled_thinking_blocks.contains(&key) {
5445                        self.expanded_thinking_blocks.remove(&key);
5446                    }
5447                }
5448            }
5449            self.auto_expanded_thinking_block = None;
5450            cx.notify();
5451        }
5452    }
5453
5454    pub(crate) fn clear_auto_expand_tracking(&mut self) {
5455        self.auto_expanded_thinking_block = None;
5456    }
5457
5458    fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &mut Context<Self>) {
5459        let thinking_display = AgentSettings::get_global(cx).thinking_display;
5460
5461        match thinking_display {
5462            ThinkingBlockDisplay::Auto => {
5463                let is_open = self.expanded_thinking_blocks.contains(&key)
5464                    || self.user_toggled_thinking_blocks.contains(&key);
5465
5466                if is_open {
5467                    self.expanded_thinking_blocks.remove(&key);
5468                    self.user_toggled_thinking_blocks.remove(&key);
5469                } else {
5470                    self.expanded_thinking_blocks.insert(key);
5471                    self.user_toggled_thinking_blocks.insert(key);
5472                }
5473            }
5474            ThinkingBlockDisplay::Preview => {
5475                let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
5476                let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5477
5478                if is_user_expanded {
5479                    self.user_toggled_thinking_blocks.remove(&key);
5480                    self.expanded_thinking_blocks.remove(&key);
5481                } else if is_in_expanded_set {
5482                    self.user_toggled_thinking_blocks.insert(key);
5483                } else {
5484                    self.expanded_thinking_blocks.insert(key);
5485                    self.user_toggled_thinking_blocks.insert(key);
5486                }
5487            }
5488            ThinkingBlockDisplay::AlwaysExpanded => {
5489                if self.user_toggled_thinking_blocks.contains(&key) {
5490                    self.user_toggled_thinking_blocks.remove(&key);
5491                } else {
5492                    self.user_toggled_thinking_blocks.insert(key);
5493                }
5494            }
5495            ThinkingBlockDisplay::AlwaysCollapsed => {
5496                if self.user_toggled_thinking_blocks.contains(&key) {
5497                    self.user_toggled_thinking_blocks.remove(&key);
5498                    self.expanded_thinking_blocks.remove(&key);
5499                } else {
5500                    self.expanded_thinking_blocks.insert(key);
5501                    self.user_toggled_thinking_blocks.insert(key);
5502                }
5503            }
5504        }
5505
5506        cx.notify();
5507    }
5508
5509    fn render_thinking_block(
5510        &self,
5511        entry_ix: usize,
5512        chunk_ix: usize,
5513        chunk: Entity<Markdown>,
5514        window: &Window,
5515        cx: &Context<Self>,
5516    ) -> AnyElement {
5517        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
5518        let card_header_id = SharedString::from("inner-card-header");
5519
5520        let key = (entry_ix, chunk_ix);
5521
5522        let thinking_display = AgentSettings::get_global(cx).thinking_display;
5523        let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
5524        let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5525
5526        let (is_open, is_constrained) = match thinking_display {
5527            ThinkingBlockDisplay::Auto => {
5528                let is_open = is_user_toggled || is_in_expanded_set;
5529                (is_open, false)
5530            }
5531            ThinkingBlockDisplay::Preview => {
5532                let is_open = is_user_toggled || is_in_expanded_set;
5533                let is_constrained = is_in_expanded_set && !is_user_toggled;
5534                (is_open, is_constrained)
5535            }
5536            ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
5537            ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
5538        };
5539
5540        let should_auto_scroll = self.auto_expanded_thinking_block == Some(key);
5541
5542        let scroll_handle = self
5543            .entry_view_state
5544            .read(cx)
5545            .entry(entry_ix)
5546            .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
5547
5548        if should_auto_scroll {
5549            if let Some(ref handle) = scroll_handle {
5550                handle.scroll_to_bottom();
5551            }
5552        }
5553
5554        let panel_bg = cx.theme().colors().panel_background;
5555
5556        v_flex()
5557            .gap_1()
5558            .child(
5559                h_flex()
5560                    .id(header_id)
5561                    .group(&card_header_id)
5562                    .relative()
5563                    .w_full()
5564                    .pr_1()
5565                    .justify_between()
5566                    .child(
5567                        h_flex()
5568                            .h(window.line_height() - px(2.))
5569                            .gap_1p5()
5570                            .overflow_hidden()
5571                            .child(
5572                                Icon::new(IconName::ToolThink)
5573                                    .size(IconSize::Small)
5574                                    .color(Color::Muted),
5575                            )
5576                            .child(
5577                                div()
5578                                    .text_size(self.tool_name_font_size())
5579                                    .text_color(cx.theme().colors().text_muted)
5580                                    .child("Thinking"),
5581                            ),
5582                    )
5583                    .child(
5584                        Disclosure::new(("expand", entry_ix), is_open)
5585                            .opened_icon(IconName::ChevronUp)
5586                            .closed_icon(IconName::ChevronDown)
5587                            .visible_on_hover(&card_header_id)
5588                            .on_click(cx.listener(
5589                                move |this, _event: &ClickEvent, _window, cx| {
5590                                    this.toggle_thinking_block_expansion(key, cx);
5591                                },
5592                            )),
5593                    )
5594                    .on_click(cx.listener(move |this, _event: &ClickEvent, _window, cx| {
5595                        this.toggle_thinking_block_expansion(key, cx);
5596                    })),
5597            )
5598            .when(is_open, |this| {
5599                this.child(
5600                    div()
5601                        .when(is_constrained, |this| this.relative())
5602                        .child(
5603                            div()
5604                                .id(("thinking-content", chunk_ix))
5605                                .ml_1p5()
5606                                .pl_3p5()
5607                                .border_l_1()
5608                                .border_color(self.tool_card_border_color(cx))
5609                                .when(is_constrained, |this| this.max_h_64())
5610                                .when_some(scroll_handle, |this, scroll_handle| {
5611                                    this.track_scroll(&scroll_handle)
5612                                })
5613                                .overflow_hidden()
5614                                .child(self.render_markdown(
5615                                    chunk,
5616                                    MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
5617                                )),
5618                        )
5619                        .when(is_constrained, |this| {
5620                            this.child(
5621                                div()
5622                                    .absolute()
5623                                    .inset_0()
5624                                    .size_full()
5625                                    .bg(linear_gradient(
5626                                        180.,
5627                                        linear_color_stop(panel_bg.opacity(0.8), 0.),
5628                                        linear_color_stop(panel_bg.opacity(0.), 0.1),
5629                                    ))
5630                                    .block_mouse_except_scroll(),
5631                            )
5632                        }),
5633                )
5634            })
5635            .into_any_element()
5636    }
5637
5638    fn render_message_context_menu(
5639        &self,
5640        entry_ix: usize,
5641        message_body: AnyElement,
5642        cx: &Context<Self>,
5643    ) -> AnyElement {
5644        let entity = cx.entity();
5645        let workspace = self.workspace.clone();
5646
5647        right_click_menu(format!("agent_context_menu-{}", entry_ix))
5648            .trigger(move |_, _, _| message_body)
5649            .menu(move |window, cx| {
5650                let focus = window.focused(cx);
5651                let entity = entity.clone();
5652                let workspace = workspace.clone();
5653
5654                ContextMenu::build(window, cx, move |menu, _, cx| {
5655                    let this = entity.read(cx);
5656                    let is_at_top = this.list_state.logical_scroll_top().item_ix == 0;
5657
5658                    let has_selection = this
5659                        .thread
5660                        .read(cx)
5661                        .entries()
5662                        .get(entry_ix)
5663                        .and_then(|entry| match &entry {
5664                            AgentThreadEntry::AssistantMessage(msg) => Some(&msg.chunks),
5665                            _ => None,
5666                        })
5667                        .map(|chunks| {
5668                            chunks.iter().any(|chunk| {
5669                                let md = match chunk {
5670                                    AssistantMessageChunk::Message { block } => block.markdown(),
5671                                    AssistantMessageChunk::Thought { block } => block.markdown(),
5672                                };
5673                                md.map_or(false, |m| m.read(cx).selected_text().is_some())
5674                            })
5675                        })
5676                        .unwrap_or(false);
5677
5678                    let copy_this_agent_response =
5679                        ContextMenuEntry::new("Copy This Agent Response").handler({
5680                            let entity = entity.clone();
5681                            move |_, cx| {
5682                                entity.update(cx, |this, cx| {
5683                                    let entries = this.thread.read(cx).entries();
5684                                    if let Some(text) =
5685                                        Self::get_agent_message_content(entries, entry_ix, cx)
5686                                    {
5687                                        cx.write_to_clipboard(ClipboardItem::new_string(text));
5688                                    }
5689                                });
5690                            }
5691                        });
5692
5693                    let scroll_item = if is_at_top {
5694                        ContextMenuEntry::new("Scroll to Bottom").handler({
5695                            let entity = entity.clone();
5696                            move |_, cx| {
5697                                entity.update(cx, |this, cx| {
5698                                    this.scroll_to_end(cx);
5699                                });
5700                            }
5701                        })
5702                    } else {
5703                        ContextMenuEntry::new("Scroll to Top").handler({
5704                            let entity = entity.clone();
5705                            move |_, cx| {
5706                                entity.update(cx, |this, cx| {
5707                                    this.scroll_to_top(cx);
5708                                });
5709                            }
5710                        })
5711                    };
5712
5713                    let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
5714                        .handler({
5715                            let entity = entity.clone();
5716                            let workspace = workspace.clone();
5717                            move |window, cx| {
5718                                if let Some(workspace) = workspace.upgrade() {
5719                                    entity
5720                                        .update(cx, |this, cx| {
5721                                            this.open_thread_as_markdown(workspace, window, cx)
5722                                        })
5723                                        .detach_and_log_err(cx);
5724                                }
5725                            }
5726                        });
5727
5728                    menu.when_some(focus, |menu, focus| menu.context(focus))
5729                        .action_disabled_when(
5730                            !has_selection,
5731                            "Copy Selection",
5732                            Box::new(markdown::CopyAsMarkdown),
5733                        )
5734                        .item(copy_this_agent_response)
5735                        .separator()
5736                        .item(scroll_item)
5737                        .item(open_thread_as_markdown)
5738                })
5739            })
5740            .into_any_element()
5741    }
5742
5743    fn get_agent_message_content(
5744        entries: &[AgentThreadEntry],
5745        entry_index: usize,
5746        cx: &App,
5747    ) -> Option<String> {
5748        let entry = entries.get(entry_index)?;
5749        if matches!(entry, AgentThreadEntry::UserMessage(_)) {
5750            return None;
5751        }
5752
5753        let start_index = (0..entry_index)
5754            .rev()
5755            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5756            .map(|i| i + 1)
5757            .unwrap_or(0);
5758
5759        let end_index = (entry_index + 1..entries.len())
5760            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5761            .map(|i| i - 1)
5762            .unwrap_or(entries.len() - 1);
5763
5764        let parts: Vec<String> = (start_index..=end_index)
5765            .filter_map(|i| entries.get(i))
5766            .filter_map(|entry| {
5767                if let AgentThreadEntry::AssistantMessage(message) = entry {
5768                    let text: String = message
5769                        .chunks
5770                        .iter()
5771                        .filter_map(|chunk| match chunk {
5772                            AssistantMessageChunk::Message { block } => {
5773                                let markdown = block.to_markdown(cx);
5774                                if markdown.trim().is_empty() {
5775                                    None
5776                                } else {
5777                                    Some(markdown.to_string())
5778                                }
5779                            }
5780                            AssistantMessageChunk::Thought { .. } => None,
5781                        })
5782                        .collect::<Vec<_>>()
5783                        .join("\n\n");
5784
5785                    if text.is_empty() { None } else { Some(text) }
5786                } else {
5787                    None
5788                }
5789            })
5790            .collect();
5791
5792        let text = parts.join("\n\n");
5793        if text.is_empty() { None } else { Some(text) }
5794    }
5795
5796    fn is_blocked_on_terminal_command(&self, cx: &App) -> bool {
5797        let thread = self.thread.read(cx);
5798        if !matches!(thread.status(), ThreadStatus::Generating) {
5799            return false;
5800        }
5801
5802        let mut has_running_terminal_call = false;
5803
5804        for entry in thread.entries().iter().rev() {
5805            match entry {
5806                AgentThreadEntry::UserMessage(_) => break,
5807                AgentThreadEntry::ToolCall(tool_call)
5808                    if matches!(
5809                        tool_call.status,
5810                        ToolCallStatus::InProgress | ToolCallStatus::Pending
5811                    ) =>
5812                {
5813                    if matches!(tool_call.kind, acp::ToolKind::Execute) {
5814                        has_running_terminal_call = true;
5815                    } else {
5816                        return false;
5817                    }
5818                }
5819                AgentThreadEntry::ToolCall(_)
5820                | AgentThreadEntry::AssistantMessage(_)
5821                | AgentThreadEntry::CompletedPlan(_) => {}
5822            }
5823        }
5824
5825        has_running_terminal_call
5826    }
5827
5828    fn render_collapsible_command(
5829        &self,
5830        group: SharedString,
5831        is_preview: bool,
5832        command_source: &str,
5833        cx: &Context<Self>,
5834    ) -> Div {
5835        v_flex()
5836            .group(group.clone())
5837            .p_1p5()
5838            .bg(self.tool_card_header_bg(cx))
5839            .when(is_preview, |this| {
5840                this.pt_1().child(
5841                    // Wrapping this label on a container with 24px height to avoid
5842                    // layout shift when it changes from being a preview label
5843                    // to the actual path where the command will run in
5844                    h_flex().h_6().child(
5845                        Label::new("Run Command")
5846                            .buffer_font(cx)
5847                            .size(LabelSize::XSmall)
5848                            .color(Color::Muted),
5849                    ),
5850                )
5851            })
5852            .children(command_source.lines().map(|line| {
5853                let text: SharedString = if line.is_empty() {
5854                    " ".into()
5855                } else {
5856                    line.to_string().into()
5857                };
5858
5859                Label::new(text).buffer_font(cx).size(LabelSize::Small)
5860            }))
5861            .child(
5862                div().absolute().top_1().right_1().child(
5863                    CopyButton::new("copy-command", command_source.to_string())
5864                        .tooltip_label("Copy Command")
5865                        .visible_on_hover(group),
5866                ),
5867            )
5868    }
5869
5870    fn render_terminal_tool_call(
5871        &self,
5872        active_session_id: &acp::SessionId,
5873        entry_ix: usize,
5874        terminal: &Entity<acp_thread::Terminal>,
5875        tool_call: &ToolCall,
5876        focus_handle: &FocusHandle,
5877        is_subagent: bool,
5878        window: &Window,
5879        cx: &Context<Self>,
5880    ) -> AnyElement {
5881        let terminal_data = terminal.read(cx);
5882        let working_dir = terminal_data.working_dir();
5883        let command = terminal_data.command();
5884        let started_at = terminal_data.started_at();
5885
5886        let tool_failed = matches!(
5887            &tool_call.status,
5888            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
5889        );
5890
5891        let confirmation_options = match &tool_call.status {
5892            ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),
5893            _ => None,
5894        };
5895        let needs_confirmation = confirmation_options.is_some();
5896
5897        let output = terminal_data.output();
5898        let command_finished = output.is_some()
5899            && !matches!(
5900                tool_call.status,
5901                ToolCallStatus::InProgress | ToolCallStatus::Pending
5902            );
5903        let truncated_output =
5904            output.is_some_and(|output| output.original_content_len > output.content.len());
5905        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
5906
5907        let command_failed = command_finished
5908            && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
5909
5910        let time_elapsed = if let Some(output) = output {
5911            output.ended_at.duration_since(started_at)
5912        } else {
5913            started_at.elapsed()
5914        };
5915
5916        let header_id =
5917            SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
5918        let header_group = SharedString::from(format!(
5919            "terminal-tool-header-group-{}",
5920            terminal.entity_id()
5921        ));
5922        let header_bg = cx
5923            .theme()
5924            .colors()
5925            .element_background
5926            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
5927        let border_color = cx.theme().colors().border.opacity(0.6);
5928
5929        let working_dir = working_dir
5930            .as_ref()
5931            .map(|path| path.display().to_string())
5932            .unwrap_or_else(|| "current directory".to_string());
5933
5934        // Since the command's source is wrapped in a markdown code block
5935        // (```\n...\n```), we need to strip that so we're left with only the
5936        // command's content.
5937        let command_source = command.read(cx).source();
5938        let command_content = command_source
5939            .strip_prefix("```\n")
5940            .and_then(|s| s.strip_suffix("\n```"))
5941            .unwrap_or(&command_source);
5942
5943        let command_element =
5944            self.render_collapsible_command(header_group.clone(), false, command_content, cx);
5945
5946        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
5947
5948        let header = h_flex()
5949            .id(header_id)
5950            .pt_1()
5951            .pl_1p5()
5952            .pr_1()
5953            .flex_none()
5954            .gap_1()
5955            .justify_between()
5956            .rounded_t_md()
5957            .child(
5958                div()
5959                    .id(("command-target-path", terminal.entity_id()))
5960                    .w_full()
5961                    .max_w_full()
5962                    .overflow_x_scroll()
5963                    .child(
5964                        Label::new(working_dir)
5965                            .buffer_font(cx)
5966                            .size(LabelSize::XSmall)
5967                            .color(Color::Muted),
5968                    ),
5969            )
5970            .child(
5971                Disclosure::new(
5972                    SharedString::from(format!(
5973                        "terminal-tool-disclosure-{}",
5974                        terminal.entity_id()
5975                    )),
5976                    is_expanded,
5977                )
5978                .opened_icon(IconName::ChevronUp)
5979                .closed_icon(IconName::ChevronDown)
5980                .visible_on_hover(&header_group)
5981                .on_click(cx.listener({
5982                    let id = tool_call.id.clone();
5983                    move |this, _event, _window, cx| {
5984                        if is_expanded {
5985                            this.expanded_tool_calls.remove(&id);
5986                        } else {
5987                            this.expanded_tool_calls.insert(id.clone());
5988                        }
5989                        cx.notify();
5990                    }
5991                })),
5992            )
5993            .when(time_elapsed > Duration::from_secs(10), |header| {
5994                header.child(
5995                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
5996                        .buffer_font(cx)
5997                        .color(Color::Muted)
5998                        .size(LabelSize::XSmall),
5999                )
6000            })
6001            .when(!command_finished && !needs_confirmation, |header| {
6002                header
6003                    .gap_1p5()
6004                    .child(
6005                        Icon::new(IconName::ArrowCircle)
6006                            .size(IconSize::XSmall)
6007                            .color(Color::Muted)
6008                            .with_rotate_animation(2)
6009                    )
6010                    .child(div().h(relative(0.6)).ml_1p5().child(Divider::vertical().color(DividerColor::Border)))
6011                    .child(
6012                        IconButton::new(
6013                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
6014                            IconName::Stop
6015                        )
6016                        .icon_size(IconSize::Small)
6017                        .icon_color(Color::Error)
6018                        .tooltip(move |_window, cx| {
6019                            Tooltip::with_meta(
6020                                "Stop This Command",
6021                                None,
6022                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
6023                                cx,
6024                            )
6025                        })
6026                        .on_click({
6027                            let terminal = terminal.clone();
6028                            cx.listener(move |this, _event, _window, cx| {
6029                                terminal.update(cx, |terminal, cx| {
6030                                    terminal.stop_by_user(cx);
6031                                });
6032                                if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
6033                                    this.cancel_generation(cx);
6034                                }
6035                            })
6036                        }),
6037                    )
6038            })
6039            .when(truncated_output, |header| {
6040                let tooltip = if let Some(output) = output {
6041                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
6042                       format!("Output exceeded terminal max lines and was \
6043                            truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
6044                    } else {
6045                        format!(
6046                            "Output is {} long, and to avoid unexpected token usage, \
6047                                only {} was sent back to the agent.",
6048                            format_file_size(output.original_content_len as u64, true),
6049                             format_file_size(output.content.len() as u64, true)
6050                        )
6051                    }
6052                } else {
6053                    "Output was truncated".to_string()
6054                };
6055
6056                header.child(
6057                    h_flex()
6058                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
6059                        .gap_1()
6060                        .child(
6061                            Icon::new(IconName::Info)
6062                                .size(IconSize::XSmall)
6063                                .color(Color::Ignored),
6064                        )
6065                        .child(
6066                            Label::new("Truncated")
6067                                .color(Color::Muted)
6068                                .size(LabelSize::XSmall),
6069                        )
6070                        .tooltip(Tooltip::text(tooltip)),
6071                )
6072            })
6073            .when(tool_failed || command_failed, |header| {
6074                header.child(
6075                    div()
6076                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
6077                        .child(
6078                            Icon::new(IconName::Close)
6079                                .size(IconSize::Small)
6080                                .color(Color::Error),
6081                        )
6082                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
6083                            this.tooltip(Tooltip::text(format!(
6084                                "Exited with code {}",
6085                                status.code().unwrap_or(-1),
6086                            )))
6087                        }),
6088                )
6089            })
6090;
6091
6092        let terminal_view = self
6093            .entry_view_state
6094            .read(cx)
6095            .entry(entry_ix)
6096            .and_then(|entry| entry.terminal(terminal));
6097
6098        v_flex()
6099            .when(!is_subagent, |this| {
6100                this.my_1p5()
6101                    .mx_5()
6102                    .border_1()
6103                    .when(tool_failed || command_failed, |card| card.border_dashed())
6104                    .border_color(border_color)
6105                    .rounded_md()
6106            })
6107            .overflow_hidden()
6108            .child(
6109                v_flex()
6110                    .group(&header_group)
6111                    .bg(header_bg)
6112                    .text_xs()
6113                    .child(header)
6114                    .child(command_element),
6115            )
6116            .when(is_expanded && terminal_view.is_some(), |this| {
6117                this.child(
6118                    div()
6119                        .pt_2()
6120                        .border_t_1()
6121                        .when(tool_failed || command_failed, |card| card.border_dashed())
6122                        .border_color(border_color)
6123                        .bg(cx.theme().colors().editor_background)
6124                        .rounded_b_md()
6125                        .text_ui_sm(cx)
6126                        .h_full()
6127                        .children(terminal_view.map(|terminal_view| {
6128                            let element = if terminal_view
6129                                .read(cx)
6130                                .content_mode(window, cx)
6131                                .is_scrollable()
6132                            {
6133                                div().h_72().child(terminal_view).into_any_element()
6134                            } else {
6135                                terminal_view.into_any_element()
6136                            };
6137
6138                            div()
6139                                .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
6140                                    window.dispatch_action(NewThread.boxed_clone(), cx);
6141                                    cx.stop_propagation();
6142                                }))
6143                                .child(element)
6144                                .into_any_element()
6145                        })),
6146                )
6147            })
6148            .when_some(confirmation_options, |this, options| {
6149                let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);
6150                this.child(self.render_permission_buttons(
6151                    self.thread.read(cx).session_id().clone(),
6152                    is_first,
6153                    options,
6154                    entry_ix,
6155                    tool_call.id.clone(),
6156                    focus_handle,
6157                    cx,
6158                ))
6159            })
6160            .into_any()
6161    }
6162
6163    fn is_first_tool_call(
6164        &self,
6165        active_session_id: &acp::SessionId,
6166        tool_call_id: &acp::ToolCallId,
6167        cx: &App,
6168    ) -> bool {
6169        self.conversation
6170            .read(cx)
6171            .pending_tool_call(active_session_id, cx)
6172            .map_or(false, |(pending_session_id, pending_tool_call_id, _)| {
6173                self.thread.read(cx).session_id() == &pending_session_id
6174                    && tool_call_id == &pending_tool_call_id
6175            })
6176    }
6177
6178    fn render_any_tool_call(
6179        &self,
6180        active_session_id: &acp::SessionId,
6181        entry_ix: usize,
6182        tool_call: &ToolCall,
6183        focus_handle: &FocusHandle,
6184        is_subagent: bool,
6185        window: &Window,
6186        cx: &Context<Self>,
6187    ) -> Div {
6188        let has_terminals = tool_call.terminals().next().is_some();
6189
6190        div().w_full().map(|this| {
6191            if tool_call.is_subagent() {
6192                this.child(
6193                    self.render_subagent_tool_call(
6194                        active_session_id,
6195                        entry_ix,
6196                        tool_call,
6197                        tool_call
6198                            .subagent_session_info
6199                            .as_ref()
6200                            .map(|i| i.session_id.clone()),
6201                        focus_handle,
6202                        window,
6203                        cx,
6204                    ),
6205                )
6206            } else if has_terminals {
6207                this.children(tool_call.terminals().map(|terminal| {
6208                    self.render_terminal_tool_call(
6209                        active_session_id,
6210                        entry_ix,
6211                        terminal,
6212                        tool_call,
6213                        focus_handle,
6214                        is_subagent,
6215                        window,
6216                        cx,
6217                    )
6218                }))
6219            } else {
6220                this.child(self.render_tool_call(
6221                    active_session_id,
6222                    entry_ix,
6223                    tool_call,
6224                    focus_handle,
6225                    is_subagent,
6226                    window,
6227                    cx,
6228                ))
6229            }
6230        })
6231    }
6232
6233    fn render_tool_call(
6234        &self,
6235        active_session_id: &acp::SessionId,
6236        entry_ix: usize,
6237        tool_call: &ToolCall,
6238        focus_handle: &FocusHandle,
6239        is_subagent: bool,
6240        window: &Window,
6241        cx: &Context<Self>,
6242    ) -> Div {
6243        let has_location = tool_call.locations.len() == 1;
6244        let card_header_id = SharedString::from("inner-tool-call-header");
6245
6246        let failed_or_canceled = match &tool_call.status {
6247            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
6248            _ => false,
6249        };
6250
6251        let needs_confirmation = matches!(
6252            tool_call.status,
6253            ToolCallStatus::WaitingForConfirmation { .. }
6254        );
6255        let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
6256
6257        let is_edit =
6258            matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
6259
6260        let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
6261        let (has_revealed_diff, tool_call_output_focus, tool_call_output_focus_handle) = tool_call
6262            .diffs()
6263            .next()
6264            .and_then(|diff| {
6265                let editor = self
6266                    .entry_view_state
6267                    .read(cx)
6268                    .entry(entry_ix)
6269                    .and_then(|entry| entry.editor_for_diff(diff))?;
6270                let has_revealed_diff = diff.read(cx).has_revealed_range(cx);
6271                let has_focus = editor.read(cx).is_focused(window);
6272                let focus_handle = editor.focus_handle(cx);
6273                Some((has_revealed_diff, has_focus, focus_handle))
6274            })
6275            .unwrap_or_else(|| (false, false, focus_handle.clone()));
6276
6277        let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
6278
6279        let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
6280        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
6281        let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
6282
6283        is_open |= needs_confirmation;
6284
6285        let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
6286
6287        let input_output_header = |label: SharedString| {
6288            Label::new(label)
6289                .size(LabelSize::XSmall)
6290                .color(Color::Muted)
6291                .buffer_font(cx)
6292        };
6293
6294        let tool_output_display = if is_open {
6295            match &tool_call.status {
6296                ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
6297                    .w_full()
6298                    .children(
6299                        tool_call
6300                            .content
6301                            .iter()
6302                            .enumerate()
6303                            .map(|(content_ix, content)| {
6304                                div()
6305                                    .child(self.render_tool_call_content(
6306                                        active_session_id,
6307                                        entry_ix,
6308                                        content,
6309                                        content_ix,
6310                                        tool_call,
6311                                        use_card_layout,
6312                                        has_image_content,
6313                                        failed_or_canceled,
6314                                        focus_handle,
6315                                        window,
6316                                        cx,
6317                                    ))
6318                                    .into_any_element()
6319                            }),
6320                    )
6321                    .when(should_show_raw_input, |this| {
6322                        let is_raw_input_expanded =
6323                            self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
6324
6325                        let input_header = if is_raw_input_expanded {
6326                            "Raw Input:"
6327                        } else {
6328                            "View Raw Input"
6329                        };
6330
6331                        this.child(
6332                            v_flex()
6333                                .p_2()
6334                                .gap_1()
6335                                .border_t_1()
6336                                .border_color(self.tool_card_border_color(cx))
6337                                .child(
6338                                    h_flex()
6339                                        .id("disclosure_container")
6340                                        .pl_0p5()
6341                                        .gap_1()
6342                                        .justify_between()
6343                                        .rounded_xs()
6344                                        .hover(|s| s.bg(cx.theme().colors().element_hover))
6345                                        .child(input_output_header(input_header.into()))
6346                                        .child(
6347                                            Disclosure::new(
6348                                                ("raw-input-disclosure", entry_ix),
6349                                                is_raw_input_expanded,
6350                                            )
6351                                            .opened_icon(IconName::ChevronUp)
6352                                            .closed_icon(IconName::ChevronDown),
6353                                        )
6354                                        .on_click(cx.listener({
6355                                            let id = tool_call.id.clone();
6356
6357                                            move |this: &mut Self, _, _, cx| {
6358                                                if this.expanded_tool_call_raw_inputs.contains(&id)
6359                                                {
6360                                                    this.expanded_tool_call_raw_inputs.remove(&id);
6361                                                } else {
6362                                                    this.expanded_tool_call_raw_inputs
6363                                                        .insert(id.clone());
6364                                                }
6365                                                cx.notify();
6366                                            }
6367                                        })),
6368                                )
6369                                .when(is_raw_input_expanded, |this| {
6370                                    this.children(tool_call.raw_input_markdown.clone().map(
6371                                        |input| {
6372                                            self.render_markdown(
6373                                                input,
6374                                                MarkdownStyle::themed(
6375                                                    MarkdownFont::Agent,
6376                                                    window,
6377                                                    cx,
6378                                                ),
6379                                            )
6380                                        },
6381                                    ))
6382                                }),
6383                        )
6384                    })
6385                    .child(self.render_permission_buttons(
6386                        self.thread.read(cx).session_id().clone(),
6387                        self.is_first_tool_call(active_session_id, &tool_call.id, cx),
6388                        options,
6389                        entry_ix,
6390                        tool_call.id.clone(),
6391                        focus_handle,
6392                        cx,
6393                    ))
6394                    .into_any(),
6395                ToolCallStatus::Pending | ToolCallStatus::InProgress
6396                    if is_edit
6397                        && tool_call.content.is_empty()
6398                        && self.as_native_connection(cx).is_some() =>
6399                {
6400                    self.render_diff_loading(cx)
6401                }
6402                ToolCallStatus::Pending
6403                | ToolCallStatus::InProgress
6404                | ToolCallStatus::Completed
6405                | ToolCallStatus::Failed
6406                | ToolCallStatus::Canceled => v_flex()
6407                    .when(should_show_raw_input, |this| {
6408                        this.mt_1p5().w_full().child(
6409                            v_flex()
6410                                .ml(rems(0.4))
6411                                .px_3p5()
6412                                .pb_1()
6413                                .gap_1()
6414                                .border_l_1()
6415                                .border_color(self.tool_card_border_color(cx))
6416                                .child(input_output_header("Raw Input:".into()))
6417                                .children(tool_call.raw_input_markdown.clone().map(|input| {
6418                                    div().id(("tool-call-raw-input-markdown", entry_ix)).child(
6419                                        self.render_markdown(
6420                                            input,
6421                                            MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
6422                                        ),
6423                                    )
6424                                }))
6425                                .child(input_output_header("Output:".into())),
6426                        )
6427                    })
6428                    .children(
6429                        tool_call
6430                            .content
6431                            .iter()
6432                            .enumerate()
6433                            .map(|(content_ix, content)| {
6434                                div().id(("tool-call-output", entry_ix)).child(
6435                                    self.render_tool_call_content(
6436                                        active_session_id,
6437                                        entry_ix,
6438                                        content,
6439                                        content_ix,
6440                                        tool_call,
6441                                        use_card_layout,
6442                                        has_image_content,
6443                                        failed_or_canceled,
6444                                        focus_handle,
6445                                        window,
6446                                        cx,
6447                                    ),
6448                                )
6449                            }),
6450                    )
6451                    .into_any(),
6452                ToolCallStatus::Rejected => Empty.into_any(),
6453            }
6454            .into()
6455        } else {
6456            None
6457        };
6458
6459        v_flex()
6460            .map(|this| {
6461                if is_subagent {
6462                    this
6463                } else if use_card_layout {
6464                    this.my_1p5()
6465                        .rounded_md()
6466                        .border_1()
6467                        .when(failed_or_canceled, |this| this.border_dashed())
6468                        .border_color(self.tool_card_border_color(cx))
6469                        .bg(cx.theme().colors().editor_background)
6470                        .overflow_hidden()
6471                } else {
6472                    this.my_1()
6473                }
6474            })
6475            .when(!is_subagent, |this| {
6476                this.map(|this| {
6477                    if has_location && !use_card_layout {
6478                        this.ml_4()
6479                    } else {
6480                        this.ml_5()
6481                    }
6482                })
6483                .mr_5()
6484            })
6485            .map(|this| {
6486                if is_terminal_tool {
6487                    let label_source = tool_call.label.read(cx).source();
6488                    this.child(self.render_collapsible_command(
6489                        card_header_id.clone(),
6490                        true,
6491                        label_source,
6492                        cx,
6493                    ))
6494                } else {
6495                    this.child(
6496                        h_flex()
6497                            .group(&card_header_id)
6498                            .relative()
6499                            .w_full()
6500                            .justify_between()
6501                            .when(use_card_layout, |this| {
6502                                this.p_0p5()
6503                                    .rounded_t(rems_from_px(5.))
6504                                    .bg(self.tool_card_header_bg(cx))
6505                            })
6506                            .child(self.render_tool_call_label(
6507                                entry_ix,
6508                                tool_call,
6509                                is_edit,
6510                                is_cancelled_edit,
6511                                has_revealed_diff,
6512                                use_card_layout,
6513                                window,
6514                                cx,
6515                            ))
6516                            .child(
6517                                h_flex()
6518                                    .when(is_collapsible || failed_or_canceled, |this| {
6519                                        let diff_for_discard = if has_revealed_diff
6520                                            && is_cancelled_edit
6521                                        {
6522                                            tool_call.diffs().next().cloned()
6523                                        } else {
6524                                            None
6525                                        };
6526
6527                                        this.child(
6528                                            h_flex()
6529                                                .pr_0p5()
6530                                                .gap_1()
6531                                                .when(is_collapsible, |this| {
6532                                                    this.child(
6533                                                        Disclosure::new(
6534                                                            ("expand-output", entry_ix),
6535                                                            is_open,
6536                                                        )
6537                                                        .opened_icon(IconName::ChevronUp)
6538                                                        .closed_icon(IconName::ChevronDown)
6539                                                        .visible_on_hover(&card_header_id)
6540                                                        .on_click(cx.listener({
6541                                                            let id = tool_call.id.clone();
6542                                                            move |this: &mut Self,
6543                                                                  _,
6544                                                                  _,
6545                                                                  cx: &mut Context<Self>| {
6546                                                                if is_open {
6547                                                                    this.expanded_tool_calls
6548                                                                        .remove(&id);
6549                                                                } else {
6550                                                                    this.expanded_tool_calls
6551                                                                        .insert(id.clone());
6552                                                                }
6553                                                                cx.notify();
6554                                                            }
6555                                                        })),
6556                                                    )
6557                                                })
6558                                                .when(failed_or_canceled, |this| {
6559                                                    if is_cancelled_edit && !has_revealed_diff {
6560                                                        this.child(
6561                                                            div()
6562                                                                .id(entry_ix)
6563                                                                .tooltip(Tooltip::text(
6564                                                                    "Interrupted Edit",
6565                                                                ))
6566                                                                .child(
6567                                                                    Icon::new(IconName::XCircle)
6568                                                                        .color(Color::Muted)
6569                                                                        .size(IconSize::Small),
6570                                                                ),
6571                                                        )
6572                                                    } else if is_cancelled_edit {
6573                                                        this
6574                                                    } else {
6575                                                        this.child(
6576                                                            Icon::new(IconName::Close)
6577                                                                .color(Color::Error)
6578                                                                .size(IconSize::Small),
6579                                                        )
6580                                                    }
6581                                                })
6582                                                .when_some(diff_for_discard, |this, diff| {
6583                                                    let tool_call_id = tool_call.id.clone();
6584                                                    let is_discarded = self
6585                                                        .discarded_partial_edits
6586                                                        .contains(&tool_call_id);
6587
6588                                                    this.when(!is_discarded, |this| {
6589                                                        this.child(
6590                                                            IconButton::new(
6591                                                                ("discard-partial-edit", entry_ix),
6592                                                                IconName::Undo,
6593                                                            )
6594                                                            .icon_size(IconSize::Small)
6595                                                            .tooltip(move |_, cx| {
6596                                                                Tooltip::with_meta(
6597                                                                    "Discard Interrupted Edit",
6598                                                                    None,
6599                                                                    "You can discard this interrupted partial edit and restore the original file content.",
6600                                                                    cx,
6601                                                                )
6602                                                            })
6603                                                            .on_click(cx.listener({
6604                                                                let tool_call_id =
6605                                                                    tool_call_id.clone();
6606                                                                move |this, _, _window, cx| {
6607                                                                    let diff_data = diff.read(cx);
6608                                                                    let base_text = diff_data
6609                                                                        .base_text()
6610                                                                        .clone();
6611                                                                    let buffer =
6612                                                                        diff_data.buffer().clone();
6613                                                                    buffer.update(
6614                                                                        cx,
6615                                                                        |buffer, cx| {
6616                                                                            buffer.set_text(
6617                                                                                base_text.as_ref(),
6618                                                                                cx,
6619                                                                            );
6620                                                                        },
6621                                                                    );
6622                                                                    this.discarded_partial_edits
6623                                                                        .insert(
6624                                                                            tool_call_id.clone(),
6625                                                                        );
6626                                                                    cx.notify();
6627                                                                }
6628                                                            })),
6629                                                        )
6630                                                    })
6631                                                }),
6632                                        )
6633                                    })
6634                                    .when(tool_call_output_focus, |this| {
6635                                        this.child(
6636                                            Button::new("open-file-button", "Open File")
6637                                                .style(ButtonStyle::Outlined)
6638                                                .label_size(LabelSize::Small)
6639                                                .key_binding(
6640                                                    KeyBinding::for_action_in(&OpenExcerpts, &tool_call_output_focus_handle, cx)
6641                                                        .map(|s| s.size(rems_from_px(12.))),
6642                                                )
6643                                                .on_click(|_, window, cx| {
6644                                                    window.dispatch_action(
6645                                                        Box::new(OpenExcerpts),
6646                                                        cx,
6647                                                    )
6648                                                }),
6649                                        )
6650                                    }),
6651                            )
6652
6653                    )
6654                }
6655            })
6656            .children(tool_output_display)
6657    }
6658
6659    fn render_permission_buttons(
6660        &self,
6661        session_id: acp::SessionId,
6662        is_first: bool,
6663        options: &PermissionOptions,
6664        entry_ix: usize,
6665        tool_call_id: acp::ToolCallId,
6666        focus_handle: &FocusHandle,
6667        cx: &Context<Self>,
6668    ) -> Div {
6669        match options {
6670            PermissionOptions::Flat(options) => self.render_permission_buttons_flat(
6671                session_id,
6672                is_first,
6673                options,
6674                entry_ix,
6675                tool_call_id,
6676                focus_handle,
6677                cx,
6678            ),
6679            PermissionOptions::Dropdown(choices) => self.render_permission_buttons_with_dropdown(
6680                is_first,
6681                choices,
6682                None,
6683                entry_ix,
6684                tool_call_id,
6685                focus_handle,
6686                cx,
6687            ),
6688            PermissionOptions::DropdownWithPatterns {
6689                choices,
6690                patterns,
6691                tool_name,
6692            } => self.render_permission_buttons_with_dropdown(
6693                is_first,
6694                choices,
6695                Some((patterns, tool_name)),
6696                entry_ix,
6697                tool_call_id,
6698                focus_handle,
6699                cx,
6700            ),
6701        }
6702    }
6703
6704    fn render_permission_buttons_with_dropdown(
6705        &self,
6706        is_first: bool,
6707        choices: &[PermissionOptionChoice],
6708        patterns: Option<(&[PermissionPattern], &str)>,
6709        entry_ix: usize,
6710        tool_call_id: acp::ToolCallId,
6711        focus_handle: &FocusHandle,
6712        cx: &Context<Self>,
6713    ) -> Div {
6714        let selection = self.permission_selections.get(&tool_call_id);
6715
6716        let selected_index = selection
6717            .and_then(|s| s.choice_index())
6718            .unwrap_or_else(|| choices.len().saturating_sub(1));
6719
6720        let dropdown_label: SharedString =
6721            if matches!(selection, Some(PermissionSelection::SelectedPatterns(_))) {
6722                "Always for selected commands".into()
6723            } else {
6724                choices
6725                    .get(selected_index)
6726                    .or(choices.last())
6727                    .map(|choice| choice.label())
6728                    .unwrap_or_else(|| "Only this time".into())
6729            };
6730
6731        let dropdown = if let Some((pattern_list, tool_name)) = patterns {
6732            self.render_permission_granularity_dropdown_with_patterns(
6733                choices,
6734                pattern_list,
6735                tool_name,
6736                dropdown_label,
6737                entry_ix,
6738                tool_call_id.clone(),
6739                is_first,
6740                cx,
6741            )
6742        } else {
6743            self.render_permission_granularity_dropdown(
6744                choices,
6745                dropdown_label,
6746                entry_ix,
6747                tool_call_id.clone(),
6748                selected_index,
6749                is_first,
6750                cx,
6751            )
6752        };
6753
6754        h_flex()
6755            .w_full()
6756            .p_1()
6757            .gap_2()
6758            .justify_between()
6759            .border_t_1()
6760            .border_color(self.tool_card_border_color(cx))
6761            .child(
6762                h_flex()
6763                    .gap_0p5()
6764                    .child(
6765                        Button::new(("allow-btn", entry_ix), "Allow")
6766                            .start_icon(
6767                                Icon::new(IconName::Check)
6768                                    .size(IconSize::XSmall)
6769                                    .color(Color::Success),
6770                            )
6771                            .label_size(LabelSize::Small)
6772                            .when(is_first, |this| {
6773                                this.key_binding(
6774                                    KeyBinding::for_action_in(
6775                                        &AllowOnce as &dyn Action,
6776                                        focus_handle,
6777                                        cx,
6778                                    )
6779                                    .map(|kb| kb.size(rems_from_px(12.))),
6780                                )
6781                            })
6782                            .on_click(cx.listener({
6783                                move |this, _, window, cx| {
6784                                    this.authorize_pending_with_granularity(true, window, cx);
6785                                }
6786                            })),
6787                    )
6788                    .child(
6789                        Button::new(("deny-btn", entry_ix), "Deny")
6790                            .start_icon(
6791                                Icon::new(IconName::Close)
6792                                    .size(IconSize::XSmall)
6793                                    .color(Color::Error),
6794                            )
6795                            .label_size(LabelSize::Small)
6796                            .when(is_first, |this| {
6797                                this.key_binding(
6798                                    KeyBinding::for_action_in(
6799                                        &RejectOnce as &dyn Action,
6800                                        focus_handle,
6801                                        cx,
6802                                    )
6803                                    .map(|kb| kb.size(rems_from_px(12.))),
6804                                )
6805                            })
6806                            .on_click(cx.listener({
6807                                move |this, _, window, cx| {
6808                                    this.authorize_pending_with_granularity(false, window, cx);
6809                                }
6810                            })),
6811                    ),
6812            )
6813            .child(dropdown)
6814    }
6815
6816    fn render_permission_granularity_dropdown(
6817        &self,
6818        choices: &[PermissionOptionChoice],
6819        current_label: SharedString,
6820        entry_ix: usize,
6821        tool_call_id: acp::ToolCallId,
6822        selected_index: usize,
6823        is_first: bool,
6824        cx: &Context<Self>,
6825    ) -> AnyElement {
6826        let menu_options: Vec<(usize, SharedString)> = choices
6827            .iter()
6828            .enumerate()
6829            .map(|(i, choice)| (i, choice.label()))
6830            .collect();
6831
6832        let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6833
6834        PopoverMenu::new(("permission-granularity", entry_ix))
6835            .with_handle(permission_dropdown_handle)
6836            .trigger(
6837                Button::new(("granularity-trigger", entry_ix), current_label)
6838                    .end_icon(
6839                        Icon::new(IconName::ChevronDown)
6840                            .size(IconSize::XSmall)
6841                            .color(Color::Muted),
6842                    )
6843                    .label_size(LabelSize::Small)
6844                    .when(is_first, |this| {
6845                        this.key_binding(
6846                            KeyBinding::for_action_in(
6847                                &crate::OpenPermissionDropdown as &dyn Action,
6848                                &self.focus_handle(cx),
6849                                cx,
6850                            )
6851                            .map(|kb| kb.size(rems_from_px(12.))),
6852                        )
6853                    }),
6854            )
6855            .menu(move |window, cx| {
6856                let tool_call_id = tool_call_id.clone();
6857                let options = menu_options.clone();
6858
6859                Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
6860                    for (index, display_name) in options.iter() {
6861                        let display_name = display_name.clone();
6862                        let index = *index;
6863                        let tool_call_id_for_entry = tool_call_id.clone();
6864                        let is_selected = index == selected_index;
6865                        menu = menu.toggleable_entry(
6866                            display_name,
6867                            is_selected,
6868                            IconPosition::End,
6869                            None,
6870                            move |window, cx| {
6871                                window.dispatch_action(
6872                                    SelectPermissionGranularity {
6873                                        tool_call_id: tool_call_id_for_entry.0.to_string(),
6874                                        index,
6875                                    }
6876                                    .boxed_clone(),
6877                                    cx,
6878                                );
6879                            },
6880                        );
6881                    }
6882
6883                    menu
6884                }))
6885            })
6886            .into_any_element()
6887    }
6888
6889    fn render_permission_granularity_dropdown_with_patterns(
6890        &self,
6891        choices: &[PermissionOptionChoice],
6892        patterns: &[PermissionPattern],
6893        _tool_name: &str,
6894        current_label: SharedString,
6895        entry_ix: usize,
6896        tool_call_id: acp::ToolCallId,
6897        is_first: bool,
6898        cx: &Context<Self>,
6899    ) -> AnyElement {
6900        let default_choice_index = choices.len().saturating_sub(1);
6901        let menu_options: Vec<(usize, SharedString)> = choices
6902            .iter()
6903            .enumerate()
6904            .map(|(i, choice)| (i, choice.label()))
6905            .collect();
6906
6907        let pattern_options: Vec<(usize, SharedString)> = patterns
6908            .iter()
6909            .enumerate()
6910            .map(|(i, cp)| {
6911                (
6912                    i,
6913                    SharedString::from(format!("Always for `{}` commands", cp.display_name)),
6914                )
6915            })
6916            .collect();
6917
6918        let pattern_count = patterns.len();
6919        let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6920        let view = cx.entity().downgrade();
6921
6922        PopoverMenu::new(("permission-granularity", entry_ix))
6923            .with_handle(permission_dropdown_handle.clone())
6924            .anchor(Corner::TopRight)
6925            .attach(Corner::BottomRight)
6926            .trigger(
6927                Button::new(("granularity-trigger", entry_ix), current_label)
6928                    .end_icon(
6929                        Icon::new(IconName::ChevronDown)
6930                            .size(IconSize::XSmall)
6931                            .color(Color::Muted),
6932                    )
6933                    .label_size(LabelSize::Small)
6934                    .when(is_first, |this| {
6935                        this.key_binding(
6936                            KeyBinding::for_action_in(
6937                                &crate::OpenPermissionDropdown as &dyn Action,
6938                                &self.focus_handle(cx),
6939                                cx,
6940                            )
6941                            .map(|kb| kb.size(rems_from_px(12.))),
6942                        )
6943                    }),
6944            )
6945            .menu(move |window, cx| {
6946                let tool_call_id = tool_call_id.clone();
6947                let options = menu_options.clone();
6948                let patterns = pattern_options.clone();
6949                let view = view.clone();
6950                let dropdown_handle = permission_dropdown_handle.clone();
6951
6952                Some(ContextMenu::build_persistent(
6953                    window,
6954                    cx,
6955                    move |menu, _window, cx| {
6956                        let mut menu = menu;
6957
6958                        // Read fresh selection state from the view on each rebuild.
6959                        let selection: Option<PermissionSelection> = view.upgrade().and_then(|v| {
6960                            let view = v.read(cx);
6961                            view.permission_selections.get(&tool_call_id).cloned()
6962                        });
6963
6964                        let is_pattern_mode =
6965                            matches!(selection, Some(PermissionSelection::SelectedPatterns(_)));
6966
6967                        // Granularity choices: "Always for terminal", "Only this time"
6968                        for (index, display_name) in options.iter() {
6969                            let display_name = display_name.clone();
6970                            let index = *index;
6971                            let tool_call_id_for_entry = tool_call_id.clone();
6972                            let is_selected = !is_pattern_mode
6973                                && selection
6974                                    .as_ref()
6975                                    .and_then(|s| s.choice_index())
6976                                    .map_or(index == default_choice_index, |ci| ci == index);
6977
6978                            let view = view.clone();
6979                            menu = menu.toggleable_entry(
6980                                display_name,
6981                                is_selected,
6982                                IconPosition::End,
6983                                None,
6984                                move |_window, cx| {
6985                                    view.update(cx, |this, cx| {
6986                                        this.permission_selections.insert(
6987                                            tool_call_id_for_entry.clone(),
6988                                            PermissionSelection::Choice(index),
6989                                        );
6990                                        cx.notify();
6991                                    })
6992                                    .log_err();
6993                                },
6994                            );
6995                        }
6996
6997                        menu = menu.separator().header("Select Options…");
6998
6999                        for (pattern_index, label) in patterns.iter() {
7000                            let label = label.clone();
7001                            let pattern_index = *pattern_index;
7002                            let tool_call_id_for_pattern = tool_call_id.clone();
7003                            let is_checked = selection
7004                                .as_ref()
7005                                .is_some_and(|s| s.is_pattern_checked(pattern_index));
7006
7007                            let view = view.clone();
7008                            menu = menu.toggleable_entry(
7009                                label,
7010                                is_checked,
7011                                IconPosition::End,
7012                                None,
7013                                move |_window, cx| {
7014                                    view.update(cx, |this, cx| {
7015                                        let selection = this
7016                                            .permission_selections
7017                                            .get_mut(&tool_call_id_for_pattern);
7018
7019                                        match selection {
7020                                            Some(PermissionSelection::SelectedPatterns(_)) => {
7021                                                // Already in pattern mode — toggle.
7022                                                this.permission_selections
7023                                                    .get_mut(&tool_call_id_for_pattern)
7024                                                    .expect("just matched above")
7025                                                    .toggle_pattern(pattern_index);
7026                                            }
7027                                            _ => {
7028                                                // First click: activate pattern mode
7029                                                // with all patterns checked.
7030                                                this.permission_selections.insert(
7031                                                    tool_call_id_for_pattern.clone(),
7032                                                    PermissionSelection::SelectedPatterns(
7033                                                        (0..pattern_count).collect(),
7034                                                    ),
7035                                                );
7036                                            }
7037                                        }
7038                                        cx.notify();
7039                                    })
7040                                    .log_err();
7041                                },
7042                            );
7043                        }
7044
7045                        let any_patterns_checked = selection
7046                            .as_ref()
7047                            .is_some_and(|s| s.has_any_checked_patterns());
7048                        let dropdown_handle = dropdown_handle.clone();
7049                        menu = menu.custom_row(move |_window, _cx| {
7050                            div()
7051                                .py_1()
7052                                .w_full()
7053                                .child(
7054                                    Button::new("apply-patterns", "Apply")
7055                                        .full_width()
7056                                        .style(ButtonStyle::Outlined)
7057                                        .label_size(LabelSize::Small)
7058                                        .disabled(!any_patterns_checked)
7059                                        .on_click({
7060                                            let dropdown_handle = dropdown_handle.clone();
7061                                            move |_event, _window, cx| {
7062                                                dropdown_handle.hide(cx);
7063                                            }
7064                                        }),
7065                                )
7066                                .into_any_element()
7067                        });
7068
7069                        menu
7070                    },
7071                ))
7072            })
7073            .into_any_element()
7074    }
7075
7076    fn render_permission_buttons_flat(
7077        &self,
7078        session_id: acp::SessionId,
7079        is_first: bool,
7080        options: &[acp::PermissionOption],
7081        entry_ix: usize,
7082        tool_call_id: acp::ToolCallId,
7083        focus_handle: &FocusHandle,
7084        cx: &Context<Self>,
7085    ) -> Div {
7086        let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3, u8> = ArrayVec::new();
7087
7088        div()
7089            .p_1()
7090            .border_t_1()
7091            .border_color(self.tool_card_border_color(cx))
7092            .w_full()
7093            .v_flex()
7094            .gap_0p5()
7095            .children(options.iter().map(move |option| {
7096                let option_id = SharedString::from(option.option_id.0.clone());
7097                Button::new((option_id, entry_ix), option.name.clone())
7098                    .map(|this| {
7099                        let (icon, action) = match option.kind {
7100                            acp::PermissionOptionKind::AllowOnce => (
7101                                Icon::new(IconName::Check)
7102                                    .size(IconSize::XSmall)
7103                                    .color(Color::Success),
7104                                Some(&AllowOnce as &dyn Action),
7105                            ),
7106                            acp::PermissionOptionKind::AllowAlways => (
7107                                Icon::new(IconName::CheckDouble)
7108                                    .size(IconSize::XSmall)
7109                                    .color(Color::Success),
7110                                Some(&AllowAlways as &dyn Action),
7111                            ),
7112                            acp::PermissionOptionKind::RejectOnce => (
7113                                Icon::new(IconName::Close)
7114                                    .size(IconSize::XSmall)
7115                                    .color(Color::Error),
7116                                Some(&RejectOnce as &dyn Action),
7117                            ),
7118                            acp::PermissionOptionKind::RejectAlways | _ => (
7119                                Icon::new(IconName::Close)
7120                                    .size(IconSize::XSmall)
7121                                    .color(Color::Error),
7122                                None,
7123                            ),
7124                        };
7125
7126                        let this = this.start_icon(icon);
7127
7128                        let Some(action) = action else {
7129                            return this;
7130                        };
7131
7132                        if !is_first || seen_kinds.contains(&option.kind) {
7133                            return this;
7134                        }
7135
7136                        seen_kinds.push(option.kind).unwrap();
7137
7138                        this.key_binding(
7139                            KeyBinding::for_action_in(action, focus_handle, cx)
7140                                .map(|kb| kb.size(rems_from_px(12.))),
7141                        )
7142                    })
7143                    .label_size(LabelSize::Small)
7144                    .on_click(cx.listener({
7145                        let tool_call_id = tool_call_id.clone();
7146                        let option_id = option.option_id.clone();
7147                        let option_kind = option.kind;
7148                        let session_id = session_id.clone();
7149                        move |this, _, window, cx| {
7150                            this.authorize_tool_call(
7151                                session_id.clone(),
7152                                tool_call_id.clone(),
7153                                SelectedPermissionOutcome::new(option_id.clone(), option_kind),
7154                                window,
7155                                cx,
7156                            );
7157                        }
7158                    }))
7159            }))
7160    }
7161
7162    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
7163        let bar = |n: u64, width_class: &str| {
7164            let bg_color = cx.theme().colors().element_active;
7165            let base = h_flex().h_1().rounded_full();
7166
7167            let modified = match width_class {
7168                "w_4_5" => base.w_3_4(),
7169                "w_1_4" => base.w_1_4(),
7170                "w_2_4" => base.w_2_4(),
7171                "w_3_5" => base.w_3_5(),
7172                "w_2_5" => base.w_2_5(),
7173                _ => base.w_1_2(),
7174            };
7175
7176            modified.with_animation(
7177                ElementId::Integer(n),
7178                Animation::new(Duration::from_secs(2)).repeat(),
7179                move |tab, delta| {
7180                    let delta = (delta - 0.15 * n as f32) / 0.7;
7181                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
7182                    let delta = ease_in_out(delta.clamp(0., 1.));
7183                    let delta = 0.1 + 0.9 * delta;
7184
7185                    tab.bg(bg_color.opacity(delta))
7186                },
7187            )
7188        };
7189
7190        v_flex()
7191            .p_3()
7192            .gap_1()
7193            .rounded_b_md()
7194            .bg(cx.theme().colors().editor_background)
7195            .child(bar(0, "w_4_5"))
7196            .child(bar(1, "w_1_4"))
7197            .child(bar(2, "w_2_4"))
7198            .child(bar(3, "w_3_5"))
7199            .child(bar(4, "w_2_5"))
7200            .into_any_element()
7201    }
7202
7203    fn render_tool_call_label(
7204        &self,
7205        entry_ix: usize,
7206        tool_call: &ToolCall,
7207        is_edit: bool,
7208        has_failed: bool,
7209        has_revealed_diff: bool,
7210        use_card_layout: bool,
7211        window: &Window,
7212        cx: &Context<Self>,
7213    ) -> Div {
7214        let has_location = tool_call.locations.len() == 1;
7215        let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
7216        let is_subagent_tool_call = tool_call.is_subagent();
7217
7218        let file_icon = if has_location {
7219            FileIcons::get_icon(&tool_call.locations[0].path, cx)
7220                .map(|from_path| Icon::from_path(from_path).color(Color::Muted))
7221                .unwrap_or(Icon::new(IconName::ToolPencil).color(Color::Muted))
7222        } else {
7223            Icon::new(IconName::ToolPencil).color(Color::Muted)
7224        };
7225
7226        let tool_icon = if is_file && has_failed && has_revealed_diff {
7227            div()
7228                .id(entry_ix)
7229                .tooltip(Tooltip::text("Interrupted Edit"))
7230                .child(DecoratedIcon::new(
7231                    file_icon,
7232                    Some(
7233                        IconDecoration::new(
7234                            IconDecorationKind::Triangle,
7235                            self.tool_card_header_bg(cx),
7236                            cx,
7237                        )
7238                        .color(cx.theme().status().warning)
7239                        .position(gpui::Point {
7240                            x: px(-2.),
7241                            y: px(-2.),
7242                        }),
7243                    ),
7244                ))
7245                .into_any_element()
7246        } else if is_file {
7247            div().child(file_icon).into_any_element()
7248        } else if is_subagent_tool_call {
7249            Icon::new(self.agent_icon)
7250                .size(IconSize::Small)
7251                .color(Color::Muted)
7252                .into_any_element()
7253        } else {
7254            Icon::new(match tool_call.kind {
7255                acp::ToolKind::Read => IconName::ToolSearch,
7256                acp::ToolKind::Edit => IconName::ToolPencil,
7257                acp::ToolKind::Delete => IconName::ToolDeleteFile,
7258                acp::ToolKind::Move => IconName::ArrowRightLeft,
7259                acp::ToolKind::Search => IconName::ToolSearch,
7260                acp::ToolKind::Execute => IconName::ToolTerminal,
7261                acp::ToolKind::Think => IconName::ToolThink,
7262                acp::ToolKind::Fetch => IconName::ToolWeb,
7263                acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
7264                acp::ToolKind::Other | _ => IconName::ToolHammer,
7265            })
7266            .size(IconSize::Small)
7267            .color(Color::Muted)
7268            .into_any_element()
7269        };
7270
7271        let gradient_overlay = {
7272            div()
7273                .absolute()
7274                .top_0()
7275                .right_0()
7276                .w_12()
7277                .h_full()
7278                .map(|this| {
7279                    if use_card_layout {
7280                        this.bg(linear_gradient(
7281                            90.,
7282                            linear_color_stop(self.tool_card_header_bg(cx), 1.),
7283                            linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
7284                        ))
7285                    } else {
7286                        this.bg(linear_gradient(
7287                            90.,
7288                            linear_color_stop(cx.theme().colors().panel_background, 1.),
7289                            linear_color_stop(
7290                                cx.theme().colors().panel_background.opacity(0.2),
7291                                0.,
7292                            ),
7293                        ))
7294                    }
7295                })
7296        };
7297
7298        h_flex()
7299            .relative()
7300            .w_full()
7301            .h(window.line_height() - px(2.))
7302            .text_size(self.tool_name_font_size())
7303            .gap_1p5()
7304            .when(has_location || use_card_layout, |this| this.px_1())
7305            .when(has_location, |this| {
7306                this.cursor(CursorStyle::PointingHand)
7307                    .rounded(rems_from_px(3.)) // Concentric border radius
7308                    .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
7309            })
7310            .overflow_hidden()
7311            .child(tool_icon)
7312            .child(if has_location {
7313                h_flex()
7314                    .id(("open-tool-call-location", entry_ix))
7315                    .w_full()
7316                    .map(|this| {
7317                        if use_card_layout {
7318                            this.text_color(cx.theme().colors().text)
7319                        } else {
7320                            this.text_color(cx.theme().colors().text_muted)
7321                        }
7322                    })
7323                    .child(
7324                        self.render_markdown(
7325                            tool_call.label.clone(),
7326                            MarkdownStyle {
7327                                prevent_mouse_interaction: true,
7328                                ..MarkdownStyle::themed(MarkdownFont::Agent, window, cx)
7329                                    .with_muted_text(cx)
7330                            },
7331                        ),
7332                    )
7333                    .tooltip(Tooltip::text("Go to File"))
7334                    .on_click(cx.listener(move |this, _, window, cx| {
7335                        this.open_tool_call_location(entry_ix, 0, window, cx);
7336                    }))
7337                    .into_any_element()
7338            } else {
7339                h_flex()
7340                    .w_full()
7341                    .child(self.render_markdown(
7342                        tool_call.label.clone(),
7343                        MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx),
7344                    ))
7345                    .into_any()
7346            })
7347            .when(!is_edit, |this| this.child(gradient_overlay))
7348    }
7349
7350    fn open_tool_call_location(
7351        &self,
7352        entry_ix: usize,
7353        location_ix: usize,
7354        window: &mut Window,
7355        cx: &mut Context<Self>,
7356    ) -> Option<()> {
7357        let (tool_call_location, agent_location) = self
7358            .thread
7359            .read(cx)
7360            .entries()
7361            .get(entry_ix)?
7362            .location(location_ix)?;
7363
7364        let project_path = self
7365            .project
7366            .upgrade()?
7367            .read(cx)
7368            .find_project_path(&tool_call_location.path, cx)?;
7369
7370        let open_task = self
7371            .workspace
7372            .update(cx, |workspace, cx| {
7373                workspace.open_path(project_path, None, true, window, cx)
7374            })
7375            .log_err()?;
7376        window
7377            .spawn(cx, async move |cx| {
7378                let item = open_task.await?;
7379
7380                let Some(active_editor) = item.downcast::<Editor>() else {
7381                    return anyhow::Ok(());
7382                };
7383
7384                active_editor.update_in(cx, |editor, window, cx| {
7385                    let snapshot = editor.buffer().read(cx).snapshot(cx);
7386                    if snapshot.as_singleton().is_some()
7387                        && let Some(anchor) = snapshot.anchor_in_excerpt(agent_location.position)
7388                    {
7389                        editor.change_selections(Default::default(), window, cx, |selections| {
7390                            selections.select_anchor_ranges([anchor..anchor]);
7391                        })
7392                    } else {
7393                        let row = tool_call_location.line.unwrap_or_default();
7394                        editor.change_selections(Default::default(), window, cx, |selections| {
7395                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
7396                        })
7397                    }
7398                })?;
7399
7400                anyhow::Ok(())
7401            })
7402            .detach_and_log_err(cx);
7403
7404        None
7405    }
7406
7407    fn render_tool_call_content(
7408        &self,
7409        session_id: &acp::SessionId,
7410        entry_ix: usize,
7411        content: &ToolCallContent,
7412        context_ix: usize,
7413        tool_call: &ToolCall,
7414        card_layout: bool,
7415        is_image_tool_call: bool,
7416        has_failed: bool,
7417        focus_handle: &FocusHandle,
7418        window: &Window,
7419        cx: &Context<Self>,
7420    ) -> AnyElement {
7421        match content {
7422            ToolCallContent::ContentBlock(content) => {
7423                if let Some(resource_link) = content.resource_link() {
7424                    self.render_resource_link(resource_link, cx)
7425                } else if let Some(markdown) = content.markdown() {
7426                    self.render_markdown_output(
7427                        markdown.clone(),
7428                        tool_call.id.clone(),
7429                        context_ix,
7430                        card_layout,
7431                        window,
7432                        cx,
7433                    )
7434                } else if let Some(image) = content.image() {
7435                    let location = tool_call.locations.first().cloned();
7436                    self.render_image_output(
7437                        entry_ix,
7438                        image.clone(),
7439                        location,
7440                        card_layout,
7441                        is_image_tool_call,
7442                        cx,
7443                    )
7444                } else {
7445                    Empty.into_any_element()
7446                }
7447            }
7448            ToolCallContent::Diff(diff) => {
7449                self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
7450            }
7451            ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(
7452                session_id,
7453                entry_ix,
7454                terminal,
7455                tool_call,
7456                focus_handle,
7457                false,
7458                window,
7459                cx,
7460            ),
7461        }
7462    }
7463
7464    fn render_resource_link(
7465        &self,
7466        resource_link: &acp::ResourceLink,
7467        cx: &Context<Self>,
7468    ) -> AnyElement {
7469        let uri: SharedString = resource_link.uri.clone().into();
7470        let is_file = resource_link.uri.strip_prefix("file://");
7471
7472        let Some(project) = self.project.upgrade() else {
7473            return Empty.into_any_element();
7474        };
7475
7476        let label: SharedString = if let Some(abs_path) = is_file {
7477            if let Some(project_path) = project
7478                .read(cx)
7479                .project_path_for_absolute_path(&Path::new(abs_path), cx)
7480                && let Some(worktree) = project
7481                    .read(cx)
7482                    .worktree_for_id(project_path.worktree_id, cx)
7483            {
7484                worktree
7485                    .read(cx)
7486                    .full_path(&project_path.path)
7487                    .to_string_lossy()
7488                    .to_string()
7489                    .into()
7490            } else {
7491                abs_path.to_string().into()
7492            }
7493        } else {
7494            uri.clone()
7495        };
7496
7497        let button_id = SharedString::from(format!("item-{}", uri));
7498
7499        div()
7500            .ml(rems(0.4))
7501            .pl_2p5()
7502            .border_l_1()
7503            .border_color(self.tool_card_border_color(cx))
7504            .overflow_hidden()
7505            .child(
7506                Button::new(button_id, label)
7507                    .label_size(LabelSize::Small)
7508                    .color(Color::Muted)
7509                    .truncate(true)
7510                    .when(is_file.is_none(), |this| {
7511                        this.end_icon(
7512                            Icon::new(IconName::ArrowUpRight)
7513                                .size(IconSize::XSmall)
7514                                .color(Color::Muted),
7515                        )
7516                    })
7517                    .on_click(cx.listener({
7518                        let workspace = self.workspace.clone();
7519                        move |_, _, window, cx: &mut Context<Self>| {
7520                            open_link(uri.clone(), &workspace, window, cx);
7521                        }
7522                    })),
7523            )
7524            .into_any_element()
7525    }
7526
7527    fn render_diff_editor(
7528        &self,
7529        entry_ix: usize,
7530        diff: &Entity<acp_thread::Diff>,
7531        tool_call: &ToolCall,
7532        has_failed: bool,
7533        cx: &Context<Self>,
7534    ) -> AnyElement {
7535        let tool_progress = matches!(
7536            &tool_call.status,
7537            ToolCallStatus::InProgress | ToolCallStatus::Pending
7538        );
7539
7540        let revealed_diff_editor = if let Some(entry) =
7541            self.entry_view_state.read(cx).entry(entry_ix)
7542            && let Some(editor) = entry.editor_for_diff(diff)
7543            && diff.read(cx).has_revealed_range(cx)
7544        {
7545            Some(editor)
7546        } else {
7547            None
7548        };
7549
7550        let show_top_border = !has_failed || revealed_diff_editor.is_some();
7551
7552        v_flex()
7553            .h_full()
7554            .when(show_top_border, |this| {
7555                this.border_t_1()
7556                    .when(has_failed, |this| this.border_dashed())
7557                    .border_color(self.tool_card_border_color(cx))
7558            })
7559            .child(if let Some(editor) = revealed_diff_editor {
7560                editor.into_any_element()
7561            } else if tool_progress && self.as_native_connection(cx).is_some() {
7562                self.render_diff_loading(cx)
7563            } else {
7564                Empty.into_any()
7565            })
7566            .into_any()
7567    }
7568
7569    fn render_markdown_output(
7570        &self,
7571        markdown: Entity<Markdown>,
7572        tool_call_id: acp::ToolCallId,
7573        context_ix: usize,
7574        card_layout: bool,
7575        window: &Window,
7576        cx: &Context<Self>,
7577    ) -> AnyElement {
7578        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
7579
7580        v_flex()
7581            .gap_2()
7582            .map(|this| {
7583                if card_layout {
7584                    this.p_2().when(context_ix > 0, |this| {
7585                        this.border_t_1()
7586                            .border_color(self.tool_card_border_color(cx))
7587                    })
7588                } else {
7589                    this.ml(rems(0.4))
7590                        .px_3p5()
7591                        .border_l_1()
7592                        .border_color(self.tool_card_border_color(cx))
7593                }
7594            })
7595            .text_xs()
7596            .text_color(cx.theme().colors().text_muted)
7597            .child(self.render_markdown(
7598                markdown,
7599                MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
7600            ))
7601            .when(!card_layout, |this| {
7602                this.child(
7603                    IconButton::new(button_id, IconName::ChevronUp)
7604                        .full_width()
7605                        .style(ButtonStyle::Outlined)
7606                        .icon_color(Color::Muted)
7607                        .on_click(cx.listener({
7608                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
7609                                this.expanded_tool_calls.remove(&tool_call_id);
7610                                cx.notify();
7611                            }
7612                        })),
7613                )
7614            })
7615            .into_any_element()
7616    }
7617
7618    fn render_image_output(
7619        &self,
7620        entry_ix: usize,
7621        image: Arc<gpui::Image>,
7622        location: Option<acp::ToolCallLocation>,
7623        card_layout: bool,
7624        show_dimensions: bool,
7625        cx: &Context<Self>,
7626    ) -> AnyElement {
7627        let dimensions_label = if show_dimensions {
7628            let format_name = match image.format() {
7629                gpui::ImageFormat::Png => "PNG",
7630                gpui::ImageFormat::Jpeg => "JPEG",
7631                gpui::ImageFormat::Webp => "WebP",
7632                gpui::ImageFormat::Gif => "GIF",
7633                gpui::ImageFormat::Svg => "SVG",
7634                gpui::ImageFormat::Bmp => "BMP",
7635                gpui::ImageFormat::Tiff => "TIFF",
7636                gpui::ImageFormat::Ico => "ICO",
7637            };
7638            let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
7639                .with_guessed_format()
7640                .ok()
7641                .and_then(|reader| reader.into_dimensions().ok());
7642            dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
7643        } else {
7644            None
7645        };
7646
7647        v_flex()
7648            .gap_2()
7649            .map(|this| {
7650                if card_layout {
7651                    this
7652                } else {
7653                    this.ml(rems(0.4))
7654                        .px_3p5()
7655                        .border_l_1()
7656                        .border_color(self.tool_card_border_color(cx))
7657                }
7658            })
7659            .when(dimensions_label.is_some() || location.is_some(), |this| {
7660                this.child(
7661                    h_flex()
7662                        .w_full()
7663                        .justify_between()
7664                        .items_center()
7665                        .children(dimensions_label.map(|label| {
7666                            Label::new(label)
7667                                .size(LabelSize::XSmall)
7668                                .color(Color::Muted)
7669                                .buffer_font(cx)
7670                        }))
7671                        .when_some(location, |this, _loc| {
7672                            this.child(
7673                                Button::new(("go-to-file", entry_ix), "Go to File")
7674                                    .label_size(LabelSize::Small)
7675                                    .on_click(cx.listener(move |this, _, window, cx| {
7676                                        this.open_tool_call_location(entry_ix, 0, window, cx);
7677                                    })),
7678                            )
7679                        }),
7680                )
7681            })
7682            .child(
7683                img(image)
7684                    .max_w_96()
7685                    .max_h_96()
7686                    .object_fit(ObjectFit::ScaleDown),
7687            )
7688            .into_any_element()
7689    }
7690
7691    fn render_subagent_tool_call(
7692        &self,
7693        active_session_id: &acp::SessionId,
7694        entry_ix: usize,
7695        tool_call: &ToolCall,
7696        subagent_session_id: Option<acp::SessionId>,
7697        focus_handle: &FocusHandle,
7698        window: &Window,
7699        cx: &Context<Self>,
7700    ) -> Div {
7701        let subagent_thread_view = subagent_session_id.and_then(|session_id| {
7702            self.server_view
7703                .upgrade()
7704                .and_then(|server_view| server_view.read(cx).as_connected())
7705                .and_then(|connected| connected.threads.get(&session_id))
7706        });
7707
7708        let content = self.render_subagent_card(
7709            active_session_id,
7710            entry_ix,
7711            subagent_thread_view,
7712            tool_call,
7713            focus_handle,
7714            window,
7715            cx,
7716        );
7717
7718        v_flex().mx_5().my_1p5().gap_3().child(content)
7719    }
7720
7721    fn render_subagent_card(
7722        &self,
7723        active_session_id: &acp::SessionId,
7724        entry_ix: usize,
7725        thread_view: Option<&Entity<ThreadView>>,
7726        tool_call: &ToolCall,
7727        focus_handle: &FocusHandle,
7728        window: &Window,
7729        cx: &Context<Self>,
7730    ) -> AnyElement {
7731        let thread = thread_view
7732            .as_ref()
7733            .map(|view| view.read(cx).thread.clone());
7734        let subagent_session_id = thread
7735            .as_ref()
7736            .map(|thread| thread.read(cx).session_id().clone());
7737        let action_log = thread.as_ref().map(|thread| thread.read(cx).action_log());
7738        let changed_buffers = action_log
7739            .map(|log| log.read(cx).changed_buffers(cx))
7740            .unwrap_or_default();
7741
7742        let is_pending_tool_call = thread_view
7743            .as_ref()
7744            .and_then(|tv| {
7745                let sid = tv.read(cx).thread.read(cx).session_id();
7746                self.conversation.read(cx).pending_tool_call(sid, cx)
7747            })
7748            .is_some();
7749
7750        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
7751        let files_changed = changed_buffers.len();
7752        let diff_stats = DiffStats::all_files(&changed_buffers, cx);
7753
7754        let is_running = matches!(
7755            tool_call.status,
7756            ToolCallStatus::Pending
7757                | ToolCallStatus::InProgress
7758                | ToolCallStatus::WaitingForConfirmation { .. }
7759        );
7760
7761        let is_failed = matches!(
7762            tool_call.status,
7763            ToolCallStatus::Failed | ToolCallStatus::Rejected
7764        );
7765
7766        let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled)
7767            || tool_call.content.iter().any(|c| match c {
7768                ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {
7769                    markdown.read(cx).source() == "User canceled"
7770                }
7771                _ => false,
7772            });
7773
7774        let thread_title = thread
7775            .as_ref()
7776            .and_then(|t| t.read(cx).title())
7777            .filter(|t| !t.is_empty());
7778        let tool_call_label = tool_call.label.read(cx).source().to_string();
7779        let has_tool_call_label = !tool_call_label.is_empty();
7780
7781        let has_title = thread_title.is_some() || has_tool_call_label;
7782        let has_no_title_or_canceled = !has_title || is_failed || is_cancelled;
7783
7784        let title: SharedString = if let Some(thread_title) = thread_title {
7785            thread_title
7786        } else if !tool_call_label.is_empty() {
7787            tool_call_label.into()
7788        } else if is_cancelled {
7789            "Subagent Canceled".into()
7790        } else if is_failed {
7791            "Subagent Failed".into()
7792        } else {
7793            "Spawning Agent…".into()
7794        };
7795
7796        let card_header_id = format!("subagent-header-{}", entry_ix);
7797        let status_icon = format!("status-icon-{}", entry_ix);
7798        let diff_stat_id = format!("subagent-diff-{}", entry_ix);
7799
7800        let icon = h_flex().w_4().justify_center().child(if is_running {
7801            SpinnerLabel::new()
7802                .size(LabelSize::Small)
7803                .into_any_element()
7804        } else if is_cancelled {
7805            div()
7806                .id(status_icon)
7807                .child(
7808                    Icon::new(IconName::Circle)
7809                        .size(IconSize::Small)
7810                        .color(Color::Custom(
7811                            cx.theme().colors().icon_disabled.opacity(0.5),
7812                        )),
7813                )
7814                .tooltip(Tooltip::text("Subagent Cancelled"))
7815                .into_any_element()
7816        } else if is_failed {
7817            div()
7818                .id(status_icon)
7819                .child(
7820                    Icon::new(IconName::Close)
7821                        .size(IconSize::Small)
7822                        .color(Color::Error),
7823                )
7824                .tooltip(Tooltip::text("Subagent Failed"))
7825                .into_any_element()
7826        } else {
7827            Icon::new(IconName::Check)
7828                .size(IconSize::Small)
7829                .color(Color::Success)
7830                .into_any_element()
7831        });
7832
7833        let has_expandable_content = thread
7834            .as_ref()
7835            .map_or(false, |thread| !thread.read(cx).entries().is_empty());
7836
7837        let tooltip_meta_description = if is_expanded {
7838            "Click to Collapse"
7839        } else {
7840            "Click to Preview"
7841        };
7842
7843        let error_message = self.subagent_error_message(&tool_call.status, tool_call, cx);
7844
7845        v_flex()
7846            .w_full()
7847            .rounded_md()
7848            .border_1()
7849            .when(has_no_title_or_canceled, |this| this.border_dashed())
7850            .border_color(self.tool_card_border_color(cx))
7851            .overflow_hidden()
7852            .child(
7853                h_flex()
7854                    .group(&card_header_id)
7855                    .h_8()
7856                    .p_1()
7857                    .w_full()
7858                    .justify_between()
7859                    .when(!has_no_title_or_canceled, |this| {
7860                        this.bg(self.tool_card_header_bg(cx))
7861                    })
7862                    .child(
7863                        h_flex()
7864                            .id(format!("subagent-title-{}", entry_ix))
7865                            .px_1()
7866                            .min_w_0()
7867                            .size_full()
7868                            .gap_2()
7869                            .justify_between()
7870                            .rounded_sm()
7871                            .overflow_hidden()
7872                            .child(
7873                                h_flex()
7874                                    .min_w_0()
7875                                    .w_full()
7876                                    .gap_1p5()
7877                                    .child(icon)
7878                                    .child(
7879                                        Label::new(title.to_string())
7880                                            .size(LabelSize::Custom(self.tool_name_font_size()))
7881                                            .truncate(),
7882                                    )
7883                                    .when(files_changed > 0, |this| {
7884                                        this.child(
7885                                            Label::new(format!(
7886                                                "{} {} changed",
7887                                                files_changed,
7888                                                if files_changed == 1 { "file" } else { "files" }
7889                                            ))
7890                                            .size(LabelSize::Custom(self.tool_name_font_size()))
7891                                            .color(Color::Muted),
7892                                        )
7893                                        .child(
7894                                            DiffStat::new(
7895                                                diff_stat_id.clone(),
7896                                                diff_stats.lines_added as usize,
7897                                                diff_stats.lines_removed as usize,
7898                                            )
7899                                            .label_size(LabelSize::Custom(
7900                                                self.tool_name_font_size(),
7901                                            )),
7902                                        )
7903                                    }),
7904                            )
7905                            .when(!has_no_title_or_canceled && !is_pending_tool_call, |this| {
7906                                this.tooltip(move |_, cx| {
7907                                    Tooltip::with_meta(
7908                                        title.to_string(),
7909                                        None,
7910                                        tooltip_meta_description,
7911                                        cx,
7912                                    )
7913                                })
7914                            })
7915                            .when(has_expandable_content && !is_pending_tool_call, |this| {
7916                                this.cursor_pointer()
7917                                    .hover(|s| s.bg(cx.theme().colors().element_hover))
7918                                    .child(
7919                                        div().visible_on_hover(card_header_id).child(
7920                                            Icon::new(if is_expanded {
7921                                                IconName::ChevronUp
7922                                            } else {
7923                                                IconName::ChevronDown
7924                                            })
7925                                            .color(Color::Muted)
7926                                            .size(IconSize::Small),
7927                                        ),
7928                                    )
7929                                    .on_click(cx.listener({
7930                                        let tool_call_id = tool_call.id.clone();
7931                                        move |this, _, _, cx| {
7932                                            if this.expanded_tool_calls.contains(&tool_call_id) {
7933                                                this.expanded_tool_calls.remove(&tool_call_id);
7934                                            } else {
7935                                                this.expanded_tool_calls
7936                                                    .insert(tool_call_id.clone());
7937                                            }
7938                                            let expanded =
7939                                                this.expanded_tool_calls.contains(&tool_call_id);
7940                                            telemetry::event!("Subagent Toggled", expanded);
7941                                            cx.notify();
7942                                        }
7943                                    }))
7944                            }),
7945                    )
7946                    .when(is_running && subagent_session_id.is_some(), |buttons| {
7947                        buttons.child(
7948                            IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
7949                                .icon_size(IconSize::Small)
7950                                .icon_color(Color::Error)
7951                                .tooltip(Tooltip::text("Stop Subagent"))
7952                                .when_some(
7953                                    thread_view
7954                                        .as_ref()
7955                                        .map(|view| view.read(cx).thread.clone()),
7956                                    |this, thread| {
7957                                        this.on_click(cx.listener(
7958                                            move |_this, _event, _window, cx| {
7959                                                telemetry::event!("Subagent Stopped");
7960                                                thread.update(cx, |thread, cx| {
7961                                                    thread.cancel(cx).detach();
7962                                                });
7963                                            },
7964                                        ))
7965                                    },
7966                                ),
7967                        )
7968                    }),
7969            )
7970            .when_some(thread_view, |this, thread_view| {
7971                let thread = &thread_view.read(cx).thread;
7972                let tv_session_id = thread.read(cx).session_id();
7973                let pending_tool_call = self
7974                    .conversation
7975                    .read(cx)
7976                    .pending_tool_call(tv_session_id, cx);
7977
7978                let nav_session_id = tv_session_id.clone();
7979
7980                let fullscreen_toggle = h_flex()
7981                    .id(entry_ix)
7982                    .py_1()
7983                    .w_full()
7984                    .justify_center()
7985                    .border_t_1()
7986                    .when(is_failed, |this| this.border_dashed())
7987                    .border_color(self.tool_card_border_color(cx))
7988                    .cursor_pointer()
7989                    .hover(|s| s.bg(cx.theme().colors().element_hover))
7990                    .child(
7991                        Icon::new(IconName::Maximize)
7992                            .color(Color::Muted)
7993                            .size(IconSize::Small),
7994                    )
7995                    .tooltip(Tooltip::text("Make Subagent Full Screen"))
7996                    .on_click(cx.listener(move |this, _event, window, cx| {
7997                        telemetry::event!("Subagent Maximized");
7998                        this.server_view
7999                            .update(cx, |this, cx| {
8000                                this.navigate_to_thread(nav_session_id.clone(), window, cx);
8001                            })
8002                            .ok();
8003                    }));
8004
8005                if is_running && let Some((_, subagent_tool_call_id, _)) = pending_tool_call {
8006                    if let Some((entry_ix, tool_call)) =
8007                        thread.read(cx).tool_call(&subagent_tool_call_id)
8008                    {
8009                        this.child(Divider::horizontal().color(DividerColor::Border))
8010                            .child(thread_view.read(cx).render_any_tool_call(
8011                                active_session_id,
8012                                entry_ix,
8013                                tool_call,
8014                                focus_handle,
8015                                true,
8016                                window,
8017                                cx,
8018                            ))
8019                            .child(fullscreen_toggle)
8020                    } else {
8021                        this
8022                    }
8023                } else {
8024                    this.when(is_expanded, |this| {
8025                        this.child(self.render_subagent_expanded_content(
8026                            thread_view,
8027                            tool_call,
8028                            window,
8029                            cx,
8030                        ))
8031                        .when_some(error_message, |this, message| {
8032                            this.child(
8033                                Callout::new()
8034                                    .severity(Severity::Error)
8035                                    .icon(IconName::XCircle)
8036                                    .title(message),
8037                            )
8038                        })
8039                        .child(fullscreen_toggle)
8040                    })
8041                }
8042            })
8043            .into_any_element()
8044    }
8045
8046    fn render_subagent_expanded_content(
8047        &self,
8048        thread_view: &Entity<ThreadView>,
8049        tool_call: &ToolCall,
8050        window: &Window,
8051        cx: &Context<Self>,
8052    ) -> impl IntoElement {
8053        const MAX_PREVIEW_ENTRIES: usize = 8;
8054
8055        let subagent_view = thread_view.read(cx);
8056        let session_id = subagent_view.thread.read(cx).session_id().clone();
8057
8058        let is_canceled_or_failed = matches!(
8059            tool_call.status,
8060            ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
8061        );
8062
8063        let editor_bg = cx.theme().colors().editor_background;
8064        let overlay = {
8065            div()
8066                .absolute()
8067                .inset_0()
8068                .size_full()
8069                .bg(linear_gradient(
8070                    180.,
8071                    linear_color_stop(editor_bg.opacity(0.5), 0.),
8072                    linear_color_stop(editor_bg.opacity(0.), 0.1),
8073                ))
8074                .block_mouse_except_scroll()
8075        };
8076
8077        let entries = subagent_view.thread.read(cx).entries();
8078        let total_entries = entries.len();
8079        let mut entry_range = if let Some(info) = tool_call.subagent_session_info.as_ref() {
8080            info.message_start_index
8081                ..info
8082                    .message_end_index
8083                    .map(|i| (i + 1).min(total_entries))
8084                    .unwrap_or(total_entries)
8085        } else {
8086            0..total_entries
8087        };
8088        entry_range.start = entry_range
8089            .end
8090            .saturating_sub(MAX_PREVIEW_ENTRIES)
8091            .max(entry_range.start);
8092        let start_ix = entry_range.start;
8093
8094        let scroll_handle = self
8095            .subagent_scroll_handles
8096            .borrow_mut()
8097            .entry(subagent_view.session_id.clone())
8098            .or_default()
8099            .clone();
8100
8101        scroll_handle.scroll_to_bottom();
8102
8103        let rendered_entries: Vec<AnyElement> = entries
8104            .get(entry_range)
8105            .unwrap_or_default()
8106            .iter()
8107            .enumerate()
8108            .map(|(i, entry)| {
8109                let actual_ix = start_ix + i;
8110                subagent_view.render_entry(actual_ix, total_entries, entry, window, cx)
8111            })
8112            .collect();
8113
8114        v_flex()
8115            .w_full()
8116            .border_t_1()
8117            .when(is_canceled_or_failed, |this| this.border_dashed())
8118            .border_color(self.tool_card_border_color(cx))
8119            .overflow_hidden()
8120            .child(
8121                div()
8122                    .pb_1()
8123                    .min_h_0()
8124                    .id(format!("subagent-entries-{}", session_id))
8125                    .track_scroll(&scroll_handle)
8126                    .children(rendered_entries),
8127            )
8128            .h_56()
8129            .child(overlay)
8130            .into_any_element()
8131    }
8132
8133    fn subagent_error_message(
8134        &self,
8135        status: &ToolCallStatus,
8136        tool_call: &ToolCall,
8137        cx: &App,
8138    ) -> Option<SharedString> {
8139        if matches!(status, ToolCallStatus::Failed) {
8140            tool_call.content.iter().find_map(|content| {
8141                if let ToolCallContent::ContentBlock(block) = content {
8142                    if let acp_thread::ContentBlock::Markdown { markdown } = block {
8143                        let source = markdown.read(cx).source().to_string();
8144                        if !source.is_empty() {
8145                            if source == "User canceled" {
8146                                return None;
8147                            } else {
8148                                return Some(SharedString::from(source));
8149                            }
8150                        }
8151                    }
8152                }
8153                None
8154            })
8155        } else {
8156            None
8157        }
8158    }
8159
8160    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
8161        cx.theme()
8162            .colors()
8163            .element_background
8164            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
8165    }
8166
8167    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
8168        cx.theme().colors().border.opacity(0.8)
8169    }
8170
8171    fn tool_name_font_size(&self) -> Rems {
8172        rems_from_px(13.)
8173    }
8174
8175    pub(crate) fn render_thread_error(
8176        &mut self,
8177        window: &mut Window,
8178        cx: &mut Context<Self>,
8179    ) -> Option<Div> {
8180        let content = match self.thread_error.as_ref()? {
8181            ThreadError::Other { message, .. } => {
8182                self.render_any_thread_error(message.clone(), window, cx)
8183            }
8184            ThreadError::Refusal => self.render_refusal_error(cx),
8185            ThreadError::AuthenticationRequired(error) => {
8186                self.render_authentication_required_error(error.clone(), cx)
8187            }
8188            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
8189            ThreadError::RateLimitExceeded { provider } => self.render_error_callout(
8190                "Rate Limit Reached",
8191                format!(
8192                    "{provider}'s rate limit was reached. Zed will retry automatically. \
8193                    You can also wait a moment and try again."
8194                )
8195                .into(),
8196                true,
8197                true,
8198                cx,
8199            ),
8200            ThreadError::ServerOverloaded { provider } => self.render_error_callout(
8201                "Provider Unavailable",
8202                format!(
8203                    "{provider}'s servers are temporarily unavailable. Zed will retry \
8204                    automatically. If the problem persists, check the provider's status page."
8205                )
8206                .into(),
8207                true,
8208                true,
8209                cx,
8210            ),
8211            ThreadError::PromptTooLarge => self.render_prompt_too_large_error(cx),
8212            ThreadError::NoApiKey { provider } => self.render_error_callout(
8213                "API Key Missing",
8214                format!(
8215                    "No API key is configured for {provider}. \
8216                    Add your key via the Agent Panel settings to continue."
8217                )
8218                .into(),
8219                false,
8220                true,
8221                cx,
8222            ),
8223            ThreadError::StreamError { provider } => self.render_error_callout(
8224                "Connection Interrupted",
8225                format!(
8226                    "The connection to {provider}'s API was interrupted. Zed will retry \
8227                    automatically. If the problem persists, check your network connection."
8228                )
8229                .into(),
8230                true,
8231                true,
8232                cx,
8233            ),
8234            ThreadError::InvalidApiKey { provider } => self.render_error_callout(
8235                "Invalid API Key",
8236                format!(
8237                    "The API key for {provider} is invalid or has expired. \
8238                    Update your key via the Agent Panel settings to continue."
8239                )
8240                .into(),
8241                false,
8242                false,
8243                cx,
8244            ),
8245            ThreadError::PermissionDenied { provider } => self.render_error_callout(
8246                "Permission Denied",
8247                format!(
8248                    "{provider}'s API rejected the request due to insufficient permissions. \
8249                    Check that your API key has access to this model."
8250                )
8251                .into(),
8252                false,
8253                false,
8254                cx,
8255            ),
8256            ThreadError::RequestFailed => self.render_error_callout(
8257                "Request Failed",
8258                "The request could not be completed after multiple attempts. \
8259                Try again in a moment."
8260                    .into(),
8261                true,
8262                false,
8263                cx,
8264            ),
8265            ThreadError::MaxOutputTokens => self.render_error_callout(
8266                "Output Limit Reached",
8267                "The model stopped because it reached its maximum output length. \
8268                You can ask it to continue where it left off."
8269                    .into(),
8270                false,
8271                false,
8272                cx,
8273            ),
8274            ThreadError::NoModelSelected => self.render_error_callout(
8275                "No Model Selected",
8276                "Select a model from the model picker below to get started.".into(),
8277                false,
8278                false,
8279                cx,
8280            ),
8281            ThreadError::ApiError { provider } => self.render_error_callout(
8282                "API Error",
8283                format!(
8284                    "{provider}'s API returned an unexpected error. \
8285                    If the problem persists, try switching models or restarting Zed."
8286                )
8287                .into(),
8288                true,
8289                true,
8290                cx,
8291            ),
8292        };
8293
8294        Some(div().child(content))
8295    }
8296
8297    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
8298        let model_or_agent_name = self.current_model_name(cx);
8299        let refusal_message = format!(
8300            "{} refused to respond to this prompt. \
8301            This can happen when a model believes the prompt violates its content policy \
8302            or safety guidelines, so rephrasing it can sometimes address the issue.",
8303            model_or_agent_name
8304        );
8305
8306        Callout::new()
8307            .severity(Severity::Error)
8308            .title("Request Refused")
8309            .icon(IconName::XCircle)
8310            .description(refusal_message.clone())
8311            .actions_slot(self.create_copy_button(&refusal_message))
8312            .dismiss_action(self.dismiss_error_button(cx))
8313    }
8314
8315    fn render_authentication_required_error(
8316        &self,
8317        error: SharedString,
8318        cx: &mut Context<Self>,
8319    ) -> Callout {
8320        Callout::new()
8321            .severity(Severity::Error)
8322            .title("Authentication Required")
8323            .icon(IconName::XCircle)
8324            .description(error.clone())
8325            .actions_slot(
8326                h_flex()
8327                    .gap_0p5()
8328                    .child(self.authenticate_button(cx))
8329                    .child(self.create_copy_button(error)),
8330            )
8331            .dismiss_action(self.dismiss_error_button(cx))
8332    }
8333
8334    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
8335        const ERROR_MESSAGE: &str =
8336            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
8337
8338        Callout::new()
8339            .severity(Severity::Error)
8340            .icon(IconName::XCircle)
8341            .title("Free Usage Exceeded")
8342            .description(ERROR_MESSAGE)
8343            .actions_slot(
8344                h_flex()
8345                    .gap_0p5()
8346                    .child(self.upgrade_button(cx))
8347                    .child(self.create_copy_button(ERROR_MESSAGE)),
8348            )
8349            .dismiss_action(self.dismiss_error_button(cx))
8350    }
8351
8352    fn render_error_callout(
8353        &self,
8354        title: &'static str,
8355        message: SharedString,
8356        show_retry: bool,
8357        show_copy: bool,
8358        cx: &mut Context<Self>,
8359    ) -> Callout {
8360        let can_resume = show_retry && self.thread.read(cx).can_retry(cx);
8361        let show_actions = can_resume || show_copy;
8362
8363        Callout::new()
8364            .severity(Severity::Error)
8365            .icon(IconName::XCircle)
8366            .title(title)
8367            .description(message.clone())
8368            .when(show_actions, |callout| {
8369                callout.actions_slot(
8370                    h_flex()
8371                        .gap_0p5()
8372                        .when(can_resume, |this| this.child(self.retry_button(cx)))
8373                        .when(show_copy, |this| {
8374                            this.child(self.create_copy_button(message.clone()))
8375                        }),
8376                )
8377            })
8378            .dismiss_action(self.dismiss_error_button(cx))
8379    }
8380
8381    fn render_prompt_too_large_error(&self, cx: &mut Context<Self>) -> Callout {
8382        const MESSAGE: &str = "This conversation is too long for the model's context window. \
8383            Start a new thread or remove some attached files to continue.";
8384
8385        Callout::new()
8386            .severity(Severity::Error)
8387            .icon(IconName::XCircle)
8388            .title("Context Too Large")
8389            .description(MESSAGE)
8390            .actions_slot(
8391                h_flex()
8392                    .gap_0p5()
8393                    .child(self.new_thread_button(cx))
8394                    .child(self.create_copy_button(MESSAGE)),
8395            )
8396            .dismiss_action(self.dismiss_error_button(cx))
8397    }
8398
8399    fn retry_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8400        Button::new("retry", "Retry")
8401            .label_size(LabelSize::Small)
8402            .style(ButtonStyle::Filled)
8403            .on_click(cx.listener(|this, _, _, cx| {
8404                this.retry_generation(cx);
8405            }))
8406    }
8407
8408    fn new_thread_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8409        Button::new("new_thread", "New Thread")
8410            .label_size(LabelSize::Small)
8411            .style(ButtonStyle::Filled)
8412            .on_click(cx.listener(|this, _, window, cx| {
8413                this.clear_thread_error(cx);
8414                window.dispatch_action(NewThread.boxed_clone(), cx);
8415            }))
8416    }
8417
8418    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8419        Button::new("upgrade", "Upgrade")
8420            .label_size(LabelSize::Small)
8421            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
8422            .on_click(cx.listener({
8423                move |this, _, _, cx| {
8424                    this.clear_thread_error(cx);
8425                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
8426                }
8427            }))
8428    }
8429
8430    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8431        Button::new("authenticate", "Authenticate")
8432            .label_size(LabelSize::Small)
8433            .style(ButtonStyle::Filled)
8434            .on_click(cx.listener({
8435                move |this, _, window, cx| {
8436                    let server_view = this.server_view.clone();
8437                    let agent_name = this.agent_id.clone();
8438
8439                    this.clear_thread_error(cx);
8440                    if let Some(message) = this.in_flight_prompt.take() {
8441                        this.message_editor.update(cx, |editor, cx| {
8442                            editor.set_message(message, window, cx);
8443                        });
8444                    }
8445                    let connection = this.thread.read(cx).connection().clone();
8446                    window.defer(cx, |window, cx| {
8447                        ConversationView::handle_auth_required(
8448                            server_view,
8449                            AuthRequired::new(),
8450                            agent_name,
8451                            connection,
8452                            window,
8453                            cx,
8454                        );
8455                    })
8456                }
8457            }))
8458    }
8459
8460    fn current_model_name(&self, cx: &App) -> SharedString {
8461        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
8462        // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
8463        // This provides better clarity about what refused the request
8464        if self.as_native_connection(cx).is_some() {
8465            self.model_selector
8466                .clone()
8467                .and_then(|selector| selector.read(cx).active_model(cx))
8468                .map(|model| model.name.clone())
8469                .unwrap_or_else(|| SharedString::from("The model"))
8470        } else {
8471            // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
8472            self.agent_id.0.clone()
8473        }
8474    }
8475
8476    fn render_any_thread_error(
8477        &mut self,
8478        error: SharedString,
8479        window: &mut Window,
8480        cx: &mut Context<'_, Self>,
8481    ) -> Callout {
8482        let can_resume = self.thread.read(cx).can_retry(cx);
8483
8484        let markdown = if let Some(markdown) = &self.thread_error_markdown {
8485            markdown.clone()
8486        } else {
8487            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
8488            self.thread_error_markdown = Some(markdown.clone());
8489            markdown
8490        };
8491
8492        let markdown_style =
8493            MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx);
8494        let description = self
8495            .render_markdown(markdown, markdown_style)
8496            .into_any_element();
8497
8498        Callout::new()
8499            .severity(Severity::Error)
8500            .icon(IconName::XCircle)
8501            .title("An Error Happened")
8502            .description_slot(description)
8503            .actions_slot(
8504                h_flex()
8505                    .gap_0p5()
8506                    .when(can_resume, |this| {
8507                        this.child(
8508                            IconButton::new("retry", IconName::RotateCw)
8509                                .icon_size(IconSize::Small)
8510                                .tooltip(Tooltip::text("Retry Generation"))
8511                                .on_click(cx.listener(|this, _, _window, cx| {
8512                                    this.retry_generation(cx);
8513                                })),
8514                        )
8515                    })
8516                    .child(self.create_copy_button(error.to_string())),
8517            )
8518            .dismiss_action(self.dismiss_error_button(cx))
8519    }
8520
8521    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
8522        let workspace = self.workspace.clone();
8523        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
8524            open_link(text, &workspace, window, cx);
8525        })
8526    }
8527
8528    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
8529        let message = message.into();
8530
8531        CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
8532    }
8533
8534    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8535        IconButton::new("dismiss", IconName::Close)
8536            .icon_size(IconSize::Small)
8537            .tooltip(Tooltip::text("Dismiss"))
8538            .on_click(cx.listener({
8539                move |this, _, _, cx| {
8540                    this.clear_thread_error(cx);
8541                    cx.notify();
8542                }
8543            }))
8544    }
8545
8546    fn render_resume_notice(_cx: &Context<Self>) -> AnyElement {
8547        let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
8548
8549        Callout::new()
8550            .border_position(ui::BorderPosition::Bottom)
8551            .severity(Severity::Info)
8552            .icon(IconName::Info)
8553            .title("Resumed Session")
8554            .description(description)
8555            .into_any_element()
8556    }
8557
8558    fn update_recent_history_from_cache(
8559        &mut self,
8560        history: &Entity<ThreadHistory>,
8561        cx: &mut Context<Self>,
8562    ) {
8563        self.recent_history_entries = history.read(cx).get_recent_sessions(3);
8564        self.hovered_recent_history_item = None;
8565        cx.notify();
8566    }
8567
8568    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
8569        Callout::new()
8570            .icon(IconName::Warning)
8571            .severity(Severity::Warning)
8572            .title("Codex on Windows")
8573            .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
8574            .actions_slot(
8575                Button::new("open-wsl-modal", "Open in WSL").on_click(cx.listener({
8576                    move |_, _, _window, cx| {
8577                        #[cfg(windows)]
8578                        _window.dispatch_action(
8579                            zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
8580                            cx,
8581                        );
8582                        cx.notify();
8583                    }
8584                })),
8585            )
8586            .dismiss_action(
8587                IconButton::new("dismiss", IconName::Close)
8588                    .icon_size(IconSize::Small)
8589                    .icon_color(Color::Muted)
8590                    .tooltip(Tooltip::text("Dismiss Warning"))
8591                    .on_click(cx.listener({
8592                        move |this, _, _, cx| {
8593                            this.show_codex_windows_warning = false;
8594                            cx.notify();
8595                        }
8596                    })),
8597            )
8598    }
8599
8600    fn render_external_source_prompt_warning(&self, cx: &mut Context<Self>) -> Callout {
8601        Callout::new()
8602            .icon(IconName::Warning)
8603            .severity(Severity::Warning)
8604            .title("Review before sending")
8605            .description("This prompt was pre-filled by an external link. Read it carefully before you send it.")
8606            .dismiss_action(
8607                IconButton::new("dismiss-external-source-prompt-warning", IconName::Close)
8608                    .icon_size(IconSize::Small)
8609                    .icon_color(Color::Muted)
8610                    .tooltip(Tooltip::text("Dismiss Warning"))
8611                    .on_click(cx.listener({
8612                        move |this, _, _, cx| {
8613                            this.show_external_source_prompt_warning = false;
8614                            cx.notify();
8615                        }
8616                    })),
8617            )
8618    }
8619
8620    fn render_multi_root_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
8621        if self.multi_root_callout_dismissed {
8622            return None;
8623        }
8624
8625        if self.as_native_connection(cx).is_some() {
8626            return None;
8627        }
8628
8629        let project = self.project.upgrade()?;
8630        let worktree_count = project.read(cx).visible_worktrees(cx).count();
8631        if worktree_count <= 1 {
8632            return None;
8633        }
8634
8635        let work_dirs = self.thread.read(cx).work_dirs()?;
8636        let active_dir = work_dirs
8637            .ordered_paths()
8638            .next()
8639            .and_then(|p| p.file_name())
8640            .map(|name| name.to_string_lossy().to_string())
8641            .unwrap_or_else(|| "one folder".to_string());
8642
8643        let description = format!(
8644            "This agent only operates on \"{}\". Other folders in this workspace are not accessible to it.",
8645            active_dir
8646        );
8647
8648        Some(
8649            Callout::new()
8650                .severity(Severity::Warning)
8651                .icon(IconName::Warning)
8652                .title("External Agents currently don't support multi-root workspaces")
8653                .description(description)
8654                .border_position(ui::BorderPosition::Bottom)
8655                .dismiss_action(
8656                    IconButton::new("dismiss-multi-root-callout", IconName::Close)
8657                        .icon_size(IconSize::Small)
8658                        .tooltip(Tooltip::text("Dismiss"))
8659                        .on_click(cx.listener(|this, _, _, cx| {
8660                            this.multi_root_callout_dismissed = true;
8661                            cx.notify();
8662                        })),
8663                ),
8664        )
8665    }
8666
8667    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
8668        let server_view = self.server_view.clone();
8669        let has_version = !version.is_empty();
8670        let title = if has_version {
8671            "New version available"
8672        } else {
8673            "Agent update available"
8674        };
8675        let button_label = if has_version {
8676            format!("Update to v{}", version)
8677        } else {
8678            "Reconnect".to_string()
8679        };
8680
8681        v_flex().w_full().justify_end().child(
8682            h_flex()
8683                .p_2()
8684                .pr_3()
8685                .w_full()
8686                .gap_1p5()
8687                .border_t_1()
8688                .border_color(cx.theme().colors().border)
8689                .bg(cx.theme().colors().element_background)
8690                .child(
8691                    h_flex()
8692                        .flex_1()
8693                        .gap_1p5()
8694                        .child(
8695                            Icon::new(IconName::Download)
8696                                .color(Color::Accent)
8697                                .size(IconSize::Small),
8698                        )
8699                        .child(Label::new(title).size(LabelSize::Small)),
8700                )
8701                .child(
8702                    Button::new("update-button", button_label)
8703                        .label_size(LabelSize::Small)
8704                        .style(ButtonStyle::Tinted(TintColor::Accent))
8705                        .on_click(move |_, window, cx| {
8706                            server_view
8707                                .update(cx, |view, cx| view.reset(window, cx))
8708                                .ok();
8709                        }),
8710                ),
8711        )
8712    }
8713
8714    fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
8715        if self.token_limit_callout_dismissed {
8716            return None;
8717        }
8718
8719        let token_usage = self.thread.read(cx).token_usage()?;
8720        let ratio = token_usage.ratio();
8721
8722        let (severity, icon, title) = match ratio {
8723            acp_thread::TokenUsageRatio::Normal => return None,
8724            acp_thread::TokenUsageRatio::Warning => (
8725                Severity::Warning,
8726                IconName::Warning,
8727                "Thread reaching the token limit soon",
8728            ),
8729            acp_thread::TokenUsageRatio::Exceeded => (
8730                Severity::Error,
8731                IconName::XCircle,
8732                "Thread reached the token limit",
8733            ),
8734        };
8735
8736        let description = "To continue, start a new thread from a summary.";
8737
8738        Some(
8739            Callout::new()
8740                .severity(severity)
8741                .icon(icon)
8742                .title(title)
8743                .description(description)
8744                .actions_slot(
8745                    h_flex().gap_0p5().child(
8746                        Button::new("start-new-thread", "Start New Thread")
8747                            .label_size(LabelSize::Small)
8748                            .on_click(cx.listener(|this, _, window, cx| {
8749                                let session_id = this.thread.read(cx).session_id().clone();
8750                                window.dispatch_action(
8751                                    crate::NewNativeAgentThreadFromSummary {
8752                                        from_session_id: session_id,
8753                                    }
8754                                    .boxed_clone(),
8755                                    cx,
8756                                );
8757                            })),
8758                    ),
8759                )
8760                .dismiss_action(self.dismiss_error_button(cx)),
8761        )
8762    }
8763
8764    fn open_permission_dropdown(
8765        &mut self,
8766        _: &crate::OpenPermissionDropdown,
8767        window: &mut Window,
8768        cx: &mut Context<Self>,
8769    ) {
8770        let menu_handle = self.permission_dropdown_handle.clone();
8771        window.defer(cx, move |window, cx| {
8772            menu_handle.toggle(window, cx);
8773        });
8774    }
8775
8776    fn open_add_context_menu(
8777        &mut self,
8778        _action: &OpenAddContextMenu,
8779        window: &mut Window,
8780        cx: &mut Context<Self>,
8781    ) {
8782        let menu_handle = self.add_context_menu_handle.clone();
8783        window.defer(cx, move |window, cx| {
8784            menu_handle.toggle(window, cx);
8785        });
8786    }
8787
8788    fn toggle_fast_mode(&mut self, cx: &mut Context<Self>) {
8789        if !self.fast_mode_available(cx) {
8790            return;
8791        }
8792        let Some(thread) = self.as_native_thread(cx) else {
8793            return;
8794        };
8795        thread.update(cx, |thread, cx| {
8796            let new_speed = thread
8797                .speed()
8798                .map(|speed| speed.toggle())
8799                .unwrap_or(Speed::Fast);
8800            thread.set_speed(new_speed, cx);
8801
8802            let fs = thread.project().read(cx).fs().clone();
8803            update_settings_file(fs, cx, move |settings, _| {
8804                if let Some(agent) = settings.agent.as_mut()
8805                    && let Some(default_model) = agent.default_model.as_mut()
8806                {
8807                    default_model.speed = Some(new_speed);
8808                }
8809            });
8810        });
8811    }
8812
8813    fn cycle_thinking_effort(&mut self, cx: &mut Context<Self>) {
8814        let Some(thread) = self.as_native_thread(cx) else {
8815            return;
8816        };
8817
8818        let (effort_levels, current_effort) = {
8819            let thread_ref = thread.read(cx);
8820            let Some(model) = thread_ref.model() else {
8821                return;
8822            };
8823            if !model.supports_thinking() || !thread_ref.thinking_enabled() {
8824                return;
8825            }
8826            let effort_levels = model.supported_effort_levels();
8827            if effort_levels.is_empty() {
8828                return;
8829            }
8830            let current_effort = thread_ref.thinking_effort().cloned();
8831            (effort_levels, current_effort)
8832        };
8833
8834        let current_index = current_effort.and_then(|current| {
8835            effort_levels
8836                .iter()
8837                .position(|level| level.value == current)
8838        });
8839        let next_index = match current_index {
8840            Some(index) => (index + 1) % effort_levels.len(),
8841            None => 0,
8842        };
8843        let next_effort = effort_levels[next_index].value.to_string();
8844
8845        thread.update(cx, |thread, cx| {
8846            thread.set_thinking_effort(Some(next_effort.clone()), cx);
8847
8848            let fs = thread.project().read(cx).fs().clone();
8849            update_settings_file(fs, cx, move |settings, _| {
8850                if let Some(agent) = settings.agent.as_mut()
8851                    && let Some(default_model) = agent.default_model.as_mut()
8852                {
8853                    default_model.effort = Some(next_effort);
8854                }
8855            });
8856        });
8857    }
8858
8859    fn toggle_thinking_effort_menu(
8860        &mut self,
8861        _action: &ToggleThinkingEffortMenu,
8862        window: &mut Window,
8863        cx: &mut Context<Self>,
8864    ) {
8865        let menu_handle = self.thinking_effort_menu_handle.clone();
8866        window.defer(cx, move |window, cx| {
8867            menu_handle.toggle(window, cx);
8868        });
8869    }
8870}
8871
8872impl Render for ThreadView {
8873    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8874        let has_messages = self.list_state.item_count() > 0;
8875        let list_state = self.list_state.clone();
8876
8877        let conversation = v_flex()
8878            .when(self.resumed_without_history, |this| {
8879                this.child(Self::render_resume_notice(cx))
8880            })
8881            .map(|this| {
8882                if has_messages {
8883                    this.flex_1()
8884                        .size_full()
8885                        .child(self.render_entries(cx))
8886                        .vertical_scrollbar_for(&list_state, window, cx)
8887                        .into_any()
8888                } else {
8889                    this.into_any()
8890                }
8891            });
8892
8893        v_flex()
8894            .key_context("AcpThread")
8895            .track_focus(&self.focus_handle)
8896            .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8897                if this.parent_session_id.is_none() {
8898                    this.cancel_generation(cx);
8899                }
8900            }))
8901            .on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
8902                if let Some(parent_session_id) = this.thread.read(cx).parent_session_id().cloned() {
8903                    this.server_view
8904                        .update(cx, |view, cx| {
8905                            view.navigate_to_thread(parent_session_id, window, cx);
8906                        })
8907                        .ok();
8908                }
8909            }))
8910            .on_action(cx.listener(Self::keep_all))
8911            .on_action(cx.listener(Self::reject_all))
8912            .on_action(cx.listener(Self::undo_last_reject))
8913            .on_action(cx.listener(Self::allow_always))
8914            .on_action(cx.listener(Self::allow_once))
8915            .on_action(cx.listener(Self::reject_once))
8916            .on_action(cx.listener(Self::handle_authorize_tool_call))
8917            .on_action(cx.listener(Self::handle_select_permission_granularity))
8918            .on_action(cx.listener(Self::handle_toggle_command_pattern))
8919            .on_action(cx.listener(Self::open_permission_dropdown))
8920            .on_action(cx.listener(Self::open_add_context_menu))
8921            .on_action(cx.listener(Self::scroll_output_page_up))
8922            .on_action(cx.listener(Self::scroll_output_page_down))
8923            .on_action(cx.listener(Self::scroll_output_line_up))
8924            .on_action(cx.listener(Self::scroll_output_line_down))
8925            .on_action(cx.listener(Self::scroll_output_to_top))
8926            .on_action(cx.listener(Self::scroll_output_to_bottom))
8927            .on_action(cx.listener(Self::scroll_output_to_previous_message))
8928            .on_action(cx.listener(Self::scroll_output_to_next_message))
8929            .on_action(cx.listener(|this, _: &ToggleFastMode, _window, cx| {
8930                this.toggle_fast_mode(cx);
8931            }))
8932            .on_action(cx.listener(|this, _: &ToggleThinkingMode, _window, cx| {
8933                if this.thread.read(cx).status() != ThreadStatus::Idle {
8934                    return;
8935                }
8936                if let Some(thread) = this.as_native_thread(cx) {
8937                    thread.update(cx, |thread, cx| {
8938                        thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
8939                    });
8940                }
8941            }))
8942            .on_action(cx.listener(|this, _: &CycleThinkingEffort, _window, cx| {
8943                if this.thread.read(cx).status() != ThreadStatus::Idle {
8944                    return;
8945                }
8946                this.cycle_thinking_effort(cx);
8947            }))
8948            .on_action(
8949                cx.listener(|this, action: &ToggleThinkingEffortMenu, window, cx| {
8950                    if this.thread.read(cx).status() != ThreadStatus::Idle {
8951                        return;
8952                    }
8953                    this.toggle_thinking_effort_menu(action, window, cx);
8954                }),
8955            )
8956            .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8957                this.send_queued_message_at_index(0, true, window, cx);
8958            }))
8959            .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
8960                this.remove_from_queue(0, cx);
8961                cx.notify();
8962            }))
8963            .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
8964                this.move_queued_message_to_main_editor(0, None, None, window, cx);
8965            }))
8966            .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8967                this.local_queued_messages.clear();
8968                this.sync_queue_flag_to_native_thread(cx);
8969                this.can_fast_track_queue = false;
8970                cx.notify();
8971            }))
8972            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8973                if this.thread.read(cx).status() != ThreadStatus::Idle {
8974                    return;
8975                }
8976                if let Some(config_options_view) = this.config_options_view.clone() {
8977                    let handled = config_options_view.update(cx, |view, cx| {
8978                        view.toggle_category_picker(
8979                            acp::SessionConfigOptionCategory::Mode,
8980                            window,
8981                            cx,
8982                        )
8983                    });
8984                    if handled {
8985                        return;
8986                    }
8987                }
8988
8989                if let Some(profile_selector) = this.profile_selector.clone() {
8990                    profile_selector.read(cx).menu_handle().toggle(window, cx);
8991                } else if let Some(mode_selector) = this.mode_selector.clone() {
8992                    mode_selector.read(cx).menu_handle().toggle(window, cx);
8993                }
8994            }))
8995            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8996                if this.thread.read(cx).status() != ThreadStatus::Idle {
8997                    return;
8998                }
8999                if let Some(config_options_view) = this.config_options_view.clone() {
9000                    let handled = config_options_view.update(cx, |view, cx| {
9001                        view.cycle_category_option(
9002                            acp::SessionConfigOptionCategory::Mode,
9003                            false,
9004                            cx,
9005                        )
9006                    });
9007                    if handled {
9008                        return;
9009                    }
9010                }
9011
9012                if let Some(profile_selector) = this.profile_selector.clone() {
9013                    profile_selector.update(cx, |profile_selector, cx| {
9014                        profile_selector.cycle_profile(cx);
9015                    });
9016                } else if let Some(mode_selector) = this.mode_selector.clone() {
9017                    mode_selector.update(cx, |mode_selector, cx| {
9018                        mode_selector.cycle_mode(window, cx);
9019                    });
9020                }
9021            }))
9022            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
9023                if this.thread.read(cx).status() != ThreadStatus::Idle {
9024                    return;
9025                }
9026                if let Some(config_options_view) = this.config_options_view.clone() {
9027                    let handled = config_options_view.update(cx, |view, cx| {
9028                        view.toggle_category_picker(
9029                            acp::SessionConfigOptionCategory::Model,
9030                            window,
9031                            cx,
9032                        )
9033                    });
9034                    if handled {
9035                        return;
9036                    }
9037                }
9038
9039                if let Some(model_selector) = this.model_selector.clone() {
9040                    model_selector
9041                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
9042                }
9043            }))
9044            .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
9045                if this.thread.read(cx).status() != ThreadStatus::Idle {
9046                    return;
9047                }
9048                if let Some(config_options_view) = this.config_options_view.clone() {
9049                    let handled = config_options_view.update(cx, |view, cx| {
9050                        view.cycle_category_option(
9051                            acp::SessionConfigOptionCategory::Model,
9052                            true,
9053                            cx,
9054                        )
9055                    });
9056                    if handled {
9057                        return;
9058                    }
9059                }
9060
9061                if let Some(model_selector) = this.model_selector.clone() {
9062                    model_selector.update(cx, |model_selector, cx| {
9063                        model_selector.cycle_favorite_models(window, cx);
9064                    });
9065                }
9066            }))
9067            .size_full()
9068            .children(self.render_subagent_titlebar(cx))
9069            .child(conversation)
9070            .children(self.render_multi_root_callout(cx))
9071            .children(self.render_activity_bar(window, cx))
9072            .when(self.show_external_source_prompt_warning, |this| {
9073                this.child(self.render_external_source_prompt_warning(cx))
9074            })
9075            .when(self.show_codex_windows_warning, |this| {
9076                this.child(self.render_codex_windows_warning(cx))
9077            })
9078            .children(self.render_thread_retry_status_callout())
9079            .children(self.render_thread_error(window, cx))
9080            .when_some(
9081                match has_messages {
9082                    true => None,
9083                    false => self.new_server_version_available.clone(),
9084                },
9085                |this, version| this.child(self.render_new_version_callout(&version, cx)),
9086            )
9087            .children(self.render_token_limit_callout(cx))
9088            .child(self.render_message_editor(window, cx))
9089    }
9090}
9091
9092pub(crate) fn open_link(
9093    url: SharedString,
9094    workspace: &WeakEntity<Workspace>,
9095    window: &mut Window,
9096    cx: &mut App,
9097) {
9098    let Some(workspace) = workspace.upgrade() else {
9099        cx.open_url(&url);
9100        return;
9101    };
9102
9103    if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err() {
9104        workspace.update(cx, |workspace, cx| match mention {
9105            MentionUri::File { abs_path } => {
9106                let project = workspace.project();
9107                let Some(path) =
9108                    project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
9109                else {
9110                    return;
9111                };
9112
9113                workspace
9114                    .open_path(path, None, true, window, cx)
9115                    .detach_and_log_err(cx);
9116            }
9117            MentionUri::PastedImage { .. } => {}
9118            MentionUri::Directory { abs_path } => {
9119                let project = workspace.project();
9120                let Some(entry_id) = project.update(cx, |project, cx| {
9121                    let path = project.find_project_path(abs_path, cx)?;
9122                    project.entry_for_path(&path, cx).map(|entry| entry.id)
9123                }) else {
9124                    return;
9125                };
9126
9127                project.update(cx, |_, cx| {
9128                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
9129                });
9130            }
9131            MentionUri::Symbol {
9132                abs_path: path,
9133                line_range,
9134                ..
9135            }
9136            | MentionUri::Selection {
9137                abs_path: Some(path),
9138                line_range,
9139            } => {
9140                let project = workspace.project();
9141                let Some(path) =
9142                    project.update(cx, |project, cx| project.find_project_path(path, cx))
9143                else {
9144                    return;
9145                };
9146
9147                let item = workspace.open_path(path, None, true, window, cx);
9148                window
9149                    .spawn(cx, async move |cx| {
9150                        let Some(editor) = item.await?.downcast::<Editor>() else {
9151                            return Ok(());
9152                        };
9153                        let range =
9154                            Point::new(*line_range.start(), 0)..Point::new(*line_range.start(), 0);
9155                        editor
9156                            .update_in(cx, |editor, window, cx| {
9157                                editor.change_selections(
9158                                    SelectionEffects::scroll(Autoscroll::center()),
9159                                    window,
9160                                    cx,
9161                                    |s| s.select_ranges(vec![range]),
9162                                );
9163                            })
9164                            .ok();
9165                        anyhow::Ok(())
9166                    })
9167                    .detach_and_log_err(cx);
9168            }
9169            MentionUri::Selection { abs_path: None, .. } => {}
9170            MentionUri::Thread { id, name } => {
9171                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
9172                    panel.update(cx, |panel, cx| {
9173                        panel.open_thread(id, None, Some(name.into()), window, cx)
9174                    });
9175                }
9176            }
9177            MentionUri::Rule { id, .. } => {
9178                let PromptId::User { uuid } = id else {
9179                    return;
9180                };
9181                window.dispatch_action(
9182                    Box::new(OpenRulesLibrary {
9183                        prompt_to_select: Some(uuid.0),
9184                    }),
9185                    cx,
9186                )
9187            }
9188            MentionUri::Fetch { url } => {
9189                cx.open_url(url.as_str());
9190            }
9191            MentionUri::Diagnostics { .. } => {}
9192            MentionUri::TerminalSelection { .. } => {}
9193            MentionUri::GitDiff { .. } => {}
9194            MentionUri::MergeConflict { .. } => {}
9195        })
9196    } else {
9197        cx.open_url(&url);
9198    }
9199}