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