thread_view.rs

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