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