thread_view.rs

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