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