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