thread_view.rs

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