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