thread_view.rs

   1use acp_thread::ContentBlock;
   2use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
   3use editor::actions::OpenExcerpts;
   4
   5use crate::StartThreadIn;
   6use gpui::{Corner, List};
   7use language_model::{LanguageModelEffortLevel, Speed};
   8use settings::update_settings_file;
   9use ui::{ButtonLike, SplitButton, SplitButtonStyle, Tab};
  10use workspace::SERIALIZATION_THROTTLE_TIME;
  11
  12use super::*;
  13
  14#[derive(Default)]
  15struct ThreadFeedbackState {
  16    feedback: Option<ThreadFeedback>,
  17    comments_editor: Option<Entity<Editor>>,
  18}
  19
  20impl ThreadFeedbackState {
  21    pub fn submit(
  22        &mut self,
  23        thread: Entity<AcpThread>,
  24        feedback: ThreadFeedback,
  25        window: &mut Window,
  26        cx: &mut App,
  27    ) {
  28        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
  29            return;
  30        };
  31
  32        let project = thread.read(cx).project().read(cx);
  33        let client = project.client();
  34        let user_store = project.user_store();
  35        let organization = user_store.read(cx).current_organization();
  36
  37        if self.feedback == Some(feedback) {
  38            return;
  39        }
  40
  41        self.feedback = Some(feedback);
  42        match feedback {
  43            ThreadFeedback::Positive => {
  44                self.comments_editor = None;
  45            }
  46            ThreadFeedback::Negative => {
  47                self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
  48            }
  49        }
  50        let session_id = thread.read(cx).session_id().clone();
  51        let parent_session_id = thread.read(cx).parent_session_id().cloned();
  52        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
  53        let task = telemetry.thread_data(&session_id, cx);
  54        let rating = match feedback {
  55            ThreadFeedback::Positive => "positive",
  56            ThreadFeedback::Negative => "negative",
  57        };
  58        cx.background_spawn(async move {
  59            let thread = task.await?;
  60
  61            client
  62                .cloud_client()
  63                .submit_agent_feedback(SubmitAgentThreadFeedbackBody {
  64                    organization_id: organization.map(|organization| organization.id.clone()),
  65                    agent: agent_telemetry_id.to_string(),
  66                    session_id: session_id.to_string(),
  67                    parent_session_id: parent_session_id.map(|id| id.to_string()),
  68                    rating: rating.to_string(),
  69                    thread,
  70                })
  71                .await?;
  72
  73            anyhow::Ok(())
  74        })
  75        .detach_and_log_err(cx);
  76    }
  77
  78    pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
  79        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
  80            return;
  81        };
  82
  83        let Some(comments) = self
  84            .comments_editor
  85            .as_ref()
  86            .map(|editor| editor.read(cx).text(cx))
  87            .filter(|text| !text.trim().is_empty())
  88        else {
  89            return;
  90        };
  91
  92        self.comments_editor.take();
  93
  94        let project = thread.read(cx).project().read(cx);
  95        let client = project.client();
  96        let user_store = project.user_store();
  97        let organization = user_store.read(cx).current_organization();
  98
  99        let session_id = thread.read(cx).session_id().clone();
 100        let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
 101        let task = telemetry.thread_data(&session_id, cx);
 102        cx.background_spawn(async move {
 103            let thread = task.await?;
 104
 105            client
 106                .cloud_client()
 107                .submit_agent_feedback_comments(SubmitAgentThreadFeedbackCommentsBody {
 108                    organization_id: organization.map(|organization| organization.id.clone()),
 109                    agent: agent_telemetry_id.to_string(),
 110                    session_id: session_id.to_string(),
 111                    comments,
 112                    thread,
 113                })
 114                .await?;
 115
 116            anyhow::Ok(())
 117        })
 118        .detach_and_log_err(cx);
 119    }
 120
 121    pub fn clear(&mut self) {
 122        *self = Self::default()
 123    }
 124
 125    pub fn dismiss_comments(&mut self) {
 126        self.comments_editor.take();
 127    }
 128
 129    fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
 130        let buffer = cx.new(|cx| {
 131            let empty_string = String::new();
 132            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
 133        });
 134
 135        let editor = cx.new(|cx| {
 136            let mut editor = Editor::new(
 137                editor::EditorMode::AutoHeight {
 138                    min_lines: 1,
 139                    max_lines: Some(4),
 140                },
 141                buffer,
 142                None,
 143                window,
 144                cx,
 145            );
 146            editor.set_placeholder_text(
 147                "What went wrong? Share your feedback so we can improve.",
 148                window,
 149                cx,
 150            );
 151            editor
 152        });
 153
 154        editor.read(cx).focus_handle(cx).focus(window, cx);
 155        editor
 156    }
 157}
 158
 159pub enum AcpThreadViewEvent {
 160    FirstSendRequested { content: Vec<acp::ContentBlock> },
 161}
 162
 163impl EventEmitter<AcpThreadViewEvent> for ThreadView {}
 164
 165pub struct ThreadView {
 166    pub id: acp::SessionId,
 167    pub parent_id: Option<acp::SessionId>,
 168    pub thread: Entity<AcpThread>,
 169    pub(crate) conversation: Entity<super::Conversation>,
 170    pub server_view: WeakEntity<ConversationView>,
 171    pub agent_icon: IconName,
 172    pub agent_icon_from_external_svg: Option<SharedString>,
 173    pub agent_id: AgentId,
 174    pub focus_handle: FocusHandle,
 175    pub workspace: WeakEntity<Workspace>,
 176    pub entry_view_state: Entity<EntryViewState>,
 177    pub title_editor: Entity<Editor>,
 178    pub config_options_view: Option<Entity<ConfigOptionsView>>,
 179    pub mode_selector: Option<Entity<ModeSelector>>,
 180    pub model_selector: Option<Entity<ModelSelectorPopover>>,
 181    pub profile_selector: Option<Entity<ProfileSelector>>,
 182    pub permission_dropdown_handle: PopoverMenuHandle<ContextMenu>,
 183    pub thread_retry_status: Option<RetryStatus>,
 184    pub(super) thread_error: Option<ThreadError>,
 185    pub thread_error_markdown: Option<Entity<Markdown>>,
 186    pub token_limit_callout_dismissed: bool,
 187    pub last_token_limit_telemetry: Option<acp_thread::TokenUsageRatio>,
 188    thread_feedback: ThreadFeedbackState,
 189    pub list_state: ListState,
 190    pub prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
 191    pub available_commands: Rc<RefCell<Vec<agent_client_protocol::AvailableCommand>>>,
 192    /// Tracks which tool calls have their content/output expanded.
 193    /// Used for showing/hiding tool call results, terminal output, etc.
 194    pub expanded_tool_calls: HashSet<agent_client_protocol::ToolCallId>,
 195    pub expanded_tool_call_raw_inputs: HashSet<agent_client_protocol::ToolCallId>,
 196    pub expanded_thinking_blocks: HashSet<(usize, usize)>,
 197    auto_expanded_thinking_block: Option<(usize, usize)>,
 198    pub subagent_scroll_handles: RefCell<HashMap<agent_client_protocol::SessionId, ScrollHandle>>,
 199    pub edits_expanded: bool,
 200    pub plan_expanded: bool,
 201    pub queue_expanded: bool,
 202    pub editor_expanded: bool,
 203    pub should_be_following: bool,
 204    pub editing_message: Option<usize>,
 205    pub local_queued_messages: Vec<QueuedMessage>,
 206    pub queued_message_editors: Vec<Entity<MessageEditor>>,
 207    pub queued_message_editor_subscriptions: Vec<Subscription>,
 208    pub last_synced_queue_length: usize,
 209    pub turn_fields: TurnFields,
 210    pub discarded_partial_edits: HashSet<agent_client_protocol::ToolCallId>,
 211    pub is_loading_contents: bool,
 212    pub new_server_version_available: Option<SharedString>,
 213    pub resumed_without_history: bool,
 214    pub _cancel_task: Option<Task<()>>,
 215    _save_task: Option<Task<()>>,
 216    _draft_resolve_task: Option<Task<()>>,
 217    pub skip_queue_processing_count: usize,
 218    pub user_interrupted_generation: bool,
 219    pub can_fast_track_queue: bool,
 220    pub hovered_edited_file_buttons: Option<usize>,
 221    pub in_flight_prompt: Option<Vec<acp::ContentBlock>>,
 222    pub _subscriptions: Vec<Subscription>,
 223    pub message_editor: Entity<MessageEditor>,
 224    pub add_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 225    pub thinking_effort_menu_handle: PopoverMenuHandle<ContextMenu>,
 226    pub project: WeakEntity<Project>,
 227    pub recent_history_entries: Vec<AgentSessionInfo>,
 228    pub hovered_recent_history_item: Option<usize>,
 229    pub show_external_source_prompt_warning: bool,
 230    pub show_codex_windows_warning: bool,
 231    pub history: Option<Entity<ThreadHistory>>,
 232    pub _history_subscription: Option<Subscription>,
 233}
 234impl Focusable for ThreadView {
 235    fn focus_handle(&self, cx: &App) -> FocusHandle {
 236        if self.parent_id.is_some() {
 237            self.focus_handle.clone()
 238        } else {
 239            self.active_editor(cx).focus_handle(cx)
 240        }
 241    }
 242}
 243
 244#[derive(Default)]
 245pub struct TurnFields {
 246    pub _turn_timer_task: Option<Task<()>>,
 247    pub last_turn_duration: Option<Duration>,
 248    pub last_turn_tokens: Option<u64>,
 249    pub turn_generation: usize,
 250    pub turn_started_at: Option<Instant>,
 251    pub turn_tokens: Option<u64>,
 252}
 253
 254impl ThreadView {
 255    pub(crate) fn new(
 256        parent_id: Option<acp::SessionId>,
 257        thread: Entity<AcpThread>,
 258        conversation: Entity<super::Conversation>,
 259        server_view: WeakEntity<ConversationView>,
 260        agent_icon: IconName,
 261        agent_icon_from_external_svg: Option<SharedString>,
 262        agent_id: AgentId,
 263        agent_display_name: SharedString,
 264        workspace: WeakEntity<Workspace>,
 265        entry_view_state: Entity<EntryViewState>,
 266        config_options_view: Option<Entity<ConfigOptionsView>>,
 267        mode_selector: Option<Entity<ModeSelector>>,
 268        model_selector: Option<Entity<ModelSelectorPopover>>,
 269        profile_selector: Option<Entity<ProfileSelector>>,
 270        list_state: ListState,
 271        prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
 272        available_commands: Rc<RefCell<Vec<agent_client_protocol::AvailableCommand>>>,
 273        resumed_without_history: bool,
 274        project: WeakEntity<Project>,
 275        thread_store: Option<Entity<ThreadStore>>,
 276        history: Option<Entity<ThreadHistory>>,
 277        prompt_store: Option<Entity<PromptStore>>,
 278        initial_content: Option<AgentInitialContent>,
 279        mut subscriptions: Vec<Subscription>,
 280        window: &mut Window,
 281        cx: &mut Context<Self>,
 282    ) -> Self {
 283        let id = thread.read(cx).session_id().clone();
 284
 285        let placeholder = placeholder_text(agent_display_name.as_ref(), false);
 286
 287        let history_subscription = history.as_ref().map(|h| {
 288            cx.observe(h, |this, history, cx| {
 289                this.update_recent_history_from_cache(&history, cx);
 290            })
 291        });
 292
 293        let mut should_auto_submit = false;
 294        let mut show_external_source_prompt_warning = false;
 295
 296        let message_editor = cx.new(|cx| {
 297            let mut editor = MessageEditor::new(
 298                workspace.clone(),
 299                project.clone(),
 300                thread_store,
 301                history.as_ref().map(|h| h.downgrade()),
 302                prompt_store,
 303                prompt_capabilities.clone(),
 304                available_commands.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            prompt_capabilities,
 421            available_commands,
 422            resumed_without_history,
 423            _subscriptions: subscriptions,
 424            permission_dropdown_handle: PopoverMenuHandle::default(),
 425            thread_retry_status: None,
 426            thread_error: None,
 427            thread_error_markdown: None,
 428            token_limit_callout_dismissed: false,
 429            last_token_limit_telemetry: None,
 430            thread_feedback: Default::default(),
 431            expanded_tool_calls: HashSet::default(),
 432            expanded_tool_call_raw_inputs: HashSet::default(),
 433            expanded_thinking_blocks: HashSet::default(),
 434            auto_expanded_thinking_block: None,
 435            subagent_scroll_handles: RefCell::new(HashMap::default()),
 436            edits_expanded: false,
 437            plan_expanded: false,
 438            queue_expanded: true,
 439            editor_expanded: false,
 440            should_be_following: false,
 441            editing_message: None,
 442            local_queued_messages: Vec::new(),
 443            queued_message_editors: Vec::new(),
 444            queued_message_editor_subscriptions: Vec::new(),
 445            last_synced_queue_length: 0,
 446            turn_fields: TurnFields::default(),
 447            discarded_partial_edits: HashSet::default(),
 448            is_loading_contents: false,
 449            new_server_version_available: None,
 450            _cancel_task: None,
 451            _save_task: None,
 452            _draft_resolve_task: None,
 453            skip_queue_processing_count: 0,
 454            user_interrupted_generation: false,
 455            can_fast_track_queue: false,
 456            hovered_edited_file_buttons: None,
 457            in_flight_prompt: None,
 458            message_editor,
 459            add_context_menu_handle: PopoverMenuHandle::default(),
 460            thinking_effort_menu_handle: PopoverMenuHandle::default(),
 461            project,
 462            recent_history_entries,
 463            hovered_recent_history_item: None,
 464            show_external_source_prompt_warning,
 465            history,
 466            _history_subscription: history_subscription,
 467            show_codex_windows_warning,
 468        };
 469        let list_state_for_scroll = this.list_state.clone();
 470        let thread_view = cx.entity().downgrade();
 471        this.list_state
 472            .set_scroll_handler(move |_event, _window, cx| {
 473                let list_state = list_state_for_scroll.clone();
 474                let thread_view = thread_view.clone();
 475                // N.B. We must defer because the scroll handler is called while the
 476                // ListState's RefCell is mutably borrowed. Reading logical_scroll_top()
 477                // directly would panic from a double borrow.
 478                cx.defer(move |cx| {
 479                    let scroll_top = list_state.logical_scroll_top();
 480                    let _ = thread_view.update(cx, |this, cx| {
 481                        if let Some(thread) = this.as_native_thread(cx) {
 482                            thread.update(cx, |thread, _cx| {
 483                                thread.set_ui_scroll_position(Some(scroll_top));
 484                            });
 485                        }
 486                        this.schedule_save(cx);
 487                    });
 488                });
 489            });
 490
 491        if should_auto_submit {
 492            this.send(window, cx);
 493        }
 494        this
 495    }
 496
 497    /// Schedule a throttled save of the thread state (draft prompt, scroll position, etc.).
 498    /// Multiple calls within `SERIALIZATION_THROTTLE_TIME` are coalesced into a single save.
 499    fn schedule_save(&mut self, cx: &mut Context<Self>) {
 500        self._save_task = Some(cx.spawn(async move |this, cx| {
 501            cx.background_executor()
 502                .timer(SERIALIZATION_THROTTLE_TIME)
 503                .await;
 504            this.update(cx, |this, cx| {
 505                if let Some(thread) = this.as_native_thread(cx) {
 506                    thread.update(cx, |_thread, cx| cx.notify());
 507                }
 508            })
 509            .ok();
 510        }));
 511    }
 512
 513    pub fn handle_message_editor_event(
 514        &mut self,
 515        _editor: &Entity<MessageEditor>,
 516        event: &MessageEditorEvent,
 517        window: &mut Window,
 518        cx: &mut Context<Self>,
 519    ) {
 520        match event {
 521            MessageEditorEvent::Send => self.send(window, cx),
 522            MessageEditorEvent::SendImmediately => self.interrupt_and_send(window, cx),
 523            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 524            MessageEditorEvent::Focus => {
 525                self.cancel_editing(&Default::default(), window, cx);
 526            }
 527            MessageEditorEvent::LostFocus => {}
 528            MessageEditorEvent::InputAttempted(_) => {}
 529        }
 530    }
 531
 532    pub(crate) fn as_native_connection(
 533        &self,
 534        cx: &App,
 535    ) -> Option<Rc<agent::NativeAgentConnection>> {
 536        let acp_thread = self.thread.read(cx);
 537        acp_thread.connection().clone().downcast()
 538    }
 539
 540    pub fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
 541        let acp_thread = self.thread.read(cx);
 542        self.as_native_connection(cx)?
 543            .thread(acp_thread.session_id(), cx)
 544    }
 545
 546    /// Resolves the message editor's contents into content blocks. For profiles
 547    /// that do not enable any tools, directory mentions are expanded to inline
 548    /// file contents since the agent can't read files on its own.
 549    fn resolve_message_contents(
 550        &self,
 551        message_editor: &Entity<MessageEditor>,
 552        cx: &mut App,
 553    ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
 554        let expand = self.as_native_thread(cx).is_some_and(|thread| {
 555            let thread = thread.read(cx);
 556            AgentSettings::get_global(cx)
 557                .profiles
 558                .get(thread.profile())
 559                .is_some_and(|profile| profile.tools.is_empty())
 560        });
 561        message_editor.update(cx, |message_editor, cx| message_editor.contents(expand, cx))
 562    }
 563
 564    pub fn current_model_id(&self, cx: &App) -> Option<String> {
 565        let selector = self.model_selector.as_ref()?;
 566        let model = selector.read(cx).active_model(cx)?;
 567        Some(model.id.to_string())
 568    }
 569
 570    pub fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
 571        if let Some(thread) = self.as_native_thread(cx) {
 572            Some(thread.read(cx).profile().0.clone())
 573        } else {
 574            let mode_selector = self.mode_selector.as_ref()?;
 575            Some(mode_selector.read(cx).mode().0)
 576        }
 577    }
 578
 579    fn is_subagent(&self) -> bool {
 580        self.parent_id.is_some()
 581    }
 582
 583    /// Returns the currently active editor, either for a message that is being
 584    /// edited or the editor for a new message.
 585    pub(crate) fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
 586        if let Some(index) = self.editing_message
 587            && let Some(editor) = self
 588                .entry_view_state
 589                .read(cx)
 590                .entry(index)
 591                .and_then(|entry| entry.message_editor())
 592                .cloned()
 593        {
 594            editor
 595        } else {
 596            self.message_editor.clone()
 597        }
 598    }
 599
 600    pub fn has_queued_messages(&self) -> bool {
 601        !self.local_queued_messages.is_empty()
 602    }
 603
 604    pub fn is_imported_thread(&self, cx: &App) -> bool {
 605        let Some(thread) = self.as_native_thread(cx) else {
 606            return false;
 607        };
 608        thread.read(cx).is_imported()
 609    }
 610
 611    // events
 612
 613    pub fn handle_entry_view_event(
 614        &mut self,
 615        _: &Entity<EntryViewState>,
 616        event: &EntryViewEvent,
 617        window: &mut Window,
 618        cx: &mut Context<Self>,
 619    ) {
 620        match &event.view_event {
 621            ViewEvent::NewDiff(tool_call_id) => {
 622                if AgentSettings::get_global(cx).expand_edit_card {
 623                    self.expanded_tool_calls.insert(tool_call_id.clone());
 624                }
 625            }
 626            ViewEvent::NewTerminal(tool_call_id) => {
 627                if AgentSettings::get_global(cx).expand_terminal_card {
 628                    self.expanded_tool_calls.insert(tool_call_id.clone());
 629                }
 630            }
 631            ViewEvent::TerminalMovedToBackground(tool_call_id) => {
 632                self.expanded_tool_calls.remove(tool_call_id);
 633            }
 634            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 635                if let Some(AgentThreadEntry::UserMessage(user_message)) =
 636                    self.thread.read(cx).entries().get(event.entry_index)
 637                    && user_message.id.is_some()
 638                    && !self.is_subagent()
 639                {
 640                    self.editing_message = Some(event.entry_index);
 641                    cx.notify();
 642                }
 643            }
 644            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
 645                if let Some(AgentThreadEntry::UserMessage(user_message)) =
 646                    self.thread.read(cx).entries().get(event.entry_index)
 647                    && user_message.id.is_some()
 648                    && !self.is_subagent()
 649                {
 650                    if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
 651                        self.editing_message = None;
 652                        cx.notify();
 653                    }
 654                }
 655            }
 656            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
 657            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 658                if !self.is_subagent() {
 659                    self.regenerate(event.entry_index, editor.clone(), window, cx);
 660                }
 661            }
 662            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 663                self.cancel_editing(&Default::default(), window, cx);
 664            }
 665            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::InputAttempted(_)) => {}
 666            ViewEvent::OpenDiffLocation {
 667                path,
 668                position,
 669                split,
 670            } => {
 671                self.open_diff_location(path, *position, *split, window, cx);
 672            }
 673        }
 674    }
 675
 676    fn open_diff_location(
 677        &self,
 678        path: &str,
 679        position: Point,
 680        split: bool,
 681        window: &mut Window,
 682        cx: &mut Context<Self>,
 683    ) {
 684        let Some(project) = self.project.upgrade() else {
 685            return;
 686        };
 687        let Some(project_path) = project.read(cx).find_project_path(path, cx) else {
 688            return;
 689        };
 690
 691        let open_task = if split {
 692            self.workspace
 693                .update(cx, |workspace, cx| {
 694                    workspace.split_path(project_path, window, cx)
 695                })
 696                .log_err()
 697        } else {
 698            self.workspace
 699                .update(cx, |workspace, cx| {
 700                    workspace.open_path(project_path, None, true, window, cx)
 701                })
 702                .log_err()
 703        };
 704
 705        let Some(open_task) = open_task else {
 706            return;
 707        };
 708
 709        window
 710            .spawn(cx, async move |cx| {
 711                let item = open_task.await?;
 712                let Some(editor) = item.downcast::<Editor>() else {
 713                    return anyhow::Ok(());
 714                };
 715                editor.update_in(cx, |editor, window, cx| {
 716                    editor.change_selections(
 717                        SelectionEffects::scroll(Autoscroll::center()),
 718                        window,
 719                        cx,
 720                        |selections| {
 721                            selections.select_ranges([position..position]);
 722                        },
 723                    );
 724                })?;
 725                anyhow::Ok(())
 726            })
 727            .detach_and_log_err(cx);
 728    }
 729
 730    // turns
 731
 732    pub fn start_turn(&mut self, cx: &mut Context<Self>) -> usize {
 733        self.turn_fields.turn_generation += 1;
 734        let generation = self.turn_fields.turn_generation;
 735        self.turn_fields.turn_started_at = Some(Instant::now());
 736        self.turn_fields.last_turn_duration = None;
 737        self.turn_fields.last_turn_tokens = None;
 738        self.turn_fields.turn_tokens = Some(0);
 739        self.turn_fields._turn_timer_task = Some(cx.spawn(async move |this, cx| {
 740            loop {
 741                cx.background_executor().timer(Duration::from_secs(1)).await;
 742                if this.update(cx, |_, cx| cx.notify()).is_err() {
 743                    break;
 744                }
 745            }
 746        }));
 747        if self.parent_id.is_none() {
 748            self.suppress_merge_conflict_notification(cx);
 749        }
 750        generation
 751    }
 752
 753    pub fn stop_turn(&mut self, generation: usize, cx: &mut Context<Self>) {
 754        if self.turn_fields.turn_generation != generation {
 755            return;
 756        }
 757        self.turn_fields.last_turn_duration = self
 758            .turn_fields
 759            .turn_started_at
 760            .take()
 761            .map(|started| started.elapsed());
 762        self.turn_fields.last_turn_tokens = self.turn_fields.turn_tokens.take();
 763        self.turn_fields._turn_timer_task = None;
 764        if self.parent_id.is_none() {
 765            self.unsuppress_merge_conflict_notification(cx);
 766        }
 767    }
 768
 769    fn suppress_merge_conflict_notification(&self, cx: &mut Context<Self>) {
 770        self.workspace
 771            .update(cx, |workspace, cx| {
 772                workspace.suppress_notification(&workspace::merge_conflict_notification_id(), cx);
 773            })
 774            .ok();
 775    }
 776
 777    fn unsuppress_merge_conflict_notification(&self, cx: &mut Context<Self>) {
 778        self.workspace
 779            .update(cx, |workspace, _cx| {
 780                workspace.unsuppress(workspace::merge_conflict_notification_id());
 781            })
 782            .ok();
 783    }
 784
 785    pub fn update_turn_tokens(&mut self, cx: &App) {
 786        if let Some(usage) = self.thread.read(cx).token_usage() {
 787            if let Some(tokens) = &mut self.turn_fields.turn_tokens {
 788                *tokens += usage.output_tokens;
 789            }
 790        }
 791    }
 792
 793    // sending
 794
 795    fn clear_external_source_prompt_warning(&mut self, cx: &mut Context<Self>) {
 796        if self.show_external_source_prompt_warning {
 797            self.show_external_source_prompt_warning = false;
 798            cx.notify();
 799        }
 800    }
 801
 802    pub fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 803        let thread = &self.thread;
 804
 805        if self.is_loading_contents {
 806            return;
 807        }
 808
 809        let message_editor = self.message_editor.clone();
 810
 811        // Intercept the first send so the agent panel can capture the full
 812        // content blocks — needed for "Start thread in New Worktree",
 813        // which must create a workspace before sending the message there.
 814        let intercept_first_send = self.thread.read(cx).entries().is_empty()
 815            && !message_editor.read(cx).is_empty(cx)
 816            && self
 817                .workspace
 818                .upgrade()
 819                .and_then(|workspace| workspace.read(cx).panel::<AgentPanel>(cx))
 820                .is_some_and(|panel| {
 821                    panel.read(cx).start_thread_in() == &StartThreadIn::NewWorktree
 822                });
 823
 824        if intercept_first_send {
 825            let content_task = self.resolve_message_contents(&message_editor, cx);
 826
 827            cx.spawn(async move |this, cx| match content_task.await {
 828                Ok((content, _tracked_buffers)) => {
 829                    if content.is_empty() {
 830                        return;
 831                    }
 832
 833                    this.update(cx, |_, cx| {
 834                        cx.emit(AcpThreadViewEvent::FirstSendRequested { content });
 835                    })
 836                    .ok();
 837                }
 838                Err(error) => {
 839                    this.update(cx, |this, cx| {
 840                        this.handle_thread_error(error, cx);
 841                    })
 842                    .ok();
 843                }
 844            })
 845            .detach();
 846
 847            return;
 848        }
 849
 850        let is_editor_empty = message_editor.read(cx).is_empty(cx);
 851        let is_generating = thread.read(cx).status() != ThreadStatus::Idle;
 852
 853        let has_queued = self.has_queued_messages();
 854        if is_editor_empty && self.can_fast_track_queue && has_queued {
 855            self.can_fast_track_queue = false;
 856            self.send_queued_message_at_index(0, true, window, cx);
 857            return;
 858        }
 859
 860        if is_editor_empty {
 861            return;
 862        }
 863
 864        if is_generating {
 865            self.queue_message(message_editor, window, cx);
 866            return;
 867        }
 868
 869        let text = message_editor.read(cx).text(cx);
 870        let text = text.trim();
 871        if text == "/login" || text == "/logout" {
 872            let connection = thread.read(cx).connection().clone();
 873            let can_login = !connection.auth_methods().is_empty();
 874            // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
 875            let logout_supported = text == "/logout"
 876                && self
 877                    .available_commands
 878                    .borrow()
 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 supports_images = self.prompt_capabilities.borrow().image;
3579        let supports_embedded_context = self.prompt_capabilities.borrow().embedded_context;
3580
3581        let has_editor_selection = workspace
3582            .upgrade()
3583            .and_then(|ws| {
3584                ws.read(cx)
3585                    .active_item(cx)
3586                    .and_then(|item| item.downcast::<Editor>())
3587            })
3588            .is_some_and(|editor| {
3589                editor.update(cx, |editor, cx| {
3590                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
3591                })
3592            });
3593
3594        let has_terminal_selection = workspace
3595            .upgrade()
3596            .and_then(|ws| ws.read(cx).panel::<TerminalPanel>(cx))
3597            .is_some_and(|panel| !panel.read(cx).terminal_selections(cx).is_empty());
3598
3599        let has_selection = has_editor_selection || has_terminal_selection;
3600
3601        ContextMenu::build(window, cx, move |menu, _window, _cx| {
3602            menu.key_context("AddContextMenu")
3603                .header("Context")
3604                .item(
3605                    ContextMenuEntry::new("Files & Directories")
3606                        .icon(IconName::File)
3607                        .icon_color(Color::Muted)
3608                        .icon_size(IconSize::XSmall)
3609                        .handler({
3610                            let message_editor = message_editor.clone();
3611                            move |window, cx| {
3612                                message_editor.focus_handle(cx).focus(window, cx);
3613                                message_editor.update(cx, |editor, cx| {
3614                                    editor.insert_context_type("file", window, cx);
3615                                });
3616                            }
3617                        }),
3618                )
3619                .item(
3620                    ContextMenuEntry::new("Symbols")
3621                        .icon(IconName::Code)
3622                        .icon_color(Color::Muted)
3623                        .icon_size(IconSize::XSmall)
3624                        .handler({
3625                            let message_editor = message_editor.clone();
3626                            move |window, cx| {
3627                                message_editor.focus_handle(cx).focus(window, cx);
3628                                message_editor.update(cx, |editor, cx| {
3629                                    editor.insert_context_type("symbol", window, cx);
3630                                });
3631                            }
3632                        }),
3633                )
3634                .item(
3635                    ContextMenuEntry::new("Threads")
3636                        .icon(IconName::Thread)
3637                        .icon_color(Color::Muted)
3638                        .icon_size(IconSize::XSmall)
3639                        .handler({
3640                            let message_editor = message_editor.clone();
3641                            move |window, cx| {
3642                                message_editor.focus_handle(cx).focus(window, cx);
3643                                message_editor.update(cx, |editor, cx| {
3644                                    editor.insert_context_type("thread", window, cx);
3645                                });
3646                            }
3647                        }),
3648                )
3649                .item(
3650                    ContextMenuEntry::new("Rules")
3651                        .icon(IconName::Reader)
3652                        .icon_color(Color::Muted)
3653                        .icon_size(IconSize::XSmall)
3654                        .handler({
3655                            let message_editor = message_editor.clone();
3656                            move |window, cx| {
3657                                message_editor.focus_handle(cx).focus(window, cx);
3658                                message_editor.update(cx, |editor, cx| {
3659                                    editor.insert_context_type("rule", window, cx);
3660                                });
3661                            }
3662                        }),
3663                )
3664                .item(
3665                    ContextMenuEntry::new("Image")
3666                        .icon(IconName::Image)
3667                        .icon_color(Color::Muted)
3668                        .icon_size(IconSize::XSmall)
3669                        .disabled(!supports_images)
3670                        .handler({
3671                            let message_editor = message_editor.clone();
3672                            move |window, cx| {
3673                                message_editor.focus_handle(cx).focus(window, cx);
3674                                message_editor.update(cx, |editor, cx| {
3675                                    editor.add_images_from_picker(window, cx);
3676                                });
3677                            }
3678                        }),
3679                )
3680                .item(
3681                    ContextMenuEntry::new("Selection")
3682                        .icon(IconName::CursorIBeam)
3683                        .icon_color(Color::Muted)
3684                        .icon_size(IconSize::XSmall)
3685                        .disabled(!has_selection)
3686                        .handler({
3687                            move |window, cx| {
3688                                window.dispatch_action(
3689                                    zed_actions::agent::AddSelectionToThread.boxed_clone(),
3690                                    cx,
3691                                );
3692                            }
3693                        }),
3694                )
3695                .item(
3696                    ContextMenuEntry::new("Branch Diff")
3697                        .icon(IconName::GitBranch)
3698                        .icon_color(Color::Muted)
3699                        .icon_size(IconSize::XSmall)
3700                        .disabled(!supports_embedded_context)
3701                        .handler({
3702                            move |window, cx| {
3703                                message_editor.update(cx, |editor, cx| {
3704                                    editor.insert_branch_diff_crease(window, cx);
3705                                });
3706                            }
3707                        }),
3708                )
3709        })
3710    }
3711
3712    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3713        let following = self.is_following(cx);
3714
3715        let tooltip_label = if following {
3716            if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
3717                format!("Stop Following the {}", self.agent_id)
3718            } else {
3719                format!("Stop Following {}", self.agent_id)
3720            }
3721        } else {
3722            if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
3723                format!("Follow the {}", self.agent_id)
3724            } else {
3725                format!("Follow {}", self.agent_id)
3726            }
3727        };
3728
3729        IconButton::new("follow-agent", IconName::Crosshair)
3730            .icon_size(IconSize::Small)
3731            .icon_color(Color::Muted)
3732            .toggle_state(following)
3733            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3734            .tooltip(move |_window, cx| {
3735                if following {
3736                    Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
3737                } else {
3738                    Tooltip::with_meta(
3739                        tooltip_label.clone(),
3740                        Some(&Follow),
3741                        "Track the agent's location as it reads and edits files.",
3742                        cx,
3743                    )
3744                }
3745            })
3746            .on_click(cx.listener(move |this, _, window, cx| {
3747                this.toggle_following(window, cx);
3748            }))
3749    }
3750}
3751
3752impl ThreadView {
3753    pub(crate) fn render_entries(&mut self, cx: &mut Context<Self>) -> List {
3754        list(
3755            self.list_state.clone(),
3756            cx.processor(|this, index: usize, window, cx| {
3757                let entries = this.thread.read(cx).entries();
3758                let Some(entry) = entries.get(index) else {
3759                    return Empty.into_any();
3760                };
3761                this.render_entry(index, entries.len(), entry, window, cx)
3762            }),
3763        )
3764        .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3765        .flex_grow()
3766    }
3767
3768    fn render_entry(
3769        &self,
3770        entry_ix: usize,
3771        total_entries: usize,
3772        entry: &AgentThreadEntry,
3773        window: &Window,
3774        cx: &Context<Self>,
3775    ) -> AnyElement {
3776        let is_indented = entry.is_indented();
3777        let is_first_indented = is_indented
3778            && self
3779                .thread
3780                .read(cx)
3781                .entries()
3782                .get(entry_ix.saturating_sub(1))
3783                .is_none_or(|entry| !entry.is_indented());
3784
3785        let primary = match &entry {
3786            AgentThreadEntry::UserMessage(message) => {
3787                let Some(editor) = self
3788                    .entry_view_state
3789                    .read(cx)
3790                    .entry(entry_ix)
3791                    .and_then(|entry| entry.message_editor())
3792                    .cloned()
3793                else {
3794                    return Empty.into_any_element();
3795                };
3796
3797                let editing = self.editing_message == Some(entry_ix);
3798                let editor_focus = editor.focus_handle(cx).is_focused(window);
3799                let focus_border = cx.theme().colors().border_focused;
3800
3801                let rules_item = if entry_ix == 0 {
3802                    self.render_rules_item(cx)
3803                } else {
3804                    None
3805                };
3806
3807                let has_checkpoint_button = message
3808                    .checkpoint
3809                    .as_ref()
3810                    .is_some_and(|checkpoint| checkpoint.show);
3811
3812                let is_subagent = self.is_subagent();
3813                let is_editable = message.id.is_some() && !is_subagent;
3814                let agent_name = if is_subagent {
3815                    "subagents".into()
3816                } else {
3817                    self.agent_id.clone()
3818                };
3819
3820                v_flex()
3821                    .id(("user_message", entry_ix))
3822                    .map(|this| {
3823                        if is_first_indented {
3824                            this.pt_0p5()
3825                        } else if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none()  {
3826                            this.pt(rems_from_px(18.))
3827                        } else if rules_item.is_some() {
3828                            this.pt_3()
3829                        } else {
3830                            this.pt_2()
3831                        }
3832                    })
3833                    .pb_3()
3834                    .px_2()
3835                    .gap_1p5()
3836                    .w_full()
3837                    .children(rules_item)
3838                    .when(is_editable && has_checkpoint_button, |this| {
3839                        this.children(message.id.clone().map(|message_id| {
3840                            h_flex()
3841                                .px_3()
3842                                .gap_2()
3843                                .child(Divider::horizontal())
3844                                .child(
3845                                    Button::new("restore-checkpoint", "Restore Checkpoint")
3846                                        .start_icon(Icon::new(IconName::Undo).size(IconSize::XSmall).color(Color::Muted))
3847                                        .label_size(LabelSize::XSmall)
3848                                        .color(Color::Muted)
3849                                        .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
3850                                        .on_click(cx.listener(move |this, _, _window, cx| {
3851                                            this.restore_checkpoint(&message_id, cx);
3852                                        }))
3853                                )
3854                                .child(Divider::horizontal())
3855                        }))
3856                    })
3857                    .child(
3858                        div()
3859                            .relative()
3860                            .child(
3861                                div()
3862                                    .py_3()
3863                                    .px_2()
3864                                    .rounded_md()
3865                                    .bg(cx.theme().colors().editor_background)
3866                                    .border_1()
3867                                    .when(is_indented, |this| {
3868                                        this.py_2().px_2().shadow_sm()
3869                                    })
3870                                    .border_color(cx.theme().colors().border)
3871                                    .map(|this| {
3872                                        if !is_editable {
3873                                            if is_subagent {
3874                                                return this.border_dashed();
3875                                            }
3876                                            return this;
3877                                        }
3878                                        if editing && editor_focus {
3879                                            return this.border_color(focus_border);
3880                                        }
3881                                        if editing && !editor_focus {
3882                                            return this.border_dashed()
3883                                        }
3884                                        this.shadow_md().hover(|s| {
3885                                            s.border_color(focus_border.opacity(0.8))
3886                                        })
3887                                    })
3888                                    .text_xs()
3889                                    .child(editor.clone().into_any_element())
3890                            )
3891                            .when(editor_focus, |this| {
3892                                let base_container = h_flex()
3893                                    .absolute()
3894                                    .top_neg_3p5()
3895                                    .right_3()
3896                                    .gap_1()
3897                                    .rounded_sm()
3898                                    .border_1()
3899                                    .border_color(cx.theme().colors().border)
3900                                    .bg(cx.theme().colors().editor_background)
3901                                    .overflow_hidden();
3902
3903                                let is_loading_contents = self.is_loading_contents;
3904                                if is_editable {
3905                                    this.child(
3906                                        base_container
3907                                            .child(
3908                                                IconButton::new("cancel", IconName::Close)
3909                                                    .disabled(is_loading_contents)
3910                                                    .icon_color(Color::Error)
3911                                                    .icon_size(IconSize::XSmall)
3912                                                    .on_click(cx.listener(Self::cancel_editing))
3913                                            )
3914                                            .child(
3915                                                if is_loading_contents {
3916                                                    div()
3917                                                        .id("loading-edited-message-content")
3918                                                        .tooltip(Tooltip::text("Loading Added Context…"))
3919                                                        .child(loading_contents_spinner(IconSize::XSmall))
3920                                                        .into_any_element()
3921                                                } else {
3922                                                    IconButton::new("regenerate", IconName::Return)
3923                                                        .icon_color(Color::Muted)
3924                                                        .icon_size(IconSize::XSmall)
3925                                                        .tooltip(Tooltip::text(
3926                                                            "Editing will restart the thread from this point."
3927                                                        ))
3928                                                        .on_click(cx.listener({
3929                                                            let editor = editor.clone();
3930                                                            move |this, _, window, cx| {
3931                                                                this.regenerate(
3932                                                                    entry_ix, editor.clone(), window, cx,
3933                                                                );
3934                                                            }
3935                                                        })).into_any_element()
3936                                                }
3937                                            )
3938                                    )
3939                                } else {
3940                                    this.child(
3941                                        base_container
3942                                            .border_dashed()
3943                                            .child(IconButton::new("non_editable", IconName::PencilUnavailable)
3944                                                .icon_size(IconSize::Small)
3945                                                .icon_color(Color::Muted)
3946                                                .style(ButtonStyle::Transparent)
3947                                                .tooltip(Tooltip::element({
3948                                                    let agent_name = agent_name.clone();
3949                                                    move |_, _| {
3950                                                        v_flex()
3951                                                            .gap_1()
3952                                                            .child(Label::new("Unavailable Editing"))
3953                                                            .child(
3954                                                                div().max_w_64().child(
3955                                                                    Label::new(format!(
3956                                                                        "Editing previous messages is not available for {} yet.",
3957                                                                        agent_name
3958                                                                    ))
3959                                                                    .size(LabelSize::Small)
3960                                                                    .color(Color::Muted),
3961                                                                ),
3962                                                            )
3963                                                            .into_any_element()
3964                                                    }
3965                                                }))),
3966                                    )
3967                                }
3968                            }),
3969                    )
3970                    .into_any()
3971            }
3972            AgentThreadEntry::AssistantMessage(AssistantMessage {
3973                chunks,
3974                indented: _,
3975                is_subagent_output: _,
3976            }) => {
3977                let mut is_blank = true;
3978                let is_last = entry_ix + 1 == total_entries;
3979
3980                let style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
3981                let message_body = v_flex()
3982                    .w_full()
3983                    .gap_3()
3984                    .children(chunks.iter().enumerate().filter_map(
3985                        |(chunk_ix, chunk)| match chunk {
3986                            AssistantMessageChunk::Message { block } => {
3987                                block.markdown().and_then(|md| {
3988                                    let this_is_blank = md.read(cx).source().trim().is_empty();
3989                                    is_blank = is_blank && this_is_blank;
3990                                    if this_is_blank {
3991                                        return None;
3992                                    }
3993
3994                                    Some(
3995                                        self.render_markdown(md.clone(), style.clone())
3996                                            .into_any_element(),
3997                                    )
3998                                })
3999                            }
4000                            AssistantMessageChunk::Thought { block } => {
4001                                block.markdown().and_then(|md| {
4002                                    let this_is_blank = md.read(cx).source().trim().is_empty();
4003                                    is_blank = is_blank && this_is_blank;
4004                                    if this_is_blank {
4005                                        return None;
4006                                    }
4007                                    Some(
4008                                        self.render_thinking_block(
4009                                            entry_ix,
4010                                            chunk_ix,
4011                                            md.clone(),
4012                                            window,
4013                                            cx,
4014                                        )
4015                                        .into_any_element(),
4016                                    )
4017                                })
4018                            }
4019                        },
4020                    ))
4021                    .into_any();
4022
4023                if is_blank {
4024                    Empty.into_any()
4025                } else {
4026                    v_flex()
4027                        .px_5()
4028                        .py_1p5()
4029                        .when(is_last, |this| this.pb_4())
4030                        .w_full()
4031                        .text_ui(cx)
4032                        .child(self.render_message_context_menu(entry_ix, message_body, cx))
4033                        .when_some(
4034                            self.entry_view_state
4035                                .read(cx)
4036                                .entry(entry_ix)
4037                                .and_then(|entry| entry.focus_handle(cx)),
4038                            |this, handle| this.track_focus(&handle),
4039                        )
4040                        .into_any()
4041                }
4042            }
4043            AgentThreadEntry::ToolCall(tool_call) => self
4044                .render_any_tool_call(
4045                    &self.id,
4046                    entry_ix,
4047                    tool_call,
4048                    &self.focus_handle(cx),
4049                    false,
4050                    window,
4051                    cx,
4052                )
4053                .into_any(),
4054        };
4055
4056        let is_subagent_output = self.is_subagent()
4057            && matches!(entry, AgentThreadEntry::AssistantMessage(msg) if msg.is_subagent_output);
4058
4059        let primary = if is_subagent_output {
4060            v_flex()
4061                .w_full()
4062                .child(
4063                    h_flex()
4064                        .id("subagent_output")
4065                        .px_5()
4066                        .py_1()
4067                        .gap_2()
4068                        .child(Divider::horizontal())
4069                        .child(
4070                            h_flex()
4071                                .gap_1()
4072                                .child(
4073                                    Icon::new(IconName::ForwardArrowUp)
4074                                        .color(Color::Muted)
4075                                        .size(IconSize::Small),
4076                                )
4077                                .child(
4078                                    Label::new("Subagent Output")
4079                                        .size(LabelSize::Custom(self.tool_name_font_size()))
4080                                        .color(Color::Muted),
4081                                ),
4082                        )
4083                        .child(Divider::horizontal())
4084                        .tooltip(Tooltip::text("Everything below this line was sent as output from this subagent to the main agent.")),
4085                )
4086                .child(primary)
4087                .into_any_element()
4088        } else {
4089            primary
4090        };
4091
4092        let primary = if is_indented {
4093            let line_top = if is_first_indented {
4094                rems_from_px(-12.0)
4095            } else {
4096                rems_from_px(0.0)
4097            };
4098
4099            div()
4100                .relative()
4101                .w_full()
4102                .pl_5()
4103                .bg(cx.theme().colors().panel_background.opacity(0.2))
4104                .child(
4105                    div()
4106                        .absolute()
4107                        .left(rems_from_px(18.0))
4108                        .top(line_top)
4109                        .bottom_0()
4110                        .w_px()
4111                        .bg(cx.theme().colors().border.opacity(0.6)),
4112                )
4113                .child(primary)
4114                .into_any_element()
4115        } else {
4116            primary
4117        };
4118
4119        let needs_confirmation = if let AgentThreadEntry::ToolCall(tool_call) = entry {
4120            matches!(
4121                tool_call.status,
4122                ToolCallStatus::WaitingForConfirmation { .. }
4123            )
4124        } else {
4125            false
4126        };
4127
4128        let thread = self.thread.clone();
4129        let comments_editor = self.thread_feedback.comments_editor.clone();
4130
4131        let primary = if entry_ix + 1 == total_entries {
4132            v_flex()
4133                .w_full()
4134                .child(primary)
4135                .map(|this| {
4136                    if needs_confirmation {
4137                        this.child(self.render_generating(true, cx))
4138                    } else {
4139                        this.child(self.render_thread_controls(&thread, cx))
4140                    }
4141                })
4142                .when_some(comments_editor, |this, editor| {
4143                    this.child(Self::render_feedback_feedback_editor(editor, cx))
4144                })
4145                .into_any_element()
4146        } else {
4147            primary
4148        };
4149
4150        if let Some(editing_index) = self.editing_message
4151            && editing_index < entry_ix
4152        {
4153            let is_subagent = self.is_subagent();
4154
4155            let backdrop = div()
4156                .id(("backdrop", entry_ix))
4157                .size_full()
4158                .absolute()
4159                .inset_0()
4160                .bg(cx.theme().colors().panel_background)
4161                .opacity(0.8)
4162                .block_mouse_except_scroll()
4163                .on_click(cx.listener(Self::cancel_editing));
4164
4165            div()
4166                .relative()
4167                .child(primary)
4168                .when(!is_subagent, |this| this.child(backdrop))
4169                .into_any_element()
4170        } else {
4171            primary
4172        }
4173    }
4174
4175    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4176        h_flex()
4177            .key_context("AgentFeedbackMessageEditor")
4178            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4179                this.thread_feedback.dismiss_comments();
4180                cx.notify();
4181            }))
4182            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4183                this.submit_feedback_message(cx);
4184            }))
4185            .p_2()
4186            .mb_2()
4187            .mx_5()
4188            .gap_1()
4189            .rounded_md()
4190            .border_1()
4191            .border_color(cx.theme().colors().border)
4192            .bg(cx.theme().colors().editor_background)
4193            .child(div().w_full().child(editor))
4194            .child(
4195                h_flex()
4196                    .child(
4197                        IconButton::new("dismiss-feedback-message", IconName::Close)
4198                            .icon_color(Color::Error)
4199                            .icon_size(IconSize::XSmall)
4200                            .shape(ui::IconButtonShape::Square)
4201                            .on_click(cx.listener(move |this, _, _window, cx| {
4202                                this.thread_feedback.dismiss_comments();
4203                                cx.notify();
4204                            })),
4205                    )
4206                    .child(
4207                        IconButton::new("submit-feedback-message", IconName::Return)
4208                            .icon_size(IconSize::XSmall)
4209                            .shape(ui::IconButtonShape::Square)
4210                            .on_click(cx.listener(move |this, _, _window, cx| {
4211                                this.submit_feedback_message(cx);
4212                            })),
4213                    ),
4214            )
4215    }
4216
4217    fn render_thread_controls(
4218        &self,
4219        thread: &Entity<AcpThread>,
4220        cx: &Context<Self>,
4221    ) -> impl IntoElement {
4222        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4223        if is_generating {
4224            return self.render_generating(false, cx).into_any_element();
4225        }
4226
4227        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4228            .shape(ui::IconButtonShape::Square)
4229            .icon_size(IconSize::Small)
4230            .icon_color(Color::Ignored)
4231            .tooltip(Tooltip::text("Open Thread as Markdown"))
4232            .on_click(cx.listener(move |this, _, window, cx| {
4233                if let Some(workspace) = this.workspace.upgrade() {
4234                    this.open_thread_as_markdown(workspace, window, cx)
4235                        .detach_and_log_err(cx);
4236                }
4237            }));
4238
4239        let scroll_to_recent_user_prompt =
4240            IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
4241                .shape(ui::IconButtonShape::Square)
4242                .icon_size(IconSize::Small)
4243                .icon_color(Color::Ignored)
4244                .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
4245                .on_click(cx.listener(move |this, _, _, cx| {
4246                    this.scroll_to_most_recent_user_prompt(cx);
4247                }));
4248
4249        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4250            .shape(ui::IconButtonShape::Square)
4251            .icon_size(IconSize::Small)
4252            .icon_color(Color::Ignored)
4253            .tooltip(Tooltip::text("Scroll To Top"))
4254            .on_click(cx.listener(move |this, _, _, cx| {
4255                this.scroll_to_top(cx);
4256            }));
4257
4258        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
4259        let last_turn_clock = show_stats
4260            .then(|| {
4261                self.turn_fields
4262                    .last_turn_duration
4263                    .filter(|&duration| duration > STOPWATCH_THRESHOLD)
4264                    .map(|duration| {
4265                        Label::new(duration_alt_display(duration))
4266                            .size(LabelSize::Small)
4267                            .color(Color::Muted)
4268                    })
4269            })
4270            .flatten();
4271
4272        let last_turn_tokens_label = last_turn_clock
4273            .is_some()
4274            .then(|| {
4275                self.turn_fields
4276                    .last_turn_tokens
4277                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4278                    .map(|tokens| {
4279                        Label::new(format!(
4280                            "{} tokens",
4281                            crate::text_thread_editor::humanize_token_count(tokens)
4282                        ))
4283                        .size(LabelSize::Small)
4284                        .color(Color::Muted)
4285                    })
4286            })
4287            .flatten();
4288
4289        let mut container = h_flex()
4290            .w_full()
4291            .py_2()
4292            .px_5()
4293            .gap_px()
4294            .opacity(0.6)
4295            .hover(|s| s.opacity(1.))
4296            .justify_end()
4297            .when(
4298                last_turn_tokens_label.is_some() || last_turn_clock.is_some(),
4299                |this| {
4300                    this.child(
4301                        h_flex()
4302                            .gap_1()
4303                            .px_1()
4304                            .when_some(last_turn_tokens_label, |this, label| this.child(label))
4305                            .when_some(last_turn_clock, |this, label| this.child(label)),
4306                    )
4307                },
4308            );
4309
4310        if AgentSettings::get_global(cx).enable_feedback
4311            && self.thread.read(cx).connection().telemetry().is_some()
4312        {
4313            let feedback = self.thread_feedback.feedback;
4314
4315            let tooltip_meta = || {
4316                SharedString::new(
4317                    "Rating the thread sends all of your current conversation to the Zed team.",
4318                )
4319            };
4320
4321            container = container
4322                    .child(
4323                        IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4324                            .shape(ui::IconButtonShape::Square)
4325                            .icon_size(IconSize::Small)
4326                            .icon_color(match feedback {
4327                                Some(ThreadFeedback::Positive) => Color::Accent,
4328                                _ => Color::Ignored,
4329                            })
4330                            .tooltip(move |window, cx| match feedback {
4331                                Some(ThreadFeedback::Positive) => {
4332                                    Tooltip::text("Thanks for your feedback!")(window, cx)
4333                                }
4334                                _ => {
4335                                    Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx)
4336                                }
4337                            })
4338                            .on_click(cx.listener(move |this, _, window, cx| {
4339                                this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4340                            })),
4341                    )
4342                    .child(
4343                        IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4344                            .shape(ui::IconButtonShape::Square)
4345                            .icon_size(IconSize::Small)
4346                            .icon_color(match feedback {
4347                                Some(ThreadFeedback::Negative) => Color::Accent,
4348                                _ => Color::Ignored,
4349                            })
4350                            .tooltip(move |window, cx| match feedback {
4351                                Some(ThreadFeedback::Negative) => {
4352                                    Tooltip::text(
4353                                    "We appreciate your feedback and will use it to improve in the future.",
4354                                )(window, cx)
4355                                }
4356                                _ => {
4357                                    Tooltip::with_meta(
4358                                        "Not Helpful Response",
4359                                        None,
4360                                        tooltip_meta(),
4361                                        cx,
4362                                    )
4363                                }
4364                            })
4365                            .on_click(cx.listener(move |this, _, window, cx| {
4366                                this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4367                            })),
4368                    );
4369        }
4370
4371        if let Some(project) = self.project.upgrade()
4372            && let Some(server_view) = self.server_view.upgrade()
4373            && cx.has_flag::<AgentSharingFeatureFlag>()
4374            && project.read(cx).client().status().borrow().is_connected()
4375        {
4376            let button = if self.is_imported_thread(cx) {
4377                IconButton::new("sync-thread", IconName::ArrowCircle)
4378                    .shape(ui::IconButtonShape::Square)
4379                    .icon_size(IconSize::Small)
4380                    .icon_color(Color::Ignored)
4381                    .tooltip(Tooltip::text("Sync with source thread"))
4382                    .on_click(cx.listener(move |this, _, window, cx| {
4383                        this.sync_thread(project.clone(), server_view.clone(), window, cx);
4384                    }))
4385            } else {
4386                IconButton::new("share-thread", IconName::ArrowUpRight)
4387                    .shape(ui::IconButtonShape::Square)
4388                    .icon_size(IconSize::Small)
4389                    .icon_color(Color::Ignored)
4390                    .tooltip(Tooltip::text("Share Thread"))
4391                    .on_click(cx.listener(move |this, _, window, cx| {
4392                        this.share_thread(window, cx);
4393                    }))
4394            };
4395
4396            container = container.child(button);
4397        }
4398
4399        container
4400            .child(open_as_markdown)
4401            .child(scroll_to_recent_user_prompt)
4402            .child(scroll_to_top)
4403            .into_any_element()
4404    }
4405
4406    pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
4407        let entries = self.thread.read(cx).entries();
4408        if entries.is_empty() {
4409            return;
4410        }
4411
4412        // Find the most recent user message and scroll it to the top of the viewport.
4413        // (Fallback: if no user message exists, scroll to the bottom.)
4414        if let Some(ix) = entries
4415            .iter()
4416            .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
4417        {
4418            self.list_state.scroll_to(ListOffset {
4419                item_ix: ix,
4420                offset_in_item: px(0.0),
4421            });
4422            cx.notify();
4423        } else {
4424            self.scroll_to_bottom(cx);
4425        }
4426    }
4427
4428    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4429        let entry_count = self.thread.read(cx).entries().len();
4430        self.list_state.reset(entry_count);
4431        cx.notify();
4432    }
4433
4434    fn handle_feedback_click(
4435        &mut self,
4436        feedback: ThreadFeedback,
4437        window: &mut Window,
4438        cx: &mut Context<Self>,
4439    ) {
4440        self.thread_feedback
4441            .submit(self.thread.clone(), feedback, window, cx);
4442        cx.notify();
4443    }
4444
4445    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4446        let thread = self.thread.clone();
4447        self.thread_feedback.submit_comments(thread, cx);
4448        cx.notify();
4449    }
4450
4451    pub(crate) fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4452        self.list_state.scroll_to(ListOffset::default());
4453        cx.notify();
4454    }
4455
4456    pub fn open_thread_as_markdown(
4457        &self,
4458        workspace: Entity<Workspace>,
4459        window: &mut Window,
4460        cx: &mut App,
4461    ) -> Task<Result<()>> {
4462        let markdown_language_task = workspace
4463            .read(cx)
4464            .app_state()
4465            .languages
4466            .language_for_name("Markdown");
4467
4468        let thread = self.thread.read(cx);
4469        let thread_title = thread.title().to_string();
4470        let markdown = thread.to_markdown(cx);
4471
4472        let project = workspace.read(cx).project().clone();
4473        window.spawn(cx, async move |cx| {
4474            let markdown_language = markdown_language_task.await?;
4475
4476            let buffer = project
4477                .update(cx, |project, cx| {
4478                    project.create_buffer(Some(markdown_language), false, cx)
4479                })
4480                .await?;
4481
4482            buffer.update(cx, |buffer, cx| {
4483                buffer.set_text(markdown, cx);
4484                buffer.set_capability(language::Capability::ReadWrite, cx);
4485            });
4486
4487            workspace.update_in(cx, |workspace, window, cx| {
4488                let buffer = cx
4489                    .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4490
4491                workspace.add_item_to_active_pane(
4492                    Box::new(cx.new(|cx| {
4493                        let mut editor =
4494                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4495                        editor.set_breadcrumb_header(thread_title);
4496                        editor
4497                    })),
4498                    None,
4499                    true,
4500                    window,
4501                    cx,
4502                );
4503            })?;
4504            anyhow::Ok(())
4505        })
4506    }
4507
4508    fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
4509        let show_stats = AgentSettings::get_global(cx).show_turn_stats;
4510        let elapsed_label = show_stats
4511            .then(|| {
4512                self.turn_fields.turn_started_at.and_then(|started_at| {
4513                    let elapsed = started_at.elapsed();
4514                    (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
4515                })
4516            })
4517            .flatten();
4518
4519        let is_blocked_on_terminal_command =
4520            !confirmation && self.is_blocked_on_terminal_command(cx);
4521        let is_waiting = confirmation || self.thread.read(cx).has_in_progress_tool_calls();
4522
4523        let turn_tokens_label = elapsed_label
4524            .is_some()
4525            .then(|| {
4526                self.turn_fields
4527                    .turn_tokens
4528                    .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4529                    .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
4530            })
4531            .flatten();
4532
4533        let arrow_icon = if is_waiting {
4534            IconName::ArrowUp
4535        } else {
4536            IconName::ArrowDown
4537        };
4538
4539        h_flex()
4540            .id("generating-spinner")
4541            .py_2()
4542            .px(rems_from_px(22.))
4543            .gap_2()
4544            .map(|this| {
4545                if confirmation {
4546                    this.child(
4547                        h_flex()
4548                            .w_2()
4549                            .child(SpinnerLabel::sand().size(LabelSize::Small)),
4550                    )
4551                    .child(
4552                        div().min_w(rems(8.)).child(
4553                            LoadingLabel::new("Awaiting Confirmation")
4554                                .size(LabelSize::Small)
4555                                .color(Color::Muted),
4556                        ),
4557                    )
4558                } else if is_blocked_on_terminal_command {
4559                    this
4560                } else {
4561                    this.child(SpinnerLabel::new().size(LabelSize::Small))
4562                }
4563            })
4564            .when_some(elapsed_label, |this, elapsed| {
4565                this.child(
4566                    Label::new(elapsed)
4567                        .size(LabelSize::Small)
4568                        .color(Color::Muted),
4569                )
4570            })
4571            .when_some(turn_tokens_label, |this, tokens| {
4572                this.child(
4573                    h_flex()
4574                        .gap_0p5()
4575                        .child(
4576                            Icon::new(arrow_icon)
4577                                .size(IconSize::XSmall)
4578                                .color(Color::Muted),
4579                        )
4580                        .child(
4581                            Label::new(format!("{} tokens", tokens))
4582                                .size(LabelSize::Small)
4583                                .color(Color::Muted),
4584                        ),
4585                )
4586            })
4587            .into_any_element()
4588    }
4589
4590    /// If the last entry's last chunk is a streaming thought block, auto-expand it.
4591    /// Also collapses the previously auto-expanded block when a new one starts.
4592    pub(crate) fn auto_expand_streaming_thought(&mut self, cx: &mut Context<Self>) {
4593        let key = {
4594            let thread = self.thread.read(cx);
4595            if thread.status() != ThreadStatus::Generating {
4596                return;
4597            }
4598            let entries = thread.entries();
4599            let last_ix = entries.len().saturating_sub(1);
4600            match entries.get(last_ix) {
4601                Some(AgentThreadEntry::AssistantMessage(msg)) => match msg.chunks.last() {
4602                    Some(AssistantMessageChunk::Thought { .. }) => {
4603                        Some((last_ix, msg.chunks.len() - 1))
4604                    }
4605                    _ => None,
4606                },
4607                _ => None,
4608            }
4609        };
4610
4611        if let Some(key) = key {
4612            if self.auto_expanded_thinking_block != Some(key) {
4613                if let Some(old_key) = self.auto_expanded_thinking_block.replace(key) {
4614                    self.expanded_thinking_blocks.remove(&old_key);
4615                }
4616                self.expanded_thinking_blocks.insert(key);
4617                cx.notify();
4618            }
4619        } else if self.auto_expanded_thinking_block.is_some() {
4620            // The last chunk is no longer a thought (model transitioned to responding),
4621            // so collapse the previously auto-expanded block.
4622            self.collapse_auto_expanded_thinking_block();
4623            cx.notify();
4624        }
4625    }
4626
4627    fn collapse_auto_expanded_thinking_block(&mut self) {
4628        if let Some(key) = self.auto_expanded_thinking_block.take() {
4629            self.expanded_thinking_blocks.remove(&key);
4630        }
4631    }
4632
4633    pub(crate) fn clear_auto_expand_tracking(&mut self) {
4634        self.auto_expanded_thinking_block = None;
4635    }
4636
4637    fn render_thinking_block(
4638        &self,
4639        entry_ix: usize,
4640        chunk_ix: usize,
4641        chunk: Entity<Markdown>,
4642        window: &Window,
4643        cx: &Context<Self>,
4644    ) -> AnyElement {
4645        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
4646        let card_header_id = SharedString::from("inner-card-header");
4647
4648        let key = (entry_ix, chunk_ix);
4649
4650        let is_open = self.expanded_thinking_blocks.contains(&key);
4651
4652        let scroll_handle = self
4653            .entry_view_state
4654            .read(cx)
4655            .entry(entry_ix)
4656            .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
4657
4658        v_flex()
4659            .gap_1()
4660            .child(
4661                h_flex()
4662                    .id(header_id)
4663                    .group(&card_header_id)
4664                    .relative()
4665                    .w_full()
4666                    .pr_1()
4667                    .justify_between()
4668                    .child(
4669                        h_flex()
4670                            .h(window.line_height() - px(2.))
4671                            .gap_1p5()
4672                            .overflow_hidden()
4673                            .child(
4674                                Icon::new(IconName::ToolThink)
4675                                    .size(IconSize::Small)
4676                                    .color(Color::Muted),
4677                            )
4678                            .child(
4679                                div()
4680                                    .text_size(self.tool_name_font_size())
4681                                    .text_color(cx.theme().colors().text_muted)
4682                                    .child("Thinking"),
4683                            ),
4684                    )
4685                    .child(
4686                        Disclosure::new(("expand", entry_ix), is_open)
4687                            .opened_icon(IconName::ChevronUp)
4688                            .closed_icon(IconName::ChevronDown)
4689                            .visible_on_hover(&card_header_id)
4690                            .on_click(cx.listener({
4691                                move |this, _event, _window, cx| {
4692                                    if is_open {
4693                                        this.expanded_thinking_blocks.remove(&key);
4694                                    } else {
4695                                        this.expanded_thinking_blocks.insert(key);
4696                                    }
4697                                    cx.notify();
4698                                }
4699                            })),
4700                    )
4701                    .on_click(cx.listener(move |this, _event, _window, cx| {
4702                        if is_open {
4703                            this.expanded_thinking_blocks.remove(&key);
4704                        } else {
4705                            this.expanded_thinking_blocks.insert(key);
4706                        }
4707                        cx.notify();
4708                    })),
4709            )
4710            .when(is_open, |this| {
4711                this.child(
4712                    div()
4713                        .id(("thinking-content", chunk_ix))
4714                        .ml_1p5()
4715                        .pl_3p5()
4716                        .border_l_1()
4717                        .border_color(self.tool_card_border_color(cx))
4718                        .when_some(scroll_handle, |this, scroll_handle| {
4719                            this.track_scroll(&scroll_handle)
4720                        })
4721                        .overflow_hidden()
4722                        .child(self.render_markdown(
4723                            chunk,
4724                            MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
4725                        )),
4726                )
4727            })
4728            .into_any_element()
4729    }
4730
4731    fn render_message_context_menu(
4732        &self,
4733        entry_ix: usize,
4734        message_body: AnyElement,
4735        cx: &Context<Self>,
4736    ) -> AnyElement {
4737        let entity = cx.entity();
4738        let workspace = self.workspace.clone();
4739
4740        right_click_menu(format!("agent_context_menu-{}", entry_ix))
4741            .trigger(move |_, _, _| message_body)
4742            .menu(move |window, cx| {
4743                let focus = window.focused(cx);
4744                let entity = entity.clone();
4745                let workspace = workspace.clone();
4746
4747                ContextMenu::build(window, cx, move |menu, _, cx| {
4748                    let this = entity.read(cx);
4749                    let is_at_top = this.list_state.logical_scroll_top().item_ix == 0;
4750
4751                    let has_selection = this
4752                        .thread
4753                        .read(cx)
4754                        .entries()
4755                        .get(entry_ix)
4756                        .and_then(|entry| match &entry {
4757                            AgentThreadEntry::AssistantMessage(msg) => Some(&msg.chunks),
4758                            _ => None,
4759                        })
4760                        .map(|chunks| {
4761                            chunks.iter().any(|chunk| {
4762                                let md = match chunk {
4763                                    AssistantMessageChunk::Message { block } => block.markdown(),
4764                                    AssistantMessageChunk::Thought { block } => block.markdown(),
4765                                };
4766                                md.map_or(false, |m| m.read(cx).selected_text().is_some())
4767                            })
4768                        })
4769                        .unwrap_or(false);
4770
4771                    let copy_this_agent_response =
4772                        ContextMenuEntry::new("Copy This Agent Response").handler({
4773                            let entity = entity.clone();
4774                            move |_, cx| {
4775                                entity.update(cx, |this, cx| {
4776                                    let entries = this.thread.read(cx).entries();
4777                                    if let Some(text) =
4778                                        Self::get_agent_message_content(entries, entry_ix, cx)
4779                                    {
4780                                        cx.write_to_clipboard(ClipboardItem::new_string(text));
4781                                    }
4782                                });
4783                            }
4784                        });
4785
4786                    let scroll_item = if is_at_top {
4787                        ContextMenuEntry::new("Scroll to Bottom").handler({
4788                            let entity = entity.clone();
4789                            move |_, cx| {
4790                                entity.update(cx, |this, cx| {
4791                                    this.scroll_to_bottom(cx);
4792                                });
4793                            }
4794                        })
4795                    } else {
4796                        ContextMenuEntry::new("Scroll to Top").handler({
4797                            let entity = entity.clone();
4798                            move |_, cx| {
4799                                entity.update(cx, |this, cx| {
4800                                    this.scroll_to_top(cx);
4801                                });
4802                            }
4803                        })
4804                    };
4805
4806                    let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
4807                        .handler({
4808                            let entity = entity.clone();
4809                            let workspace = workspace.clone();
4810                            move |window, cx| {
4811                                if let Some(workspace) = workspace.upgrade() {
4812                                    entity
4813                                        .update(cx, |this, cx| {
4814                                            this.open_thread_as_markdown(workspace, window, cx)
4815                                        })
4816                                        .detach_and_log_err(cx);
4817                                }
4818                            }
4819                        });
4820
4821                    menu.when_some(focus, |menu, focus| menu.context(focus))
4822                        .action_disabled_when(
4823                            !has_selection,
4824                            "Copy Selection",
4825                            Box::new(markdown::CopyAsMarkdown),
4826                        )
4827                        .item(copy_this_agent_response)
4828                        .separator()
4829                        .item(scroll_item)
4830                        .item(open_thread_as_markdown)
4831                })
4832            })
4833            .into_any_element()
4834    }
4835
4836    fn get_agent_message_content(
4837        entries: &[AgentThreadEntry],
4838        entry_index: usize,
4839        cx: &App,
4840    ) -> Option<String> {
4841        let entry = entries.get(entry_index)?;
4842        if matches!(entry, AgentThreadEntry::UserMessage(_)) {
4843            return None;
4844        }
4845
4846        let start_index = (0..entry_index)
4847            .rev()
4848            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
4849            .map(|i| i + 1)
4850            .unwrap_or(0);
4851
4852        let end_index = (entry_index + 1..entries.len())
4853            .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
4854            .map(|i| i - 1)
4855            .unwrap_or(entries.len() - 1);
4856
4857        let parts: Vec<String> = (start_index..=end_index)
4858            .filter_map(|i| entries.get(i))
4859            .filter_map(|entry| {
4860                if let AgentThreadEntry::AssistantMessage(message) = entry {
4861                    let text: String = message
4862                        .chunks
4863                        .iter()
4864                        .filter_map(|chunk| match chunk {
4865                            AssistantMessageChunk::Message { block } => {
4866                                let markdown = block.to_markdown(cx);
4867                                if markdown.trim().is_empty() {
4868                                    None
4869                                } else {
4870                                    Some(markdown.to_string())
4871                                }
4872                            }
4873                            AssistantMessageChunk::Thought { .. } => None,
4874                        })
4875                        .collect::<Vec<_>>()
4876                        .join("\n\n");
4877
4878                    if text.is_empty() { None } else { Some(text) }
4879                } else {
4880                    None
4881                }
4882            })
4883            .collect();
4884
4885        let text = parts.join("\n\n");
4886        if text.is_empty() { None } else { Some(text) }
4887    }
4888
4889    fn is_blocked_on_terminal_command(&self, cx: &App) -> bool {
4890        let thread = self.thread.read(cx);
4891        if !matches!(thread.status(), ThreadStatus::Generating) {
4892            return false;
4893        }
4894
4895        let mut has_running_terminal_call = false;
4896
4897        for entry in thread.entries().iter().rev() {
4898            match entry {
4899                AgentThreadEntry::UserMessage(_) => break,
4900                AgentThreadEntry::ToolCall(tool_call)
4901                    if matches!(
4902                        tool_call.status,
4903                        ToolCallStatus::InProgress | ToolCallStatus::Pending
4904                    ) =>
4905                {
4906                    if matches!(tool_call.kind, acp::ToolKind::Execute) {
4907                        has_running_terminal_call = true;
4908                    } else {
4909                        return false;
4910                    }
4911                }
4912                AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
4913            }
4914        }
4915
4916        has_running_terminal_call
4917    }
4918
4919    fn render_collapsible_command(
4920        &self,
4921        group: SharedString,
4922        is_preview: bool,
4923        command_source: &str,
4924        cx: &Context<Self>,
4925    ) -> Div {
4926        v_flex()
4927            .group(group.clone())
4928            .p_1p5()
4929            .bg(self.tool_card_header_bg(cx))
4930            .when(is_preview, |this| {
4931                this.pt_1().child(
4932                    // Wrapping this label on a container with 24px height to avoid
4933                    // layout shift when it changes from being a preview label
4934                    // to the actual path where the command will run in
4935                    h_flex().h_6().child(
4936                        Label::new("Run Command")
4937                            .buffer_font(cx)
4938                            .size(LabelSize::XSmall)
4939                            .color(Color::Muted),
4940                    ),
4941                )
4942            })
4943            .children(command_source.lines().map(|line| {
4944                let text: SharedString = if line.is_empty() {
4945                    " ".into()
4946                } else {
4947                    line.to_string().into()
4948                };
4949
4950                Label::new(text).buffer_font(cx).size(LabelSize::Small)
4951            }))
4952            .child(
4953                div().absolute().top_1().right_1().child(
4954                    CopyButton::new("copy-command", command_source.to_string())
4955                        .tooltip_label("Copy Command")
4956                        .visible_on_hover(group),
4957                ),
4958            )
4959    }
4960
4961    fn render_terminal_tool_call(
4962        &self,
4963        active_session_id: &acp::SessionId,
4964        entry_ix: usize,
4965        terminal: &Entity<acp_thread::Terminal>,
4966        tool_call: &ToolCall,
4967        focus_handle: &FocusHandle,
4968        is_subagent: bool,
4969        window: &Window,
4970        cx: &Context<Self>,
4971    ) -> AnyElement {
4972        let terminal_data = terminal.read(cx);
4973        let working_dir = terminal_data.working_dir();
4974        let command = terminal_data.command();
4975        let started_at = terminal_data.started_at();
4976
4977        let tool_failed = matches!(
4978            &tool_call.status,
4979            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
4980        );
4981
4982        let confirmation_options = match &tool_call.status {
4983            ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),
4984            _ => None,
4985        };
4986        let needs_confirmation = confirmation_options.is_some();
4987
4988        let output = terminal_data.output();
4989        let command_finished = output.is_some()
4990            && !matches!(
4991                tool_call.status,
4992                ToolCallStatus::InProgress | ToolCallStatus::Pending
4993            );
4994        let truncated_output =
4995            output.is_some_and(|output| output.original_content_len > output.content.len());
4996        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
4997
4998        let command_failed = command_finished
4999            && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
5000
5001        let time_elapsed = if let Some(output) = output {
5002            output.ended_at.duration_since(started_at)
5003        } else {
5004            started_at.elapsed()
5005        };
5006
5007        let header_id =
5008            SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
5009        let header_group = SharedString::from(format!(
5010            "terminal-tool-header-group-{}",
5011            terminal.entity_id()
5012        ));
5013        let header_bg = cx
5014            .theme()
5015            .colors()
5016            .element_background
5017            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
5018        let border_color = cx.theme().colors().border.opacity(0.6);
5019
5020        let working_dir = working_dir
5021            .as_ref()
5022            .map(|path| path.display().to_string())
5023            .unwrap_or_else(|| "current directory".to_string());
5024
5025        // Since the command's source is wrapped in a markdown code block
5026        // (```\n...\n```), we need to strip that so we're left with only the
5027        // command's content.
5028        let command_source = command.read(cx).source();
5029        let command_content = command_source
5030            .strip_prefix("```\n")
5031            .and_then(|s| s.strip_suffix("\n```"))
5032            .unwrap_or(&command_source);
5033
5034        let command_element =
5035            self.render_collapsible_command(header_group.clone(), false, command_content, cx);
5036
5037        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
5038
5039        let header = h_flex()
5040            .id(header_id)
5041            .pt_1()
5042            .pl_1p5()
5043            .pr_1()
5044            .flex_none()
5045            .gap_1()
5046            .justify_between()
5047            .rounded_t_md()
5048            .child(
5049                div()
5050                    .id(("command-target-path", terminal.entity_id()))
5051                    .w_full()
5052                    .max_w_full()
5053                    .overflow_x_scroll()
5054                    .child(
5055                        Label::new(working_dir)
5056                            .buffer_font(cx)
5057                            .size(LabelSize::XSmall)
5058                            .color(Color::Muted),
5059                    ),
5060            )
5061            .child(
5062                Disclosure::new(
5063                    SharedString::from(format!(
5064                        "terminal-tool-disclosure-{}",
5065                        terminal.entity_id()
5066                    )),
5067                    is_expanded,
5068                )
5069                .opened_icon(IconName::ChevronUp)
5070                .closed_icon(IconName::ChevronDown)
5071                .visible_on_hover(&header_group)
5072                .on_click(cx.listener({
5073                    let id = tool_call.id.clone();
5074                    move |this, _event, _window, cx| {
5075                        if is_expanded {
5076                            this.expanded_tool_calls.remove(&id);
5077                        } else {
5078                            this.expanded_tool_calls.insert(id.clone());
5079                        }
5080                        cx.notify();
5081                    }
5082                })),
5083            )
5084            .when(time_elapsed > Duration::from_secs(10), |header| {
5085                header.child(
5086                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
5087                        .buffer_font(cx)
5088                        .color(Color::Muted)
5089                        .size(LabelSize::XSmall),
5090                )
5091            })
5092            .when(!command_finished && !needs_confirmation, |header| {
5093                header
5094                    .gap_1p5()
5095                    .child(
5096                        Icon::new(IconName::ArrowCircle)
5097                            .size(IconSize::XSmall)
5098                            .color(Color::Muted)
5099                            .with_rotate_animation(2)
5100                    )
5101                    .child(div().h(relative(0.6)).ml_1p5().child(Divider::vertical().color(DividerColor::Border)))
5102                    .child(
5103                        IconButton::new(
5104                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
5105                            IconName::Stop
5106                        )
5107                        .icon_size(IconSize::Small)
5108                        .icon_color(Color::Error)
5109                        .tooltip(move |_window, cx| {
5110                            Tooltip::with_meta(
5111                                "Stop This Command",
5112                                None,
5113                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
5114                                cx,
5115                            )
5116                        })
5117                        .on_click({
5118                            let terminal = terminal.clone();
5119                            cx.listener(move |this, _event, _window, cx| {
5120                                terminal.update(cx, |terminal, cx| {
5121                                    terminal.stop_by_user(cx);
5122                                });
5123                                if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
5124                                    this.cancel_generation(cx);
5125                                }
5126                            })
5127                        }),
5128                    )
5129            })
5130            .when(truncated_output, |header| {
5131                let tooltip = if let Some(output) = output {
5132                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
5133                       format!("Output exceeded terminal max lines and was \
5134                            truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
5135                    } else {
5136                        format!(
5137                            "Output is {} long, and to avoid unexpected token usage, \
5138                                only {} was sent back to the agent.",
5139                            format_file_size(output.original_content_len as u64, true),
5140                             format_file_size(output.content.len() as u64, true)
5141                        )
5142                    }
5143                } else {
5144                    "Output was truncated".to_string()
5145                };
5146
5147                header.child(
5148                    h_flex()
5149                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
5150                        .gap_1()
5151                        .child(
5152                            Icon::new(IconName::Info)
5153                                .size(IconSize::XSmall)
5154                                .color(Color::Ignored),
5155                        )
5156                        .child(
5157                            Label::new("Truncated")
5158                                .color(Color::Muted)
5159                                .size(LabelSize::XSmall),
5160                        )
5161                        .tooltip(Tooltip::text(tooltip)),
5162                )
5163            })
5164            .when(tool_failed || command_failed, |header| {
5165                header.child(
5166                    div()
5167                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
5168                        .child(
5169                            Icon::new(IconName::Close)
5170                                .size(IconSize::Small)
5171                                .color(Color::Error),
5172                        )
5173                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
5174                            this.tooltip(Tooltip::text(format!(
5175                                "Exited with code {}",
5176                                status.code().unwrap_or(-1),
5177                            )))
5178                        }),
5179                )
5180            })
5181;
5182
5183        let terminal_view = self
5184            .entry_view_state
5185            .read(cx)
5186            .entry(entry_ix)
5187            .and_then(|entry| entry.terminal(terminal));
5188
5189        v_flex()
5190            .when(!is_subagent, |this| {
5191                this.my_1p5()
5192                    .mx_5()
5193                    .border_1()
5194                    .when(tool_failed || command_failed, |card| card.border_dashed())
5195                    .border_color(border_color)
5196                    .rounded_md()
5197            })
5198            .overflow_hidden()
5199            .child(
5200                v_flex()
5201                    .group(&header_group)
5202                    .bg(header_bg)
5203                    .text_xs()
5204                    .child(header)
5205                    .child(command_element),
5206            )
5207            .when(is_expanded && terminal_view.is_some(), |this| {
5208                this.child(
5209                    div()
5210                        .pt_2()
5211                        .border_t_1()
5212                        .when(tool_failed || command_failed, |card| card.border_dashed())
5213                        .border_color(border_color)
5214                        .bg(cx.theme().colors().editor_background)
5215                        .rounded_b_md()
5216                        .text_ui_sm(cx)
5217                        .h_full()
5218                        .children(terminal_view.map(|terminal_view| {
5219                            let element = if terminal_view
5220                                .read(cx)
5221                                .content_mode(window, cx)
5222                                .is_scrollable()
5223                            {
5224                                div().h_72().child(terminal_view).into_any_element()
5225                            } else {
5226                                terminal_view.into_any_element()
5227                            };
5228
5229                            div()
5230                                .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
5231                                    window.dispatch_action(NewThread.boxed_clone(), cx);
5232                                    cx.stop_propagation();
5233                                }))
5234                                .child(element)
5235                                .into_any_element()
5236                        })),
5237                )
5238            })
5239            .when_some(confirmation_options, |this, options| {
5240                let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);
5241                this.child(self.render_permission_buttons(
5242                    self.id.clone(),
5243                    is_first,
5244                    options,
5245                    entry_ix,
5246                    tool_call.id.clone(),
5247                    focus_handle,
5248                    cx,
5249                ))
5250            })
5251            .into_any()
5252    }
5253
5254    fn is_first_tool_call(
5255        &self,
5256        active_session_id: &acp::SessionId,
5257        tool_call_id: &acp::ToolCallId,
5258        cx: &App,
5259    ) -> bool {
5260        self.conversation
5261            .read(cx)
5262            .pending_tool_call(active_session_id, cx)
5263            .map_or(false, |(pending_session_id, pending_tool_call_id, _)| {
5264                self.id == pending_session_id && tool_call_id == &pending_tool_call_id
5265            })
5266    }
5267
5268    fn render_any_tool_call(
5269        &self,
5270        active_session_id: &acp::SessionId,
5271        entry_ix: usize,
5272        tool_call: &ToolCall,
5273        focus_handle: &FocusHandle,
5274        is_subagent: bool,
5275        window: &Window,
5276        cx: &Context<Self>,
5277    ) -> Div {
5278        let has_terminals = tool_call.terminals().next().is_some();
5279
5280        div().w_full().map(|this| {
5281            if tool_call.is_subagent() {
5282                this.child(
5283                    self.render_subagent_tool_call(
5284                        active_session_id,
5285                        entry_ix,
5286                        tool_call,
5287                        tool_call
5288                            .subagent_session_info
5289                            .as_ref()
5290                            .map(|i| i.session_id.clone()),
5291                        focus_handle,
5292                        window,
5293                        cx,
5294                    ),
5295                )
5296            } else if has_terminals {
5297                this.children(tool_call.terminals().map(|terminal| {
5298                    self.render_terminal_tool_call(
5299                        active_session_id,
5300                        entry_ix,
5301                        terminal,
5302                        tool_call,
5303                        focus_handle,
5304                        is_subagent,
5305                        window,
5306                        cx,
5307                    )
5308                }))
5309            } else {
5310                this.child(self.render_tool_call(
5311                    active_session_id,
5312                    entry_ix,
5313                    tool_call,
5314                    focus_handle,
5315                    is_subagent,
5316                    window,
5317                    cx,
5318                ))
5319            }
5320        })
5321    }
5322
5323    fn render_tool_call(
5324        &self,
5325        active_session_id: &acp::SessionId,
5326        entry_ix: usize,
5327        tool_call: &ToolCall,
5328        focus_handle: &FocusHandle,
5329        is_subagent: bool,
5330        window: &Window,
5331        cx: &Context<Self>,
5332    ) -> Div {
5333        let has_location = tool_call.locations.len() == 1;
5334        let card_header_id = SharedString::from("inner-tool-call-header");
5335
5336        let failed_or_canceled = match &tool_call.status {
5337            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
5338            _ => false,
5339        };
5340
5341        let needs_confirmation = matches!(
5342            tool_call.status,
5343            ToolCallStatus::WaitingForConfirmation { .. }
5344        );
5345        let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
5346
5347        let is_edit =
5348            matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
5349
5350        let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
5351        let (has_revealed_diff, tool_call_output_focus) = tool_call
5352            .diffs()
5353            .next()
5354            .and_then(|diff| {
5355                let editor = self
5356                    .entry_view_state
5357                    .read(cx)
5358                    .entry(entry_ix)
5359                    .and_then(|entry| entry.editor_for_diff(diff))?;
5360                let has_revealed_diff = diff.read(cx).has_revealed_range(cx);
5361                let has_focus = editor.read(cx).is_focused(window);
5362                Some((has_revealed_diff, has_focus))
5363            })
5364            .unwrap_or((false, false));
5365
5366        let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
5367
5368        let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
5369        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
5370        let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
5371
5372        is_open |= needs_confirmation;
5373
5374        let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
5375
5376        let input_output_header = |label: SharedString| {
5377            Label::new(label)
5378                .size(LabelSize::XSmall)
5379                .color(Color::Muted)
5380                .buffer_font(cx)
5381        };
5382
5383        let tool_output_display = if is_open {
5384            match &tool_call.status {
5385                ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
5386                    .w_full()
5387                    .children(
5388                        tool_call
5389                            .content
5390                            .iter()
5391                            .enumerate()
5392                            .map(|(content_ix, content)| {
5393                                div()
5394                                    .child(self.render_tool_call_content(
5395                                        active_session_id,
5396                                        entry_ix,
5397                                        content,
5398                                        content_ix,
5399                                        tool_call,
5400                                        use_card_layout,
5401                                        has_image_content,
5402                                        failed_or_canceled,
5403                                        focus_handle,
5404                                        window,
5405                                        cx,
5406                                    ))
5407                                    .into_any_element()
5408                            }),
5409                    )
5410                    .when(should_show_raw_input, |this| {
5411                        let is_raw_input_expanded =
5412                            self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
5413
5414                        let input_header = if is_raw_input_expanded {
5415                            "Raw Input:"
5416                        } else {
5417                            "View Raw Input"
5418                        };
5419
5420                        this.child(
5421                            v_flex()
5422                                .p_2()
5423                                .gap_1()
5424                                .border_t_1()
5425                                .border_color(self.tool_card_border_color(cx))
5426                                .child(
5427                                    h_flex()
5428                                        .id("disclosure_container")
5429                                        .pl_0p5()
5430                                        .gap_1()
5431                                        .justify_between()
5432                                        .rounded_xs()
5433                                        .hover(|s| s.bg(cx.theme().colors().element_hover))
5434                                        .child(input_output_header(input_header.into()))
5435                                        .child(
5436                                            Disclosure::new(
5437                                                ("raw-input-disclosure", entry_ix),
5438                                                is_raw_input_expanded,
5439                                            )
5440                                            .opened_icon(IconName::ChevronUp)
5441                                            .closed_icon(IconName::ChevronDown),
5442                                        )
5443                                        .on_click(cx.listener({
5444                                            let id = tool_call.id.clone();
5445
5446                                            move |this: &mut Self, _, _, cx| {
5447                                                if this.expanded_tool_call_raw_inputs.contains(&id)
5448                                                {
5449                                                    this.expanded_tool_call_raw_inputs.remove(&id);
5450                                                } else {
5451                                                    this.expanded_tool_call_raw_inputs
5452                                                        .insert(id.clone());
5453                                                }
5454                                                cx.notify();
5455                                            }
5456                                        })),
5457                                )
5458                                .when(is_raw_input_expanded, |this| {
5459                                    this.children(tool_call.raw_input_markdown.clone().map(
5460                                        |input| {
5461                                            self.render_markdown(
5462                                                input,
5463                                                MarkdownStyle::themed(
5464                                                    MarkdownFont::Agent,
5465                                                    window,
5466                                                    cx,
5467                                                ),
5468                                            )
5469                                        },
5470                                    ))
5471                                }),
5472                        )
5473                    })
5474                    .child(self.render_permission_buttons(
5475                        self.id.clone(),
5476                        self.is_first_tool_call(active_session_id, &tool_call.id, cx),
5477                        options,
5478                        entry_ix,
5479                        tool_call.id.clone(),
5480                        focus_handle,
5481                        cx,
5482                    ))
5483                    .into_any(),
5484                ToolCallStatus::Pending | ToolCallStatus::InProgress
5485                    if is_edit
5486                        && tool_call.content.is_empty()
5487                        && self.as_native_connection(cx).is_some() =>
5488                {
5489                    self.render_diff_loading(cx)
5490                }
5491                ToolCallStatus::Pending
5492                | ToolCallStatus::InProgress
5493                | ToolCallStatus::Completed
5494                | ToolCallStatus::Failed
5495                | ToolCallStatus::Canceled => v_flex()
5496                    .when(should_show_raw_input, |this| {
5497                        this.mt_1p5().w_full().child(
5498                            v_flex()
5499                                .ml(rems(0.4))
5500                                .px_3p5()
5501                                .pb_1()
5502                                .gap_1()
5503                                .border_l_1()
5504                                .border_color(self.tool_card_border_color(cx))
5505                                .child(input_output_header("Raw Input:".into()))
5506                                .children(tool_call.raw_input_markdown.clone().map(|input| {
5507                                    div().id(("tool-call-raw-input-markdown", entry_ix)).child(
5508                                        self.render_markdown(
5509                                            input,
5510                                            MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
5511                                        ),
5512                                    )
5513                                }))
5514                                .child(input_output_header("Output:".into())),
5515                        )
5516                    })
5517                    .children(
5518                        tool_call
5519                            .content
5520                            .iter()
5521                            .enumerate()
5522                            .map(|(content_ix, content)| {
5523                                div().id(("tool-call-output", entry_ix)).child(
5524                                    self.render_tool_call_content(
5525                                        active_session_id,
5526                                        entry_ix,
5527                                        content,
5528                                        content_ix,
5529                                        tool_call,
5530                                        use_card_layout,
5531                                        has_image_content,
5532                                        failed_or_canceled,
5533                                        focus_handle,
5534                                        window,
5535                                        cx,
5536                                    ),
5537                                )
5538                            }),
5539                    )
5540                    .into_any(),
5541                ToolCallStatus::Rejected => Empty.into_any(),
5542            }
5543            .into()
5544        } else {
5545            None
5546        };
5547
5548        v_flex()
5549            .map(|this| {
5550                if is_subagent {
5551                    this
5552                } else if use_card_layout {
5553                    this.my_1p5()
5554                        .rounded_md()
5555                        .border_1()
5556                        .when(failed_or_canceled, |this| this.border_dashed())
5557                        .border_color(self.tool_card_border_color(cx))
5558                        .bg(cx.theme().colors().editor_background)
5559                        .overflow_hidden()
5560                } else {
5561                    this.my_1()
5562                }
5563            })
5564            .when(!is_subagent, |this| {
5565                this.map(|this| {
5566                    if has_location && !use_card_layout {
5567                        this.ml_4()
5568                    } else {
5569                        this.ml_5()
5570                    }
5571                })
5572                .mr_5()
5573            })
5574            .map(|this| {
5575                if is_terminal_tool {
5576                    let label_source = tool_call.label.read(cx).source();
5577                    this.child(self.render_collapsible_command(
5578                        card_header_id.clone(),
5579                        true,
5580                        label_source,
5581                        cx,
5582                    ))
5583                } else {
5584                    this.child(
5585                        h_flex()
5586                            .group(&card_header_id)
5587                            .relative()
5588                            .w_full()
5589                            .gap_1()
5590                            .justify_between()
5591                            .when(use_card_layout, |this| {
5592                                this.p_0p5()
5593                                    .rounded_t(rems_from_px(5.))
5594                                    .bg(self.tool_card_header_bg(cx))
5595                            })
5596                            .child(self.render_tool_call_label(
5597                                entry_ix,
5598                                tool_call,
5599                                is_edit,
5600                                is_cancelled_edit,
5601                                has_revealed_diff,
5602                                use_card_layout,
5603                                window,
5604                                cx,
5605                            ))
5606                            .child(
5607                                h_flex()
5608                                    .gap_0p5()
5609                                    .when(is_collapsible || failed_or_canceled, |this| {
5610                                        let diff_for_discard = if has_revealed_diff
5611                                            && is_cancelled_edit
5612                                            && cx.has_flag::<AgentV2FeatureFlag>()
5613                                        {
5614                                            tool_call.diffs().next().cloned()
5615                                        } else {
5616                                            None
5617                                        };
5618
5619                                        this.child(
5620                                            h_flex()
5621                                                .px_1()
5622                                                .when_some(diff_for_discard.clone(), |this, _| {
5623                                                    this.pr_0p5()
5624                                                })
5625                                                .gap_1()
5626                                                .when(is_collapsible, |this| {
5627                                                    this.child(
5628                                                        Disclosure::new(
5629                                                            ("expand-output", entry_ix),
5630                                                            is_open,
5631                                                        )
5632                                                        .opened_icon(IconName::ChevronUp)
5633                                                        .closed_icon(IconName::ChevronDown)
5634                                                        .visible_on_hover(&card_header_id)
5635                                                        .on_click(cx.listener({
5636                                                            let id = tool_call.id.clone();
5637                                                            move |this: &mut Self,
5638                                                                  _,
5639                                                                  _,
5640                                                                  cx: &mut Context<Self>| {
5641                                                                if is_open {
5642                                                                    this.expanded_tool_calls
5643                                                                        .remove(&id);
5644                                                                } else {
5645                                                                    this.expanded_tool_calls
5646                                                                        .insert(id.clone());
5647                                                                }
5648                                                                cx.notify();
5649                                                            }
5650                                                        })),
5651                                                    )
5652                                                })
5653                                                .when(failed_or_canceled, |this| {
5654                                                    if is_cancelled_edit && !has_revealed_diff {
5655                                                        this.child(
5656                                                            div()
5657                                                                .id(entry_ix)
5658                                                                .tooltip(Tooltip::text(
5659                                                                    "Interrupted Edit",
5660                                                                ))
5661                                                                .child(
5662                                                                    Icon::new(IconName::XCircle)
5663                                                                        .color(Color::Muted)
5664                                                                        .size(IconSize::Small),
5665                                                                ),
5666                                                        )
5667                                                    } else if is_cancelled_edit {
5668                                                        this
5669                                                    } else {
5670                                                        this.child(
5671                                                            Icon::new(IconName::Close)
5672                                                                .color(Color::Error)
5673                                                                .size(IconSize::Small),
5674                                                        )
5675                                                    }
5676                                                })
5677                                                .when_some(diff_for_discard, |this, diff| {
5678                                                    let tool_call_id = tool_call.id.clone();
5679                                                    let is_discarded = self
5680                                                        .discarded_partial_edits
5681                                                        .contains(&tool_call_id);
5682
5683                                                    this.when(!is_discarded, |this| {
5684                                                        this.child(
5685                                                            IconButton::new(
5686                                                                ("discard-partial-edit", entry_ix),
5687                                                                IconName::Undo,
5688                                                            )
5689                                                            .icon_size(IconSize::Small)
5690                                                            .tooltip(move |_, cx| {
5691                                                                Tooltip::with_meta(
5692                                                                    "Discard Interrupted Edit",
5693                                                                    None,
5694                                                                    "You can discard this interrupted partial edit and restore the original file content.",
5695                                                                    cx,
5696                                                                )
5697                                                            })
5698                                                            .on_click(cx.listener({
5699                                                                let tool_call_id =
5700                                                                    tool_call_id.clone();
5701                                                                move |this, _, _window, cx| {
5702                                                                    let diff_data = diff.read(cx);
5703                                                                    let base_text = diff_data
5704                                                                        .base_text()
5705                                                                        .clone();
5706                                                                    let buffer =
5707                                                                        diff_data.buffer().clone();
5708                                                                    buffer.update(
5709                                                                        cx,
5710                                                                        |buffer, cx| {
5711                                                                            buffer.set_text(
5712                                                                                base_text.as_ref(),
5713                                                                                cx,
5714                                                                            );
5715                                                                        },
5716                                                                    );
5717                                                                    this.discarded_partial_edits
5718                                                                        .insert(
5719                                                                            tool_call_id.clone(),
5720                                                                        );
5721                                                                    cx.notify();
5722                                                                }
5723                                                            })),
5724                                                        )
5725                                                    })
5726                                                }),
5727                                        )
5728                                    })
5729                                    .when(tool_call_output_focus, |this| {
5730                                        this.child(
5731                                            Button::new("open-file-button", "Open File")
5732                                                .label_size(LabelSize::Small)
5733                                                .style(ButtonStyle::OutlinedGhost)
5734                                                .key_binding(
5735                                                    KeyBinding::for_action(&OpenExcerpts, cx)
5736                                                        .map(|s| s.size(rems_from_px(12.))),
5737                                                )
5738                                                .on_click(|_, window, cx| {
5739                                                    window.dispatch_action(
5740                                                        Box::new(OpenExcerpts),
5741                                                        cx,
5742                                                    )
5743                                                }),
5744                                        )
5745                                    }),
5746                            )
5747
5748                    )
5749                }
5750            })
5751            .children(tool_output_display)
5752    }
5753
5754    fn render_permission_buttons(
5755        &self,
5756        session_id: acp::SessionId,
5757        is_first: bool,
5758        options: &PermissionOptions,
5759        entry_ix: usize,
5760        tool_call_id: acp::ToolCallId,
5761        focus_handle: &FocusHandle,
5762        cx: &Context<Self>,
5763    ) -> Div {
5764        match options {
5765            PermissionOptions::Flat(options) => self.render_permission_buttons_flat(
5766                session_id,
5767                is_first,
5768                options,
5769                entry_ix,
5770                tool_call_id,
5771                focus_handle,
5772                cx,
5773            ),
5774            PermissionOptions::Dropdown(options) => self.render_permission_buttons_dropdown(
5775                session_id,
5776                is_first,
5777                options,
5778                entry_ix,
5779                tool_call_id,
5780                focus_handle,
5781                cx,
5782            ),
5783        }
5784    }
5785
5786    fn render_permission_buttons_dropdown(
5787        &self,
5788        session_id: acp::SessionId,
5789        is_first: bool,
5790        choices: &[PermissionOptionChoice],
5791        entry_ix: usize,
5792        tool_call_id: acp::ToolCallId,
5793        focus_handle: &FocusHandle,
5794        cx: &Context<Self>,
5795    ) -> Div {
5796        // Get the selected granularity index, defaulting to the last option ("Only this time")
5797        let selected_index = self
5798            .conversation
5799            .read(cx)
5800            .selected_permission_granularity(&session_id, &tool_call_id)
5801            .unwrap_or_else(|| choices.len().saturating_sub(1));
5802
5803        let selected_choice = choices.get(selected_index).or(choices.last());
5804
5805        let dropdown_label: SharedString = selected_choice
5806            .map(|choice| choice.label())
5807            .unwrap_or_else(|| "Only this time".into());
5808
5809        let (allow_option_id, allow_option_kind, deny_option_id, deny_option_kind) =
5810            if let Some(choice) = selected_choice {
5811                (
5812                    choice.allow.option_id.clone(),
5813                    choice.allow.kind,
5814                    choice.deny.option_id.clone(),
5815                    choice.deny.kind,
5816                )
5817            } else {
5818                (
5819                    acp::PermissionOptionId::new("allow"),
5820                    acp::PermissionOptionKind::AllowOnce,
5821                    acp::PermissionOptionId::new("deny"),
5822                    acp::PermissionOptionKind::RejectOnce,
5823                )
5824            };
5825
5826        h_flex()
5827            .w_full()
5828            .p_1()
5829            .gap_2()
5830            .justify_between()
5831            .border_t_1()
5832            .border_color(self.tool_card_border_color(cx))
5833            .child(
5834                h_flex()
5835                    .gap_0p5()
5836                    .child(
5837                        Button::new(("allow-btn", entry_ix), "Allow")
5838                            .start_icon(
5839                                Icon::new(IconName::Check)
5840                                    .size(IconSize::XSmall)
5841                                    .color(Color::Success),
5842                            )
5843                            .label_size(LabelSize::Small)
5844                            .when(is_first, |this| {
5845                                this.key_binding(
5846                                    KeyBinding::for_action_in(
5847                                        &AllowOnce as &dyn Action,
5848                                        focus_handle,
5849                                        cx,
5850                                    )
5851                                    .map(|kb| kb.size(rems_from_px(10.))),
5852                                )
5853                            })
5854                            .on_click(cx.listener({
5855                                let session_id = session_id.clone();
5856                                let tool_call_id = tool_call_id.clone();
5857                                let option_id = allow_option_id;
5858                                let option_kind = allow_option_kind;
5859                                move |this, _, window, cx| {
5860                                    this.authorize_tool_call(
5861                                        session_id.clone(),
5862                                        tool_call_id.clone(),
5863                                        option_id.clone(),
5864                                        option_kind,
5865                                        window,
5866                                        cx,
5867                                    );
5868                                }
5869                            })),
5870                    )
5871                    .child(
5872                        Button::new(("deny-btn", entry_ix), "Deny")
5873                            .start_icon(
5874                                Icon::new(IconName::Close)
5875                                    .size(IconSize::XSmall)
5876                                    .color(Color::Error),
5877                            )
5878                            .label_size(LabelSize::Small)
5879                            .when(is_first, |this| {
5880                                this.key_binding(
5881                                    KeyBinding::for_action_in(
5882                                        &RejectOnce as &dyn Action,
5883                                        focus_handle,
5884                                        cx,
5885                                    )
5886                                    .map(|kb| kb.size(rems_from_px(10.))),
5887                                )
5888                            })
5889                            .on_click(cx.listener({
5890                                let session_id = session_id.clone();
5891                                let tool_call_id = tool_call_id.clone();
5892                                let option_id = deny_option_id;
5893                                let option_kind = deny_option_kind;
5894                                move |this, _, window, cx| {
5895                                    this.authorize_tool_call(
5896                                        session_id.clone(),
5897                                        tool_call_id.clone(),
5898                                        option_id.clone(),
5899                                        option_kind,
5900                                        window,
5901                                        cx,
5902                                    );
5903                                }
5904                            })),
5905                    ),
5906            )
5907            .child(self.render_permission_granularity_dropdown(
5908                choices,
5909                dropdown_label,
5910                entry_ix,
5911                session_id,
5912                tool_call_id,
5913                selected_index,
5914                is_first,
5915                cx,
5916            ))
5917    }
5918
5919    fn render_permission_granularity_dropdown(
5920        &self,
5921        choices: &[PermissionOptionChoice],
5922        current_label: SharedString,
5923        entry_ix: usize,
5924        session_id: acp::SessionId,
5925        tool_call_id: acp::ToolCallId,
5926        selected_index: usize,
5927        is_first: bool,
5928        cx: &Context<Self>,
5929    ) -> AnyElement {
5930        let menu_options: Vec<(usize, SharedString)> = choices
5931            .iter()
5932            .enumerate()
5933            .map(|(i, choice)| (i, choice.label()))
5934            .collect();
5935
5936        let permission_dropdown_handle = self.permission_dropdown_handle.clone();
5937
5938        let conversation = self.conversation.clone();
5939
5940        PopoverMenu::new(("permission-granularity", entry_ix))
5941            .with_handle(permission_dropdown_handle)
5942            .trigger(
5943                Button::new(("granularity-trigger", entry_ix), current_label)
5944                    .end_icon(
5945                        Icon::new(IconName::ChevronDown)
5946                            .size(IconSize::XSmall)
5947                            .color(Color::Muted),
5948                    )
5949                    .label_size(LabelSize::Small)
5950                    .when(is_first, |this| {
5951                        this.key_binding(
5952                            KeyBinding::for_action_in(
5953                                &crate::OpenPermissionDropdown as &dyn Action,
5954                                &self.focus_handle(cx),
5955                                cx,
5956                            )
5957                            .map(|kb| kb.size(rems_from_px(10.))),
5958                        )
5959                    }),
5960            )
5961            .menu(move |window, cx| {
5962                let session_id = session_id.clone();
5963                let conversation = conversation.clone();
5964                let tool_call_id = tool_call_id.clone();
5965                let options = menu_options.clone();
5966
5967                Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
5968                    for (index, display_name) in options.iter() {
5969                        let display_name = display_name.clone();
5970                        let index = *index;
5971                        let session_id = session_id.clone();
5972                        let conversation = conversation.clone();
5973                        let tool_call_id = tool_call_id.clone();
5974                        let is_selected = index == selected_index;
5975                        menu = menu.toggleable_entry(
5976                            display_name,
5977                            is_selected,
5978                            IconPosition::End,
5979                            None,
5980                            move |_window, cx| {
5981                                conversation.update(cx, |conversation, _cx| {
5982                                    conversation.set_selected_permission_granularity(
5983                                        session_id.clone(),
5984                                        tool_call_id.clone(),
5985                                        index,
5986                                    );
5987                                });
5988                            },
5989                        );
5990                    }
5991
5992                    menu
5993                }))
5994            })
5995            .into_any_element()
5996    }
5997
5998    fn render_permission_buttons_flat(
5999        &self,
6000        session_id: acp::SessionId,
6001        is_first: bool,
6002        options: &[acp::PermissionOption],
6003        entry_ix: usize,
6004        tool_call_id: acp::ToolCallId,
6005        focus_handle: &FocusHandle,
6006        cx: &Context<Self>,
6007    ) -> Div {
6008        let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
6009
6010        div()
6011            .p_1()
6012            .border_t_1()
6013            .border_color(self.tool_card_border_color(cx))
6014            .w_full()
6015            .v_flex()
6016            .gap_0p5()
6017            .children(options.iter().map(move |option| {
6018                let option_id = SharedString::from(option.option_id.0.clone());
6019                Button::new((option_id, entry_ix), option.name.clone())
6020                    .map(|this| {
6021                        let (icon, action) = match option.kind {
6022                            acp::PermissionOptionKind::AllowOnce => (
6023                                Icon::new(IconName::Check)
6024                                    .size(IconSize::XSmall)
6025                                    .color(Color::Success),
6026                                Some(&AllowOnce as &dyn Action),
6027                            ),
6028                            acp::PermissionOptionKind::AllowAlways => (
6029                                Icon::new(IconName::CheckDouble)
6030                                    .size(IconSize::XSmall)
6031                                    .color(Color::Success),
6032                                Some(&AllowAlways as &dyn Action),
6033                            ),
6034                            acp::PermissionOptionKind::RejectOnce => (
6035                                Icon::new(IconName::Close)
6036                                    .size(IconSize::XSmall)
6037                                    .color(Color::Error),
6038                                Some(&RejectOnce as &dyn Action),
6039                            ),
6040                            acp::PermissionOptionKind::RejectAlways | _ => (
6041                                Icon::new(IconName::Close)
6042                                    .size(IconSize::XSmall)
6043                                    .color(Color::Error),
6044                                None,
6045                            ),
6046                        };
6047
6048                        let this = this.start_icon(icon);
6049
6050                        let Some(action) = action else {
6051                            return this;
6052                        };
6053
6054                        if !is_first || seen_kinds.contains(&option.kind) {
6055                            return this;
6056                        }
6057
6058                        seen_kinds.push(option.kind);
6059
6060                        this.key_binding(
6061                            KeyBinding::for_action_in(action, focus_handle, cx)
6062                                .map(|kb| kb.size(rems_from_px(10.))),
6063                        )
6064                    })
6065                    .label_size(LabelSize::Small)
6066                    .on_click(cx.listener({
6067                        let session_id = session_id.clone();
6068                        let tool_call_id = tool_call_id.clone();
6069                        let option_id = option.option_id.clone();
6070                        let option_kind = option.kind;
6071                        move |this, _, window, cx| {
6072                            this.authorize_tool_call(
6073                                session_id.clone(),
6074                                tool_call_id.clone(),
6075                                option_id.clone(),
6076                                option_kind,
6077                                window,
6078                                cx,
6079                            );
6080                        }
6081                    }))
6082            }))
6083    }
6084
6085    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
6086        let bar = |n: u64, width_class: &str| {
6087            let bg_color = cx.theme().colors().element_active;
6088            let base = h_flex().h_1().rounded_full();
6089
6090            let modified = match width_class {
6091                "w_4_5" => base.w_3_4(),
6092                "w_1_4" => base.w_1_4(),
6093                "w_2_4" => base.w_2_4(),
6094                "w_3_5" => base.w_3_5(),
6095                "w_2_5" => base.w_2_5(),
6096                _ => base.w_1_2(),
6097            };
6098
6099            modified.with_animation(
6100                ElementId::Integer(n),
6101                Animation::new(Duration::from_secs(2)).repeat(),
6102                move |tab, delta| {
6103                    let delta = (delta - 0.15 * n as f32) / 0.7;
6104                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
6105                    let delta = ease_in_out(delta.clamp(0., 1.));
6106                    let delta = 0.1 + 0.9 * delta;
6107
6108                    tab.bg(bg_color.opacity(delta))
6109                },
6110            )
6111        };
6112
6113        v_flex()
6114            .p_3()
6115            .gap_1()
6116            .rounded_b_md()
6117            .bg(cx.theme().colors().editor_background)
6118            .child(bar(0, "w_4_5"))
6119            .child(bar(1, "w_1_4"))
6120            .child(bar(2, "w_2_4"))
6121            .child(bar(3, "w_3_5"))
6122            .child(bar(4, "w_2_5"))
6123            .into_any_element()
6124    }
6125
6126    fn render_tool_call_label(
6127        &self,
6128        entry_ix: usize,
6129        tool_call: &ToolCall,
6130        is_edit: bool,
6131        has_failed: bool,
6132        has_revealed_diff: bool,
6133        use_card_layout: bool,
6134        window: &Window,
6135        cx: &Context<Self>,
6136    ) -> Div {
6137        let has_location = tool_call.locations.len() == 1;
6138        let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
6139        let is_subagent_tool_call = tool_call.is_subagent();
6140
6141        let file_icon = if has_location {
6142            FileIcons::get_icon(&tool_call.locations[0].path, cx)
6143                .map(Icon::from_path)
6144                .unwrap_or(Icon::new(IconName::ToolPencil))
6145        } else {
6146            Icon::new(IconName::ToolPencil)
6147        };
6148
6149        let tool_icon = if is_file && has_failed && has_revealed_diff {
6150            div()
6151                .id(entry_ix)
6152                .tooltip(Tooltip::text("Interrupted Edit"))
6153                .child(DecoratedIcon::new(
6154                    file_icon,
6155                    Some(
6156                        IconDecoration::new(
6157                            IconDecorationKind::Triangle,
6158                            self.tool_card_header_bg(cx),
6159                            cx,
6160                        )
6161                        .color(cx.theme().status().warning)
6162                        .position(gpui::Point {
6163                            x: px(-2.),
6164                            y: px(-2.),
6165                        }),
6166                    ),
6167                ))
6168                .into_any_element()
6169        } else if is_file {
6170            div().child(file_icon).into_any_element()
6171        } else if is_subagent_tool_call {
6172            Icon::new(self.agent_icon)
6173                .size(IconSize::Small)
6174                .color(Color::Muted)
6175                .into_any_element()
6176        } else {
6177            Icon::new(match tool_call.kind {
6178                acp::ToolKind::Read => IconName::ToolSearch,
6179                acp::ToolKind::Edit => IconName::ToolPencil,
6180                acp::ToolKind::Delete => IconName::ToolDeleteFile,
6181                acp::ToolKind::Move => IconName::ArrowRightLeft,
6182                acp::ToolKind::Search => IconName::ToolSearch,
6183                acp::ToolKind::Execute => IconName::ToolTerminal,
6184                acp::ToolKind::Think => IconName::ToolThink,
6185                acp::ToolKind::Fetch => IconName::ToolWeb,
6186                acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
6187                acp::ToolKind::Other | _ => IconName::ToolHammer,
6188            })
6189            .size(IconSize::Small)
6190            .color(Color::Muted)
6191            .into_any_element()
6192        };
6193
6194        let gradient_overlay = {
6195            div()
6196                .absolute()
6197                .top_0()
6198                .right_0()
6199                .w_12()
6200                .h_full()
6201                .map(|this| {
6202                    if use_card_layout {
6203                        this.bg(linear_gradient(
6204                            90.,
6205                            linear_color_stop(self.tool_card_header_bg(cx), 1.),
6206                            linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
6207                        ))
6208                    } else {
6209                        this.bg(linear_gradient(
6210                            90.,
6211                            linear_color_stop(cx.theme().colors().panel_background, 1.),
6212                            linear_color_stop(
6213                                cx.theme().colors().panel_background.opacity(0.2),
6214                                0.,
6215                            ),
6216                        ))
6217                    }
6218                })
6219        };
6220
6221        h_flex()
6222            .relative()
6223            .w_full()
6224            .h(window.line_height() - px(2.))
6225            .text_size(self.tool_name_font_size())
6226            .gap_1p5()
6227            .when(has_location || use_card_layout, |this| this.px_1())
6228            .when(has_location, |this| {
6229                this.cursor(CursorStyle::PointingHand)
6230                    .rounded(rems_from_px(3.)) // Concentric border radius
6231                    .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
6232            })
6233            .overflow_hidden()
6234            .child(tool_icon)
6235            .child(if has_location {
6236                h_flex()
6237                    .id(("open-tool-call-location", entry_ix))
6238                    .w_full()
6239                    .map(|this| {
6240                        if use_card_layout {
6241                            this.text_color(cx.theme().colors().text)
6242                        } else {
6243                            this.text_color(cx.theme().colors().text_muted)
6244                        }
6245                    })
6246                    .child(
6247                        self.render_markdown(
6248                            tool_call.label.clone(),
6249                            MarkdownStyle {
6250                                prevent_mouse_interaction: true,
6251                                ..MarkdownStyle::themed(MarkdownFont::Agent, window, cx)
6252                                    .with_muted_text(cx)
6253                            },
6254                        ),
6255                    )
6256                    .tooltip(Tooltip::text("Go to File"))
6257                    .on_click(cx.listener(move |this, _, window, cx| {
6258                        this.open_tool_call_location(entry_ix, 0, window, cx);
6259                    }))
6260                    .into_any_element()
6261            } else {
6262                h_flex()
6263                    .w_full()
6264                    .child(self.render_markdown(
6265                        tool_call.label.clone(),
6266                        MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx),
6267                    ))
6268                    .into_any()
6269            })
6270            .when(!is_edit, |this| this.child(gradient_overlay))
6271    }
6272
6273    fn open_tool_call_location(
6274        &self,
6275        entry_ix: usize,
6276        location_ix: usize,
6277        window: &mut Window,
6278        cx: &mut Context<Self>,
6279    ) -> Option<()> {
6280        let (tool_call_location, agent_location) = self
6281            .thread
6282            .read(cx)
6283            .entries()
6284            .get(entry_ix)?
6285            .location(location_ix)?;
6286
6287        let project_path = self
6288            .project
6289            .upgrade()?
6290            .read(cx)
6291            .find_project_path(&tool_call_location.path, cx)?;
6292
6293        let open_task = self
6294            .workspace
6295            .update(cx, |workspace, cx| {
6296                workspace.open_path(project_path, None, true, window, cx)
6297            })
6298            .log_err()?;
6299        window
6300            .spawn(cx, async move |cx| {
6301                let item = open_task.await?;
6302
6303                let Some(active_editor) = item.downcast::<Editor>() else {
6304                    return anyhow::Ok(());
6305                };
6306
6307                active_editor.update_in(cx, |editor, window, cx| {
6308                    let singleton = editor
6309                        .buffer()
6310                        .read(cx)
6311                        .read(cx)
6312                        .as_singleton()
6313                        .map(|(a, b, _)| (a, b));
6314                    if let Some((excerpt_id, buffer_id)) = singleton
6315                        && let Some(agent_buffer) = agent_location.buffer.upgrade()
6316                        && agent_buffer.read(cx).remote_id() == buffer_id
6317                    {
6318                        let anchor = editor::Anchor::in_buffer(excerpt_id, agent_location.position);
6319                        editor.change_selections(Default::default(), window, cx, |selections| {
6320                            selections.select_anchor_ranges([anchor..anchor]);
6321                        })
6322                    } else {
6323                        let row = tool_call_location.line.unwrap_or_default();
6324                        editor.change_selections(Default::default(), window, cx, |selections| {
6325                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
6326                        })
6327                    }
6328                })?;
6329
6330                anyhow::Ok(())
6331            })
6332            .detach_and_log_err(cx);
6333
6334        None
6335    }
6336
6337    fn render_tool_call_content(
6338        &self,
6339        session_id: &acp::SessionId,
6340        entry_ix: usize,
6341        content: &ToolCallContent,
6342        context_ix: usize,
6343        tool_call: &ToolCall,
6344        card_layout: bool,
6345        is_image_tool_call: bool,
6346        has_failed: bool,
6347        focus_handle: &FocusHandle,
6348        window: &Window,
6349        cx: &Context<Self>,
6350    ) -> AnyElement {
6351        match content {
6352            ToolCallContent::ContentBlock(content) => {
6353                if let Some(resource_link) = content.resource_link() {
6354                    self.render_resource_link(resource_link, cx)
6355                } else if let Some(markdown) = content.markdown() {
6356                    self.render_markdown_output(
6357                        markdown.clone(),
6358                        tool_call.id.clone(),
6359                        context_ix,
6360                        card_layout,
6361                        window,
6362                        cx,
6363                    )
6364                } else if let Some(image) = content.image() {
6365                    let location = tool_call.locations.first().cloned();
6366                    self.render_image_output(
6367                        entry_ix,
6368                        image.clone(),
6369                        location,
6370                        card_layout,
6371                        is_image_tool_call,
6372                        cx,
6373                    )
6374                } else {
6375                    Empty.into_any_element()
6376                }
6377            }
6378            ToolCallContent::Diff(diff) => {
6379                self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
6380            }
6381            ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(
6382                session_id,
6383                entry_ix,
6384                terminal,
6385                tool_call,
6386                focus_handle,
6387                false,
6388                window,
6389                cx,
6390            ),
6391        }
6392    }
6393
6394    fn render_resource_link(
6395        &self,
6396        resource_link: &acp::ResourceLink,
6397        cx: &Context<Self>,
6398    ) -> AnyElement {
6399        let uri: SharedString = resource_link.uri.clone().into();
6400        let is_file = resource_link.uri.strip_prefix("file://");
6401
6402        let Some(project) = self.project.upgrade() else {
6403            return Empty.into_any_element();
6404        };
6405
6406        let label: SharedString = if let Some(abs_path) = is_file {
6407            if let Some(project_path) = project
6408                .read(cx)
6409                .project_path_for_absolute_path(&Path::new(abs_path), cx)
6410                && let Some(worktree) = project
6411                    .read(cx)
6412                    .worktree_for_id(project_path.worktree_id, cx)
6413            {
6414                worktree
6415                    .read(cx)
6416                    .full_path(&project_path.path)
6417                    .to_string_lossy()
6418                    .to_string()
6419                    .into()
6420            } else {
6421                abs_path.to_string().into()
6422            }
6423        } else {
6424            uri.clone()
6425        };
6426
6427        let button_id = SharedString::from(format!("item-{}", uri));
6428
6429        div()
6430            .ml(rems(0.4))
6431            .pl_2p5()
6432            .border_l_1()
6433            .border_color(self.tool_card_border_color(cx))
6434            .overflow_hidden()
6435            .child(
6436                Button::new(button_id, label)
6437                    .label_size(LabelSize::Small)
6438                    .color(Color::Muted)
6439                    .truncate(true)
6440                    .when(is_file.is_none(), |this| {
6441                        this.end_icon(
6442                            Icon::new(IconName::ArrowUpRight)
6443                                .size(IconSize::XSmall)
6444                                .color(Color::Muted),
6445                        )
6446                    })
6447                    .on_click(cx.listener({
6448                        let workspace = self.workspace.clone();
6449                        move |_, _, window, cx: &mut Context<Self>| {
6450                            open_link(uri.clone(), &workspace, window, cx);
6451                        }
6452                    })),
6453            )
6454            .into_any_element()
6455    }
6456
6457    fn render_diff_editor(
6458        &self,
6459        entry_ix: usize,
6460        diff: &Entity<acp_thread::Diff>,
6461        tool_call: &ToolCall,
6462        has_failed: bool,
6463        cx: &Context<Self>,
6464    ) -> AnyElement {
6465        let tool_progress = matches!(
6466            &tool_call.status,
6467            ToolCallStatus::InProgress | ToolCallStatus::Pending
6468        );
6469
6470        let revealed_diff_editor = if let Some(entry) =
6471            self.entry_view_state.read(cx).entry(entry_ix)
6472            && let Some(editor) = entry.editor_for_diff(diff)
6473            && diff.read(cx).has_revealed_range(cx)
6474        {
6475            Some(editor)
6476        } else {
6477            None
6478        };
6479
6480        let show_top_border = !has_failed || revealed_diff_editor.is_some();
6481
6482        v_flex()
6483            .h_full()
6484            .when(show_top_border, |this| {
6485                this.border_t_1()
6486                    .when(has_failed, |this| this.border_dashed())
6487                    .border_color(self.tool_card_border_color(cx))
6488            })
6489            .child(if let Some(editor) = revealed_diff_editor {
6490                editor.into_any_element()
6491            } else if tool_progress && self.as_native_connection(cx).is_some() {
6492                self.render_diff_loading(cx)
6493            } else {
6494                Empty.into_any()
6495            })
6496            .into_any()
6497    }
6498
6499    fn render_markdown_output(
6500        &self,
6501        markdown: Entity<Markdown>,
6502        tool_call_id: acp::ToolCallId,
6503        context_ix: usize,
6504        card_layout: bool,
6505        window: &Window,
6506        cx: &Context<Self>,
6507    ) -> AnyElement {
6508        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
6509
6510        v_flex()
6511            .gap_2()
6512            .map(|this| {
6513                if card_layout {
6514                    this.when(context_ix > 0, |this| {
6515                        this.pt_2()
6516                            .border_t_1()
6517                            .border_color(self.tool_card_border_color(cx))
6518                    })
6519                } else {
6520                    this.ml(rems(0.4))
6521                        .px_3p5()
6522                        .border_l_1()
6523                        .border_color(self.tool_card_border_color(cx))
6524                }
6525            })
6526            .text_xs()
6527            .text_color(cx.theme().colors().text_muted)
6528            .child(self.render_markdown(
6529                markdown,
6530                MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
6531            ))
6532            .when(!card_layout, |this| {
6533                this.child(
6534                    IconButton::new(button_id, IconName::ChevronUp)
6535                        .full_width()
6536                        .style(ButtonStyle::Outlined)
6537                        .icon_color(Color::Muted)
6538                        .on_click(cx.listener({
6539                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
6540                                this.expanded_tool_calls.remove(&tool_call_id);
6541                                cx.notify();
6542                            }
6543                        })),
6544                )
6545            })
6546            .into_any_element()
6547    }
6548
6549    fn render_image_output(
6550        &self,
6551        entry_ix: usize,
6552        image: Arc<gpui::Image>,
6553        location: Option<acp::ToolCallLocation>,
6554        card_layout: bool,
6555        show_dimensions: bool,
6556        cx: &Context<Self>,
6557    ) -> AnyElement {
6558        let dimensions_label = if show_dimensions {
6559            let format_name = match image.format() {
6560                gpui::ImageFormat::Png => "PNG",
6561                gpui::ImageFormat::Jpeg => "JPEG",
6562                gpui::ImageFormat::Webp => "WebP",
6563                gpui::ImageFormat::Gif => "GIF",
6564                gpui::ImageFormat::Svg => "SVG",
6565                gpui::ImageFormat::Bmp => "BMP",
6566                gpui::ImageFormat::Tiff => "TIFF",
6567                gpui::ImageFormat::Ico => "ICO",
6568            };
6569            let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
6570                .with_guessed_format()
6571                .ok()
6572                .and_then(|reader| reader.into_dimensions().ok());
6573            dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
6574        } else {
6575            None
6576        };
6577
6578        v_flex()
6579            .gap_2()
6580            .map(|this| {
6581                if card_layout {
6582                    this
6583                } else {
6584                    this.ml(rems(0.4))
6585                        .px_3p5()
6586                        .border_l_1()
6587                        .border_color(self.tool_card_border_color(cx))
6588                }
6589            })
6590            .when(dimensions_label.is_some() || location.is_some(), |this| {
6591                this.child(
6592                    h_flex()
6593                        .w_full()
6594                        .justify_between()
6595                        .items_center()
6596                        .children(dimensions_label.map(|label| {
6597                            Label::new(label)
6598                                .size(LabelSize::XSmall)
6599                                .color(Color::Muted)
6600                                .buffer_font(cx)
6601                        }))
6602                        .when_some(location, |this, _loc| {
6603                            this.child(
6604                                Button::new(("go-to-file", entry_ix), "Go to File")
6605                                    .label_size(LabelSize::Small)
6606                                    .on_click(cx.listener(move |this, _, window, cx| {
6607                                        this.open_tool_call_location(entry_ix, 0, window, cx);
6608                                    })),
6609                            )
6610                        }),
6611                )
6612            })
6613            .child(
6614                img(image)
6615                    .max_w_96()
6616                    .max_h_96()
6617                    .object_fit(ObjectFit::ScaleDown),
6618            )
6619            .into_any_element()
6620    }
6621
6622    fn render_subagent_tool_call(
6623        &self,
6624        active_session_id: &acp::SessionId,
6625        entry_ix: usize,
6626        tool_call: &ToolCall,
6627        subagent_session_id: Option<acp::SessionId>,
6628        focus_handle: &FocusHandle,
6629        window: &Window,
6630        cx: &Context<Self>,
6631    ) -> Div {
6632        let subagent_thread_view = subagent_session_id.and_then(|id| {
6633            self.server_view
6634                .upgrade()
6635                .and_then(|server_view| server_view.read(cx).as_connected())
6636                .and_then(|connected| connected.threads.get(&id))
6637        });
6638
6639        let content = self.render_subagent_card(
6640            active_session_id,
6641            entry_ix,
6642            subagent_thread_view,
6643            tool_call,
6644            focus_handle,
6645            window,
6646            cx,
6647        );
6648
6649        v_flex().mx_5().my_1p5().gap_3().child(content)
6650    }
6651
6652    fn render_subagent_card(
6653        &self,
6654        active_session_id: &acp::SessionId,
6655        entry_ix: usize,
6656        thread_view: Option<&Entity<ThreadView>>,
6657        tool_call: &ToolCall,
6658        focus_handle: &FocusHandle,
6659        window: &Window,
6660        cx: &Context<Self>,
6661    ) -> AnyElement {
6662        let thread = thread_view
6663            .as_ref()
6664            .map(|view| view.read(cx).thread.clone());
6665        let subagent_session_id = thread
6666            .as_ref()
6667            .map(|thread| thread.read(cx).session_id().clone());
6668        let action_log = thread.as_ref().map(|thread| thread.read(cx).action_log());
6669        let changed_buffers = action_log
6670            .map(|log| log.read(cx).changed_buffers(cx))
6671            .unwrap_or_default();
6672
6673        let is_pending_tool_call = thread
6674            .as_ref()
6675            .and_then(|thread| {
6676                self.conversation
6677                    .read(cx)
6678                    .pending_tool_call(thread.read(cx).session_id(), cx)
6679            })
6680            .is_some();
6681
6682        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
6683        let files_changed = changed_buffers.len();
6684        let diff_stats = DiffStats::all_files(&changed_buffers, cx);
6685
6686        let is_running = matches!(
6687            tool_call.status,
6688            ToolCallStatus::Pending
6689                | ToolCallStatus::InProgress
6690                | ToolCallStatus::WaitingForConfirmation { .. }
6691        );
6692
6693        let is_failed = matches!(
6694            tool_call.status,
6695            ToolCallStatus::Failed | ToolCallStatus::Rejected
6696        );
6697
6698        let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled)
6699            || tool_call.content.iter().any(|c| match c {
6700                ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {
6701                    markdown.read(cx).source() == "User canceled"
6702                }
6703                _ => false,
6704            });
6705
6706        let thread_title = thread
6707            .as_ref()
6708            .map(|t| t.read(cx).title())
6709            .filter(|t| !t.is_empty());
6710        let tool_call_label = tool_call.label.read(cx).source().to_string();
6711        let has_tool_call_label = !tool_call_label.is_empty();
6712
6713        let has_title = thread_title.is_some() || has_tool_call_label;
6714        let has_no_title_or_canceled = !has_title || is_failed || is_cancelled;
6715
6716        let title: SharedString = if let Some(thread_title) = thread_title {
6717            thread_title
6718        } else if !tool_call_label.is_empty() {
6719            tool_call_label.into()
6720        } else if is_cancelled {
6721            "Subagent Canceled".into()
6722        } else if is_failed {
6723            "Subagent Failed".into()
6724        } else {
6725            "Spawning Agent…".into()
6726        };
6727
6728        let card_header_id = format!("subagent-header-{}", entry_ix);
6729        let status_icon = format!("status-icon-{}", entry_ix);
6730        let diff_stat_id = format!("subagent-diff-{}", entry_ix);
6731
6732        let icon = h_flex().w_4().justify_center().child(if is_running {
6733            SpinnerLabel::new()
6734                .size(LabelSize::Small)
6735                .into_any_element()
6736        } else if is_cancelled {
6737            div()
6738                .id(status_icon)
6739                .child(
6740                    Icon::new(IconName::Circle)
6741                        .size(IconSize::Small)
6742                        .color(Color::Custom(
6743                            cx.theme().colors().icon_disabled.opacity(0.5),
6744                        )),
6745                )
6746                .tooltip(Tooltip::text("Subagent Cancelled"))
6747                .into_any_element()
6748        } else if is_failed {
6749            div()
6750                .id(status_icon)
6751                .child(
6752                    Icon::new(IconName::Close)
6753                        .size(IconSize::Small)
6754                        .color(Color::Error),
6755                )
6756                .tooltip(Tooltip::text("Subagent Failed"))
6757                .into_any_element()
6758        } else {
6759            Icon::new(IconName::Check)
6760                .size(IconSize::Small)
6761                .color(Color::Success)
6762                .into_any_element()
6763        });
6764
6765        let has_expandable_content = thread
6766            .as_ref()
6767            .map_or(false, |thread| !thread.read(cx).entries().is_empty());
6768
6769        let tooltip_meta_description = if is_expanded {
6770            "Click to Collapse"
6771        } else {
6772            "Click to Preview"
6773        };
6774
6775        let error_message = self.subagent_error_message(&tool_call.status, tool_call, cx);
6776
6777        v_flex()
6778            .w_full()
6779            .rounded_md()
6780            .border_1()
6781            .when(has_no_title_or_canceled, |this| this.border_dashed())
6782            .border_color(self.tool_card_border_color(cx))
6783            .overflow_hidden()
6784            .child(
6785                h_flex()
6786                    .group(&card_header_id)
6787                    .h_8()
6788                    .p_1()
6789                    .w_full()
6790                    .justify_between()
6791                    .when(!has_no_title_or_canceled, |this| {
6792                        this.bg(self.tool_card_header_bg(cx))
6793                    })
6794                    .child(
6795                        h_flex()
6796                            .id(format!("subagent-title-{}", entry_ix))
6797                            .px_1()
6798                            .min_w_0()
6799                            .size_full()
6800                            .gap_2()
6801                            .justify_between()
6802                            .rounded_sm()
6803                            .overflow_hidden()
6804                            .child(
6805                                h_flex()
6806                                    .min_w_0()
6807                                    .w_full()
6808                                    .gap_1p5()
6809                                    .child(icon)
6810                                    .child(
6811                                        Label::new(title.to_string())
6812                                            .size(LabelSize::Custom(self.tool_name_font_size()))
6813                                            .truncate(),
6814                                    )
6815                                    .when(files_changed > 0, |this| {
6816                                        this.child(
6817                                            Label::new(format!(
6818                                                "{} {} changed",
6819                                                files_changed,
6820                                                if files_changed == 1 { "file" } else { "files" }
6821                                            ))
6822                                            .size(LabelSize::Custom(self.tool_name_font_size()))
6823                                            .color(Color::Muted),
6824                                        )
6825                                        .child(
6826                                            DiffStat::new(
6827                                                diff_stat_id.clone(),
6828                                                diff_stats.lines_added as usize,
6829                                                diff_stats.lines_removed as usize,
6830                                            )
6831                                            .label_size(LabelSize::Custom(
6832                                                self.tool_name_font_size(),
6833                                            )),
6834                                        )
6835                                    }),
6836                            )
6837                            .when(!has_no_title_or_canceled && !is_pending_tool_call, |this| {
6838                                this.tooltip(move |_, cx| {
6839                                    Tooltip::with_meta(
6840                                        title.to_string(),
6841                                        None,
6842                                        tooltip_meta_description,
6843                                        cx,
6844                                    )
6845                                })
6846                            })
6847                            .when(has_expandable_content && !is_pending_tool_call, |this| {
6848                                this.cursor_pointer()
6849                                    .hover(|s| s.bg(cx.theme().colors().element_hover))
6850                                    .child(
6851                                        div().visible_on_hover(card_header_id).child(
6852                                            Icon::new(if is_expanded {
6853                                                IconName::ChevronUp
6854                                            } else {
6855                                                IconName::ChevronDown
6856                                            })
6857                                            .color(Color::Muted)
6858                                            .size(IconSize::Small),
6859                                        ),
6860                                    )
6861                                    .on_click(cx.listener({
6862                                        let tool_call_id = tool_call.id.clone();
6863                                        move |this, _, _, cx| {
6864                                            if this.expanded_tool_calls.contains(&tool_call_id) {
6865                                                this.expanded_tool_calls.remove(&tool_call_id);
6866                                            } else {
6867                                                this.expanded_tool_calls
6868                                                    .insert(tool_call_id.clone());
6869                                            }
6870                                            let expanded =
6871                                                this.expanded_tool_calls.contains(&tool_call_id);
6872                                            telemetry::event!("Subagent Toggled", expanded);
6873                                            cx.notify();
6874                                        }
6875                                    }))
6876                            }),
6877                    )
6878                    .when(is_running && subagent_session_id.is_some(), |buttons| {
6879                        buttons.child(
6880                            IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
6881                                .icon_size(IconSize::Small)
6882                                .icon_color(Color::Error)
6883                                .tooltip(Tooltip::text("Stop Subagent"))
6884                                .when_some(
6885                                    thread_view
6886                                        .as_ref()
6887                                        .map(|view| view.read(cx).thread.clone()),
6888                                    |this, thread| {
6889                                        this.on_click(cx.listener(
6890                                            move |_this, _event, _window, cx| {
6891                                                telemetry::event!("Subagent Stopped");
6892                                                thread.update(cx, |thread, cx| {
6893                                                    thread.cancel(cx).detach();
6894                                                });
6895                                            },
6896                                        ))
6897                                    },
6898                                ),
6899                        )
6900                    }),
6901            )
6902            .when_some(thread_view, |this, thread_view| {
6903                let thread = &thread_view.read(cx).thread;
6904                let pending_tool_call = self
6905                    .conversation
6906                    .read(cx)
6907                    .pending_tool_call(thread.read(cx).session_id(), cx);
6908
6909                let session_id = thread.read(cx).session_id().clone();
6910
6911                let fullscreen_toggle = h_flex()
6912                    .id(entry_ix)
6913                    .py_1()
6914                    .w_full()
6915                    .justify_center()
6916                    .border_t_1()
6917                    .when(is_failed, |this| this.border_dashed())
6918                    .border_color(self.tool_card_border_color(cx))
6919                    .cursor_pointer()
6920                    .hover(|s| s.bg(cx.theme().colors().element_hover))
6921                    .child(
6922                        Icon::new(IconName::Maximize)
6923                            .color(Color::Muted)
6924                            .size(IconSize::Small),
6925                    )
6926                    .tooltip(Tooltip::text("Make Subagent Full Screen"))
6927                    .on_click(cx.listener(move |this, _event, window, cx| {
6928                        telemetry::event!("Subagent Maximized");
6929                        this.server_view
6930                            .update(cx, |this, cx| {
6931                                this.navigate_to_session(session_id.clone(), window, cx);
6932                            })
6933                            .ok();
6934                    }));
6935
6936                if is_running && let Some((_, subagent_tool_call_id, _)) = pending_tool_call {
6937                    if let Some((entry_ix, tool_call)) =
6938                        thread.read(cx).tool_call(&subagent_tool_call_id)
6939                    {
6940                        this.child(Divider::horizontal().color(DividerColor::Border))
6941                            .child(thread_view.read(cx).render_any_tool_call(
6942                                active_session_id,
6943                                entry_ix,
6944                                tool_call,
6945                                focus_handle,
6946                                true,
6947                                window,
6948                                cx,
6949                            ))
6950                            .child(fullscreen_toggle)
6951                    } else {
6952                        this
6953                    }
6954                } else {
6955                    this.when(is_expanded, |this| {
6956                        this.child(self.render_subagent_expanded_content(
6957                            thread_view,
6958                            is_running,
6959                            tool_call,
6960                            window,
6961                            cx,
6962                        ))
6963                        .when_some(error_message, |this, message| {
6964                            this.child(
6965                                Callout::new()
6966                                    .severity(Severity::Error)
6967                                    .icon(IconName::XCircle)
6968                                    .title(message),
6969                            )
6970                        })
6971                        .child(fullscreen_toggle)
6972                    })
6973                }
6974            })
6975            .into_any_element()
6976    }
6977
6978    fn render_subagent_expanded_content(
6979        &self,
6980        thread_view: &Entity<ThreadView>,
6981        is_running: bool,
6982        tool_call: &ToolCall,
6983        window: &Window,
6984        cx: &Context<Self>,
6985    ) -> impl IntoElement {
6986        const MAX_PREVIEW_ENTRIES: usize = 8;
6987
6988        let subagent_view = thread_view.read(cx);
6989        let session_id = subagent_view.thread.read(cx).session_id().clone();
6990
6991        let is_canceled_or_failed = matches!(
6992            tool_call.status,
6993            ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
6994        );
6995
6996        let editor_bg = cx.theme().colors().editor_background;
6997        let overlay = {
6998            div()
6999                .absolute()
7000                .inset_0()
7001                .size_full()
7002                .bg(linear_gradient(
7003                    180.,
7004                    linear_color_stop(editor_bg.opacity(0.5), 0.),
7005                    linear_color_stop(editor_bg.opacity(0.), 0.1),
7006                ))
7007                .block_mouse_except_scroll()
7008        };
7009
7010        let entries = subagent_view.thread.read(cx).entries();
7011        let total_entries = entries.len();
7012        let mut entry_range = if let Some(info) = tool_call.subagent_session_info.as_ref() {
7013            info.message_start_index
7014                ..info
7015                    .message_end_index
7016                    .map(|i| (i + 1).min(total_entries))
7017                    .unwrap_or(total_entries)
7018        } else {
7019            0..total_entries
7020        };
7021        entry_range.start = entry_range
7022            .end
7023            .saturating_sub(MAX_PREVIEW_ENTRIES)
7024            .max(entry_range.start);
7025        let start_ix = entry_range.start;
7026
7027        let scroll_handle = self
7028            .subagent_scroll_handles
7029            .borrow_mut()
7030            .entry(session_id.clone())
7031            .or_default()
7032            .clone();
7033        if is_running {
7034            scroll_handle.scroll_to_bottom();
7035        }
7036
7037        let rendered_entries: Vec<AnyElement> = entries
7038            .get(entry_range)
7039            .unwrap_or_default()
7040            .iter()
7041            .enumerate()
7042            .map(|(i, entry)| {
7043                let actual_ix = start_ix + i;
7044                subagent_view.render_entry(actual_ix, total_entries, entry, window, cx)
7045            })
7046            .collect();
7047
7048        v_flex()
7049            .w_full()
7050            .border_t_1()
7051            .when(is_canceled_or_failed, |this| this.border_dashed())
7052            .border_color(self.tool_card_border_color(cx))
7053            .overflow_hidden()
7054            .child(
7055                div()
7056                    .pb_1()
7057                    .min_h_0()
7058                    .id(format!("subagent-entries-{}", session_id))
7059                    .track_scroll(&scroll_handle)
7060                    .children(rendered_entries),
7061            )
7062            .h_56()
7063            .child(overlay)
7064            .into_any_element()
7065    }
7066
7067    fn subagent_error_message(
7068        &self,
7069        status: &ToolCallStatus,
7070        tool_call: &ToolCall,
7071        cx: &App,
7072    ) -> Option<SharedString> {
7073        if matches!(status, ToolCallStatus::Failed) {
7074            tool_call.content.iter().find_map(|content| {
7075                if let ToolCallContent::ContentBlock(block) = content {
7076                    if let acp_thread::ContentBlock::Markdown { markdown } = block {
7077                        let source = markdown.read(cx).source().to_string();
7078                        if !source.is_empty() {
7079                            if source == "User canceled" {
7080                                return None;
7081                            } else {
7082                                return Some(SharedString::from(source));
7083                            }
7084                        }
7085                    }
7086                }
7087                None
7088            })
7089        } else {
7090            None
7091        }
7092    }
7093
7094    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
7095        let project_context = self
7096            .as_native_thread(cx)?
7097            .read(cx)
7098            .project_context()
7099            .read(cx);
7100
7101        let user_rules_text = if project_context.user_rules.is_empty() {
7102            None
7103        } else if project_context.user_rules.len() == 1 {
7104            let user_rules = &project_context.user_rules[0];
7105
7106            match user_rules.title.as_ref() {
7107                Some(title) => Some(format!("Using \"{title}\" user rule")),
7108                None => Some("Using user rule".into()),
7109            }
7110        } else {
7111            Some(format!(
7112                "Using {} user rules",
7113                project_context.user_rules.len()
7114            ))
7115        };
7116
7117        let first_user_rules_id = project_context
7118            .user_rules
7119            .first()
7120            .map(|user_rules| user_rules.uuid.0);
7121
7122        let rules_files = project_context
7123            .worktrees
7124            .iter()
7125            .filter_map(|worktree| worktree.rules_file.as_ref())
7126            .collect::<Vec<_>>();
7127
7128        let rules_file_text = match rules_files.as_slice() {
7129            &[] => None,
7130            &[rules_file] => Some(format!(
7131                "Using project {:?} file",
7132                rules_file.path_in_worktree
7133            )),
7134            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
7135        };
7136
7137        if user_rules_text.is_none() && rules_file_text.is_none() {
7138            return None;
7139        }
7140
7141        let has_both = user_rules_text.is_some() && rules_file_text.is_some();
7142
7143        Some(
7144            h_flex()
7145                .px_2p5()
7146                .child(
7147                    Icon::new(IconName::Attach)
7148                        .size(IconSize::XSmall)
7149                        .color(Color::Disabled),
7150                )
7151                .when_some(user_rules_text, |parent, user_rules_text| {
7152                    parent.child(
7153                        h_flex()
7154                            .id("user-rules")
7155                            .ml_1()
7156                            .mr_1p5()
7157                            .child(
7158                                Label::new(user_rules_text)
7159                                    .size(LabelSize::XSmall)
7160                                    .color(Color::Muted)
7161                                    .truncate(),
7162                            )
7163                            .hover(|s| s.bg(cx.theme().colors().element_hover))
7164                            .tooltip(Tooltip::text("View User Rules"))
7165                            .on_click(move |_event, window, cx| {
7166                                window.dispatch_action(
7167                                    Box::new(OpenRulesLibrary {
7168                                        prompt_to_select: first_user_rules_id,
7169                                    }),
7170                                    cx,
7171                                )
7172                            }),
7173                    )
7174                })
7175                .when(has_both, |this| {
7176                    this.child(
7177                        Label::new("")
7178                            .size(LabelSize::XSmall)
7179                            .color(Color::Disabled),
7180                    )
7181                })
7182                .when_some(rules_file_text, |parent, rules_file_text| {
7183                    parent.child(
7184                        h_flex()
7185                            .id("project-rules")
7186                            .ml_1p5()
7187                            .child(
7188                                Label::new(rules_file_text)
7189                                    .size(LabelSize::XSmall)
7190                                    .color(Color::Muted),
7191                            )
7192                            .hover(|s| s.bg(cx.theme().colors().element_hover))
7193                            .tooltip(Tooltip::text("View Project Rules"))
7194                            .on_click(cx.listener(Self::handle_open_rules)),
7195                    )
7196                })
7197                .into_any(),
7198        )
7199    }
7200
7201    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
7202        cx.theme()
7203            .colors()
7204            .element_background
7205            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
7206    }
7207
7208    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
7209        cx.theme().colors().border.opacity(0.8)
7210    }
7211
7212    fn tool_name_font_size(&self) -> Rems {
7213        rems_from_px(13.)
7214    }
7215
7216    pub(crate) fn render_thread_error(
7217        &mut self,
7218        window: &mut Window,
7219        cx: &mut Context<Self>,
7220    ) -> Option<Div> {
7221        let content = match self.thread_error.as_ref()? {
7222            ThreadError::Other { message, .. } => {
7223                self.render_any_thread_error(message.clone(), window, cx)
7224            }
7225            ThreadError::Refusal => self.render_refusal_error(cx),
7226            ThreadError::AuthenticationRequired(error) => {
7227                self.render_authentication_required_error(error.clone(), cx)
7228            }
7229            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
7230        };
7231
7232        Some(div().child(content))
7233    }
7234
7235    fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
7236        let model_or_agent_name = self.current_model_name(cx);
7237        let refusal_message = format!(
7238            "{} refused to respond to this prompt. \
7239            This can happen when a model believes the prompt violates its content policy \
7240            or safety guidelines, so rephrasing it can sometimes address the issue.",
7241            model_or_agent_name
7242        );
7243
7244        Callout::new()
7245            .severity(Severity::Error)
7246            .title("Request Refused")
7247            .icon(IconName::XCircle)
7248            .description(refusal_message.clone())
7249            .actions_slot(self.create_copy_button(&refusal_message))
7250            .dismiss_action(self.dismiss_error_button(cx))
7251    }
7252
7253    fn render_authentication_required_error(
7254        &self,
7255        error: SharedString,
7256        cx: &mut Context<Self>,
7257    ) -> Callout {
7258        Callout::new()
7259            .severity(Severity::Error)
7260            .title("Authentication Required")
7261            .icon(IconName::XCircle)
7262            .description(error.clone())
7263            .actions_slot(
7264                h_flex()
7265                    .gap_0p5()
7266                    .child(self.authenticate_button(cx))
7267                    .child(self.create_copy_button(error)),
7268            )
7269            .dismiss_action(self.dismiss_error_button(cx))
7270    }
7271
7272    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
7273        const ERROR_MESSAGE: &str =
7274            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
7275
7276        Callout::new()
7277            .severity(Severity::Error)
7278            .icon(IconName::XCircle)
7279            .title("Free Usage Exceeded")
7280            .description(ERROR_MESSAGE)
7281            .actions_slot(
7282                h_flex()
7283                    .gap_0p5()
7284                    .child(self.upgrade_button(cx))
7285                    .child(self.create_copy_button(ERROR_MESSAGE)),
7286            )
7287            .dismiss_action(self.dismiss_error_button(cx))
7288    }
7289
7290    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7291        Button::new("upgrade", "Upgrade")
7292            .label_size(LabelSize::Small)
7293            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7294            .on_click(cx.listener({
7295                move |this, _, _, cx| {
7296                    this.clear_thread_error(cx);
7297                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
7298                }
7299            }))
7300    }
7301
7302    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7303        Button::new("authenticate", "Authenticate")
7304            .label_size(LabelSize::Small)
7305            .style(ButtonStyle::Filled)
7306            .on_click(cx.listener({
7307                move |this, _, window, cx| {
7308                    let server_view = this.server_view.clone();
7309                    let agent_name = this.agent_id.clone();
7310
7311                    this.clear_thread_error(cx);
7312                    if let Some(message) = this.in_flight_prompt.take() {
7313                        this.message_editor.update(cx, |editor, cx| {
7314                            editor.set_message(message, window, cx);
7315                        });
7316                    }
7317                    let connection = this.thread.read(cx).connection().clone();
7318                    window.defer(cx, |window, cx| {
7319                        ConversationView::handle_auth_required(
7320                            server_view,
7321                            AuthRequired::new(),
7322                            agent_name,
7323                            connection,
7324                            window,
7325                            cx,
7326                        );
7327                    })
7328                }
7329            }))
7330    }
7331
7332    fn current_model_name(&self, cx: &App) -> SharedString {
7333        // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
7334        // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
7335        // This provides better clarity about what refused the request
7336        if self.as_native_connection(cx).is_some() {
7337            self.model_selector
7338                .clone()
7339                .and_then(|selector| selector.read(cx).active_model(cx))
7340                .map(|model| model.name.clone())
7341                .unwrap_or_else(|| SharedString::from("The model"))
7342        } else {
7343            // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
7344            self.agent_id.0.clone()
7345        }
7346    }
7347
7348    fn render_any_thread_error(
7349        &mut self,
7350        error: SharedString,
7351        window: &mut Window,
7352        cx: &mut Context<'_, Self>,
7353    ) -> Callout {
7354        let can_resume = self.thread.read(cx).can_retry(cx);
7355
7356        let markdown = if let Some(markdown) = &self.thread_error_markdown {
7357            markdown.clone()
7358        } else {
7359            let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
7360            self.thread_error_markdown = Some(markdown.clone());
7361            markdown
7362        };
7363
7364        let markdown_style =
7365            MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx);
7366        let description = self
7367            .render_markdown(markdown, markdown_style)
7368            .into_any_element();
7369
7370        Callout::new()
7371            .severity(Severity::Error)
7372            .icon(IconName::XCircle)
7373            .title("An Error Happened")
7374            .description_slot(description)
7375            .actions_slot(
7376                h_flex()
7377                    .gap_0p5()
7378                    .when(can_resume, |this| {
7379                        this.child(
7380                            IconButton::new("retry", IconName::RotateCw)
7381                                .icon_size(IconSize::Small)
7382                                .tooltip(Tooltip::text("Retry Generation"))
7383                                .on_click(cx.listener(|this, _, _window, cx| {
7384                                    this.retry_generation(cx);
7385                                })),
7386                        )
7387                    })
7388                    .child(self.create_copy_button(error.to_string())),
7389            )
7390            .dismiss_action(self.dismiss_error_button(cx))
7391    }
7392
7393    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
7394        let workspace = self.workspace.clone();
7395        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
7396            open_link(text, &workspace, window, cx);
7397        })
7398    }
7399
7400    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
7401        let message = message.into();
7402
7403        CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
7404    }
7405
7406    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7407        IconButton::new("dismiss", IconName::Close)
7408            .icon_size(IconSize::Small)
7409            .tooltip(Tooltip::text("Dismiss"))
7410            .on_click(cx.listener({
7411                move |this, _, _, cx| {
7412                    this.clear_thread_error(cx);
7413                    cx.notify();
7414                }
7415            }))
7416    }
7417
7418    fn render_resume_notice(_cx: &Context<Self>) -> AnyElement {
7419        let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
7420
7421        div()
7422            .px_2()
7423            .pt_2()
7424            .pb_3()
7425            .w_full()
7426            .child(
7427                Callout::new()
7428                    .severity(Severity::Info)
7429                    .icon(IconName::Info)
7430                    .title("Resumed Session")
7431                    .description(description),
7432            )
7433            .into_any_element()
7434    }
7435
7436    fn update_recent_history_from_cache(
7437        &mut self,
7438        history: &Entity<ThreadHistory>,
7439        cx: &mut Context<Self>,
7440    ) {
7441        self.recent_history_entries = history.read(cx).get_recent_sessions(3);
7442        self.hovered_recent_history_item = None;
7443        cx.notify();
7444    }
7445
7446    fn render_empty_state_section_header(
7447        &self,
7448        label: impl Into<SharedString>,
7449        action_slot: Option<AnyElement>,
7450        cx: &mut Context<Self>,
7451    ) -> impl IntoElement {
7452        div().pl_1().pr_1p5().child(
7453            h_flex()
7454                .mt_2()
7455                .pl_1p5()
7456                .pb_1()
7457                .w_full()
7458                .justify_between()
7459                .border_b_1()
7460                .border_color(cx.theme().colors().border_variant)
7461                .child(
7462                    Label::new(label.into())
7463                        .size(LabelSize::Small)
7464                        .color(Color::Muted),
7465                )
7466                .children(action_slot),
7467        )
7468    }
7469
7470    fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
7471        let render_history = !self.recent_history_entries.is_empty();
7472
7473        v_flex()
7474            .size_full()
7475            .when(render_history, |this| {
7476                let recent_history = self.recent_history_entries.clone();
7477                this.justify_end().child(
7478                    v_flex()
7479                        .child(
7480                            self.render_empty_state_section_header(
7481                                "Recent",
7482                                Some(
7483                                    Button::new("view-history", "View All")
7484                                        .style(ButtonStyle::Subtle)
7485                                        .label_size(LabelSize::Small)
7486                                        .key_binding(
7487                                            KeyBinding::for_action_in(
7488                                                &OpenHistory,
7489                                                &self.focus_handle(cx),
7490                                                cx,
7491                                            )
7492                                            .map(|kb| kb.size(rems_from_px(12.))),
7493                                        )
7494                                        .on_click(move |_event, window, cx| {
7495                                            window.dispatch_action(OpenHistory.boxed_clone(), cx);
7496                                        })
7497                                        .into_any_element(),
7498                                ),
7499                                cx,
7500                            ),
7501                        )
7502                        .child(v_flex().p_1().pr_1p5().gap_1().children({
7503                            let supports_delete = self
7504                                .history
7505                                .as_ref()
7506                                .map_or(false, |h| h.read(cx).supports_delete());
7507                            recent_history
7508                                .into_iter()
7509                                .enumerate()
7510                                .map(move |(index, entry)| {
7511                                    // TODO: Add keyboard navigation.
7512                                    let is_hovered =
7513                                        self.hovered_recent_history_item == Some(index);
7514                                    crate::thread_history_view::HistoryEntryElement::new(
7515                                        entry,
7516                                        self.server_view.clone(),
7517                                    )
7518                                    .hovered(is_hovered)
7519                                    .supports_delete(supports_delete)
7520                                    .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
7521                                        if *is_hovered {
7522                                            this.hovered_recent_history_item = Some(index);
7523                                        } else if this.hovered_recent_history_item == Some(index) {
7524                                            this.hovered_recent_history_item = None;
7525                                        }
7526                                        cx.notify();
7527                                    }))
7528                                    .into_any_element()
7529                                })
7530                        })),
7531                )
7532            })
7533            .into_any()
7534    }
7535
7536    fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
7537        Callout::new()
7538            .icon(IconName::Warning)
7539            .severity(Severity::Warning)
7540            .title("Codex on Windows")
7541            .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
7542            .actions_slot(
7543                Button::new("open-wsl-modal", "Open in WSL").on_click(cx.listener({
7544                    move |_, _, _window, cx| {
7545                        #[cfg(windows)]
7546                        _window.dispatch_action(
7547                            zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
7548                            cx,
7549                        );
7550                        cx.notify();
7551                    }
7552                })),
7553            )
7554            .dismiss_action(
7555                IconButton::new("dismiss", IconName::Close)
7556                    .icon_size(IconSize::Small)
7557                    .icon_color(Color::Muted)
7558                    .tooltip(Tooltip::text("Dismiss Warning"))
7559                    .on_click(cx.listener({
7560                        move |this, _, _, cx| {
7561                            this.show_codex_windows_warning = false;
7562                            cx.notify();
7563                        }
7564                    })),
7565            )
7566    }
7567
7568    fn render_external_source_prompt_warning(&self, cx: &mut Context<Self>) -> Callout {
7569        Callout::new()
7570            .icon(IconName::Warning)
7571            .severity(Severity::Warning)
7572            .title("Review before sending")
7573            .description("This prompt was pre-filled by an external link. Read it carefully before you send it.")
7574            .dismiss_action(
7575                IconButton::new("dismiss-external-source-prompt-warning", IconName::Close)
7576                    .icon_size(IconSize::Small)
7577                    .icon_color(Color::Muted)
7578                    .tooltip(Tooltip::text("Dismiss Warning"))
7579                    .on_click(cx.listener({
7580                        move |this, _, _, cx| {
7581                            this.show_external_source_prompt_warning = false;
7582                            cx.notify();
7583                        }
7584                    })),
7585            )
7586    }
7587
7588    fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
7589        let server_view = self.server_view.clone();
7590        v_flex().w_full().justify_end().child(
7591            h_flex()
7592                .p_2()
7593                .pr_3()
7594                .w_full()
7595                .gap_1p5()
7596                .border_t_1()
7597                .border_color(cx.theme().colors().border)
7598                .bg(cx.theme().colors().element_background)
7599                .child(
7600                    h_flex()
7601                        .flex_1()
7602                        .gap_1p5()
7603                        .child(
7604                            Icon::new(IconName::Download)
7605                                .color(Color::Accent)
7606                                .size(IconSize::Small),
7607                        )
7608                        .child(Label::new("New version available").size(LabelSize::Small)),
7609                )
7610                .child(
7611                    Button::new("update-button", format!("Update to v{}", version))
7612                        .label_size(LabelSize::Small)
7613                        .style(ButtonStyle::Tinted(TintColor::Accent))
7614                        .on_click(move |_, window, cx| {
7615                            server_view
7616                                .update(cx, |view, cx| view.reset(window, cx))
7617                                .ok();
7618                        }),
7619                ),
7620        )
7621    }
7622
7623    fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
7624        if self.token_limit_callout_dismissed {
7625            return None;
7626        }
7627
7628        let token_usage = self.thread.read(cx).token_usage()?;
7629        let ratio = token_usage.ratio();
7630
7631        let (severity, icon, title) = match ratio {
7632            acp_thread::TokenUsageRatio::Normal => return None,
7633            acp_thread::TokenUsageRatio::Warning => (
7634                Severity::Warning,
7635                IconName::Warning,
7636                "Thread reaching the token limit soon",
7637            ),
7638            acp_thread::TokenUsageRatio::Exceeded => (
7639                Severity::Error,
7640                IconName::XCircle,
7641                "Thread reached the token limit",
7642            ),
7643        };
7644
7645        let description = "To continue, start a new thread from a summary.";
7646
7647        Some(
7648            Callout::new()
7649                .severity(severity)
7650                .icon(icon)
7651                .title(title)
7652                .description(description)
7653                .actions_slot(
7654                    h_flex().gap_0p5().child(
7655                        Button::new("start-new-thread", "Start New Thread")
7656                            .label_size(LabelSize::Small)
7657                            .on_click(cx.listener(|this, _, window, cx| {
7658                                let session_id = this.thread.read(cx).session_id().clone();
7659                                window.dispatch_action(
7660                                    crate::NewNativeAgentThreadFromSummary {
7661                                        from_session_id: session_id,
7662                                    }
7663                                    .boxed_clone(),
7664                                    cx,
7665                                );
7666                            })),
7667                    ),
7668                )
7669                .dismiss_action(self.dismiss_error_button(cx)),
7670        )
7671    }
7672
7673    fn open_permission_dropdown(
7674        &mut self,
7675        _: &crate::OpenPermissionDropdown,
7676        window: &mut Window,
7677        cx: &mut Context<Self>,
7678    ) {
7679        self.permission_dropdown_handle.clone().toggle(window, cx);
7680    }
7681
7682    fn open_add_context_menu(
7683        &mut self,
7684        _action: &OpenAddContextMenu,
7685        window: &mut Window,
7686        cx: &mut Context<Self>,
7687    ) {
7688        let menu_handle = self.add_context_menu_handle.clone();
7689        window.defer(cx, move |window, cx| {
7690            menu_handle.toggle(window, cx);
7691        });
7692    }
7693
7694    fn toggle_fast_mode(&mut self, cx: &mut Context<Self>) {
7695        if !self.fast_mode_available(cx) {
7696            return;
7697        }
7698        let Some(thread) = self.as_native_thread(cx) else {
7699            return;
7700        };
7701        thread.update(cx, |thread, cx| {
7702            thread.set_speed(
7703                thread
7704                    .speed()
7705                    .map(|speed| speed.toggle())
7706                    .unwrap_or(Speed::Fast),
7707                cx,
7708            );
7709        });
7710    }
7711
7712    fn cycle_thinking_effort(&mut self, cx: &mut Context<Self>) {
7713        let Some(thread) = self.as_native_thread(cx) else {
7714            return;
7715        };
7716
7717        let (effort_levels, current_effort) = {
7718            let thread_ref = thread.read(cx);
7719            let Some(model) = thread_ref.model() else {
7720                return;
7721            };
7722            if !model.supports_thinking() || !thread_ref.thinking_enabled() {
7723                return;
7724            }
7725            let effort_levels = model.supported_effort_levels();
7726            if effort_levels.is_empty() {
7727                return;
7728            }
7729            let current_effort = thread_ref.thinking_effort().cloned();
7730            (effort_levels, current_effort)
7731        };
7732
7733        let current_index = current_effort.and_then(|current| {
7734            effort_levels
7735                .iter()
7736                .position(|level| level.value == current)
7737        });
7738        let next_index = match current_index {
7739            Some(index) => (index + 1) % effort_levels.len(),
7740            None => 0,
7741        };
7742        let next_effort = effort_levels[next_index].value.to_string();
7743
7744        thread.update(cx, |thread, cx| {
7745            thread.set_thinking_effort(Some(next_effort.clone()), cx);
7746
7747            let fs = thread.project().read(cx).fs().clone();
7748            update_settings_file(fs, cx, move |settings, _| {
7749                if let Some(agent) = settings.agent.as_mut()
7750                    && let Some(default_model) = agent.default_model.as_mut()
7751                {
7752                    default_model.effort = Some(next_effort);
7753                }
7754            });
7755        });
7756    }
7757
7758    fn toggle_thinking_effort_menu(
7759        &mut self,
7760        _action: &ToggleThinkingEffortMenu,
7761        window: &mut Window,
7762        cx: &mut Context<Self>,
7763    ) {
7764        let menu_handle = self.thinking_effort_menu_handle.clone();
7765        window.defer(cx, move |window, cx| {
7766            menu_handle.toggle(window, cx);
7767        });
7768    }
7769}
7770
7771impl Render for ThreadView {
7772    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7773        let has_messages = self.list_state.item_count() > 0;
7774        let v2_empty_state = cx.has_flag::<AgentV2FeatureFlag>() && !has_messages;
7775
7776        let conversation = v_flex()
7777            .when(!v2_empty_state, |this| this.flex_1())
7778            .map(|this| {
7779                let this = this.when(self.resumed_without_history, |this| {
7780                    this.child(Self::render_resume_notice(cx))
7781                });
7782                if has_messages {
7783                    let list_state = self.list_state.clone();
7784                    this.child(self.render_entries(cx))
7785                        .vertical_scrollbar_for(&list_state, window, cx)
7786                        .into_any()
7787                } else if v2_empty_state {
7788                    this.into_any()
7789                } else {
7790                    this.child(self.render_recent_history(cx)).into_any()
7791                }
7792            });
7793
7794        v_flex()
7795            .key_context("AcpThread")
7796            .track_focus(&self.focus_handle)
7797            .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
7798                if this.parent_id.is_none() {
7799                    this.cancel_generation(cx);
7800                }
7801            }))
7802            .on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
7803                if let Some(parent_session_id) = this.parent_id.clone() {
7804                    this.server_view
7805                        .update(cx, |view, cx| {
7806                            view.navigate_to_session(parent_session_id, window, cx);
7807                        })
7808                        .ok();
7809                }
7810            }))
7811            .on_action(cx.listener(Self::keep_all))
7812            .on_action(cx.listener(Self::reject_all))
7813            .on_action(cx.listener(Self::undo_last_reject))
7814            .on_action(cx.listener(Self::allow_always))
7815            .on_action(cx.listener(Self::allow_once))
7816            .on_action(cx.listener(Self::reject_once))
7817            .on_action(cx.listener(Self::handle_authorize_tool_call))
7818            .on_action(cx.listener(Self::open_permission_dropdown))
7819            .on_action(cx.listener(Self::open_add_context_menu))
7820            .on_action(cx.listener(|this, _: &ToggleFastMode, _window, cx| {
7821                this.toggle_fast_mode(cx);
7822            }))
7823            .on_action(cx.listener(|this, _: &ToggleThinkingMode, _window, cx| {
7824                if this.thread.read(cx).status() != ThreadStatus::Idle {
7825                    return;
7826                }
7827                if let Some(thread) = this.as_native_thread(cx) {
7828                    thread.update(cx, |thread, cx| {
7829                        thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
7830                    });
7831                }
7832            }))
7833            .on_action(cx.listener(|this, _: &CycleThinkingEffort, _window, cx| {
7834                if this.thread.read(cx).status() != ThreadStatus::Idle {
7835                    return;
7836                }
7837                this.cycle_thinking_effort(cx);
7838            }))
7839            .on_action(
7840                cx.listener(|this, action: &ToggleThinkingEffortMenu, window, cx| {
7841                    if this.thread.read(cx).status() != ThreadStatus::Idle {
7842                        return;
7843                    }
7844                    this.toggle_thinking_effort_menu(action, window, cx);
7845                }),
7846            )
7847            .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
7848                this.send_queued_message_at_index(0, true, window, cx);
7849            }))
7850            .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
7851                this.remove_from_queue(0, cx);
7852                cx.notify();
7853            }))
7854            .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
7855                this.move_queued_message_to_main_editor(0, None, window, cx);
7856            }))
7857            .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
7858                this.local_queued_messages.clear();
7859                this.sync_queue_flag_to_native_thread(cx);
7860                this.can_fast_track_queue = false;
7861                cx.notify();
7862            }))
7863            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
7864                if this.thread.read(cx).status() != ThreadStatus::Idle {
7865                    return;
7866                }
7867                if let Some(config_options_view) = this.config_options_view.clone() {
7868                    let handled = config_options_view.update(cx, |view, cx| {
7869                        view.toggle_category_picker(
7870                            acp::SessionConfigOptionCategory::Mode,
7871                            window,
7872                            cx,
7873                        )
7874                    });
7875                    if handled {
7876                        return;
7877                    }
7878                }
7879
7880                if let Some(profile_selector) = this.profile_selector.clone() {
7881                    profile_selector.read(cx).menu_handle().toggle(window, cx);
7882                } else if let Some(mode_selector) = this.mode_selector.clone() {
7883                    mode_selector.read(cx).menu_handle().toggle(window, cx);
7884                }
7885            }))
7886            .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
7887                if this.thread.read(cx).status() != ThreadStatus::Idle {
7888                    return;
7889                }
7890                if let Some(config_options_view) = this.config_options_view.clone() {
7891                    let handled = config_options_view.update(cx, |view, cx| {
7892                        view.cycle_category_option(
7893                            acp::SessionConfigOptionCategory::Mode,
7894                            false,
7895                            cx,
7896                        )
7897                    });
7898                    if handled {
7899                        return;
7900                    }
7901                }
7902
7903                if let Some(profile_selector) = this.profile_selector.clone() {
7904                    profile_selector.update(cx, |profile_selector, cx| {
7905                        profile_selector.cycle_profile(cx);
7906                    });
7907                } else if let Some(mode_selector) = this.mode_selector.clone() {
7908                    mode_selector.update(cx, |mode_selector, cx| {
7909                        mode_selector.cycle_mode(window, cx);
7910                    });
7911                }
7912            }))
7913            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
7914                if this.thread.read(cx).status() != ThreadStatus::Idle {
7915                    return;
7916                }
7917                if let Some(config_options_view) = this.config_options_view.clone() {
7918                    let handled = config_options_view.update(cx, |view, cx| {
7919                        view.toggle_category_picker(
7920                            acp::SessionConfigOptionCategory::Model,
7921                            window,
7922                            cx,
7923                        )
7924                    });
7925                    if handled {
7926                        return;
7927                    }
7928                }
7929
7930                if let Some(model_selector) = this.model_selector.clone() {
7931                    model_selector
7932                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
7933                }
7934            }))
7935            .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
7936                if this.thread.read(cx).status() != ThreadStatus::Idle {
7937                    return;
7938                }
7939                if let Some(config_options_view) = this.config_options_view.clone() {
7940                    let handled = config_options_view.update(cx, |view, cx| {
7941                        view.cycle_category_option(
7942                            acp::SessionConfigOptionCategory::Model,
7943                            true,
7944                            cx,
7945                        )
7946                    });
7947                    if handled {
7948                        return;
7949                    }
7950                }
7951
7952                if let Some(model_selector) = this.model_selector.clone() {
7953                    model_selector.update(cx, |model_selector, cx| {
7954                        model_selector.cycle_favorite_models(window, cx);
7955                    });
7956                }
7957            }))
7958            .size_full()
7959            .children(self.render_subagent_titlebar(cx))
7960            .child(conversation)
7961            .children(self.render_activity_bar(window, cx))
7962            .when(self.show_external_source_prompt_warning, |this| {
7963                this.child(self.render_external_source_prompt_warning(cx))
7964            })
7965            .when(self.show_codex_windows_warning, |this| {
7966                this.child(self.render_codex_windows_warning(cx))
7967            })
7968            .children(self.render_thread_retry_status_callout())
7969            .children(self.render_thread_error(window, cx))
7970            .when_some(
7971                match has_messages {
7972                    true => None,
7973                    false => self.new_server_version_available.clone(),
7974                },
7975                |this, version| this.child(self.render_new_version_callout(&version, cx)),
7976            )
7977            .children(self.render_token_limit_callout(cx))
7978            .child(self.render_message_editor(window, cx))
7979    }
7980}
7981
7982pub(crate) fn open_link(
7983    url: SharedString,
7984    workspace: &WeakEntity<Workspace>,
7985    window: &mut Window,
7986    cx: &mut App,
7987) {
7988    let Some(workspace) = workspace.upgrade() else {
7989        cx.open_url(&url);
7990        return;
7991    };
7992
7993    if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err() {
7994        workspace.update(cx, |workspace, cx| match mention {
7995            MentionUri::File { abs_path } => {
7996                let project = workspace.project();
7997                let Some(path) =
7998                    project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
7999                else {
8000                    return;
8001                };
8002
8003                workspace
8004                    .open_path(path, None, true, window, cx)
8005                    .detach_and_log_err(cx);
8006            }
8007            MentionUri::PastedImage => {}
8008            MentionUri::Directory { abs_path } => {
8009                let project = workspace.project();
8010                let Some(entry_id) = project.update(cx, |project, cx| {
8011                    let path = project.find_project_path(abs_path, cx)?;
8012                    project.entry_for_path(&path, cx).map(|entry| entry.id)
8013                }) else {
8014                    return;
8015                };
8016
8017                project.update(cx, |_, cx| {
8018                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
8019                });
8020            }
8021            MentionUri::Symbol {
8022                abs_path: path,
8023                line_range,
8024                ..
8025            }
8026            | MentionUri::Selection {
8027                abs_path: Some(path),
8028                line_range,
8029            } => {
8030                let project = workspace.project();
8031                let Some(path) =
8032                    project.update(cx, |project, cx| project.find_project_path(path, cx))
8033                else {
8034                    return;
8035                };
8036
8037                let item = workspace.open_path(path, None, true, window, cx);
8038                window
8039                    .spawn(cx, async move |cx| {
8040                        let Some(editor) = item.await?.downcast::<Editor>() else {
8041                            return Ok(());
8042                        };
8043                        let range =
8044                            Point::new(*line_range.start(), 0)..Point::new(*line_range.start(), 0);
8045                        editor
8046                            .update_in(cx, |editor, window, cx| {
8047                                editor.change_selections(
8048                                    SelectionEffects::scroll(Autoscroll::center()),
8049                                    window,
8050                                    cx,
8051                                    |s| s.select_ranges(vec![range]),
8052                                );
8053                            })
8054                            .ok();
8055                        anyhow::Ok(())
8056                    })
8057                    .detach_and_log_err(cx);
8058            }
8059            MentionUri::Selection { abs_path: None, .. } => {}
8060            MentionUri::Thread { id, name } => {
8061                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
8062                    panel.update(cx, |panel, cx| {
8063                        panel.open_thread(id, None, Some(name.into()), window, cx)
8064                    });
8065                }
8066            }
8067            MentionUri::TextThread { path, .. } => {
8068                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
8069                    panel.update(cx, |panel, cx| {
8070                        panel
8071                            .open_saved_text_thread(path.as_path().into(), window, cx)
8072                            .detach_and_log_err(cx);
8073                    });
8074                }
8075            }
8076            MentionUri::Rule { id, .. } => {
8077                let PromptId::User { uuid } = id else {
8078                    return;
8079                };
8080                window.dispatch_action(
8081                    Box::new(OpenRulesLibrary {
8082                        prompt_to_select: Some(uuid.0),
8083                    }),
8084                    cx,
8085                )
8086            }
8087            MentionUri::Fetch { url } => {
8088                cx.open_url(url.as_str());
8089            }
8090            MentionUri::Diagnostics { .. } => {}
8091            MentionUri::TerminalSelection { .. } => {}
8092            MentionUri::GitDiff { .. } => {}
8093            MentionUri::MergeConflict { .. } => {}
8094        })
8095    } else {
8096        cx.open_url(&url);
8097    }
8098}