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