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