thread_view.rs

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