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