thread_view.rs

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