thread_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
   3    AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
   4    ToolCallStatus, UserMessageId,
   5};
   6use acp_thread::{AgentConnection, Plan};
   7use action_log::ActionLog;
   8use agent_client_protocol::{self as acp};
   9use agent_servers::{AgentServer, ClaudeCode};
  10use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, NotifyWhenAgentWaiting};
  11use agent2::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore};
  12use anyhow::bail;
  13use audio::{Audio, Sound};
  14use buffer_diff::BufferDiff;
  15use client::zed_urls;
  16use collections::{HashMap, HashSet};
  17use editor::scroll::Autoscroll;
  18use editor::{Editor, EditorMode, MultiBuffer, PathKey, SelectionEffects};
  19use file_icons::FileIcons;
  20use fs::Fs;
  21use gpui::{
  22    Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
  23    EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length, ListOffset,
  24    ListState, MouseButton, PlatformDisplay, SharedString, Stateful, StyleRefinement, Subscription,
  25    Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity, Window,
  26    WindowHandle, div, ease_in_out, linear_color_stop, linear_gradient, list, percentage, point,
  27    prelude::*, pulsating_between,
  28};
  29use language::Buffer;
  30
  31use language_model::LanguageModelRegistry;
  32use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  33use project::{Project, ProjectEntryId};
  34use prompt_store::{PromptId, PromptStore};
  35use rope::Point;
  36use settings::{Settings as _, SettingsStore};
  37use std::sync::Arc;
  38use std::time::Instant;
  39use std::{collections::BTreeMap, rc::Rc, time::Duration};
  40use text::Anchor;
  41use theme::ThemeSettings;
  42use ui::{
  43    Callout, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding, PopoverMenuHandle,
  44    Scrollbar, ScrollbarState, Tooltip, prelude::*,
  45};
  46use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  47use workspace::{CollaboratorId, Workspace};
  48use zed_actions::agent::{Chat, ToggleModelSelector};
  49use zed_actions::assistant::OpenRulesLibrary;
  50
  51use super::entry_view_state::EntryViewState;
  52use crate::acp::AcpModelSelectorPopover;
  53use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
  54use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
  55use crate::agent_diff::AgentDiff;
  56use crate::profile_selector::{ProfileProvider, ProfileSelector};
  57
  58use crate::ui::preview::UsageCallout;
  59use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip};
  60use crate::{
  61    AgentDiffPane, AgentPanel, ContinueThread, ContinueWithBurnMode, ExpandMessageEditor, Follow,
  62    KeepAll, OpenAgentDiff, OpenHistory, RejectAll, ToggleBurnMode, ToggleProfileSelector,
  63};
  64
  65const RESPONSE_PADDING_X: Pixels = px(19.);
  66pub const MIN_EDITOR_LINES: usize = 4;
  67pub const MAX_EDITOR_LINES: usize = 8;
  68
  69#[derive(Copy, Clone, Debug, PartialEq, Eq)]
  70enum ThreadFeedback {
  71    Positive,
  72    Negative,
  73}
  74
  75enum ThreadError {
  76    PaymentRequired,
  77    ModelRequestLimitReached(cloud_llm_client::Plan),
  78    ToolUseLimitReached,
  79    Other(SharedString),
  80}
  81
  82impl ThreadError {
  83    fn from_err(error: anyhow::Error) -> Self {
  84        if error.is::<language_model::PaymentRequiredError>() {
  85            Self::PaymentRequired
  86        } else if error.is::<language_model::ToolUseLimitReachedError>() {
  87            Self::ToolUseLimitReached
  88        } else if let Some(error) =
  89            error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
  90        {
  91            Self::ModelRequestLimitReached(error.plan)
  92        } else {
  93            Self::Other(error.to_string().into())
  94        }
  95    }
  96}
  97
  98impl ProfileProvider for Entity<agent2::Thread> {
  99    fn profile_id(&self, cx: &App) -> AgentProfileId {
 100        self.read(cx).profile().clone()
 101    }
 102
 103    fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
 104        self.update(cx, |thread, _cx| {
 105            thread.set_profile(profile_id);
 106        });
 107    }
 108
 109    fn profiles_supported(&self, cx: &App) -> bool {
 110        self.read(cx)
 111            .model()
 112            .is_some_and(|model| model.supports_tools())
 113    }
 114}
 115
 116#[derive(Default)]
 117struct ThreadFeedbackState {
 118    feedback: Option<ThreadFeedback>,
 119    comments_editor: Option<Entity<Editor>>,
 120}
 121
 122impl ThreadFeedbackState {
 123    pub fn submit(
 124        &mut self,
 125        thread: Entity<AcpThread>,
 126        feedback: ThreadFeedback,
 127        window: &mut Window,
 128        cx: &mut App,
 129    ) {
 130        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 131            return;
 132        };
 133
 134        if self.feedback == Some(feedback) {
 135            return;
 136        }
 137
 138        self.feedback = Some(feedback);
 139        match feedback {
 140            ThreadFeedback::Positive => {
 141                self.comments_editor = None;
 142            }
 143            ThreadFeedback::Negative => {
 144                self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
 145            }
 146        }
 147        let session_id = thread.read(cx).session_id().clone();
 148        let agent_name = telemetry.agent_name();
 149        let task = telemetry.thread_data(&session_id, cx);
 150        let rating = match feedback {
 151            ThreadFeedback::Positive => "positive",
 152            ThreadFeedback::Negative => "negative",
 153        };
 154        cx.background_spawn(async move {
 155            let thread = task.await?;
 156            telemetry::event!(
 157                "Agent Thread Rated",
 158                session_id = session_id,
 159                rating = rating,
 160                agent = agent_name,
 161                thread = thread
 162            );
 163            anyhow::Ok(())
 164        })
 165        .detach_and_log_err(cx);
 166    }
 167
 168    pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
 169        let Some(telemetry) = thread.read(cx).connection().telemetry() else {
 170            return;
 171        };
 172
 173        let Some(comments) = self
 174            .comments_editor
 175            .as_ref()
 176            .map(|editor| editor.read(cx).text(cx))
 177            .filter(|text| !text.trim().is_empty())
 178        else {
 179            return;
 180        };
 181
 182        self.comments_editor.take();
 183
 184        let session_id = thread.read(cx).session_id().clone();
 185        let agent_name = telemetry.agent_name();
 186        let task = telemetry.thread_data(&session_id, cx);
 187        cx.background_spawn(async move {
 188            let thread = task.await?;
 189            telemetry::event!(
 190                "Agent Thread Feedback Comments",
 191                session_id = session_id,
 192                comments = comments,
 193                agent = agent_name,
 194                thread = thread
 195            );
 196            anyhow::Ok(())
 197        })
 198        .detach_and_log_err(cx);
 199    }
 200
 201    pub fn clear(&mut self) {
 202        *self = Self::default()
 203    }
 204
 205    pub fn dismiss_comments(&mut self) {
 206        self.comments_editor.take();
 207    }
 208
 209    fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
 210        let buffer = cx.new(|cx| {
 211            let empty_string = String::new();
 212            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
 213        });
 214
 215        let editor = cx.new(|cx| {
 216            let mut editor = Editor::new(
 217                editor::EditorMode::AutoHeight {
 218                    min_lines: 1,
 219                    max_lines: Some(4),
 220                },
 221                buffer,
 222                None,
 223                window,
 224                cx,
 225            );
 226            editor.set_placeholder_text(
 227                "What went wrong? Share your feedback so we can improve.",
 228                cx,
 229            );
 230            editor
 231        });
 232
 233        editor.read(cx).focus_handle(cx).focus(window);
 234        editor
 235    }
 236}
 237
 238pub struct AcpThreadView {
 239    agent: Rc<dyn AgentServer>,
 240    workspace: WeakEntity<Workspace>,
 241    project: Entity<Project>,
 242    thread_state: ThreadState,
 243    history_store: Entity<HistoryStore>,
 244    hovered_recent_history_item: Option<usize>,
 245    entry_view_state: Entity<EntryViewState>,
 246    message_editor: Entity<MessageEditor>,
 247    model_selector: Option<Entity<AcpModelSelectorPopover>>,
 248    profile_selector: Option<Entity<ProfileSelector>>,
 249    notifications: Vec<WindowHandle<AgentNotification>>,
 250    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
 251    thread_retry_status: Option<RetryStatus>,
 252    thread_error: Option<ThreadError>,
 253    thread_feedback: ThreadFeedbackState,
 254    list_state: ListState,
 255    scrollbar_state: ScrollbarState,
 256    auth_task: Option<Task<()>>,
 257    expanded_tool_calls: HashSet<acp::ToolCallId>,
 258    expanded_thinking_blocks: HashSet<(usize, usize)>,
 259    edits_expanded: bool,
 260    plan_expanded: bool,
 261    editor_expanded: bool,
 262    editing_message: Option<usize>,
 263    _cancel_task: Option<Task<()>>,
 264    _subscriptions: [Subscription; 3],
 265}
 266
 267enum ThreadState {
 268    Loading {
 269        _task: Task<()>,
 270    },
 271    Ready {
 272        thread: Entity<AcpThread>,
 273        _subscription: [Subscription; 2],
 274    },
 275    LoadError(LoadError),
 276    Unauthenticated {
 277        connection: Rc<dyn AgentConnection>,
 278        description: Option<Entity<Markdown>>,
 279        configuration_view: Option<AnyView>,
 280        pending_auth_method: Option<acp::AuthMethodId>,
 281        _subscription: Option<Subscription>,
 282    },
 283}
 284
 285impl AcpThreadView {
 286    pub fn new(
 287        agent: Rc<dyn AgentServer>,
 288        resume_thread: Option<DbThreadMetadata>,
 289        summarize_thread: Option<DbThreadMetadata>,
 290        workspace: WeakEntity<Workspace>,
 291        project: Entity<Project>,
 292        history_store: Entity<HistoryStore>,
 293        prompt_store: Option<Entity<PromptStore>>,
 294        window: &mut Window,
 295        cx: &mut Context<Self>,
 296    ) -> Self {
 297        let prevent_slash_commands = agent.clone().downcast::<ClaudeCode>().is_some();
 298        let message_editor = cx.new(|cx| {
 299            let mut editor = MessageEditor::new(
 300                workspace.clone(),
 301                project.clone(),
 302                history_store.clone(),
 303                prompt_store.clone(),
 304                "Message the agent — @ to include context",
 305                prevent_slash_commands,
 306                editor::EditorMode::AutoHeight {
 307                    min_lines: MIN_EDITOR_LINES,
 308                    max_lines: Some(MAX_EDITOR_LINES),
 309                },
 310                window,
 311                cx,
 312            );
 313            if let Some(entry) = summarize_thread {
 314                editor.insert_thread_summary(entry, window, cx);
 315            }
 316            editor
 317        });
 318
 319        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 320
 321        let entry_view_state = cx.new(|_| {
 322            EntryViewState::new(
 323                workspace.clone(),
 324                project.clone(),
 325                history_store.clone(),
 326                prompt_store.clone(),
 327                prevent_slash_commands,
 328            )
 329        });
 330
 331        let subscriptions = [
 332            cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 333            cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
 334            cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
 335        ];
 336
 337        Self {
 338            agent: agent.clone(),
 339            workspace: workspace.clone(),
 340            project: project.clone(),
 341            entry_view_state,
 342            thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
 343            message_editor,
 344            model_selector: None,
 345            profile_selector: None,
 346            notifications: Vec::new(),
 347            notification_subscriptions: HashMap::default(),
 348            list_state: list_state.clone(),
 349            scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
 350            thread_retry_status: None,
 351            thread_error: None,
 352            thread_feedback: Default::default(),
 353            auth_task: None,
 354            expanded_tool_calls: HashSet::default(),
 355            expanded_thinking_blocks: HashSet::default(),
 356            editing_message: None,
 357            edits_expanded: false,
 358            plan_expanded: false,
 359            editor_expanded: false,
 360            history_store,
 361            hovered_recent_history_item: None,
 362            _subscriptions: subscriptions,
 363            _cancel_task: None,
 364        }
 365    }
 366
 367    fn initial_state(
 368        agent: Rc<dyn AgentServer>,
 369        resume_thread: Option<DbThreadMetadata>,
 370        workspace: WeakEntity<Workspace>,
 371        project: Entity<Project>,
 372        window: &mut Window,
 373        cx: &mut Context<Self>,
 374    ) -> ThreadState {
 375        let root_dir = project
 376            .read(cx)
 377            .visible_worktrees(cx)
 378            .next()
 379            .map(|worktree| worktree.read(cx).abs_path())
 380            .unwrap_or_else(|| paths::home_dir().as_path().into());
 381
 382        let connect_task = agent.connect(&root_dir, &project, cx);
 383        let load_task = cx.spawn_in(window, async move |this, cx| {
 384            let connection = match connect_task.await {
 385                Ok(connection) => connection,
 386                Err(err) => {
 387                    this.update(cx, |this, cx| {
 388                        this.handle_load_error(err, cx);
 389                        cx.notify();
 390                    })
 391                    .log_err();
 392                    return;
 393                }
 394            };
 395
 396            let result = if let Some(native_agent) = connection
 397                .clone()
 398                .downcast::<agent2::NativeAgentConnection>()
 399                && let Some(resume) = resume_thread.clone()
 400            {
 401                cx.update(|_, cx| {
 402                    native_agent
 403                        .0
 404                        .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
 405                })
 406                .log_err()
 407            } else {
 408                cx.update(|_, cx| {
 409                    connection
 410                        .clone()
 411                        .new_thread(project.clone(), &root_dir, cx)
 412                })
 413                .log_err()
 414            };
 415
 416            let Some(result) = result else {
 417                return;
 418            };
 419
 420            let result = match result.await {
 421                Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
 422                    Ok(err) => {
 423                        cx.update(|window, cx| {
 424                            Self::handle_auth_required(this, err, agent, connection, window, cx)
 425                        })
 426                        .log_err();
 427                        return;
 428                    }
 429                    Err(err) => Err(err),
 430                },
 431                Ok(thread) => Ok(thread),
 432            };
 433
 434            this.update_in(cx, |this, window, cx| {
 435                match result {
 436                    Ok(thread) => {
 437                        let thread_subscription =
 438                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 439
 440                        let action_log = thread.read(cx).action_log().clone();
 441                        let action_log_subscription =
 442                            cx.observe(&action_log, |_, _, cx| cx.notify());
 443
 444                        let count = thread.read(cx).entries().len();
 445                        this.list_state.splice(0..0, count);
 446                        this.entry_view_state.update(cx, |view_state, cx| {
 447                            for ix in 0..count {
 448                                view_state.sync_entry(ix, &thread, window, cx);
 449                            }
 450                        });
 451
 452                        if let Some(resume) = resume_thread {
 453                            this.history_store.update(cx, |history, cx| {
 454                                history.push_recently_opened_entry(
 455                                    HistoryEntryId::AcpThread(resume.id),
 456                                    cx,
 457                                );
 458                            });
 459                        }
 460
 461                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 462
 463                        this.model_selector =
 464                            thread
 465                                .read(cx)
 466                                .connection()
 467                                .model_selector()
 468                                .map(|selector| {
 469                                    cx.new(|cx| {
 470                                        AcpModelSelectorPopover::new(
 471                                            thread.read(cx).session_id().clone(),
 472                                            selector,
 473                                            PopoverMenuHandle::default(),
 474                                            this.focus_handle(cx),
 475                                            window,
 476                                            cx,
 477                                        )
 478                                    })
 479                                });
 480
 481                        this.thread_state = ThreadState::Ready {
 482                            thread,
 483                            _subscription: [thread_subscription, action_log_subscription],
 484                        };
 485
 486                        this.profile_selector = this.as_native_thread(cx).map(|thread| {
 487                            cx.new(|cx| {
 488                                ProfileSelector::new(
 489                                    <dyn Fs>::global(cx),
 490                                    Arc::new(thread.clone()),
 491                                    this.focus_handle(cx),
 492                                    cx,
 493                                )
 494                            })
 495                        });
 496
 497                        this.message_editor.update(cx, |message_editor, _cx| {
 498                            message_editor
 499                                .set_prompt_capabilities(connection.prompt_capabilities());
 500                        });
 501
 502                        cx.notify();
 503                    }
 504                    Err(err) => {
 505                        this.handle_load_error(err, cx);
 506                    }
 507                };
 508            })
 509            .log_err();
 510        });
 511
 512        ThreadState::Loading { _task: load_task }
 513    }
 514
 515    fn handle_auth_required(
 516        this: WeakEntity<Self>,
 517        err: AuthRequired,
 518        agent: Rc<dyn AgentServer>,
 519        connection: Rc<dyn AgentConnection>,
 520        window: &mut Window,
 521        cx: &mut App,
 522    ) {
 523        let agent_name = agent.name();
 524        let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
 525            let registry = LanguageModelRegistry::global(cx);
 526
 527            let sub = window.subscribe(&registry, cx, {
 528                let provider_id = provider_id.clone();
 529                let this = this.clone();
 530                move |_, ev, window, cx| {
 531                    if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
 532                        && &provider_id == updated_provider_id
 533                    {
 534                        this.update(cx, |this, cx| {
 535                            this.thread_state = Self::initial_state(
 536                                agent.clone(),
 537                                None,
 538                                this.workspace.clone(),
 539                                this.project.clone(),
 540                                window,
 541                                cx,
 542                            );
 543                            cx.notify();
 544                        })
 545                        .ok();
 546                    }
 547                }
 548            });
 549
 550            let view = registry.read(cx).provider(&provider_id).map(|provider| {
 551                provider.configuration_view(
 552                    language_model::ConfigurationViewTargetAgent::Other(agent_name),
 553                    window,
 554                    cx,
 555                )
 556            });
 557
 558            (view, Some(sub))
 559        } else {
 560            (None, None)
 561        };
 562
 563        this.update(cx, |this, cx| {
 564            this.thread_state = ThreadState::Unauthenticated {
 565                pending_auth_method: None,
 566                connection,
 567                configuration_view,
 568                description: err
 569                    .description
 570                    .clone()
 571                    .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
 572                _subscription: subscription,
 573            };
 574            cx.notify();
 575        })
 576        .ok();
 577    }
 578
 579    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 580        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 581            self.thread_state = ThreadState::LoadError(load_err.clone());
 582        } else {
 583            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 584        }
 585        cx.notify();
 586    }
 587
 588    pub fn workspace(&self) -> &WeakEntity<Workspace> {
 589        &self.workspace
 590    }
 591
 592    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 593        match &self.thread_state {
 594            ThreadState::Ready { thread, .. } => Some(thread),
 595            ThreadState::Unauthenticated { .. }
 596            | ThreadState::Loading { .. }
 597            | ThreadState::LoadError { .. } => None,
 598        }
 599    }
 600
 601    pub fn title(&self, cx: &App) -> SharedString {
 602        match &self.thread_state {
 603            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 604            ThreadState::Loading { .. } => "Loading…".into(),
 605            ThreadState::LoadError(_) => "Failed to load".into(),
 606            ThreadState::Unauthenticated { .. } => "Authentication Required".into(),
 607        }
 608    }
 609
 610    pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
 611        self.thread_error.take();
 612        self.thread_retry_status.take();
 613
 614        if let Some(thread) = self.thread() {
 615            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 616        }
 617    }
 618
 619    pub fn expand_message_editor(
 620        &mut self,
 621        _: &ExpandMessageEditor,
 622        _window: &mut Window,
 623        cx: &mut Context<Self>,
 624    ) {
 625        self.set_editor_is_expanded(!self.editor_expanded, cx);
 626        cx.notify();
 627    }
 628
 629    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 630        self.editor_expanded = is_expanded;
 631        self.message_editor.update(cx, |editor, cx| {
 632            if is_expanded {
 633                editor.set_mode(
 634                    EditorMode::Full {
 635                        scale_ui_elements_with_buffer_font_size: false,
 636                        show_active_line_background: false,
 637                        sized_by_content: false,
 638                    },
 639                    cx,
 640                )
 641            } else {
 642                editor.set_mode(
 643                    EditorMode::AutoHeight {
 644                        min_lines: MIN_EDITOR_LINES,
 645                        max_lines: Some(MAX_EDITOR_LINES),
 646                    },
 647                    cx,
 648                )
 649            }
 650        });
 651        cx.notify();
 652    }
 653
 654    pub fn handle_message_editor_event(
 655        &mut self,
 656        _: &Entity<MessageEditor>,
 657        event: &MessageEditorEvent,
 658        window: &mut Window,
 659        cx: &mut Context<Self>,
 660    ) {
 661        match event {
 662            MessageEditorEvent::Send => self.send(window, cx),
 663            MessageEditorEvent::Cancel => self.cancel_generation(cx),
 664            MessageEditorEvent::Focus => {
 665                self.cancel_editing(&Default::default(), window, cx);
 666            }
 667        }
 668    }
 669
 670    pub fn handle_entry_view_event(
 671        &mut self,
 672        _: &Entity<EntryViewState>,
 673        event: &EntryViewEvent,
 674        window: &mut Window,
 675        cx: &mut Context<Self>,
 676    ) {
 677        match &event.view_event {
 678            ViewEvent::NewDiff(tool_call_id) => {
 679                if AgentSettings::get_global(cx).expand_edit_card {
 680                    self.expanded_tool_calls.insert(tool_call_id.clone());
 681                }
 682            }
 683            ViewEvent::NewTerminal(tool_call_id) => {
 684                if AgentSettings::get_global(cx).expand_terminal_card {
 685                    self.expanded_tool_calls.insert(tool_call_id.clone());
 686                }
 687            }
 688            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
 689                if let Some(thread) = self.thread()
 690                    && let Some(AgentThreadEntry::UserMessage(user_message)) =
 691                        thread.read(cx).entries().get(event.entry_index)
 692                    && user_message.id.is_some()
 693                {
 694                    self.editing_message = Some(event.entry_index);
 695                    cx.notify();
 696                }
 697            }
 698            ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
 699                self.regenerate(event.entry_index, editor, window, cx);
 700            }
 701            ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
 702                self.cancel_editing(&Default::default(), window, cx);
 703            }
 704        }
 705    }
 706
 707    fn resume_chat(&mut self, cx: &mut Context<Self>) {
 708        self.thread_error.take();
 709        let Some(thread) = self.thread() else {
 710            return;
 711        };
 712
 713        let task = thread.update(cx, |thread, cx| thread.resume(cx));
 714        cx.spawn(async move |this, cx| {
 715            let result = task.await;
 716
 717            this.update(cx, |this, cx| {
 718                if let Err(err) = result {
 719                    this.handle_thread_error(err, cx);
 720                }
 721            })
 722        })
 723        .detach();
 724    }
 725
 726    fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 727        let Some(thread) = self.thread() else { return };
 728        self.history_store.update(cx, |history, cx| {
 729            history.push_recently_opened_entry(
 730                HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
 731                cx,
 732            );
 733        });
 734
 735        if thread.read(cx).status() != ThreadStatus::Idle {
 736            self.stop_current_and_send_new_message(window, cx);
 737            return;
 738        }
 739
 740        let contents = self
 741            .message_editor
 742            .update(cx, |message_editor, cx| message_editor.contents(window, cx));
 743        self.send_impl(contents, window, cx)
 744    }
 745
 746    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 747        let Some(thread) = self.thread().cloned() else {
 748            return;
 749        };
 750
 751        let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
 752
 753        let contents = self
 754            .message_editor
 755            .update(cx, |message_editor, cx| message_editor.contents(window, cx));
 756
 757        cx.spawn_in(window, async move |this, cx| {
 758            cancelled.await;
 759
 760            this.update_in(cx, |this, window, cx| {
 761                this.send_impl(contents, window, cx);
 762            })
 763            .ok();
 764        })
 765        .detach();
 766    }
 767
 768    fn send_impl(
 769        &mut self,
 770        contents: Task<anyhow::Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
 771        window: &mut Window,
 772        cx: &mut Context<Self>,
 773    ) {
 774        self.thread_error.take();
 775        self.editing_message.take();
 776        self.thread_feedback.clear();
 777
 778        let Some(thread) = self.thread().cloned() else {
 779            return;
 780        };
 781        let task = cx.spawn_in(window, async move |this, cx| {
 782            let (contents, tracked_buffers) = contents.await?;
 783
 784            if contents.is_empty() {
 785                return Ok(());
 786            }
 787
 788            this.update_in(cx, |this, window, cx| {
 789                this.set_editor_is_expanded(false, cx);
 790                this.scroll_to_bottom(cx);
 791                this.message_editor.update(cx, |message_editor, cx| {
 792                    message_editor.clear(window, cx);
 793                });
 794            })?;
 795            let send = thread.update(cx, |thread, cx| {
 796                thread.action_log().update(cx, |action_log, cx| {
 797                    for buffer in tracked_buffers {
 798                        action_log.buffer_read(buffer, cx)
 799                    }
 800                });
 801                thread.send(contents, cx)
 802            })?;
 803            send.await
 804        });
 805
 806        cx.spawn(async move |this, cx| {
 807            if let Err(err) = task.await {
 808                this.update(cx, |this, cx| {
 809                    this.handle_thread_error(err, cx);
 810                })
 811                .ok();
 812            }
 813        })
 814        .detach();
 815    }
 816
 817    fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 818        let Some(thread) = self.thread().cloned() else {
 819            return;
 820        };
 821
 822        if let Some(index) = self.editing_message.take()
 823            && let Some(editor) = self
 824                .entry_view_state
 825                .read(cx)
 826                .entry(index)
 827                .and_then(|e| e.message_editor())
 828                .cloned()
 829        {
 830            editor.update(cx, |editor, cx| {
 831                if let Some(user_message) = thread
 832                    .read(cx)
 833                    .entries()
 834                    .get(index)
 835                    .and_then(|e| e.user_message())
 836                {
 837                    editor.set_message(user_message.chunks.clone(), window, cx);
 838                }
 839            })
 840        };
 841        self.focus_handle(cx).focus(window);
 842        cx.notify();
 843    }
 844
 845    fn regenerate(
 846        &mut self,
 847        entry_ix: usize,
 848        message_editor: &Entity<MessageEditor>,
 849        window: &mut Window,
 850        cx: &mut Context<Self>,
 851    ) {
 852        let Some(thread) = self.thread().cloned() else {
 853            return;
 854        };
 855
 856        let Some(rewind) = thread.update(cx, |thread, cx| {
 857            let user_message_id = thread.entries().get(entry_ix)?.user_message()?.id.clone()?;
 858            Some(thread.rewind(user_message_id, cx))
 859        }) else {
 860            return;
 861        };
 862
 863        let contents =
 864            message_editor.update(cx, |message_editor, cx| message_editor.contents(window, cx));
 865
 866        let task = cx.foreground_executor().spawn(async move {
 867            rewind.await?;
 868            contents.await
 869        });
 870        self.send_impl(task, window, cx);
 871    }
 872
 873    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 874        if let Some(thread) = self.thread() {
 875            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 876        }
 877    }
 878
 879    fn open_edited_buffer(
 880        &mut self,
 881        buffer: &Entity<Buffer>,
 882        window: &mut Window,
 883        cx: &mut Context<Self>,
 884    ) {
 885        let Some(thread) = self.thread() else {
 886            return;
 887        };
 888
 889        let Some(diff) =
 890            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 891        else {
 892            return;
 893        };
 894
 895        diff.update(cx, |diff, cx| {
 896            diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
 897        })
 898    }
 899
 900    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
 901        let Some(thread) = self.as_native_thread(cx) else {
 902            return;
 903        };
 904        let project_context = thread.read(cx).project_context().read(cx);
 905
 906        let project_entry_ids = project_context
 907            .worktrees
 908            .iter()
 909            .flat_map(|worktree| worktree.rules_file.as_ref())
 910            .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
 911            .collect::<Vec<_>>();
 912
 913        self.workspace
 914            .update(cx, move |workspace, cx| {
 915                // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
 916                // files clear. For example, if rules file 1 is already open but rules file 2 is not,
 917                // this would open and focus rules file 2 in a tab that is not next to rules file 1.
 918                let project = workspace.project().read(cx);
 919                let project_paths = project_entry_ids
 920                    .into_iter()
 921                    .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
 922                    .collect::<Vec<_>>();
 923                for project_path in project_paths {
 924                    workspace
 925                        .open_path(project_path, None, true, window, cx)
 926                        .detach_and_log_err(cx);
 927                }
 928            })
 929            .ok();
 930    }
 931
 932    fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
 933        self.thread_error = Some(ThreadError::from_err(error));
 934        cx.notify();
 935    }
 936
 937    fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
 938        self.thread_error = None;
 939        cx.notify();
 940    }
 941
 942    fn handle_thread_event(
 943        &mut self,
 944        thread: &Entity<AcpThread>,
 945        event: &AcpThreadEvent,
 946        window: &mut Window,
 947        cx: &mut Context<Self>,
 948    ) {
 949        match event {
 950            AcpThreadEvent::NewEntry => {
 951                let len = thread.read(cx).entries().len();
 952                let index = len - 1;
 953                self.entry_view_state.update(cx, |view_state, cx| {
 954                    view_state.sync_entry(index, thread, window, cx)
 955                });
 956                self.list_state.splice(index..index, 1);
 957            }
 958            AcpThreadEvent::EntryUpdated(index) => {
 959                self.entry_view_state.update(cx, |view_state, cx| {
 960                    view_state.sync_entry(*index, thread, window, cx)
 961                });
 962            }
 963            AcpThreadEvent::EntriesRemoved(range) => {
 964                self.entry_view_state
 965                    .update(cx, |view_state, _cx| view_state.remove(range.clone()));
 966                self.list_state.splice(range.clone(), 0);
 967            }
 968            AcpThreadEvent::ToolAuthorizationRequired => {
 969                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
 970            }
 971            AcpThreadEvent::Retry(retry) => {
 972                self.thread_retry_status = Some(retry.clone());
 973            }
 974            AcpThreadEvent::Stopped => {
 975                self.thread_retry_status.take();
 976                let used_tools = thread.read(cx).used_tools_since_last_user_message();
 977                self.notify_with_sound(
 978                    if used_tools {
 979                        "Finished running tools"
 980                    } else {
 981                        "New message"
 982                    },
 983                    IconName::ZedAssistant,
 984                    window,
 985                    cx,
 986                );
 987            }
 988            AcpThreadEvent::Error => {
 989                self.thread_retry_status.take();
 990                self.notify_with_sound(
 991                    "Agent stopped due to an error",
 992                    IconName::Warning,
 993                    window,
 994                    cx,
 995                );
 996            }
 997            AcpThreadEvent::LoadError(error) => {
 998                self.thread_retry_status.take();
 999                self.thread_state = ThreadState::LoadError(error.clone());
1000            }
1001            AcpThreadEvent::TitleUpdated | AcpThreadEvent::TokenUsageUpdated => {}
1002        }
1003        cx.notify();
1004    }
1005
1006    fn authenticate(
1007        &mut self,
1008        method: acp::AuthMethodId,
1009        window: &mut Window,
1010        cx: &mut Context<Self>,
1011    ) {
1012        let ThreadState::Unauthenticated {
1013            connection,
1014            pending_auth_method,
1015            configuration_view,
1016            ..
1017        } = &mut self.thread_state
1018        else {
1019            return;
1020        };
1021
1022        if method.0.as_ref() == "gemini-api-key" {
1023            let registry = LanguageModelRegistry::global(cx);
1024            let provider = registry
1025                .read(cx)
1026                .provider(&language_model::GOOGLE_PROVIDER_ID)
1027                .unwrap();
1028            if !provider.is_authenticated(cx) {
1029                let this = cx.weak_entity();
1030                let agent = self.agent.clone();
1031                let connection = connection.clone();
1032                window.defer(cx, |window, cx| {
1033                    Self::handle_auth_required(
1034                        this,
1035                        AuthRequired {
1036                            description: Some("GEMINI_API_KEY must be set".to_owned()),
1037                            provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1038                        },
1039                        agent,
1040                        connection,
1041                        window,
1042                        cx,
1043                    );
1044                });
1045                return;
1046            }
1047        } else if method.0.as_ref() == "vertex-ai"
1048            && std::env::var("GOOGLE_API_KEY").is_err()
1049            && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1050                || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1051        {
1052            let this = cx.weak_entity();
1053            let agent = self.agent.clone();
1054            let connection = connection.clone();
1055
1056            window.defer(cx, |window, cx| {
1057                    Self::handle_auth_required(
1058                        this,
1059                        AuthRequired {
1060                            description: Some(
1061                                "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1062                                    .to_owned(),
1063                            ),
1064                            provider_id: None,
1065                        },
1066                        agent,
1067                        connection,
1068                        window,
1069                        cx,
1070                    )
1071                });
1072            return;
1073        }
1074
1075        self.thread_error.take();
1076        configuration_view.take();
1077        pending_auth_method.replace(method.clone());
1078        let authenticate = connection.authenticate(method, cx);
1079        cx.notify();
1080        self.auth_task = Some(cx.spawn_in(window, {
1081            let project = self.project.clone();
1082            let agent = self.agent.clone();
1083            async move |this, cx| {
1084                let result = authenticate.await;
1085
1086                this.update_in(cx, |this, window, cx| {
1087                    if let Err(err) = result {
1088                        this.handle_thread_error(err, cx);
1089                    } else {
1090                        this.thread_state = Self::initial_state(
1091                            agent,
1092                            None,
1093                            this.workspace.clone(),
1094                            project.clone(),
1095                            window,
1096                            cx,
1097                        )
1098                    }
1099                    this.auth_task.take()
1100                })
1101                .ok();
1102            }
1103        }));
1104    }
1105
1106    fn authorize_tool_call(
1107        &mut self,
1108        tool_call_id: acp::ToolCallId,
1109        option_id: acp::PermissionOptionId,
1110        option_kind: acp::PermissionOptionKind,
1111        cx: &mut Context<Self>,
1112    ) {
1113        let Some(thread) = self.thread() else {
1114            return;
1115        };
1116        thread.update(cx, |thread, cx| {
1117            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1118        });
1119        cx.notify();
1120    }
1121
1122    fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1123        let Some(thread) = self.thread() else {
1124            return;
1125        };
1126        thread
1127            .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
1128            .detach_and_log_err(cx);
1129        cx.notify();
1130    }
1131
1132    fn render_entry(
1133        &self,
1134        entry_ix: usize,
1135        total_entries: usize,
1136        entry: &AgentThreadEntry,
1137        window: &mut Window,
1138        cx: &Context<Self>,
1139    ) -> AnyElement {
1140        let primary = match &entry {
1141            AgentThreadEntry::UserMessage(message) => {
1142                let Some(editor) = self
1143                    .entry_view_state
1144                    .read(cx)
1145                    .entry(entry_ix)
1146                    .and_then(|entry| entry.message_editor())
1147                    .cloned()
1148                else {
1149                    return Empty.into_any_element();
1150                };
1151
1152                let editing = self.editing_message == Some(entry_ix);
1153                let editor_focus = editor.focus_handle(cx).is_focused(window);
1154                let focus_border = cx.theme().colors().border_focused;
1155
1156                let rules_item = if entry_ix == 0 {
1157                    self.render_rules_item(cx)
1158                } else {
1159                    None
1160                };
1161
1162                v_flex()
1163                    .id(("user_message", entry_ix))
1164                    .pt_2()
1165                    .pb_4()
1166                    .px_2()
1167                    .gap_1p5()
1168                    .w_full()
1169                    .children(rules_item)
1170                    .children(message.id.clone().and_then(|message_id| {
1171                        message.checkpoint.as_ref()?.show.then(|| {
1172                            h_flex()
1173                                .gap_2()
1174                                .child(Divider::horizontal())
1175                                .child(
1176                                    Button::new("restore-checkpoint", "Restore Checkpoint")
1177                                        .icon(IconName::Undo)
1178                                        .icon_size(IconSize::XSmall)
1179                                        .icon_position(IconPosition::Start)
1180                                        .label_size(LabelSize::XSmall)
1181                                        .icon_color(Color::Muted)
1182                                        .color(Color::Muted)
1183                                        .on_click(cx.listener(move |this, _, _window, cx| {
1184                                            this.rewind(&message_id, cx);
1185                                        }))
1186                                )
1187                                .child(Divider::horizontal())
1188                        })
1189                    }))
1190                    .child(
1191                        div()
1192                            .relative()
1193                            .child(
1194                                div()
1195                                    .py_3()
1196                                    .px_2()
1197                                    .rounded_lg()
1198                                    .shadow_md()
1199                                    .bg(cx.theme().colors().editor_background)
1200                                    .border_1()
1201                                    .when(editing && !editor_focus, |this| this.border_dashed())
1202                                    .border_color(cx.theme().colors().border)
1203                                    .map(|this|{
1204                                        if editing && editor_focus {
1205                                            this.border_color(focus_border)
1206                                        } else if message.id.is_some() {
1207                                            this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1208                                        } else {
1209                                            this
1210                                        }
1211                                    })
1212                                    .text_xs()
1213                                    .child(editor.clone().into_any_element()),
1214                            )
1215                            .when(editing && editor_focus, |this|
1216                                this.child(
1217                                    h_flex()
1218                                        .absolute()
1219                                        .top_neg_3p5()
1220                                        .right_3()
1221                                        .gap_1()
1222                                        .rounded_sm()
1223                                        .border_1()
1224                                        .border_color(cx.theme().colors().border)
1225                                        .bg(cx.theme().colors().editor_background)
1226                                        .overflow_hidden()
1227                                        .child(
1228                                            IconButton::new("cancel", IconName::Close)
1229                                                .icon_color(Color::Error)
1230                                                .icon_size(IconSize::XSmall)
1231                                                .on_click(cx.listener(Self::cancel_editing))
1232                                        )
1233                                        .child(
1234                                            IconButton::new("regenerate", IconName::Return)
1235                                                .icon_color(Color::Muted)
1236                                                .icon_size(IconSize::XSmall)
1237                                                .tooltip(Tooltip::text(
1238                                                    "Editing will restart the thread from this point."
1239                                                ))
1240                                                .on_click(cx.listener({
1241                                                    let editor = editor.clone();
1242                                                    move |this, _, window, cx| {
1243                                                        this.regenerate(
1244                                                            entry_ix, &editor, window, cx,
1245                                                        );
1246                                                    }
1247                                                })),
1248                                        )
1249                                )
1250                            ),
1251                    )
1252                    .into_any()
1253            }
1254            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1255                let style = default_markdown_style(false, window, cx);
1256                let message_body = v_flex()
1257                    .w_full()
1258                    .gap_2p5()
1259                    .children(chunks.iter().enumerate().filter_map(
1260                        |(chunk_ix, chunk)| match chunk {
1261                            AssistantMessageChunk::Message { block } => {
1262                                block.markdown().map(|md| {
1263                                    self.render_markdown(md.clone(), style.clone())
1264                                        .into_any_element()
1265                                })
1266                            }
1267                            AssistantMessageChunk::Thought { block } => {
1268                                block.markdown().map(|md| {
1269                                    self.render_thinking_block(
1270                                        entry_ix,
1271                                        chunk_ix,
1272                                        md.clone(),
1273                                        window,
1274                                        cx,
1275                                    )
1276                                    .into_any_element()
1277                                })
1278                            }
1279                        },
1280                    ))
1281                    .into_any();
1282
1283                v_flex()
1284                    .px_5()
1285                    .py_1()
1286                    .when(entry_ix + 1 == total_entries, |this| this.pb_4())
1287                    .w_full()
1288                    .text_ui(cx)
1289                    .child(message_body)
1290                    .into_any()
1291            }
1292            AgentThreadEntry::ToolCall(tool_call) => {
1293                let has_terminals = tool_call.terminals().next().is_some();
1294
1295                div().w_full().py_1p5().px_5().map(|this| {
1296                    if has_terminals {
1297                        this.children(tool_call.terminals().map(|terminal| {
1298                            self.render_terminal_tool_call(
1299                                entry_ix, terminal, tool_call, window, cx,
1300                            )
1301                        }))
1302                    } else {
1303                        this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1304                    }
1305                })
1306            }
1307            .into_any(),
1308        };
1309
1310        let Some(thread) = self.thread() else {
1311            return primary;
1312        };
1313
1314        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
1315        let primary = if entry_ix == total_entries - 1 && !is_generating {
1316            v_flex()
1317                .w_full()
1318                .child(primary)
1319                .child(self.render_thread_controls(cx))
1320                .when_some(
1321                    self.thread_feedback.comments_editor.clone(),
1322                    |this, editor| {
1323                        this.child(Self::render_feedback_feedback_editor(editor, window, cx))
1324                    },
1325                )
1326                .into_any_element()
1327        } else {
1328            primary
1329        };
1330
1331        if let Some(editing_index) = self.editing_message.as_ref()
1332            && *editing_index < entry_ix
1333        {
1334            let backdrop = div()
1335                .id(("backdrop", entry_ix))
1336                .size_full()
1337                .absolute()
1338                .inset_0()
1339                .bg(cx.theme().colors().panel_background)
1340                .opacity(0.8)
1341                .block_mouse_except_scroll()
1342                .on_click(cx.listener(Self::cancel_editing));
1343
1344            div()
1345                .relative()
1346                .child(primary)
1347                .child(backdrop)
1348                .into_any_element()
1349        } else {
1350            primary
1351        }
1352    }
1353
1354    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1355        cx.theme()
1356            .colors()
1357            .element_background
1358            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1359    }
1360
1361    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1362        cx.theme().colors().border.opacity(0.8)
1363    }
1364
1365    fn tool_name_font_size(&self) -> Rems {
1366        rems_from_px(13.)
1367    }
1368
1369    fn render_thinking_block(
1370        &self,
1371        entry_ix: usize,
1372        chunk_ix: usize,
1373        chunk: Entity<Markdown>,
1374        window: &Window,
1375        cx: &Context<Self>,
1376    ) -> AnyElement {
1377        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1378        let card_header_id = SharedString::from("inner-card-header");
1379        let key = (entry_ix, chunk_ix);
1380        let is_open = self.expanded_thinking_blocks.contains(&key);
1381
1382        v_flex()
1383            .child(
1384                h_flex()
1385                    .id(header_id)
1386                    .group(&card_header_id)
1387                    .relative()
1388                    .w_full()
1389                    .gap_1p5()
1390                    .opacity(0.8)
1391                    .hover(|style| style.opacity(1.))
1392                    .child(
1393                        h_flex()
1394                            .size_4()
1395                            .justify_center()
1396                            .child(
1397                                div()
1398                                    .group_hover(&card_header_id, |s| s.invisible().w_0())
1399                                    .child(
1400                                        Icon::new(IconName::ToolThink)
1401                                            .size(IconSize::Small)
1402                                            .color(Color::Muted),
1403                                    ),
1404                            )
1405                            .child(
1406                                h_flex()
1407                                    .absolute()
1408                                    .inset_0()
1409                                    .invisible()
1410                                    .justify_center()
1411                                    .group_hover(&card_header_id, |s| s.visible())
1412                                    .child(
1413                                        Disclosure::new(("expand", entry_ix), is_open)
1414                                            .opened_icon(IconName::ChevronUp)
1415                                            .closed_icon(IconName::ChevronRight)
1416                                            .on_click(cx.listener({
1417                                                move |this, _event, _window, cx| {
1418                                                    if is_open {
1419                                                        this.expanded_thinking_blocks.remove(&key);
1420                                                    } else {
1421                                                        this.expanded_thinking_blocks.insert(key);
1422                                                    }
1423                                                    cx.notify();
1424                                                }
1425                                            })),
1426                                    ),
1427                            ),
1428                    )
1429                    .child(
1430                        div()
1431                            .text_size(self.tool_name_font_size())
1432                            .child("Thinking"),
1433                    )
1434                    .on_click(cx.listener({
1435                        move |this, _event, _window, cx| {
1436                            if is_open {
1437                                this.expanded_thinking_blocks.remove(&key);
1438                            } else {
1439                                this.expanded_thinking_blocks.insert(key);
1440                            }
1441                            cx.notify();
1442                        }
1443                    })),
1444            )
1445            .when(is_open, |this| {
1446                this.child(
1447                    div()
1448                        .relative()
1449                        .mt_1p5()
1450                        .ml(px(7.))
1451                        .pl_4()
1452                        .border_l_1()
1453                        .border_color(self.tool_card_border_color(cx))
1454                        .text_ui_sm(cx)
1455                        .child(
1456                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
1457                        ),
1458                )
1459            })
1460            .into_any_element()
1461    }
1462
1463    fn render_tool_call_icon(
1464        &self,
1465        group_name: SharedString,
1466        entry_ix: usize,
1467        is_collapsible: bool,
1468        is_open: bool,
1469        tool_call: &ToolCall,
1470        cx: &Context<Self>,
1471    ) -> Div {
1472        let tool_icon =
1473            if tool_call.kind == acp::ToolKind::Edit && tool_call.locations.len() == 1 {
1474                FileIcons::get_icon(&tool_call.locations[0].path, cx)
1475                    .map(Icon::from_path)
1476                    .unwrap_or(Icon::new(IconName::ToolPencil))
1477            } else {
1478                Icon::new(match tool_call.kind {
1479                    acp::ToolKind::Read => IconName::ToolRead,
1480                    acp::ToolKind::Edit => IconName::ToolPencil,
1481                    acp::ToolKind::Delete => IconName::ToolDeleteFile,
1482                    acp::ToolKind::Move => IconName::ArrowRightLeft,
1483                    acp::ToolKind::Search => IconName::ToolSearch,
1484                    acp::ToolKind::Execute => IconName::ToolTerminal,
1485                    acp::ToolKind::Think => IconName::ToolThink,
1486                    acp::ToolKind::Fetch => IconName::ToolWeb,
1487                    acp::ToolKind::Other => IconName::ToolHammer,
1488                })
1489            }
1490            .size(IconSize::Small)
1491            .color(Color::Muted);
1492
1493        let base_container = h_flex().size_4().justify_center();
1494
1495        if is_collapsible {
1496            base_container
1497                .child(
1498                    div()
1499                        .group_hover(&group_name, |s| s.invisible().w_0())
1500                        .child(tool_icon),
1501                )
1502                .child(
1503                    h_flex()
1504                        .absolute()
1505                        .inset_0()
1506                        .invisible()
1507                        .justify_center()
1508                        .group_hover(&group_name, |s| s.visible())
1509                        .child(
1510                            Disclosure::new(("expand", entry_ix), is_open)
1511                                .opened_icon(IconName::ChevronUp)
1512                                .closed_icon(IconName::ChevronRight)
1513                                .on_click(cx.listener({
1514                                    let id = tool_call.id.clone();
1515                                    move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1516                                        if is_open {
1517                                            this.expanded_tool_calls.remove(&id);
1518                                        } else {
1519                                            this.expanded_tool_calls.insert(id.clone());
1520                                        }
1521                                        cx.notify();
1522                                    }
1523                                })),
1524                        ),
1525                )
1526        } else {
1527            base_container.child(tool_icon)
1528        }
1529    }
1530
1531    fn render_tool_call(
1532        &self,
1533        entry_ix: usize,
1534        tool_call: &ToolCall,
1535        window: &Window,
1536        cx: &Context<Self>,
1537    ) -> Div {
1538        let header_id = SharedString::from(format!("outer-tool-call-header-{}", entry_ix));
1539        let card_header_id = SharedString::from("inner-tool-call-header");
1540
1541        let status_icon = match &tool_call.status {
1542            ToolCallStatus::Pending
1543            | ToolCallStatus::WaitingForConfirmation { .. }
1544            | ToolCallStatus::Completed => None,
1545            ToolCallStatus::InProgress => Some(
1546                Icon::new(IconName::ArrowCircle)
1547                    .color(Color::Accent)
1548                    .size(IconSize::Small)
1549                    .with_animation(
1550                        "running",
1551                        Animation::new(Duration::from_secs(2)).repeat(),
1552                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1553                    )
1554                    .into_any(),
1555            ),
1556            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => Some(
1557                Icon::new(IconName::Close)
1558                    .color(Color::Error)
1559                    .size(IconSize::Small)
1560                    .into_any_element(),
1561            ),
1562        };
1563
1564        let needs_confirmation = matches!(
1565            tool_call.status,
1566            ToolCallStatus::WaitingForConfirmation { .. }
1567        );
1568        let is_edit =
1569            matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
1570        let use_card_layout = needs_confirmation || is_edit;
1571
1572        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
1573
1574        let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
1575
1576        let gradient_overlay = |color: Hsla| {
1577            div()
1578                .absolute()
1579                .top_0()
1580                .right_0()
1581                .w_12()
1582                .h_full()
1583                .bg(linear_gradient(
1584                    90.,
1585                    linear_color_stop(color, 1.),
1586                    linear_color_stop(color.opacity(0.2), 0.),
1587                ))
1588        };
1589        let gradient_color = if use_card_layout {
1590            self.tool_card_header_bg(cx)
1591        } else {
1592            cx.theme().colors().panel_background
1593        };
1594
1595        let tool_output_display = if is_open {
1596            match &tool_call.status {
1597                ToolCallStatus::WaitingForConfirmation { options, .. } => {
1598                    v_flex()
1599                        .w_full()
1600                        .children(tool_call.content.iter().map(|content| {
1601                            div()
1602                                .child(self.render_tool_call_content(
1603                                    entry_ix, content, tool_call, window, cx,
1604                                ))
1605                                .into_any_element()
1606                        }))
1607                        .child(self.render_permission_buttons(
1608                            options,
1609                            entry_ix,
1610                            tool_call.id.clone(),
1611                            tool_call.content.is_empty(),
1612                            cx,
1613                        ))
1614                        .into_any()
1615                }
1616                ToolCallStatus::Pending | ToolCallStatus::InProgress
1617                    if is_edit && tool_call.content.is_empty() =>
1618                {
1619                    self.render_diff_loading(cx).into_any()
1620                }
1621                ToolCallStatus::Pending
1622                | ToolCallStatus::InProgress
1623                | ToolCallStatus::Completed
1624                | ToolCallStatus::Failed
1625                | ToolCallStatus::Canceled => v_flex()
1626                    .w_full()
1627                    .children(tool_call.content.iter().map(|content| {
1628                        div().child(
1629                            self.render_tool_call_content(entry_ix, content, tool_call, window, cx),
1630                        )
1631                    }))
1632                    .into_any(),
1633                ToolCallStatus::Rejected => Empty.into_any(),
1634            }
1635            .into()
1636        } else {
1637            None
1638        };
1639
1640        v_flex()
1641            .when(use_card_layout, |this| {
1642                this.rounded_lg()
1643                    .border_1()
1644                    .border_color(self.tool_card_border_color(cx))
1645                    .bg(cx.theme().colors().editor_background)
1646                    .overflow_hidden()
1647            })
1648            .child(
1649                h_flex()
1650                    .id(header_id)
1651                    .w_full()
1652                    .gap_1()
1653                    .justify_between()
1654                    .map(|this| {
1655                        if use_card_layout {
1656                            this.pl_2()
1657                                .pr_1p5()
1658                                .py_1()
1659                                .rounded_t_md()
1660                                .when(is_open, |this| {
1661                                    this.border_b_1()
1662                                        .border_color(self.tool_card_border_color(cx))
1663                                })
1664                                .bg(self.tool_card_header_bg(cx))
1665                        } else {
1666                            this.opacity(0.8).hover(|style| style.opacity(1.))
1667                        }
1668                    })
1669                    .child(
1670                        h_flex()
1671                            .group(&card_header_id)
1672                            .relative()
1673                            .w_full()
1674                            .min_h_6()
1675                            .text_size(self.tool_name_font_size())
1676                            .child(self.render_tool_call_icon(
1677                                card_header_id,
1678                                entry_ix,
1679                                is_collapsible,
1680                                is_open,
1681                                tool_call,
1682                                cx,
1683                            ))
1684                            .child(if tool_call.locations.len() == 1 {
1685                                let name = tool_call.locations[0]
1686                                    .path
1687                                    .file_name()
1688                                    .unwrap_or_default()
1689                                    .display()
1690                                    .to_string();
1691
1692                                h_flex()
1693                                    .id(("open-tool-call-location", entry_ix))
1694                                    .w_full()
1695                                    .max_w_full()
1696                                    .px_1p5()
1697                                    .rounded_sm()
1698                                    .overflow_x_scroll()
1699                                    .opacity(0.8)
1700                                    .hover(|label| {
1701                                        label.opacity(1.).bg(cx
1702                                            .theme()
1703                                            .colors()
1704                                            .element_hover
1705                                            .opacity(0.5))
1706                                    })
1707                                    .child(name)
1708                                    .tooltip(Tooltip::text("Jump to File"))
1709                                    .on_click(cx.listener(move |this, _, window, cx| {
1710                                        this.open_tool_call_location(entry_ix, 0, window, cx);
1711                                    }))
1712                                    .into_any_element()
1713                            } else {
1714                                h_flex()
1715                                    .id("non-card-label-container")
1716                                    .w_full()
1717                                    .relative()
1718                                    .ml_1p5()
1719                                    .overflow_hidden()
1720                                    .child(
1721                                        h_flex()
1722                                            .id("non-card-label")
1723                                            .pr_8()
1724                                            .w_full()
1725                                            .overflow_x_scroll()
1726                                            .child(self.render_markdown(
1727                                                tool_call.label.clone(),
1728                                                default_markdown_style(false, window, cx),
1729                                            )),
1730                                    )
1731                                    .child(gradient_overlay(gradient_color))
1732                                    .on_click(cx.listener({
1733                                        let id = tool_call.id.clone();
1734                                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1735                                            if is_open {
1736                                                this.expanded_tool_calls.remove(&id);
1737                                            } else {
1738                                                this.expanded_tool_calls.insert(id.clone());
1739                                            }
1740                                            cx.notify();
1741                                        }
1742                                    }))
1743                                    .into_any()
1744                            }),
1745                    )
1746                    .children(status_icon),
1747            )
1748            .children(tool_output_display)
1749    }
1750
1751    fn render_tool_call_content(
1752        &self,
1753        entry_ix: usize,
1754        content: &ToolCallContent,
1755        tool_call: &ToolCall,
1756        window: &Window,
1757        cx: &Context<Self>,
1758    ) -> AnyElement {
1759        match content {
1760            ToolCallContent::ContentBlock(content) => {
1761                if let Some(resource_link) = content.resource_link() {
1762                    self.render_resource_link(resource_link, cx)
1763                } else if let Some(markdown) = content.markdown() {
1764                    self.render_markdown_output(markdown.clone(), tool_call.id.clone(), window, cx)
1765                } else {
1766                    Empty.into_any_element()
1767                }
1768            }
1769            ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
1770            ToolCallContent::Terminal(terminal) => {
1771                self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
1772            }
1773        }
1774    }
1775
1776    fn render_markdown_output(
1777        &self,
1778        markdown: Entity<Markdown>,
1779        tool_call_id: acp::ToolCallId,
1780        window: &Window,
1781        cx: &Context<Self>,
1782    ) -> AnyElement {
1783        let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
1784
1785        v_flex()
1786            .mt_1p5()
1787            .ml(px(7.))
1788            .px_3p5()
1789            .gap_2()
1790            .border_l_1()
1791            .border_color(self.tool_card_border_color(cx))
1792            .text_sm()
1793            .text_color(cx.theme().colors().text_muted)
1794            .child(self.render_markdown(markdown, default_markdown_style(false, window, cx)))
1795            .child(
1796                Button::new(button_id, "Collapse Output")
1797                    .full_width()
1798                    .style(ButtonStyle::Outlined)
1799                    .label_size(LabelSize::Small)
1800                    .icon(IconName::ChevronUp)
1801                    .icon_color(Color::Muted)
1802                    .icon_position(IconPosition::Start)
1803                    .on_click(cx.listener({
1804                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1805                            this.expanded_tool_calls.remove(&tool_call_id);
1806                            cx.notify();
1807                        }
1808                    })),
1809            )
1810            .into_any_element()
1811    }
1812
1813    fn render_resource_link(
1814        &self,
1815        resource_link: &acp::ResourceLink,
1816        cx: &Context<Self>,
1817    ) -> AnyElement {
1818        let uri: SharedString = resource_link.uri.clone().into();
1819
1820        let label: SharedString = if let Some(path) = resource_link.uri.strip_prefix("file://") {
1821            path.to_string().into()
1822        } else {
1823            uri.clone()
1824        };
1825
1826        let button_id = SharedString::from(format!("item-{}", uri));
1827
1828        div()
1829            .ml(px(7.))
1830            .pl_2p5()
1831            .border_l_1()
1832            .border_color(self.tool_card_border_color(cx))
1833            .overflow_hidden()
1834            .child(
1835                Button::new(button_id, label)
1836                    .label_size(LabelSize::Small)
1837                    .color(Color::Muted)
1838                    .icon(IconName::ArrowUpRight)
1839                    .icon_size(IconSize::XSmall)
1840                    .icon_color(Color::Muted)
1841                    .truncate(true)
1842                    .on_click(cx.listener({
1843                        let workspace = self.workspace.clone();
1844                        move |_, _, window, cx: &mut Context<Self>| {
1845                            Self::open_link(uri.clone(), &workspace, window, cx);
1846                        }
1847                    })),
1848            )
1849            .into_any_element()
1850    }
1851
1852    fn render_permission_buttons(
1853        &self,
1854        options: &[acp::PermissionOption],
1855        entry_ix: usize,
1856        tool_call_id: acp::ToolCallId,
1857        empty_content: bool,
1858        cx: &Context<Self>,
1859    ) -> Div {
1860        h_flex()
1861            .py_1()
1862            .pl_2()
1863            .pr_1()
1864            .gap_1()
1865            .justify_between()
1866            .flex_wrap()
1867            .when(!empty_content, |this| {
1868                this.border_t_1()
1869                    .border_color(self.tool_card_border_color(cx))
1870            })
1871            .child(
1872                div()
1873                    .min_w(rems_from_px(145.))
1874                    .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1875            )
1876            .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1877                let option_id = SharedString::from(option.id.0.clone());
1878                Button::new((option_id, entry_ix), option.name.clone())
1879                    .map(|this| match option.kind {
1880                        acp::PermissionOptionKind::AllowOnce => {
1881                            this.icon(IconName::Check).icon_color(Color::Success)
1882                        }
1883                        acp::PermissionOptionKind::AllowAlways => {
1884                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1885                        }
1886                        acp::PermissionOptionKind::RejectOnce => {
1887                            this.icon(IconName::Close).icon_color(Color::Error)
1888                        }
1889                        acp::PermissionOptionKind::RejectAlways => {
1890                            this.icon(IconName::Close).icon_color(Color::Error)
1891                        }
1892                    })
1893                    .icon_position(IconPosition::Start)
1894                    .icon_size(IconSize::XSmall)
1895                    .label_size(LabelSize::Small)
1896                    .on_click(cx.listener({
1897                        let tool_call_id = tool_call_id.clone();
1898                        let option_id = option.id.clone();
1899                        let option_kind = option.kind;
1900                        move |this, _, _, cx| {
1901                            this.authorize_tool_call(
1902                                tool_call_id.clone(),
1903                                option_id.clone(),
1904                                option_kind,
1905                                cx,
1906                            );
1907                        }
1908                    }))
1909            })))
1910    }
1911
1912    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
1913        let bar = |n: u64, width_class: &str| {
1914            let bg_color = cx.theme().colors().element_active;
1915            let base = h_flex().h_1().rounded_full();
1916
1917            let modified = match width_class {
1918                "w_4_5" => base.w_3_4(),
1919                "w_1_4" => base.w_1_4(),
1920                "w_2_4" => base.w_2_4(),
1921                "w_3_5" => base.w_3_5(),
1922                "w_2_5" => base.w_2_5(),
1923                _ => base.w_1_2(),
1924            };
1925
1926            modified.with_animation(
1927                ElementId::Integer(n),
1928                Animation::new(Duration::from_secs(2)).repeat(),
1929                move |tab, delta| {
1930                    let delta = (delta - 0.15 * n as f32) / 0.7;
1931                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
1932                    let delta = ease_in_out(delta.clamp(0., 1.));
1933                    let delta = 0.1 + 0.9 * delta;
1934
1935                    tab.bg(bg_color.opacity(delta))
1936                },
1937            )
1938        };
1939
1940        v_flex()
1941            .p_3()
1942            .gap_1()
1943            .rounded_b_md()
1944            .bg(cx.theme().colors().editor_background)
1945            .child(bar(0, "w_4_5"))
1946            .child(bar(1, "w_1_4"))
1947            .child(bar(2, "w_2_4"))
1948            .child(bar(3, "w_3_5"))
1949            .child(bar(4, "w_2_5"))
1950            .into_any_element()
1951    }
1952
1953    fn render_diff_editor(
1954        &self,
1955        entry_ix: usize,
1956        diff: &Entity<acp_thread::Diff>,
1957        tool_call: &ToolCall,
1958        cx: &Context<Self>,
1959    ) -> AnyElement {
1960        let tool_progress = matches!(
1961            &tool_call.status,
1962            ToolCallStatus::InProgress | ToolCallStatus::Pending
1963        );
1964
1965        v_flex()
1966            .h_full()
1967            .child(
1968                if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
1969                    && let Some(editor) = entry.editor_for_diff(diff)
1970                    && diff.read(cx).has_revealed_range(cx)
1971                {
1972                    editor.into_any_element()
1973                } else if tool_progress {
1974                    self.render_diff_loading(cx)
1975                } else {
1976                    Empty.into_any()
1977                },
1978            )
1979            .into_any()
1980    }
1981
1982    fn render_terminal_tool_call(
1983        &self,
1984        entry_ix: usize,
1985        terminal: &Entity<acp_thread::Terminal>,
1986        tool_call: &ToolCall,
1987        window: &Window,
1988        cx: &Context<Self>,
1989    ) -> AnyElement {
1990        let terminal_data = terminal.read(cx);
1991        let working_dir = terminal_data.working_dir();
1992        let command = terminal_data.command();
1993        let started_at = terminal_data.started_at();
1994
1995        let tool_failed = matches!(
1996            &tool_call.status,
1997            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
1998        );
1999
2000        let output = terminal_data.output();
2001        let command_finished = output.is_some();
2002        let truncated_output = output.is_some_and(|output| output.was_content_truncated);
2003        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2004
2005        let command_failed = command_finished
2006            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2007
2008        let time_elapsed = if let Some(output) = output {
2009            output.ended_at.duration_since(started_at)
2010        } else {
2011            started_at.elapsed()
2012        };
2013
2014        let header_bg = cx
2015            .theme()
2016            .colors()
2017            .element_background
2018            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2019        let border_color = cx.theme().colors().border.opacity(0.6);
2020
2021        let working_dir = working_dir
2022            .as_ref()
2023            .map(|path| format!("{}", path.display()))
2024            .unwrap_or_else(|| "current directory".to_string());
2025
2026        let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2027
2028        let header = h_flex()
2029            .id(SharedString::from(format!(
2030                "terminal-tool-header-{}",
2031                terminal.entity_id()
2032            )))
2033            .flex_none()
2034            .gap_1()
2035            .justify_between()
2036            .rounded_t_md()
2037            .child(
2038                div()
2039                    .id(("command-target-path", terminal.entity_id()))
2040                    .w_full()
2041                    .max_w_full()
2042                    .overflow_x_scroll()
2043                    .child(
2044                        Label::new(working_dir)
2045                            .buffer_font(cx)
2046                            .size(LabelSize::XSmall)
2047                            .color(Color::Muted),
2048                    ),
2049            )
2050            .when(!command_finished, |header| {
2051                header
2052                    .gap_1p5()
2053                    .child(
2054                        Button::new(
2055                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2056                            "Stop",
2057                        )
2058                        .icon(IconName::Stop)
2059                        .icon_position(IconPosition::Start)
2060                        .icon_size(IconSize::Small)
2061                        .icon_color(Color::Error)
2062                        .label_size(LabelSize::Small)
2063                        .tooltip(move |window, cx| {
2064                            Tooltip::with_meta(
2065                                "Stop This Command",
2066                                None,
2067                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2068                                window,
2069                                cx,
2070                            )
2071                        })
2072                        .on_click({
2073                            let terminal = terminal.clone();
2074                            cx.listener(move |_this, _event, _window, cx| {
2075                                let inner_terminal = terminal.read(cx).inner().clone();
2076                                inner_terminal.update(cx, |inner_terminal, _cx| {
2077                                    inner_terminal.kill_active_task();
2078                                });
2079                            })
2080                        }),
2081                    )
2082                    .child(Divider::vertical())
2083                    .child(
2084                        Icon::new(IconName::ArrowCircle)
2085                            .size(IconSize::XSmall)
2086                            .color(Color::Info)
2087                            .with_animation(
2088                                "arrow-circle",
2089                                Animation::new(Duration::from_secs(2)).repeat(),
2090                                |icon, delta| {
2091                                    icon.transform(Transformation::rotate(percentage(delta)))
2092                                },
2093                            ),
2094                    )
2095            })
2096            .when(tool_failed || command_failed, |header| {
2097                header.child(
2098                    div()
2099                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2100                        .child(
2101                            Icon::new(IconName::Close)
2102                                .size(IconSize::Small)
2103                                .color(Color::Error),
2104                        )
2105                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
2106                            this.tooltip(Tooltip::text(format!(
2107                                "Exited with code {}",
2108                                status.code().unwrap_or(-1),
2109                            )))
2110                        }),
2111                )
2112            })
2113            .when(truncated_output, |header| {
2114                let tooltip = if let Some(output) = output {
2115                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2116                        "Output exceeded terminal max lines and was \
2117                            truncated, the model received the first 16 KB."
2118                            .to_string()
2119                    } else {
2120                        format!(
2121                            "Output is {} long—to avoid unexpected token usage, \
2122                                only 16 KB was sent back to the model.",
2123                            format_file_size(output.original_content_len as u64, true),
2124                        )
2125                    }
2126                } else {
2127                    "Output was truncated".to_string()
2128                };
2129
2130                header.child(
2131                    h_flex()
2132                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
2133                        .gap_1()
2134                        .child(
2135                            Icon::new(IconName::Info)
2136                                .size(IconSize::XSmall)
2137                                .color(Color::Ignored),
2138                        )
2139                        .child(
2140                            Label::new("Truncated")
2141                                .color(Color::Muted)
2142                                .size(LabelSize::XSmall),
2143                        )
2144                        .tooltip(Tooltip::text(tooltip)),
2145                )
2146            })
2147            .when(time_elapsed > Duration::from_secs(10), |header| {
2148                header.child(
2149                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
2150                        .buffer_font(cx)
2151                        .color(Color::Muted)
2152                        .size(LabelSize::XSmall),
2153                )
2154            })
2155            .child(
2156                Disclosure::new(
2157                    SharedString::from(format!(
2158                        "terminal-tool-disclosure-{}",
2159                        terminal.entity_id()
2160                    )),
2161                    is_expanded,
2162                )
2163                .opened_icon(IconName::ChevronUp)
2164                .closed_icon(IconName::ChevronDown)
2165                .on_click(cx.listener({
2166                    let id = tool_call.id.clone();
2167                    move |this, _event, _window, _cx| {
2168                        if is_expanded {
2169                            this.expanded_tool_calls.remove(&id);
2170                        } else {
2171                            this.expanded_tool_calls.insert(id.clone());
2172                        }
2173                    }
2174                })),
2175            );
2176
2177        let terminal_view = self
2178            .entry_view_state
2179            .read(cx)
2180            .entry(entry_ix)
2181            .and_then(|entry| entry.terminal(terminal));
2182        let show_output = is_expanded && terminal_view.is_some();
2183
2184        v_flex()
2185            .mb_2()
2186            .border_1()
2187            .when(tool_failed || command_failed, |card| card.border_dashed())
2188            .border_color(border_color)
2189            .rounded_lg()
2190            .overflow_hidden()
2191            .child(
2192                v_flex()
2193                    .py_1p5()
2194                    .pl_2()
2195                    .pr_1p5()
2196                    .gap_0p5()
2197                    .bg(header_bg)
2198                    .text_xs()
2199                    .child(header)
2200                    .child(
2201                        MarkdownElement::new(
2202                            command.clone(),
2203                            terminal_command_markdown_style(window, cx),
2204                        )
2205                        .code_block_renderer(
2206                            markdown::CodeBlockRenderer::Default {
2207                                copy_button: false,
2208                                copy_button_on_hover: true,
2209                                border: false,
2210                            },
2211                        ),
2212                    ),
2213            )
2214            .when(show_output, |this| {
2215                this.child(
2216                    div()
2217                        .pt_2()
2218                        .border_t_1()
2219                        .when(tool_failed || command_failed, |card| card.border_dashed())
2220                        .border_color(border_color)
2221                        .bg(cx.theme().colors().editor_background)
2222                        .rounded_b_md()
2223                        .text_ui_sm(cx)
2224                        .children(terminal_view.clone()),
2225                )
2226            })
2227            .into_any()
2228    }
2229
2230    fn render_agent_logo(&self) -> AnyElement {
2231        Icon::new(self.agent.logo())
2232            .color(Color::Muted)
2233            .size(IconSize::XLarge)
2234            .into_any_element()
2235    }
2236
2237    fn render_error_agent_logo(&self) -> AnyElement {
2238        let logo = Icon::new(self.agent.logo())
2239            .color(Color::Muted)
2240            .size(IconSize::XLarge)
2241            .into_any_element();
2242
2243        h_flex()
2244            .relative()
2245            .justify_center()
2246            .child(div().opacity(0.3).child(logo))
2247            .child(
2248                h_flex()
2249                    .absolute()
2250                    .right_1()
2251                    .bottom_0()
2252                    .child(Icon::new(IconName::XCircleFilled).color(Color::Error)),
2253            )
2254            .into_any_element()
2255    }
2256
2257    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2258        let project_context = self
2259            .as_native_thread(cx)?
2260            .read(cx)
2261            .project_context()
2262            .read(cx);
2263
2264        let user_rules_text = if project_context.user_rules.is_empty() {
2265            None
2266        } else if project_context.user_rules.len() == 1 {
2267            let user_rules = &project_context.user_rules[0];
2268
2269            match user_rules.title.as_ref() {
2270                Some(title) => Some(format!("Using \"{title}\" user rule")),
2271                None => Some("Using user rule".into()),
2272            }
2273        } else {
2274            Some(format!(
2275                "Using {} user rules",
2276                project_context.user_rules.len()
2277            ))
2278        };
2279
2280        let first_user_rules_id = project_context
2281            .user_rules
2282            .first()
2283            .map(|user_rules| user_rules.uuid.0);
2284
2285        let rules_files = project_context
2286            .worktrees
2287            .iter()
2288            .filter_map(|worktree| worktree.rules_file.as_ref())
2289            .collect::<Vec<_>>();
2290
2291        let rules_file_text = match rules_files.as_slice() {
2292            &[] => None,
2293            &[rules_file] => Some(format!(
2294                "Using project {:?} file",
2295                rules_file.path_in_worktree
2296            )),
2297            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2298        };
2299
2300        if user_rules_text.is_none() && rules_file_text.is_none() {
2301            return None;
2302        }
2303
2304        Some(
2305            v_flex()
2306                .px_2p5()
2307                .gap_1()
2308                .when_some(user_rules_text, |parent, user_rules_text| {
2309                    parent.child(
2310                        h_flex()
2311                            .group("user-rules")
2312                            .id("user-rules")
2313                            .w_full()
2314                            .child(
2315                                Icon::new(IconName::Reader)
2316                                    .size(IconSize::XSmall)
2317                                    .color(Color::Disabled),
2318                            )
2319                            .child(
2320                                Label::new(user_rules_text)
2321                                    .size(LabelSize::XSmall)
2322                                    .color(Color::Muted)
2323                                    .truncate()
2324                                    .buffer_font(cx)
2325                                    .ml_1p5()
2326                                    .mr_0p5(),
2327                            )
2328                            .child(
2329                                IconButton::new("open-prompt-library", IconName::ArrowUpRight)
2330                                    .shape(ui::IconButtonShape::Square)
2331                                    .icon_size(IconSize::XSmall)
2332                                    .icon_color(Color::Ignored)
2333                                    .visible_on_hover("user-rules")
2334                                    // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary`  keybinding
2335                                    .tooltip(Tooltip::text("View User Rules")),
2336                            )
2337                            .on_click(move |_event, window, cx| {
2338                                window.dispatch_action(
2339                                    Box::new(OpenRulesLibrary {
2340                                        prompt_to_select: first_user_rules_id,
2341                                    }),
2342                                    cx,
2343                                )
2344                            }),
2345                    )
2346                })
2347                .when_some(rules_file_text, |parent, rules_file_text| {
2348                    parent.child(
2349                        h_flex()
2350                            .group("project-rules")
2351                            .id("project-rules")
2352                            .w_full()
2353                            .child(
2354                                Icon::new(IconName::Reader)
2355                                    .size(IconSize::XSmall)
2356                                    .color(Color::Disabled),
2357                            )
2358                            .child(
2359                                Label::new(rules_file_text)
2360                                    .size(LabelSize::XSmall)
2361                                    .color(Color::Muted)
2362                                    .buffer_font(cx)
2363                                    .ml_1p5()
2364                                    .mr_0p5(),
2365                            )
2366                            .child(
2367                                IconButton::new("open-rule", IconName::ArrowUpRight)
2368                                    .shape(ui::IconButtonShape::Square)
2369                                    .icon_size(IconSize::XSmall)
2370                                    .icon_color(Color::Ignored)
2371                                    .visible_on_hover("project-rules")
2372                                    .tooltip(Tooltip::text("View Project Rules")),
2373                            )
2374                            .on_click(cx.listener(Self::handle_open_rules)),
2375                    )
2376                })
2377                .into_any(),
2378        )
2379    }
2380
2381    fn render_empty_state_section_header(
2382        &self,
2383        label: impl Into<SharedString>,
2384        action_slot: Option<AnyElement>,
2385        cx: &mut Context<Self>,
2386    ) -> impl IntoElement {
2387        div().pl_1().pr_1p5().child(
2388            h_flex()
2389                .mt_2()
2390                .pl_1p5()
2391                .pb_1()
2392                .w_full()
2393                .justify_between()
2394                .border_b_1()
2395                .border_color(cx.theme().colors().border_variant)
2396                .child(
2397                    Label::new(label.into())
2398                        .size(LabelSize::Small)
2399                        .color(Color::Muted),
2400                )
2401                .children(action_slot),
2402        )
2403    }
2404
2405    fn render_empty_state(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2406        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
2407        let render_history = self
2408            .agent
2409            .clone()
2410            .downcast::<agent2::NativeAgentServer>()
2411            .is_some()
2412            && self
2413                .history_store
2414                .update(cx, |history_store, cx| !history_store.is_empty(cx));
2415
2416        v_flex()
2417            .size_full()
2418            .when(!render_history, |this| {
2419                this.child(
2420                    v_flex()
2421                        .size_full()
2422                        .items_center()
2423                        .justify_center()
2424                        .child(if loading {
2425                            h_flex()
2426                                .justify_center()
2427                                .child(self.render_agent_logo())
2428                                .with_animation(
2429                                    "pulsating_icon",
2430                                    Animation::new(Duration::from_secs(2))
2431                                        .repeat()
2432                                        .with_easing(pulsating_between(0.4, 1.0)),
2433                                    |icon, delta| icon.opacity(delta),
2434                                )
2435                                .into_any()
2436                        } else {
2437                            self.render_agent_logo().into_any_element()
2438                        })
2439                        .child(h_flex().mt_4().mb_2().justify_center().child(if loading {
2440                            div()
2441                                .child(LoadingLabel::new("").size(LabelSize::Large))
2442                                .into_any_element()
2443                        } else {
2444                            Headline::new(self.agent.empty_state_headline())
2445                                .size(HeadlineSize::Medium)
2446                                .into_any_element()
2447                        })),
2448                )
2449            })
2450            .when(render_history, |this| {
2451                let recent_history = self
2452                    .history_store
2453                    .update(cx, |history_store, cx| history_store.recent_entries(3, cx));
2454                this.justify_end().child(
2455                    v_flex()
2456                        .child(
2457                            self.render_empty_state_section_header(
2458                                "Recent",
2459                                Some(
2460                                    Button::new("view-history", "View All")
2461                                        .style(ButtonStyle::Subtle)
2462                                        .label_size(LabelSize::Small)
2463                                        .key_binding(
2464                                            KeyBinding::for_action_in(
2465                                                &OpenHistory,
2466                                                &self.focus_handle(cx),
2467                                                window,
2468                                                cx,
2469                                            )
2470                                            .map(|kb| kb.size(rems_from_px(12.))),
2471                                        )
2472                                        .on_click(move |_event, window, cx| {
2473                                            window.dispatch_action(OpenHistory.boxed_clone(), cx);
2474                                        })
2475                                        .into_any_element(),
2476                                ),
2477                                cx,
2478                            ),
2479                        )
2480                        .child(
2481                            v_flex().p_1().pr_1p5().gap_1().children(
2482                                recent_history
2483                                    .into_iter()
2484                                    .enumerate()
2485                                    .map(|(index, entry)| {
2486                                        // TODO: Add keyboard navigation.
2487                                        let is_hovered =
2488                                            self.hovered_recent_history_item == Some(index);
2489                                        crate::acp::thread_history::AcpHistoryEntryElement::new(
2490                                            entry,
2491                                            cx.entity().downgrade(),
2492                                        )
2493                                        .hovered(is_hovered)
2494                                        .on_hover(cx.listener(
2495                                            move |this, is_hovered, _window, cx| {
2496                                                if *is_hovered {
2497                                                    this.hovered_recent_history_item = Some(index);
2498                                                } else if this.hovered_recent_history_item
2499                                                    == Some(index)
2500                                                {
2501                                                    this.hovered_recent_history_item = None;
2502                                                }
2503                                                cx.notify();
2504                                            },
2505                                        ))
2506                                        .into_any_element()
2507                                    }),
2508                            ),
2509                        ),
2510                )
2511            })
2512            .into_any()
2513    }
2514
2515    fn render_auth_required_state(
2516        &self,
2517        connection: &Rc<dyn AgentConnection>,
2518        description: Option<&Entity<Markdown>>,
2519        configuration_view: Option<&AnyView>,
2520        pending_auth_method: Option<&acp::AuthMethodId>,
2521        window: &mut Window,
2522        cx: &Context<Self>,
2523    ) -> Div {
2524        v_flex()
2525            .p_2()
2526            .gap_2()
2527            .flex_1()
2528            .items_center()
2529            .justify_center()
2530            .child(
2531                v_flex()
2532                    .items_center()
2533                    .justify_center()
2534                    .child(self.render_error_agent_logo())
2535                    .child(
2536                        h_flex().mt_4().mb_1().justify_center().child(
2537                            Headline::new("Authentication Required").size(HeadlineSize::Medium),
2538                        ),
2539                    )
2540                    .into_any(),
2541            )
2542            .children(description.map(|desc| {
2543                div().text_ui(cx).text_center().child(
2544                    self.render_markdown(desc.clone(), default_markdown_style(false, window, cx)),
2545                )
2546            }))
2547            .children(
2548                configuration_view
2549                    .cloned()
2550                    .map(|view| div().px_4().w_full().max_w_128().child(view)),
2551            )
2552            .when(
2553                configuration_view.is_none()
2554                    && description.is_none()
2555                    && pending_auth_method.is_none(),
2556                |el| {
2557                    el.child(
2558                        div()
2559                            .text_ui(cx)
2560                            .text_center()
2561                            .px_4()
2562                            .w_full()
2563                            .max_w_128()
2564                            .child(Label::new("Authentication required")),
2565                    )
2566                },
2567            )
2568            .when_some(pending_auth_method, |el, _| {
2569                let spinner_icon = div()
2570                    .px_0p5()
2571                    .id("generating")
2572                    .tooltip(Tooltip::text("Generating Changes…"))
2573                    .child(
2574                        Icon::new(IconName::ArrowCircle)
2575                            .size(IconSize::Small)
2576                            .with_animation(
2577                                "arrow-circle",
2578                                Animation::new(Duration::from_secs(2)).repeat(),
2579                                |icon, delta| {
2580                                    icon.transform(Transformation::rotate(percentage(delta)))
2581                                },
2582                            )
2583                            .into_any_element(),
2584                    )
2585                    .into_any();
2586                el.child(
2587                    h_flex()
2588                        .text_ui(cx)
2589                        .text_center()
2590                        .justify_center()
2591                        .gap_2()
2592                        .px_4()
2593                        .w_full()
2594                        .max_w_128()
2595                        .child(Label::new("Authenticating..."))
2596                        .child(spinner_icon),
2597                )
2598            })
2599            .child(
2600                h_flex()
2601                    .mt_1p5()
2602                    .gap_1()
2603                    .flex_wrap()
2604                    .justify_center()
2605                    .children(connection.auth_methods().iter().enumerate().rev().map(
2606                        |(ix, method)| {
2607                            Button::new(
2608                                SharedString::from(method.id.0.clone()),
2609                                method.name.clone(),
2610                            )
2611                            .style(ButtonStyle::Outlined)
2612                            .when(ix == 0, |el| {
2613                                el.style(ButtonStyle::Tinted(ui::TintColor::Accent))
2614                            })
2615                            .size(ButtonSize::Medium)
2616                            .label_size(LabelSize::Small)
2617                            .on_click({
2618                                let method_id = method.id.clone();
2619                                cx.listener(move |this, _, window, cx| {
2620                                    this.authenticate(method_id.clone(), window, cx)
2621                                })
2622                            })
2623                        },
2624                    )),
2625            )
2626    }
2627
2628    fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
2629        let mut container = v_flex()
2630            .items_center()
2631            .justify_center()
2632            .child(self.render_error_agent_logo())
2633            .child(
2634                v_flex()
2635                    .mt_4()
2636                    .mb_2()
2637                    .gap_0p5()
2638                    .text_center()
2639                    .items_center()
2640                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
2641                    .child(
2642                        Label::new(e.to_string())
2643                            .size(LabelSize::Small)
2644                            .color(Color::Muted),
2645                    ),
2646            );
2647
2648        if let LoadError::Unsupported {
2649            upgrade_message,
2650            upgrade_command,
2651            ..
2652        } = &e
2653        {
2654            let upgrade_message = upgrade_message.clone();
2655            let upgrade_command = upgrade_command.clone();
2656            container = container.child(
2657                Button::new("upgrade", upgrade_message)
2658                    .tooltip(Tooltip::text(upgrade_command.clone()))
2659                    .on_click(cx.listener(move |this, _, window, cx| {
2660                        let task = this
2661                            .workspace
2662                            .update(cx, |workspace, cx| {
2663                                let project = workspace.project().read(cx);
2664                                let cwd = project.first_project_directory(cx);
2665                                let shell = project.terminal_settings(&cwd, cx).shell.clone();
2666                                let spawn_in_terminal = task::SpawnInTerminal {
2667                                    id: task::TaskId("upgrade".to_string()),
2668                                    full_label: upgrade_command.clone(),
2669                                    label: upgrade_command.clone(),
2670                                    command: Some(upgrade_command.clone()),
2671                                    args: Vec::new(),
2672                                    command_label: upgrade_command.clone(),
2673                                    cwd,
2674                                    env: Default::default(),
2675                                    use_new_terminal: true,
2676                                    allow_concurrent_runs: true,
2677                                    reveal: Default::default(),
2678                                    reveal_target: Default::default(),
2679                                    hide: Default::default(),
2680                                    shell,
2681                                    show_summary: true,
2682                                    show_command: true,
2683                                    show_rerun: false,
2684                                };
2685                                workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2686                            })
2687                            .ok();
2688                        let Some(task) = task else { return };
2689                        cx.spawn_in(window, async move |this, cx| {
2690                            if let Some(Ok(_)) = task.await {
2691                                this.update_in(cx, |this, window, cx| {
2692                                    this.reset(window, cx);
2693                                })
2694                                .ok();
2695                            }
2696                        })
2697                        .detach()
2698                    })),
2699            );
2700        } else if let LoadError::NotInstalled {
2701            install_message,
2702            install_command,
2703            ..
2704        } = e
2705        {
2706            let install_message = install_message.clone();
2707            let install_command = install_command.clone();
2708            container = container.child(
2709                Button::new("install", install_message)
2710                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2711                    .size(ButtonSize::Medium)
2712                    .tooltip(Tooltip::text(install_command.clone()))
2713                    .on_click(cx.listener(move |this, _, window, cx| {
2714                        let task = this
2715                            .workspace
2716                            .update(cx, |workspace, cx| {
2717                                let project = workspace.project().read(cx);
2718                                let cwd = project.first_project_directory(cx);
2719                                let shell = project.terminal_settings(&cwd, cx).shell.clone();
2720                                let spawn_in_terminal = task::SpawnInTerminal {
2721                                    id: task::TaskId("install".to_string()),
2722                                    full_label: install_command.clone(),
2723                                    label: install_command.clone(),
2724                                    command: Some(install_command.clone()),
2725                                    args: Vec::new(),
2726                                    command_label: install_command.clone(),
2727                                    cwd,
2728                                    env: Default::default(),
2729                                    use_new_terminal: true,
2730                                    allow_concurrent_runs: true,
2731                                    reveal: Default::default(),
2732                                    reveal_target: Default::default(),
2733                                    hide: Default::default(),
2734                                    shell,
2735                                    show_summary: true,
2736                                    show_command: true,
2737                                    show_rerun: false,
2738                                };
2739                                workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2740                            })
2741                            .ok();
2742                        let Some(task) = task else { return };
2743                        cx.spawn_in(window, async move |this, cx| {
2744                            if let Some(Ok(_)) = task.await {
2745                                this.update_in(cx, |this, window, cx| {
2746                                    this.reset(window, cx);
2747                                })
2748                                .ok();
2749                            }
2750                        })
2751                        .detach()
2752                    })),
2753            );
2754        }
2755
2756        container.into_any()
2757    }
2758
2759    fn render_activity_bar(
2760        &self,
2761        thread_entity: &Entity<AcpThread>,
2762        window: &mut Window,
2763        cx: &Context<Self>,
2764    ) -> Option<AnyElement> {
2765        let thread = thread_entity.read(cx);
2766        let action_log = thread.action_log();
2767        let changed_buffers = action_log.read(cx).changed_buffers(cx);
2768        let plan = thread.plan();
2769
2770        if changed_buffers.is_empty() && plan.is_empty() {
2771            return None;
2772        }
2773
2774        let editor_bg_color = cx.theme().colors().editor_background;
2775        let active_color = cx.theme().colors().element_selected;
2776        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2777
2778        let pending_edits = thread.has_pending_edit_tool_calls();
2779
2780        v_flex()
2781            .mt_1()
2782            .mx_2()
2783            .bg(bg_edit_files_disclosure)
2784            .border_1()
2785            .border_b_0()
2786            .border_color(cx.theme().colors().border)
2787            .rounded_t_md()
2788            .shadow(vec![gpui::BoxShadow {
2789                color: gpui::black().opacity(0.15),
2790                offset: point(px(1.), px(-1.)),
2791                blur_radius: px(3.),
2792                spread_radius: px(0.),
2793            }])
2794            .when(!plan.is_empty(), |this| {
2795                this.child(self.render_plan_summary(plan, window, cx))
2796                    .when(self.plan_expanded, |parent| {
2797                        parent.child(self.render_plan_entries(plan, window, cx))
2798                    })
2799            })
2800            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2801                this.child(Divider::horizontal().color(DividerColor::Border))
2802            })
2803            .when(!changed_buffers.is_empty(), |this| {
2804                this.child(self.render_edits_summary(
2805                    &changed_buffers,
2806                    self.edits_expanded,
2807                    pending_edits,
2808                    window,
2809                    cx,
2810                ))
2811                .when(self.edits_expanded, |parent| {
2812                    parent.child(self.render_edited_files(
2813                        action_log,
2814                        &changed_buffers,
2815                        pending_edits,
2816                        cx,
2817                    ))
2818                })
2819            })
2820            .into_any()
2821            .into()
2822    }
2823
2824    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2825        let stats = plan.stats();
2826
2827        let title = if let Some(entry) = stats.in_progress_entry
2828            && !self.plan_expanded
2829        {
2830            h_flex()
2831                .w_full()
2832                .cursor_default()
2833                .gap_1()
2834                .text_xs()
2835                .text_color(cx.theme().colors().text_muted)
2836                .justify_between()
2837                .child(
2838                    h_flex()
2839                        .gap_1()
2840                        .child(
2841                            Label::new("Current:")
2842                                .size(LabelSize::Small)
2843                                .color(Color::Muted),
2844                        )
2845                        .child(MarkdownElement::new(
2846                            entry.content.clone(),
2847                            plan_label_markdown_style(&entry.status, window, cx),
2848                        )),
2849                )
2850                .when(stats.pending > 0, |this| {
2851                    this.child(
2852                        Label::new(format!("{} left", stats.pending))
2853                            .size(LabelSize::Small)
2854                            .color(Color::Muted)
2855                            .mr_1(),
2856                    )
2857                })
2858        } else {
2859            let status_label = if stats.pending == 0 {
2860                "All Done".to_string()
2861            } else if stats.completed == 0 {
2862                format!("{} Tasks", plan.entries.len())
2863            } else {
2864                format!("{}/{}", stats.completed, plan.entries.len())
2865            };
2866
2867            h_flex()
2868                .w_full()
2869                .gap_1()
2870                .justify_between()
2871                .child(
2872                    Label::new("Plan")
2873                        .size(LabelSize::Small)
2874                        .color(Color::Muted),
2875                )
2876                .child(
2877                    Label::new(status_label)
2878                        .size(LabelSize::Small)
2879                        .color(Color::Muted)
2880                        .mr_1(),
2881                )
2882        };
2883
2884        h_flex()
2885            .p_1()
2886            .justify_between()
2887            .when(self.plan_expanded, |this| {
2888                this.border_b_1().border_color(cx.theme().colors().border)
2889            })
2890            .child(
2891                h_flex()
2892                    .id("plan_summary")
2893                    .w_full()
2894                    .gap_1()
2895                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2896                    .child(title)
2897                    .on_click(cx.listener(|this, _, _, cx| {
2898                        this.plan_expanded = !this.plan_expanded;
2899                        cx.notify();
2900                    })),
2901            )
2902    }
2903
2904    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2905        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2906            let element = h_flex()
2907                .py_1()
2908                .px_2()
2909                .gap_2()
2910                .justify_between()
2911                .bg(cx.theme().colors().editor_background)
2912                .when(index < plan.entries.len() - 1, |parent| {
2913                    parent.border_color(cx.theme().colors().border).border_b_1()
2914                })
2915                .child(
2916                    h_flex()
2917                        .id(("plan_entry", index))
2918                        .gap_1p5()
2919                        .max_w_full()
2920                        .overflow_x_scroll()
2921                        .text_xs()
2922                        .text_color(cx.theme().colors().text_muted)
2923                        .child(match entry.status {
2924                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2925                                .size(IconSize::Small)
2926                                .color(Color::Muted)
2927                                .into_any_element(),
2928                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2929                                .size(IconSize::Small)
2930                                .color(Color::Accent)
2931                                .with_animation(
2932                                    "running",
2933                                    Animation::new(Duration::from_secs(2)).repeat(),
2934                                    |icon, delta| {
2935                                        icon.transform(Transformation::rotate(percentage(delta)))
2936                                    },
2937                                )
2938                                .into_any_element(),
2939                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2940                                .size(IconSize::Small)
2941                                .color(Color::Success)
2942                                .into_any_element(),
2943                        })
2944                        .child(MarkdownElement::new(
2945                            entry.content.clone(),
2946                            plan_label_markdown_style(&entry.status, window, cx),
2947                        )),
2948                );
2949
2950            Some(element)
2951        }))
2952    }
2953
2954    fn render_edits_summary(
2955        &self,
2956        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2957        expanded: bool,
2958        pending_edits: bool,
2959        window: &mut Window,
2960        cx: &Context<Self>,
2961    ) -> Div {
2962        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2963
2964        let focus_handle = self.focus_handle(cx);
2965
2966        h_flex()
2967            .p_1()
2968            .justify_between()
2969            .when(expanded, |this| {
2970                this.border_b_1().border_color(cx.theme().colors().border)
2971            })
2972            .child(
2973                h_flex()
2974                    .id("edits-container")
2975                    .w_full()
2976                    .gap_1()
2977                    .child(Disclosure::new("edits-disclosure", expanded))
2978                    .map(|this| {
2979                        if pending_edits {
2980                            this.child(
2981                                Label::new(format!(
2982                                    "Editing {} {}",
2983                                    changed_buffers.len(),
2984                                    if changed_buffers.len() == 1 {
2985                                        "file"
2986                                    } else {
2987                                        "files"
2988                                    }
2989                                ))
2990                                .color(Color::Muted)
2991                                .size(LabelSize::Small)
2992                                .with_animation(
2993                                    "edit-label",
2994                                    Animation::new(Duration::from_secs(2))
2995                                        .repeat()
2996                                        .with_easing(pulsating_between(0.3, 0.7)),
2997                                    |label, delta| label.alpha(delta),
2998                                ),
2999                            )
3000                        } else {
3001                            this.child(
3002                                Label::new("Edits")
3003                                    .size(LabelSize::Small)
3004                                    .color(Color::Muted),
3005                            )
3006                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
3007                            .child(
3008                                Label::new(format!(
3009                                    "{} {}",
3010                                    changed_buffers.len(),
3011                                    if changed_buffers.len() == 1 {
3012                                        "file"
3013                                    } else {
3014                                        "files"
3015                                    }
3016                                ))
3017                                .size(LabelSize::Small)
3018                                .color(Color::Muted),
3019                            )
3020                        }
3021                    })
3022                    .on_click(cx.listener(|this, _, _, cx| {
3023                        this.edits_expanded = !this.edits_expanded;
3024                        cx.notify();
3025                    })),
3026            )
3027            .child(
3028                h_flex()
3029                    .gap_1()
3030                    .child(
3031                        IconButton::new("review-changes", IconName::ListTodo)
3032                            .icon_size(IconSize::Small)
3033                            .tooltip({
3034                                let focus_handle = focus_handle.clone();
3035                                move |window, cx| {
3036                                    Tooltip::for_action_in(
3037                                        "Review Changes",
3038                                        &OpenAgentDiff,
3039                                        &focus_handle,
3040                                        window,
3041                                        cx,
3042                                    )
3043                                }
3044                            })
3045                            .on_click(cx.listener(|_, _, window, cx| {
3046                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3047                            })),
3048                    )
3049                    .child(Divider::vertical().color(DividerColor::Border))
3050                    .child(
3051                        Button::new("reject-all-changes", "Reject All")
3052                            .label_size(LabelSize::Small)
3053                            .disabled(pending_edits)
3054                            .when(pending_edits, |this| {
3055                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3056                            })
3057                            .key_binding(
3058                                KeyBinding::for_action_in(
3059                                    &RejectAll,
3060                                    &focus_handle.clone(),
3061                                    window,
3062                                    cx,
3063                                )
3064                                .map(|kb| kb.size(rems_from_px(10.))),
3065                            )
3066                            .on_click(cx.listener(move |this, _, window, cx| {
3067                                this.reject_all(&RejectAll, window, cx);
3068                            })),
3069                    )
3070                    .child(
3071                        Button::new("keep-all-changes", "Keep All")
3072                            .label_size(LabelSize::Small)
3073                            .disabled(pending_edits)
3074                            .when(pending_edits, |this| {
3075                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3076                            })
3077                            .key_binding(
3078                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3079                                    .map(|kb| kb.size(rems_from_px(10.))),
3080                            )
3081                            .on_click(cx.listener(move |this, _, window, cx| {
3082                                this.keep_all(&KeepAll, window, cx);
3083                            })),
3084                    ),
3085            )
3086    }
3087
3088    fn render_edited_files(
3089        &self,
3090        action_log: &Entity<ActionLog>,
3091        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3092        pending_edits: bool,
3093        cx: &Context<Self>,
3094    ) -> Div {
3095        let editor_bg_color = cx.theme().colors().editor_background;
3096
3097        v_flex().children(changed_buffers.iter().enumerate().flat_map(
3098            |(index, (buffer, _diff))| {
3099                let file = buffer.read(cx).file()?;
3100                let path = file.path();
3101
3102                let file_path = path.parent().and_then(|parent| {
3103                    let parent_str = parent.to_string_lossy();
3104
3105                    if parent_str.is_empty() {
3106                        None
3107                    } else {
3108                        Some(
3109                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3110                                .color(Color::Muted)
3111                                .size(LabelSize::XSmall)
3112                                .buffer_font(cx),
3113                        )
3114                    }
3115                });
3116
3117                let file_name = path.file_name().map(|name| {
3118                    Label::new(name.to_string_lossy().to_string())
3119                        .size(LabelSize::XSmall)
3120                        .buffer_font(cx)
3121                });
3122
3123                let file_icon = FileIcons::get_icon(path, cx)
3124                    .map(Icon::from_path)
3125                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3126                    .unwrap_or_else(|| {
3127                        Icon::new(IconName::File)
3128                            .color(Color::Muted)
3129                            .size(IconSize::Small)
3130                    });
3131
3132                let overlay_gradient = linear_gradient(
3133                    90.,
3134                    linear_color_stop(editor_bg_color, 1.),
3135                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3136                );
3137
3138                let element = h_flex()
3139                    .group("edited-code")
3140                    .id(("file-container", index))
3141                    .relative()
3142                    .py_1()
3143                    .pl_2()
3144                    .pr_1()
3145                    .gap_2()
3146                    .justify_between()
3147                    .bg(editor_bg_color)
3148                    .when(index < changed_buffers.len() - 1, |parent| {
3149                        parent.border_color(cx.theme().colors().border).border_b_1()
3150                    })
3151                    .child(
3152                        h_flex()
3153                            .id(("file-name", index))
3154                            .pr_8()
3155                            .gap_1p5()
3156                            .max_w_full()
3157                            .overflow_x_scroll()
3158                            .child(file_icon)
3159                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3160                            .on_click({
3161                                let buffer = buffer.clone();
3162                                cx.listener(move |this, _, window, cx| {
3163                                    this.open_edited_buffer(&buffer, window, cx);
3164                                })
3165                            }),
3166                    )
3167                    .child(
3168                        h_flex()
3169                            .gap_1()
3170                            .visible_on_hover("edited-code")
3171                            .child(
3172                                Button::new("review", "Review")
3173                                    .label_size(LabelSize::Small)
3174                                    .on_click({
3175                                        let buffer = buffer.clone();
3176                                        cx.listener(move |this, _, window, cx| {
3177                                            this.open_edited_buffer(&buffer, window, cx);
3178                                        })
3179                                    }),
3180                            )
3181                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3182                            .child(
3183                                Button::new("reject-file", "Reject")
3184                                    .label_size(LabelSize::Small)
3185                                    .disabled(pending_edits)
3186                                    .on_click({
3187                                        let buffer = buffer.clone();
3188                                        let action_log = action_log.clone();
3189                                        move |_, _, cx| {
3190                                            action_log.update(cx, |action_log, cx| {
3191                                                action_log
3192                                                    .reject_edits_in_ranges(
3193                                                        buffer.clone(),
3194                                                        vec![Anchor::MIN..Anchor::MAX],
3195                                                        cx,
3196                                                    )
3197                                                    .detach_and_log_err(cx);
3198                                            })
3199                                        }
3200                                    }),
3201                            )
3202                            .child(
3203                                Button::new("keep-file", "Keep")
3204                                    .label_size(LabelSize::Small)
3205                                    .disabled(pending_edits)
3206                                    .on_click({
3207                                        let buffer = buffer.clone();
3208                                        let action_log = action_log.clone();
3209                                        move |_, _, cx| {
3210                                            action_log.update(cx, |action_log, cx| {
3211                                                action_log.keep_edits_in_range(
3212                                                    buffer.clone(),
3213                                                    Anchor::MIN..Anchor::MAX,
3214                                                    cx,
3215                                                );
3216                                            })
3217                                        }
3218                                    }),
3219                            ),
3220                    )
3221                    .child(
3222                        div()
3223                            .id("gradient-overlay")
3224                            .absolute()
3225                            .h_full()
3226                            .w_12()
3227                            .top_0()
3228                            .bottom_0()
3229                            .right(px(152.))
3230                            .bg(overlay_gradient),
3231                    );
3232
3233                Some(element)
3234            },
3235        ))
3236    }
3237
3238    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3239        let focus_handle = self.message_editor.focus_handle(cx);
3240        let editor_bg_color = cx.theme().colors().editor_background;
3241        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3242            (IconName::Minimize, "Minimize Message Editor")
3243        } else {
3244            (IconName::Maximize, "Expand Message Editor")
3245        };
3246
3247        v_flex()
3248            .on_action(cx.listener(Self::expand_message_editor))
3249            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3250                if let Some(profile_selector) = this.profile_selector.as_ref() {
3251                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3252                }
3253            }))
3254            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3255                if let Some(model_selector) = this.model_selector.as_ref() {
3256                    model_selector
3257                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3258                }
3259            }))
3260            .p_2()
3261            .gap_2()
3262            .border_t_1()
3263            .border_color(cx.theme().colors().border)
3264            .bg(editor_bg_color)
3265            .when(self.editor_expanded, |this| {
3266                this.h(vh(0.8, window)).size_full().justify_between()
3267            })
3268            .child(
3269                v_flex()
3270                    .relative()
3271                    .size_full()
3272                    .pt_1()
3273                    .pr_2p5()
3274                    .child(self.message_editor.clone())
3275                    .child(
3276                        h_flex()
3277                            .absolute()
3278                            .top_0()
3279                            .right_0()
3280                            .opacity(0.5)
3281                            .hover(|this| this.opacity(1.0))
3282                            .child(
3283                                IconButton::new("toggle-height", expand_icon)
3284                                    .icon_size(IconSize::Small)
3285                                    .icon_color(Color::Muted)
3286                                    .tooltip({
3287                                        move |window, cx| {
3288                                            Tooltip::for_action_in(
3289                                                expand_tooltip,
3290                                                &ExpandMessageEditor,
3291                                                &focus_handle,
3292                                                window,
3293                                                cx,
3294                                            )
3295                                        }
3296                                    })
3297                                    .on_click(cx.listener(|_, _, window, cx| {
3298                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3299                                    })),
3300                            ),
3301                    ),
3302            )
3303            .child(
3304                h_flex()
3305                    .flex_none()
3306                    .flex_wrap()
3307                    .justify_between()
3308                    .child(
3309                        h_flex()
3310                            .child(self.render_follow_toggle(cx))
3311                            .children(self.render_burn_mode_toggle(cx)),
3312                    )
3313                    .child(
3314                        h_flex()
3315                            .gap_1()
3316                            .children(self.render_token_usage(cx))
3317                            .children(self.profile_selector.clone())
3318                            .children(self.model_selector.clone())
3319                            .child(self.render_send_button(cx)),
3320                    ),
3321            )
3322            .into_any()
3323    }
3324
3325    pub(crate) fn as_native_connection(
3326        &self,
3327        cx: &App,
3328    ) -> Option<Rc<agent2::NativeAgentConnection>> {
3329        let acp_thread = self.thread()?.read(cx);
3330        acp_thread.connection().clone().downcast()
3331    }
3332
3333    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3334        let acp_thread = self.thread()?.read(cx);
3335        self.as_native_connection(cx)?
3336            .thread(acp_thread.session_id(), cx)
3337    }
3338
3339    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3340        self.as_native_thread(cx)
3341            .and_then(|thread| thread.read(cx).model())
3342            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3343    }
3344
3345    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3346        let thread = self.thread()?.read(cx);
3347        let usage = thread.token_usage()?;
3348        let is_generating = thread.status() != ThreadStatus::Idle;
3349
3350        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3351        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3352
3353        Some(
3354            h_flex()
3355                .flex_shrink_0()
3356                .gap_0p5()
3357                .mr_1p5()
3358                .child(
3359                    Label::new(used)
3360                        .size(LabelSize::Small)
3361                        .color(Color::Muted)
3362                        .map(|label| {
3363                            if is_generating {
3364                                label
3365                                    .with_animation(
3366                                        "used-tokens-label",
3367                                        Animation::new(Duration::from_secs(2))
3368                                            .repeat()
3369                                            .with_easing(pulsating_between(0.6, 1.)),
3370                                        |label, delta| label.alpha(delta),
3371                                    )
3372                                    .into_any()
3373                            } else {
3374                                label.into_any_element()
3375                            }
3376                        }),
3377                )
3378                .child(
3379                    Label::new("/")
3380                        .size(LabelSize::Small)
3381                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3382                )
3383                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3384        )
3385    }
3386
3387    fn toggle_burn_mode(
3388        &mut self,
3389        _: &ToggleBurnMode,
3390        _window: &mut Window,
3391        cx: &mut Context<Self>,
3392    ) {
3393        let Some(thread) = self.as_native_thread(cx) else {
3394            return;
3395        };
3396
3397        thread.update(cx, |thread, cx| {
3398            let current_mode = thread.completion_mode();
3399            thread.set_completion_mode(
3400                match current_mode {
3401                    CompletionMode::Burn => CompletionMode::Normal,
3402                    CompletionMode::Normal => CompletionMode::Burn,
3403                },
3404                cx,
3405            );
3406        });
3407    }
3408
3409    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3410        let Some(thread) = self.thread() else {
3411            return;
3412        };
3413        let action_log = thread.read(cx).action_log().clone();
3414        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3415    }
3416
3417    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3418        let Some(thread) = self.thread() else {
3419            return;
3420        };
3421        let action_log = thread.read(cx).action_log().clone();
3422        action_log
3423            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3424            .detach();
3425    }
3426
3427    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3428        let thread = self.as_native_thread(cx)?.read(cx);
3429
3430        if thread
3431            .model()
3432            .is_none_or(|model| !model.supports_burn_mode())
3433        {
3434            return None;
3435        }
3436
3437        let active_completion_mode = thread.completion_mode();
3438        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3439        let icon = if burn_mode_enabled {
3440            IconName::ZedBurnModeOn
3441        } else {
3442            IconName::ZedBurnMode
3443        };
3444
3445        Some(
3446            IconButton::new("burn-mode", icon)
3447                .icon_size(IconSize::Small)
3448                .icon_color(Color::Muted)
3449                .toggle_state(burn_mode_enabled)
3450                .selected_icon_color(Color::Error)
3451                .on_click(cx.listener(|this, _event, window, cx| {
3452                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3453                }))
3454                .tooltip(move |_window, cx| {
3455                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3456                        .into()
3457                })
3458                .into_any_element(),
3459        )
3460    }
3461
3462    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3463        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3464        let is_generating = self
3465            .thread()
3466            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3467
3468        if is_generating && is_editor_empty {
3469            IconButton::new("stop-generation", IconName::Stop)
3470                .icon_color(Color::Error)
3471                .style(ButtonStyle::Tinted(ui::TintColor::Error))
3472                .tooltip(move |window, cx| {
3473                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3474                })
3475                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3476                .into_any_element()
3477        } else {
3478            let send_btn_tooltip = if is_editor_empty && !is_generating {
3479                "Type to Send"
3480            } else if is_generating {
3481                "Stop and Send Message"
3482            } else {
3483                "Send"
3484            };
3485
3486            IconButton::new("send-message", IconName::Send)
3487                .style(ButtonStyle::Filled)
3488                .map(|this| {
3489                    if is_editor_empty && !is_generating {
3490                        this.disabled(true).icon_color(Color::Muted)
3491                    } else {
3492                        this.icon_color(Color::Accent)
3493                    }
3494                })
3495                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3496                .on_click(cx.listener(|this, _, window, cx| {
3497                    this.send(window, cx);
3498                }))
3499                .into_any_element()
3500        }
3501    }
3502
3503    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3504        let following = self
3505            .workspace
3506            .read_with(cx, |workspace, _| {
3507                workspace.is_being_followed(CollaboratorId::Agent)
3508            })
3509            .unwrap_or(false);
3510
3511        IconButton::new("follow-agent", IconName::Crosshair)
3512            .icon_size(IconSize::Small)
3513            .icon_color(Color::Muted)
3514            .toggle_state(following)
3515            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3516            .tooltip(move |window, cx| {
3517                if following {
3518                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
3519                } else {
3520                    Tooltip::with_meta(
3521                        "Follow Agent",
3522                        Some(&Follow),
3523                        "Track the agent's location as it reads and edits files.",
3524                        window,
3525                        cx,
3526                    )
3527                }
3528            })
3529            .on_click(cx.listener(move |this, _, window, cx| {
3530                this.workspace
3531                    .update(cx, |workspace, cx| {
3532                        if following {
3533                            workspace.unfollow(CollaboratorId::Agent, window, cx);
3534                        } else {
3535                            workspace.follow(CollaboratorId::Agent, window, cx);
3536                        }
3537                    })
3538                    .ok();
3539            }))
3540    }
3541
3542    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3543        let workspace = self.workspace.clone();
3544        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3545            Self::open_link(text, &workspace, window, cx);
3546        })
3547    }
3548
3549    fn open_link(
3550        url: SharedString,
3551        workspace: &WeakEntity<Workspace>,
3552        window: &mut Window,
3553        cx: &mut App,
3554    ) {
3555        let Some(workspace) = workspace.upgrade() else {
3556            cx.open_url(&url);
3557            return;
3558        };
3559
3560        if let Some(mention) = MentionUri::parse(&url).log_err() {
3561            workspace.update(cx, |workspace, cx| match mention {
3562                MentionUri::File { abs_path } => {
3563                    let project = workspace.project();
3564                    let Some(path) =
3565                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3566                    else {
3567                        return;
3568                    };
3569
3570                    workspace
3571                        .open_path(path, None, true, window, cx)
3572                        .detach_and_log_err(cx);
3573                }
3574                MentionUri::Directory { abs_path } => {
3575                    let project = workspace.project();
3576                    let Some(entry) = project.update(cx, |project, cx| {
3577                        let path = project.find_project_path(abs_path, cx)?;
3578                        project.entry_for_path(&path, cx)
3579                    }) else {
3580                        return;
3581                    };
3582
3583                    project.update(cx, |_, cx| {
3584                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
3585                    });
3586                }
3587                MentionUri::Symbol {
3588                    path, line_range, ..
3589                }
3590                | MentionUri::Selection { path, line_range } => {
3591                    let project = workspace.project();
3592                    let Some((path, _)) = project.update(cx, |project, cx| {
3593                        let path = project.find_project_path(path, cx)?;
3594                        let entry = project.entry_for_path(&path, cx)?;
3595                        Some((path, entry))
3596                    }) else {
3597                        return;
3598                    };
3599
3600                    let item = workspace.open_path(path, None, true, window, cx);
3601                    window
3602                        .spawn(cx, async move |cx| {
3603                            let Some(editor) = item.await?.downcast::<Editor>() else {
3604                                return Ok(());
3605                            };
3606                            let range =
3607                                Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
3608                            editor
3609                                .update_in(cx, |editor, window, cx| {
3610                                    editor.change_selections(
3611                                        SelectionEffects::scroll(Autoscroll::center()),
3612                                        window,
3613                                        cx,
3614                                        |s| s.select_ranges(vec![range]),
3615                                    );
3616                                })
3617                                .ok();
3618                            anyhow::Ok(())
3619                        })
3620                        .detach_and_log_err(cx);
3621                }
3622                MentionUri::Thread { id, name } => {
3623                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3624                        panel.update(cx, |panel, cx| {
3625                            panel.load_agent_thread(
3626                                DbThreadMetadata {
3627                                    id,
3628                                    title: name.into(),
3629                                    updated_at: Default::default(),
3630                                },
3631                                window,
3632                                cx,
3633                            )
3634                        });
3635                    }
3636                }
3637                MentionUri::TextThread { path, .. } => {
3638                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3639                        panel.update(cx, |panel, cx| {
3640                            panel
3641                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
3642                                .detach_and_log_err(cx);
3643                        });
3644                    }
3645                }
3646                MentionUri::Rule { id, .. } => {
3647                    let PromptId::User { uuid } = id else {
3648                        return;
3649                    };
3650                    window.dispatch_action(
3651                        Box::new(OpenRulesLibrary {
3652                            prompt_to_select: Some(uuid.0),
3653                        }),
3654                        cx,
3655                    )
3656                }
3657                MentionUri::Fetch { url } => {
3658                    cx.open_url(url.as_str());
3659                }
3660            })
3661        } else {
3662            cx.open_url(&url);
3663        }
3664    }
3665
3666    fn open_tool_call_location(
3667        &self,
3668        entry_ix: usize,
3669        location_ix: usize,
3670        window: &mut Window,
3671        cx: &mut Context<Self>,
3672    ) -> Option<()> {
3673        let (tool_call_location, agent_location) = self
3674            .thread()?
3675            .read(cx)
3676            .entries()
3677            .get(entry_ix)?
3678            .location(location_ix)?;
3679
3680        let project_path = self
3681            .project
3682            .read(cx)
3683            .find_project_path(&tool_call_location.path, cx)?;
3684
3685        let open_task = self
3686            .workspace
3687            .update(cx, |workspace, cx| {
3688                workspace.open_path(project_path, None, true, window, cx)
3689            })
3690            .log_err()?;
3691        window
3692            .spawn(cx, async move |cx| {
3693                let item = open_task.await?;
3694
3695                let Some(active_editor) = item.downcast::<Editor>() else {
3696                    return anyhow::Ok(());
3697                };
3698
3699                active_editor.update_in(cx, |editor, window, cx| {
3700                    let multibuffer = editor.buffer().read(cx);
3701                    let buffer = multibuffer.as_singleton();
3702                    if agent_location.buffer.upgrade() == buffer {
3703                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3704                        let anchor = editor::Anchor::in_buffer(
3705                            excerpt_id.unwrap(),
3706                            buffer.unwrap().read(cx).remote_id(),
3707                            agent_location.position,
3708                        );
3709                        editor.change_selections(Default::default(), window, cx, |selections| {
3710                            selections.select_anchor_ranges([anchor..anchor]);
3711                        })
3712                    } else {
3713                        let row = tool_call_location.line.unwrap_or_default();
3714                        editor.change_selections(Default::default(), window, cx, |selections| {
3715                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3716                        })
3717                    }
3718                })?;
3719
3720                anyhow::Ok(())
3721            })
3722            .detach_and_log_err(cx);
3723
3724        None
3725    }
3726
3727    pub fn open_thread_as_markdown(
3728        &self,
3729        workspace: Entity<Workspace>,
3730        window: &mut Window,
3731        cx: &mut App,
3732    ) -> Task<anyhow::Result<()>> {
3733        let markdown_language_task = workspace
3734            .read(cx)
3735            .app_state()
3736            .languages
3737            .language_for_name("Markdown");
3738
3739        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3740            let thread = thread.read(cx);
3741            (thread.title().to_string(), thread.to_markdown(cx))
3742        } else {
3743            return Task::ready(Ok(()));
3744        };
3745
3746        window.spawn(cx, async move |cx| {
3747            let markdown_language = markdown_language_task.await?;
3748
3749            workspace.update_in(cx, |workspace, window, cx| {
3750                let project = workspace.project().clone();
3751
3752                if !project.read(cx).is_local() {
3753                    bail!("failed to open active thread as markdown in remote project");
3754                }
3755
3756                let buffer = project.update(cx, |project, cx| {
3757                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
3758                });
3759                let buffer = cx.new(|cx| {
3760                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3761                });
3762
3763                workspace.add_item_to_active_pane(
3764                    Box::new(cx.new(|cx| {
3765                        let mut editor =
3766                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3767                        editor.set_breadcrumb_header(thread_summary);
3768                        editor
3769                    })),
3770                    None,
3771                    true,
3772                    window,
3773                    cx,
3774                );
3775
3776                anyhow::Ok(())
3777            })??;
3778            anyhow::Ok(())
3779        })
3780    }
3781
3782    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3783        self.list_state.scroll_to(ListOffset::default());
3784        cx.notify();
3785    }
3786
3787    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3788        if let Some(thread) = self.thread() {
3789            let entry_count = thread.read(cx).entries().len();
3790            self.list_state.reset(entry_count);
3791            cx.notify();
3792        }
3793    }
3794
3795    fn notify_with_sound(
3796        &mut self,
3797        caption: impl Into<SharedString>,
3798        icon: IconName,
3799        window: &mut Window,
3800        cx: &mut Context<Self>,
3801    ) {
3802        self.play_notification_sound(window, cx);
3803        self.show_notification(caption, icon, window, cx);
3804    }
3805
3806    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
3807        let settings = AgentSettings::get_global(cx);
3808        if settings.play_sound_when_agent_done && !window.is_window_active() {
3809            Audio::play_sound(Sound::AgentDone, cx);
3810        }
3811    }
3812
3813    fn show_notification(
3814        &mut self,
3815        caption: impl Into<SharedString>,
3816        icon: IconName,
3817        window: &mut Window,
3818        cx: &mut Context<Self>,
3819    ) {
3820        if window.is_window_active() || !self.notifications.is_empty() {
3821            return;
3822        }
3823
3824        let title = self.title(cx);
3825
3826        match AgentSettings::get_global(cx).notify_when_agent_waiting {
3827            NotifyWhenAgentWaiting::PrimaryScreen => {
3828                if let Some(primary) = cx.primary_display() {
3829                    self.pop_up(icon, caption.into(), title, window, primary, cx);
3830                }
3831            }
3832            NotifyWhenAgentWaiting::AllScreens => {
3833                let caption = caption.into();
3834                for screen in cx.displays() {
3835                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
3836                }
3837            }
3838            NotifyWhenAgentWaiting::Never => {
3839                // Don't show anything
3840            }
3841        }
3842    }
3843
3844    fn pop_up(
3845        &mut self,
3846        icon: IconName,
3847        caption: SharedString,
3848        title: SharedString,
3849        window: &mut Window,
3850        screen: Rc<dyn PlatformDisplay>,
3851        cx: &mut Context<Self>,
3852    ) {
3853        let options = AgentNotification::window_options(screen, cx);
3854
3855        let project_name = self.workspace.upgrade().and_then(|workspace| {
3856            workspace
3857                .read(cx)
3858                .project()
3859                .read(cx)
3860                .visible_worktrees(cx)
3861                .next()
3862                .map(|worktree| worktree.read(cx).root_name().to_string())
3863        });
3864
3865        if let Some(screen_window) = cx
3866            .open_window(options, |_, cx| {
3867                cx.new(|_| {
3868                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
3869                })
3870            })
3871            .log_err()
3872            && let Some(pop_up) = screen_window.entity(cx).log_err()
3873        {
3874            self.notification_subscriptions
3875                .entry(screen_window)
3876                .or_insert_with(Vec::new)
3877                .push(cx.subscribe_in(&pop_up, window, {
3878                    |this, _, event, window, cx| match event {
3879                        AgentNotificationEvent::Accepted => {
3880                            let handle = window.window_handle();
3881                            cx.activate(true);
3882
3883                            let workspace_handle = this.workspace.clone();
3884
3885                            // If there are multiple Zed windows, activate the correct one.
3886                            cx.defer(move |cx| {
3887                                handle
3888                                    .update(cx, |_view, window, _cx| {
3889                                        window.activate_window();
3890
3891                                        if let Some(workspace) = workspace_handle.upgrade() {
3892                                            workspace.update(_cx, |workspace, cx| {
3893                                                workspace.focus_panel::<AgentPanel>(window, cx);
3894                                            });
3895                                        }
3896                                    })
3897                                    .log_err();
3898                            });
3899
3900                            this.dismiss_notifications(cx);
3901                        }
3902                        AgentNotificationEvent::Dismissed => {
3903                            this.dismiss_notifications(cx);
3904                        }
3905                    }
3906                }));
3907
3908            self.notifications.push(screen_window);
3909
3910            // If the user manually refocuses the original window, dismiss the popup.
3911            self.notification_subscriptions
3912                .entry(screen_window)
3913                .or_insert_with(Vec::new)
3914                .push({
3915                    let pop_up_weak = pop_up.downgrade();
3916
3917                    cx.observe_window_activation(window, move |_, window, cx| {
3918                        if window.is_window_active()
3919                            && let Some(pop_up) = pop_up_weak.upgrade()
3920                        {
3921                            pop_up.update(cx, |_, cx| {
3922                                cx.emit(AgentNotificationEvent::Dismissed);
3923                            });
3924                        }
3925                    })
3926                });
3927        }
3928    }
3929
3930    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3931        for window in self.notifications.drain(..) {
3932            window
3933                .update(cx, |_, window, _| {
3934                    window.remove_window();
3935                })
3936                .ok();
3937
3938            self.notification_subscriptions.remove(&window);
3939        }
3940    }
3941
3942    fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3943        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3944            .shape(ui::IconButtonShape::Square)
3945            .icon_size(IconSize::Small)
3946            .icon_color(Color::Ignored)
3947            .tooltip(Tooltip::text("Open Thread as Markdown"))
3948            .on_click(cx.listener(move |this, _, window, cx| {
3949                if let Some(workspace) = this.workspace.upgrade() {
3950                    this.open_thread_as_markdown(workspace, window, cx)
3951                        .detach_and_log_err(cx);
3952                }
3953            }));
3954
3955        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3956            .shape(ui::IconButtonShape::Square)
3957            .icon_size(IconSize::Small)
3958            .icon_color(Color::Ignored)
3959            .tooltip(Tooltip::text("Scroll To Top"))
3960            .on_click(cx.listener(move |this, _, _, cx| {
3961                this.scroll_to_top(cx);
3962            }));
3963
3964        let mut container = h_flex()
3965            .id("thread-controls-container")
3966            .group("thread-controls-container")
3967            .w_full()
3968            .mr_1()
3969            .pb_2()
3970            .px(RESPONSE_PADDING_X)
3971            .opacity(0.4)
3972            .hover(|style| style.opacity(1.))
3973            .flex_wrap()
3974            .justify_end();
3975
3976        if AgentSettings::get_global(cx).enable_feedback
3977            && self
3978                .thread()
3979                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
3980        {
3981            let feedback = self.thread_feedback.feedback;
3982            container = container.child(
3983                div().visible_on_hover("thread-controls-container").child(
3984                    Label::new(
3985                        match feedback {
3986                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
3987                            Some(ThreadFeedback::Negative) => "We appreciate your feedback and will use it to improve.",
3988                            None => "Rating the thread sends all of your current conversation to the Zed team.",
3989                        }
3990                    )
3991                    .color(Color::Muted)
3992                    .size(LabelSize::XSmall)
3993                    .truncate(),
3994                ),
3995            ).child(
3996                h_flex()
3997                    .child(
3998                        IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
3999                            .shape(ui::IconButtonShape::Square)
4000                            .icon_size(IconSize::Small)
4001                            .icon_color(match feedback {
4002                                Some(ThreadFeedback::Positive) => Color::Accent,
4003                                _ => Color::Ignored,
4004                            })
4005                            .tooltip(Tooltip::text("Helpful Response"))
4006                            .on_click(cx.listener(move |this, _, window, cx| {
4007                                this.handle_feedback_click(
4008                                    ThreadFeedback::Positive,
4009                                    window,
4010                                    cx,
4011                                );
4012                            })),
4013                    )
4014                    .child(
4015                        IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4016                            .shape(ui::IconButtonShape::Square)
4017                            .icon_size(IconSize::Small)
4018                            .icon_color(match feedback {
4019                                Some(ThreadFeedback::Negative) => Color::Accent,
4020                                _ => Color::Ignored,
4021                            })
4022                            .tooltip(Tooltip::text("Not Helpful"))
4023                            .on_click(cx.listener(move |this, _, window, cx| {
4024                                this.handle_feedback_click(
4025                                    ThreadFeedback::Negative,
4026                                    window,
4027                                    cx,
4028                                );
4029                            })),
4030                    )
4031            )
4032        }
4033
4034        container.child(open_as_markdown).child(scroll_to_top)
4035    }
4036
4037    fn render_feedback_feedback_editor(
4038        editor: Entity<Editor>,
4039        window: &mut Window,
4040        cx: &Context<Self>,
4041    ) -> Div {
4042        let focus_handle = editor.focus_handle(cx);
4043        v_flex()
4044            .key_context("AgentFeedbackMessageEditor")
4045            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4046                this.thread_feedback.dismiss_comments();
4047                cx.notify();
4048            }))
4049            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4050                this.submit_feedback_message(cx);
4051            }))
4052            .mb_2()
4053            .mx_4()
4054            .p_2()
4055            .rounded_md()
4056            .border_1()
4057            .border_color(cx.theme().colors().border)
4058            .bg(cx.theme().colors().editor_background)
4059            .child(editor)
4060            .child(
4061                h_flex()
4062                    .gap_1()
4063                    .justify_end()
4064                    .child(
4065                        Button::new("dismiss-feedback-message", "Cancel")
4066                            .label_size(LabelSize::Small)
4067                            .key_binding(
4068                                KeyBinding::for_action_in(&menu::Cancel, &focus_handle, window, cx)
4069                                    .map(|kb| kb.size(rems_from_px(10.))),
4070                            )
4071                            .on_click(cx.listener(move |this, _, _window, cx| {
4072                                this.thread_feedback.dismiss_comments();
4073                                cx.notify();
4074                            })),
4075                    )
4076                    .child(
4077                        Button::new("submit-feedback-message", "Share Feedback")
4078                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4079                            .label_size(LabelSize::Small)
4080                            .key_binding(
4081                                KeyBinding::for_action_in(
4082                                    &menu::Confirm,
4083                                    &focus_handle,
4084                                    window,
4085                                    cx,
4086                                )
4087                                .map(|kb| kb.size(rems_from_px(10.))),
4088                            )
4089                            .on_click(cx.listener(move |this, _, _window, cx| {
4090                                this.submit_feedback_message(cx);
4091                            })),
4092                    ),
4093            )
4094    }
4095
4096    fn handle_feedback_click(
4097        &mut self,
4098        feedback: ThreadFeedback,
4099        window: &mut Window,
4100        cx: &mut Context<Self>,
4101    ) {
4102        let Some(thread) = self.thread().cloned() else {
4103            return;
4104        };
4105
4106        self.thread_feedback.submit(thread, feedback, window, cx);
4107        cx.notify();
4108    }
4109
4110    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4111        let Some(thread) = self.thread().cloned() else {
4112            return;
4113        };
4114
4115        self.thread_feedback.submit_comments(thread, cx);
4116        cx.notify();
4117    }
4118
4119    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4120        div()
4121            .id("acp-thread-scrollbar")
4122            .occlude()
4123            .on_mouse_move(cx.listener(|_, _, _, cx| {
4124                cx.notify();
4125                cx.stop_propagation()
4126            }))
4127            .on_hover(|_, _, cx| {
4128                cx.stop_propagation();
4129            })
4130            .on_any_mouse_down(|_, _, cx| {
4131                cx.stop_propagation();
4132            })
4133            .on_mouse_up(
4134                MouseButton::Left,
4135                cx.listener(|_, _, _, cx| {
4136                    cx.stop_propagation();
4137                }),
4138            )
4139            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4140                cx.notify();
4141            }))
4142            .h_full()
4143            .absolute()
4144            .right_1()
4145            .top_1()
4146            .bottom_0()
4147            .w(px(12.))
4148            .cursor_default()
4149            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4150    }
4151
4152    fn render_token_limit_callout(
4153        &self,
4154        line_height: Pixels,
4155        cx: &mut Context<Self>,
4156    ) -> Option<Callout> {
4157        let token_usage = self.thread()?.read(cx).token_usage()?;
4158        let ratio = token_usage.ratio();
4159
4160        let (severity, title) = match ratio {
4161            acp_thread::TokenUsageRatio::Normal => return None,
4162            acp_thread::TokenUsageRatio::Warning => {
4163                (Severity::Warning, "Thread reaching the token limit soon")
4164            }
4165            acp_thread::TokenUsageRatio::Exceeded => {
4166                (Severity::Error, "Thread reached the token limit")
4167            }
4168        };
4169
4170        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4171            thread.read(cx).completion_mode() == CompletionMode::Normal
4172                && thread
4173                    .read(cx)
4174                    .model()
4175                    .is_some_and(|model| model.supports_burn_mode())
4176        });
4177
4178        let description = if burn_mode_available {
4179            "To continue, start a new thread from a summary or turn Burn Mode on."
4180        } else {
4181            "To continue, start a new thread from a summary."
4182        };
4183
4184        Some(
4185            Callout::new()
4186                .severity(severity)
4187                .line_height(line_height)
4188                .title(title)
4189                .description(description)
4190                .actions_slot(
4191                    h_flex()
4192                        .gap_0p5()
4193                        .child(
4194                            Button::new("start-new-thread", "Start New Thread")
4195                                .label_size(LabelSize::Small)
4196                                .on_click(cx.listener(|this, _, window, cx| {
4197                                    let Some(thread) = this.thread() else {
4198                                        return;
4199                                    };
4200                                    let session_id = thread.read(cx).session_id().clone();
4201                                    window.dispatch_action(
4202                                        crate::NewNativeAgentThreadFromSummary {
4203                                            from_session_id: session_id,
4204                                        }
4205                                        .boxed_clone(),
4206                                        cx,
4207                                    );
4208                                })),
4209                        )
4210                        .when(burn_mode_available, |this| {
4211                            this.child(
4212                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4213                                    .icon_size(IconSize::XSmall)
4214                                    .on_click(cx.listener(|this, _event, window, cx| {
4215                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4216                                    })),
4217                            )
4218                        }),
4219                ),
4220        )
4221    }
4222
4223    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4224        if !self.is_using_zed_ai_models(cx) {
4225            return None;
4226        }
4227
4228        let user_store = self.project.read(cx).user_store().read(cx);
4229        if user_store.is_usage_based_billing_enabled() {
4230            return None;
4231        }
4232
4233        let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4234
4235        let usage = user_store.model_request_usage()?;
4236
4237        Some(
4238            div()
4239                .child(UsageCallout::new(plan, usage))
4240                .line_height(line_height),
4241        )
4242    }
4243
4244    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4245        self.entry_view_state.update(cx, |entry_view_state, cx| {
4246            entry_view_state.settings_changed(cx);
4247        });
4248    }
4249
4250    pub(crate) fn insert_dragged_files(
4251        &self,
4252        paths: Vec<project::ProjectPath>,
4253        added_worktrees: Vec<Entity<project::Worktree>>,
4254        window: &mut Window,
4255        cx: &mut Context<Self>,
4256    ) {
4257        self.message_editor.update(cx, |message_editor, cx| {
4258            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4259        })
4260    }
4261
4262    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4263        self.message_editor.update(cx, |message_editor, cx| {
4264            message_editor.insert_selections(window, cx);
4265        })
4266    }
4267
4268    fn render_thread_retry_status_callout(
4269        &self,
4270        _window: &mut Window,
4271        _cx: &mut Context<Self>,
4272    ) -> Option<Callout> {
4273        let state = self.thread_retry_status.as_ref()?;
4274
4275        let next_attempt_in = state
4276            .duration
4277            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4278        if next_attempt_in.is_zero() {
4279            return None;
4280        }
4281
4282        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4283
4284        let retry_message = if state.max_attempts == 1 {
4285            if next_attempt_in_secs == 1 {
4286                "Retrying. Next attempt in 1 second.".to_string()
4287            } else {
4288                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4289            }
4290        } else if next_attempt_in_secs == 1 {
4291            format!(
4292                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4293                state.attempt, state.max_attempts,
4294            )
4295        } else {
4296            format!(
4297                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4298                state.attempt, state.max_attempts,
4299            )
4300        };
4301
4302        Some(
4303            Callout::new()
4304                .severity(Severity::Warning)
4305                .title(state.last_error.clone())
4306                .description(retry_message),
4307        )
4308    }
4309
4310    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4311        let content = match self.thread_error.as_ref()? {
4312            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4313            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4314            ThreadError::ModelRequestLimitReached(plan) => {
4315                self.render_model_request_limit_reached_error(*plan, cx)
4316            }
4317            ThreadError::ToolUseLimitReached => {
4318                self.render_tool_use_limit_reached_error(window, cx)?
4319            }
4320        };
4321
4322        Some(div().child(content))
4323    }
4324
4325    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4326        Callout::new()
4327            .severity(Severity::Error)
4328            .title("Error")
4329            .description(error.clone())
4330            .actions_slot(self.create_copy_button(error.to_string()))
4331            .dismiss_action(self.dismiss_error_button(cx))
4332    }
4333
4334    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4335        const ERROR_MESSAGE: &str =
4336            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4337
4338        Callout::new()
4339            .severity(Severity::Error)
4340            .title("Free Usage Exceeded")
4341            .description(ERROR_MESSAGE)
4342            .actions_slot(
4343                h_flex()
4344                    .gap_0p5()
4345                    .child(self.upgrade_button(cx))
4346                    .child(self.create_copy_button(ERROR_MESSAGE)),
4347            )
4348            .dismiss_action(self.dismiss_error_button(cx))
4349    }
4350
4351    fn render_model_request_limit_reached_error(
4352        &self,
4353        plan: cloud_llm_client::Plan,
4354        cx: &mut Context<Self>,
4355    ) -> Callout {
4356        let error_message = match plan {
4357            cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4358            cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4359                "Upgrade to Zed Pro for more prompts."
4360            }
4361        };
4362
4363        Callout::new()
4364            .severity(Severity::Error)
4365            .title("Model Prompt Limit Reached")
4366            .description(error_message)
4367            .actions_slot(
4368                h_flex()
4369                    .gap_0p5()
4370                    .child(self.upgrade_button(cx))
4371                    .child(self.create_copy_button(error_message)),
4372            )
4373            .dismiss_action(self.dismiss_error_button(cx))
4374    }
4375
4376    fn render_tool_use_limit_reached_error(
4377        &self,
4378        window: &mut Window,
4379        cx: &mut Context<Self>,
4380    ) -> Option<Callout> {
4381        let thread = self.as_native_thread(cx)?;
4382        let supports_burn_mode = thread
4383            .read(cx)
4384            .model()
4385            .is_some_and(|model| model.supports_burn_mode());
4386
4387        let focus_handle = self.focus_handle(cx);
4388
4389        Some(
4390            Callout::new()
4391                .icon(IconName::Info)
4392                .title("Consecutive tool use limit reached.")
4393                .actions_slot(
4394                    h_flex()
4395                        .gap_0p5()
4396                        .when(supports_burn_mode, |this| {
4397                            this.child(
4398                                Button::new("continue-burn-mode", "Continue with Burn Mode")
4399                                    .style(ButtonStyle::Filled)
4400                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4401                                    .layer(ElevationIndex::ModalSurface)
4402                                    .label_size(LabelSize::Small)
4403                                    .key_binding(
4404                                        KeyBinding::for_action_in(
4405                                            &ContinueWithBurnMode,
4406                                            &focus_handle,
4407                                            window,
4408                                            cx,
4409                                        )
4410                                        .map(|kb| kb.size(rems_from_px(10.))),
4411                                    )
4412                                    .tooltip(Tooltip::text(
4413                                        "Enable Burn Mode for unlimited tool use.",
4414                                    ))
4415                                    .on_click({
4416                                        cx.listener(move |this, _, _window, cx| {
4417                                            thread.update(cx, |thread, cx| {
4418                                                thread
4419                                                    .set_completion_mode(CompletionMode::Burn, cx);
4420                                            });
4421                                            this.resume_chat(cx);
4422                                        })
4423                                    }),
4424                            )
4425                        })
4426                        .child(
4427                            Button::new("continue-conversation", "Continue")
4428                                .layer(ElevationIndex::ModalSurface)
4429                                .label_size(LabelSize::Small)
4430                                .key_binding(
4431                                    KeyBinding::for_action_in(
4432                                        &ContinueThread,
4433                                        &focus_handle,
4434                                        window,
4435                                        cx,
4436                                    )
4437                                    .map(|kb| kb.size(rems_from_px(10.))),
4438                                )
4439                                .on_click(cx.listener(|this, _, _window, cx| {
4440                                    this.resume_chat(cx);
4441                                })),
4442                        ),
4443                ),
4444        )
4445    }
4446
4447    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4448        let message = message.into();
4449
4450        IconButton::new("copy", IconName::Copy)
4451            .icon_size(IconSize::Small)
4452            .icon_color(Color::Muted)
4453            .tooltip(Tooltip::text("Copy Error Message"))
4454            .on_click(move |_, _, cx| {
4455                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4456            })
4457    }
4458
4459    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4460        IconButton::new("dismiss", IconName::Close)
4461            .icon_size(IconSize::Small)
4462            .icon_color(Color::Muted)
4463            .tooltip(Tooltip::text("Dismiss Error"))
4464            .on_click(cx.listener({
4465                move |this, _, _, cx| {
4466                    this.clear_thread_error(cx);
4467                    cx.notify();
4468                }
4469            }))
4470    }
4471
4472    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4473        Button::new("upgrade", "Upgrade")
4474            .label_size(LabelSize::Small)
4475            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4476            .on_click(cx.listener({
4477                move |this, _, _, cx| {
4478                    this.clear_thread_error(cx);
4479                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4480                }
4481            }))
4482    }
4483
4484    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4485        self.thread_state = Self::initial_state(
4486            self.agent.clone(),
4487            None,
4488            self.workspace.clone(),
4489            self.project.clone(),
4490            window,
4491            cx,
4492        );
4493        cx.notify();
4494    }
4495
4496    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4497        let task = match entry {
4498            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4499                history.delete_thread(thread.id.clone(), cx)
4500            }),
4501            HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4502                history.delete_text_thread(context.path.clone(), cx)
4503            }),
4504        };
4505        task.detach_and_log_err(cx);
4506    }
4507}
4508
4509impl Focusable for AcpThreadView {
4510    fn focus_handle(&self, cx: &App) -> FocusHandle {
4511        self.message_editor.focus_handle(cx)
4512    }
4513}
4514
4515impl Render for AcpThreadView {
4516    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4517        let has_messages = self.list_state.item_count() > 0;
4518        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4519
4520        v_flex()
4521            .size_full()
4522            .key_context("AcpThread")
4523            .on_action(cx.listener(Self::open_agent_diff))
4524            .on_action(cx.listener(Self::toggle_burn_mode))
4525            .on_action(cx.listener(Self::keep_all))
4526            .on_action(cx.listener(Self::reject_all))
4527            .bg(cx.theme().colors().panel_background)
4528            .child(match &self.thread_state {
4529                ThreadState::Unauthenticated {
4530                    connection,
4531                    description,
4532                    configuration_view,
4533                    pending_auth_method,
4534                    ..
4535                } => self.render_auth_required_state(
4536                    connection,
4537                    description.as_ref(),
4538                    configuration_view.as_ref(),
4539                    pending_auth_method.as_ref(),
4540                    window,
4541                    cx,
4542                ),
4543                ThreadState::Loading { .. } => {
4544                    v_flex().flex_1().child(self.render_empty_state(window, cx))
4545                }
4546                ThreadState::LoadError(e) => v_flex()
4547                    .p_2()
4548                    .flex_1()
4549                    .items_center()
4550                    .justify_center()
4551                    .child(self.render_load_error(e, cx)),
4552                ThreadState::Ready { thread, .. } => {
4553                    let thread_clone = thread.clone();
4554
4555                    v_flex().flex_1().map(|this| {
4556                        if has_messages {
4557                            this.child(
4558                                list(
4559                                    self.list_state.clone(),
4560                                    cx.processor(|this, index: usize, window, cx| {
4561                                        let Some((entry, len)) = this.thread().and_then(|thread| {
4562                                            let entries = &thread.read(cx).entries();
4563                                            Some((entries.get(index)?, entries.len()))
4564                                        }) else {
4565                                            return Empty.into_any();
4566                                        };
4567                                        this.render_entry(index, len, entry, window, cx)
4568                                    }),
4569                                )
4570                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4571                                .flex_grow()
4572                                .into_any(),
4573                            )
4574                            .child(self.render_vertical_scrollbar(cx))
4575                            .children(
4576                                match thread_clone.read(cx).status() {
4577                                    ThreadStatus::Idle
4578                                    | ThreadStatus::WaitingForToolConfirmation => None,
4579                                    ThreadStatus::Generating => div()
4580                                        .px_5()
4581                                        .py_2()
4582                                        .child(LoadingLabel::new("").size(LabelSize::Small))
4583                                        .into(),
4584                                },
4585                            )
4586                        } else {
4587                            this.child(self.render_empty_state(window, cx))
4588                        }
4589                    })
4590                }
4591            })
4592            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4593            // above so that the scrollbar doesn't render behind it. The current setup allows
4594            // the scrollbar to stop exactly at the activity bar start.
4595            .when(has_messages, |this| match &self.thread_state {
4596                ThreadState::Ready { thread, .. } => {
4597                    this.children(self.render_activity_bar(thread, window, cx))
4598                }
4599                _ => this,
4600            })
4601            .children(self.render_thread_retry_status_callout(window, cx))
4602            .children(self.render_thread_error(window, cx))
4603            .children(
4604                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4605                    Some(usage_callout.into_any_element())
4606                } else {
4607                    self.render_token_limit_callout(line_height, cx)
4608                        .map(|token_limit_callout| token_limit_callout.into_any_element())
4609                },
4610            )
4611            .child(self.render_message_editor(window, cx))
4612    }
4613}
4614
4615fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
4616    let theme_settings = ThemeSettings::get_global(cx);
4617    let colors = cx.theme().colors();
4618
4619    let buffer_font_size = TextSize::Small.rems(cx);
4620
4621    let mut text_style = window.text_style();
4622    let line_height = buffer_font_size * 1.75;
4623
4624    let font_family = if buffer_font {
4625        theme_settings.buffer_font.family.clone()
4626    } else {
4627        theme_settings.ui_font.family.clone()
4628    };
4629
4630    let font_size = if buffer_font {
4631        TextSize::Small.rems(cx)
4632    } else {
4633        TextSize::Default.rems(cx)
4634    };
4635
4636    text_style.refine(&TextStyleRefinement {
4637        font_family: Some(font_family),
4638        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
4639        font_features: Some(theme_settings.ui_font.features.clone()),
4640        font_size: Some(font_size.into()),
4641        line_height: Some(line_height.into()),
4642        color: Some(cx.theme().colors().text),
4643        ..Default::default()
4644    });
4645
4646    MarkdownStyle {
4647        base_text_style: text_style.clone(),
4648        syntax: cx.theme().syntax().clone(),
4649        selection_background_color: cx.theme().colors().element_selection_background,
4650        code_block_overflow_x_scroll: true,
4651        table_overflow_x_scroll: true,
4652        heading_level_styles: Some(HeadingLevelStyles {
4653            h1: Some(TextStyleRefinement {
4654                font_size: Some(rems(1.15).into()),
4655                ..Default::default()
4656            }),
4657            h2: Some(TextStyleRefinement {
4658                font_size: Some(rems(1.1).into()),
4659                ..Default::default()
4660            }),
4661            h3: Some(TextStyleRefinement {
4662                font_size: Some(rems(1.05).into()),
4663                ..Default::default()
4664            }),
4665            h4: Some(TextStyleRefinement {
4666                font_size: Some(rems(1.).into()),
4667                ..Default::default()
4668            }),
4669            h5: Some(TextStyleRefinement {
4670                font_size: Some(rems(0.95).into()),
4671                ..Default::default()
4672            }),
4673            h6: Some(TextStyleRefinement {
4674                font_size: Some(rems(0.875).into()),
4675                ..Default::default()
4676            }),
4677        }),
4678        code_block: StyleRefinement {
4679            padding: EdgesRefinement {
4680                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4681                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4682                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4683                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4684            },
4685            margin: EdgesRefinement {
4686                top: Some(Length::Definite(Pixels(8.).into())),
4687                left: Some(Length::Definite(Pixels(0.).into())),
4688                right: Some(Length::Definite(Pixels(0.).into())),
4689                bottom: Some(Length::Definite(Pixels(12.).into())),
4690            },
4691            border_style: Some(BorderStyle::Solid),
4692            border_widths: EdgesRefinement {
4693                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
4694                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
4695                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
4696                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
4697            },
4698            border_color: Some(colors.border_variant),
4699            background: Some(colors.editor_background.into()),
4700            text: Some(TextStyleRefinement {
4701                font_family: Some(theme_settings.buffer_font.family.clone()),
4702                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4703                font_features: Some(theme_settings.buffer_font.features.clone()),
4704                font_size: Some(buffer_font_size.into()),
4705                ..Default::default()
4706            }),
4707            ..Default::default()
4708        },
4709        inline_code: TextStyleRefinement {
4710            font_family: Some(theme_settings.buffer_font.family.clone()),
4711            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4712            font_features: Some(theme_settings.buffer_font.features.clone()),
4713            font_size: Some(buffer_font_size.into()),
4714            background_color: Some(colors.editor_foreground.opacity(0.08)),
4715            ..Default::default()
4716        },
4717        link: TextStyleRefinement {
4718            background_color: Some(colors.editor_foreground.opacity(0.025)),
4719            underline: Some(UnderlineStyle {
4720                color: Some(colors.text_accent.opacity(0.5)),
4721                thickness: px(1.),
4722                ..Default::default()
4723            }),
4724            ..Default::default()
4725        },
4726        ..Default::default()
4727    }
4728}
4729
4730fn plan_label_markdown_style(
4731    status: &acp::PlanEntryStatus,
4732    window: &Window,
4733    cx: &App,
4734) -> MarkdownStyle {
4735    let default_md_style = default_markdown_style(false, window, cx);
4736
4737    MarkdownStyle {
4738        base_text_style: TextStyle {
4739            color: cx.theme().colors().text_muted,
4740            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
4741                Some(gpui::StrikethroughStyle {
4742                    thickness: px(1.),
4743                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
4744                })
4745            } else {
4746                None
4747            },
4748            ..default_md_style.base_text_style
4749        },
4750        ..default_md_style
4751    }
4752}
4753
4754fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
4755    let default_md_style = default_markdown_style(true, window, cx);
4756
4757    MarkdownStyle {
4758        base_text_style: TextStyle {
4759            ..default_md_style.base_text_style
4760        },
4761        selection_background_color: cx.theme().colors().element_selection_background,
4762        ..Default::default()
4763    }
4764}
4765
4766#[cfg(test)]
4767pub(crate) mod tests {
4768    use acp_thread::StubAgentConnection;
4769    use agent_client_protocol::SessionId;
4770    use assistant_context::ContextStore;
4771    use editor::EditorSettings;
4772    use fs::FakeFs;
4773    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
4774    use project::Project;
4775    use serde_json::json;
4776    use settings::SettingsStore;
4777    use std::any::Any;
4778    use std::path::Path;
4779    use workspace::Item;
4780
4781    use super::*;
4782
4783    #[gpui::test]
4784    async fn test_drop(cx: &mut TestAppContext) {
4785        init_test(cx);
4786
4787        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4788        let weak_view = thread_view.downgrade();
4789        drop(thread_view);
4790        assert!(!weak_view.is_upgradable());
4791    }
4792
4793    #[gpui::test]
4794    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
4795        init_test(cx);
4796
4797        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4798
4799        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4800        message_editor.update_in(cx, |editor, window, cx| {
4801            editor.set_text("Hello", window, cx);
4802        });
4803
4804        cx.deactivate_window();
4805
4806        thread_view.update_in(cx, |thread_view, window, cx| {
4807            thread_view.send(window, cx);
4808        });
4809
4810        cx.run_until_parked();
4811
4812        assert!(
4813            cx.windows()
4814                .iter()
4815                .any(|window| window.downcast::<AgentNotification>().is_some())
4816        );
4817    }
4818
4819    #[gpui::test]
4820    async fn test_notification_for_error(cx: &mut TestAppContext) {
4821        init_test(cx);
4822
4823        let (thread_view, cx) =
4824            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
4825
4826        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4827        message_editor.update_in(cx, |editor, window, cx| {
4828            editor.set_text("Hello", window, cx);
4829        });
4830
4831        cx.deactivate_window();
4832
4833        thread_view.update_in(cx, |thread_view, window, cx| {
4834            thread_view.send(window, cx);
4835        });
4836
4837        cx.run_until_parked();
4838
4839        assert!(
4840            cx.windows()
4841                .iter()
4842                .any(|window| window.downcast::<AgentNotification>().is_some())
4843        );
4844    }
4845
4846    #[gpui::test]
4847    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
4848        init_test(cx);
4849
4850        let tool_call_id = acp::ToolCallId("1".into());
4851        let tool_call = acp::ToolCall {
4852            id: tool_call_id.clone(),
4853            title: "Label".into(),
4854            kind: acp::ToolKind::Edit,
4855            status: acp::ToolCallStatus::Pending,
4856            content: vec!["hi".into()],
4857            locations: vec![],
4858            raw_input: None,
4859            raw_output: None,
4860        };
4861        let connection =
4862            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4863                tool_call_id,
4864                vec![acp::PermissionOption {
4865                    id: acp::PermissionOptionId("1".into()),
4866                    name: "Allow".into(),
4867                    kind: acp::PermissionOptionKind::AllowOnce,
4868                }],
4869            )]));
4870
4871        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4872
4873        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4874
4875        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4876        message_editor.update_in(cx, |editor, window, cx| {
4877            editor.set_text("Hello", window, cx);
4878        });
4879
4880        cx.deactivate_window();
4881
4882        thread_view.update_in(cx, |thread_view, window, cx| {
4883            thread_view.send(window, cx);
4884        });
4885
4886        cx.run_until_parked();
4887
4888        assert!(
4889            cx.windows()
4890                .iter()
4891                .any(|window| window.downcast::<AgentNotification>().is_some())
4892        );
4893    }
4894
4895    async fn setup_thread_view(
4896        agent: impl AgentServer + 'static,
4897        cx: &mut TestAppContext,
4898    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4899        let fs = FakeFs::new(cx.executor());
4900        let project = Project::test(fs, [], cx).await;
4901        let (workspace, cx) =
4902            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4903
4904        let context_store =
4905            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4906        let history_store =
4907            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4908
4909        let thread_view = cx.update(|window, cx| {
4910            cx.new(|cx| {
4911                AcpThreadView::new(
4912                    Rc::new(agent),
4913                    None,
4914                    None,
4915                    workspace.downgrade(),
4916                    project,
4917                    history_store,
4918                    None,
4919                    window,
4920                    cx,
4921                )
4922            })
4923        });
4924        cx.run_until_parked();
4925        (thread_view, cx)
4926    }
4927
4928    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4929        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4930
4931        workspace
4932            .update_in(cx, |workspace, window, cx| {
4933                workspace.add_item_to_active_pane(
4934                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4935                    None,
4936                    true,
4937                    window,
4938                    cx,
4939                );
4940            })
4941            .unwrap();
4942    }
4943
4944    struct ThreadViewItem(Entity<AcpThreadView>);
4945
4946    impl Item for ThreadViewItem {
4947        type Event = ();
4948
4949        fn include_in_nav_history() -> bool {
4950            false
4951        }
4952
4953        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
4954            "Test".into()
4955        }
4956    }
4957
4958    impl EventEmitter<()> for ThreadViewItem {}
4959
4960    impl Focusable for ThreadViewItem {
4961        fn focus_handle(&self, cx: &App) -> FocusHandle {
4962            self.0.read(cx).focus_handle(cx)
4963        }
4964    }
4965
4966    impl Render for ThreadViewItem {
4967        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4968            self.0.clone().into_any_element()
4969        }
4970    }
4971
4972    struct StubAgentServer<C> {
4973        connection: C,
4974    }
4975
4976    impl<C> StubAgentServer<C> {
4977        fn new(connection: C) -> Self {
4978            Self { connection }
4979        }
4980    }
4981
4982    impl StubAgentServer<StubAgentConnection> {
4983        fn default_response() -> Self {
4984            let conn = StubAgentConnection::new();
4985            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4986                content: "Default response".into(),
4987            }]);
4988            Self::new(conn)
4989        }
4990    }
4991
4992    impl<C> AgentServer for StubAgentServer<C>
4993    where
4994        C: 'static + AgentConnection + Send + Clone,
4995    {
4996        fn logo(&self) -> ui::IconName {
4997            ui::IconName::Ai
4998        }
4999
5000        fn name(&self) -> &'static str {
5001            "Test"
5002        }
5003
5004        fn empty_state_headline(&self) -> &'static str {
5005            "Test"
5006        }
5007
5008        fn empty_state_message(&self) -> &'static str {
5009            "Test"
5010        }
5011
5012        fn connect(
5013            &self,
5014            _root_dir: &Path,
5015            _project: &Entity<Project>,
5016            _cx: &mut App,
5017        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5018            Task::ready(Ok(Rc::new(self.connection.clone())))
5019        }
5020
5021        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5022            self
5023        }
5024    }
5025
5026    #[derive(Clone)]
5027    struct SaboteurAgentConnection;
5028
5029    impl AgentConnection for SaboteurAgentConnection {
5030        fn new_thread(
5031            self: Rc<Self>,
5032            project: Entity<Project>,
5033            _cwd: &Path,
5034            cx: &mut gpui::App,
5035        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5036            Task::ready(Ok(cx.new(|cx| {
5037                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5038                AcpThread::new(
5039                    "SaboteurAgentConnection",
5040                    self,
5041                    project,
5042                    action_log,
5043                    SessionId("test".into()),
5044                )
5045            })))
5046        }
5047
5048        fn auth_methods(&self) -> &[acp::AuthMethod] {
5049            &[]
5050        }
5051
5052        fn prompt_capabilities(&self) -> acp::PromptCapabilities {
5053            acp::PromptCapabilities {
5054                image: true,
5055                audio: true,
5056                embedded_context: true,
5057            }
5058        }
5059
5060        fn authenticate(
5061            &self,
5062            _method_id: acp::AuthMethodId,
5063            _cx: &mut App,
5064        ) -> Task<gpui::Result<()>> {
5065            unimplemented!()
5066        }
5067
5068        fn prompt(
5069            &self,
5070            _id: Option<acp_thread::UserMessageId>,
5071            _params: acp::PromptRequest,
5072            _cx: &mut App,
5073        ) -> Task<gpui::Result<acp::PromptResponse>> {
5074            Task::ready(Err(anyhow::anyhow!("Error prompting")))
5075        }
5076
5077        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5078            unimplemented!()
5079        }
5080
5081        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5082            self
5083        }
5084    }
5085
5086    pub(crate) fn init_test(cx: &mut TestAppContext) {
5087        cx.update(|cx| {
5088            let settings_store = SettingsStore::test(cx);
5089            cx.set_global(settings_store);
5090            language::init(cx);
5091            Project::init_settings(cx);
5092            AgentSettings::register(cx);
5093            workspace::init_settings(cx);
5094            ThemeSettings::register(cx);
5095            release_channel::init(SemanticVersion::default(), cx);
5096            EditorSettings::register(cx);
5097            prompt_store::init(cx)
5098        });
5099    }
5100
5101    #[gpui::test]
5102    async fn test_rewind_views(cx: &mut TestAppContext) {
5103        init_test(cx);
5104
5105        let fs = FakeFs::new(cx.executor());
5106        fs.insert_tree(
5107            "/project",
5108            json!({
5109                "test1.txt": "old content 1",
5110                "test2.txt": "old content 2"
5111            }),
5112        )
5113        .await;
5114        let project = Project::test(fs, [Path::new("/project")], cx).await;
5115        let (workspace, cx) =
5116            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5117
5118        let context_store =
5119            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5120        let history_store =
5121            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5122
5123        let connection = Rc::new(StubAgentConnection::new());
5124        let thread_view = cx.update(|window, cx| {
5125            cx.new(|cx| {
5126                AcpThreadView::new(
5127                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5128                    None,
5129                    None,
5130                    workspace.downgrade(),
5131                    project.clone(),
5132                    history_store.clone(),
5133                    None,
5134                    window,
5135                    cx,
5136                )
5137            })
5138        });
5139
5140        cx.run_until_parked();
5141
5142        let thread = thread_view
5143            .read_with(cx, |view, _| view.thread().cloned())
5144            .unwrap();
5145
5146        // First user message
5147        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5148            id: acp::ToolCallId("tool1".into()),
5149            title: "Edit file 1".into(),
5150            kind: acp::ToolKind::Edit,
5151            status: acp::ToolCallStatus::Completed,
5152            content: vec![acp::ToolCallContent::Diff {
5153                diff: acp::Diff {
5154                    path: "/project/test1.txt".into(),
5155                    old_text: Some("old content 1".into()),
5156                    new_text: "new content 1".into(),
5157                },
5158            }],
5159            locations: vec![],
5160            raw_input: None,
5161            raw_output: None,
5162        })]);
5163
5164        thread
5165            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5166            .await
5167            .unwrap();
5168        cx.run_until_parked();
5169
5170        thread.read_with(cx, |thread, _| {
5171            assert_eq!(thread.entries().len(), 2);
5172        });
5173
5174        thread_view.read_with(cx, |view, cx| {
5175            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5176                assert!(
5177                    entry_view_state
5178                        .entry(0)
5179                        .unwrap()
5180                        .message_editor()
5181                        .is_some()
5182                );
5183                assert!(entry_view_state.entry(1).unwrap().has_content());
5184            });
5185        });
5186
5187        // Second user message
5188        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5189            id: acp::ToolCallId("tool2".into()),
5190            title: "Edit file 2".into(),
5191            kind: acp::ToolKind::Edit,
5192            status: acp::ToolCallStatus::Completed,
5193            content: vec![acp::ToolCallContent::Diff {
5194                diff: acp::Diff {
5195                    path: "/project/test2.txt".into(),
5196                    old_text: Some("old content 2".into()),
5197                    new_text: "new content 2".into(),
5198                },
5199            }],
5200            locations: vec![],
5201            raw_input: None,
5202            raw_output: None,
5203        })]);
5204
5205        thread
5206            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5207            .await
5208            .unwrap();
5209        cx.run_until_parked();
5210
5211        let second_user_message_id = thread.read_with(cx, |thread, _| {
5212            assert_eq!(thread.entries().len(), 4);
5213            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5214                panic!();
5215            };
5216            user_message.id.clone().unwrap()
5217        });
5218
5219        thread_view.read_with(cx, |view, cx| {
5220            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5221                assert!(
5222                    entry_view_state
5223                        .entry(0)
5224                        .unwrap()
5225                        .message_editor()
5226                        .is_some()
5227                );
5228                assert!(entry_view_state.entry(1).unwrap().has_content());
5229                assert!(
5230                    entry_view_state
5231                        .entry(2)
5232                        .unwrap()
5233                        .message_editor()
5234                        .is_some()
5235                );
5236                assert!(entry_view_state.entry(3).unwrap().has_content());
5237            });
5238        });
5239
5240        // Rewind to first message
5241        thread
5242            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5243            .await
5244            .unwrap();
5245
5246        cx.run_until_parked();
5247
5248        thread.read_with(cx, |thread, _| {
5249            assert_eq!(thread.entries().len(), 2);
5250        });
5251
5252        thread_view.read_with(cx, |view, cx| {
5253            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5254                assert!(
5255                    entry_view_state
5256                        .entry(0)
5257                        .unwrap()
5258                        .message_editor()
5259                        .is_some()
5260                );
5261                assert!(entry_view_state.entry(1).unwrap().has_content());
5262
5263                // Old views should be dropped
5264                assert!(entry_view_state.entry(2).is_none());
5265                assert!(entry_view_state.entry(3).is_none());
5266            });
5267        });
5268    }
5269
5270    #[gpui::test]
5271    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5272        init_test(cx);
5273
5274        let connection = StubAgentConnection::new();
5275
5276        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5277            content: acp::ContentBlock::Text(acp::TextContent {
5278                text: "Response".into(),
5279                annotations: None,
5280            }),
5281        }]);
5282
5283        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5284        add_to_workspace(thread_view.clone(), cx);
5285
5286        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5287        message_editor.update_in(cx, |editor, window, cx| {
5288            editor.set_text("Original message to edit", window, cx);
5289        });
5290        thread_view.update_in(cx, |thread_view, window, cx| {
5291            thread_view.send(window, cx);
5292        });
5293
5294        cx.run_until_parked();
5295
5296        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5297            assert_eq!(view.editing_message, None);
5298
5299            view.entry_view_state
5300                .read(cx)
5301                .entry(0)
5302                .unwrap()
5303                .message_editor()
5304                .unwrap()
5305                .clone()
5306        });
5307
5308        // Focus
5309        cx.focus(&user_message_editor);
5310        thread_view.read_with(cx, |view, _cx| {
5311            assert_eq!(view.editing_message, Some(0));
5312        });
5313
5314        // Edit
5315        user_message_editor.update_in(cx, |editor, window, cx| {
5316            editor.set_text("Edited message content", window, cx);
5317        });
5318
5319        // Cancel
5320        user_message_editor.update_in(cx, |_editor, window, cx| {
5321            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5322        });
5323
5324        thread_view.read_with(cx, |view, _cx| {
5325            assert_eq!(view.editing_message, None);
5326        });
5327
5328        user_message_editor.read_with(cx, |editor, cx| {
5329            assert_eq!(editor.text(cx), "Original message to edit");
5330        });
5331    }
5332
5333    #[gpui::test]
5334    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5335        init_test(cx);
5336
5337        let connection = StubAgentConnection::new();
5338
5339        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5340        add_to_workspace(thread_view.clone(), cx);
5341
5342        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5343        let mut events = cx.events(&message_editor);
5344        message_editor.update_in(cx, |editor, window, cx| {
5345            editor.set_text("", window, cx);
5346        });
5347
5348        message_editor.update_in(cx, |_editor, window, cx| {
5349            window.dispatch_action(Box::new(Chat), cx);
5350        });
5351        cx.run_until_parked();
5352        // We shouldn't have received any messages
5353        assert!(matches!(
5354            events.try_next(),
5355            Err(futures::channel::mpsc::TryRecvError { .. })
5356        ));
5357    }
5358
5359    #[gpui::test]
5360    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5361        init_test(cx);
5362
5363        let connection = StubAgentConnection::new();
5364
5365        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5366            content: acp::ContentBlock::Text(acp::TextContent {
5367                text: "Response".into(),
5368                annotations: None,
5369            }),
5370        }]);
5371
5372        let (thread_view, cx) =
5373            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5374        add_to_workspace(thread_view.clone(), cx);
5375
5376        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5377        message_editor.update_in(cx, |editor, window, cx| {
5378            editor.set_text("Original message to edit", window, cx);
5379        });
5380        thread_view.update_in(cx, |thread_view, window, cx| {
5381            thread_view.send(window, cx);
5382        });
5383
5384        cx.run_until_parked();
5385
5386        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5387            assert_eq!(view.editing_message, None);
5388            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5389
5390            view.entry_view_state
5391                .read(cx)
5392                .entry(0)
5393                .unwrap()
5394                .message_editor()
5395                .unwrap()
5396                .clone()
5397        });
5398
5399        // Focus
5400        cx.focus(&user_message_editor);
5401
5402        // Edit
5403        user_message_editor.update_in(cx, |editor, window, cx| {
5404            editor.set_text("Edited message content", window, cx);
5405        });
5406
5407        // Send
5408        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5409            content: acp::ContentBlock::Text(acp::TextContent {
5410                text: "New Response".into(),
5411                annotations: None,
5412            }),
5413        }]);
5414
5415        user_message_editor.update_in(cx, |_editor, window, cx| {
5416            window.dispatch_action(Box::new(Chat), cx);
5417        });
5418
5419        cx.run_until_parked();
5420
5421        thread_view.read_with(cx, |view, cx| {
5422            assert_eq!(view.editing_message, None);
5423
5424            let entries = view.thread().unwrap().read(cx).entries();
5425            assert_eq!(entries.len(), 2);
5426            assert_eq!(
5427                entries[0].to_markdown(cx),
5428                "## User\n\nEdited message content\n\n"
5429            );
5430            assert_eq!(
5431                entries[1].to_markdown(cx),
5432                "## Assistant\n\nNew Response\n\n"
5433            );
5434
5435            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5436                assert!(!state.entry(1).unwrap().has_content());
5437                state.entry(0).unwrap().message_editor().unwrap().clone()
5438            });
5439
5440            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5441        })
5442    }
5443
5444    #[gpui::test]
5445    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5446        init_test(cx);
5447
5448        let connection = StubAgentConnection::new();
5449
5450        let (thread_view, cx) =
5451            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5452        add_to_workspace(thread_view.clone(), cx);
5453
5454        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5455        message_editor.update_in(cx, |editor, window, cx| {
5456            editor.set_text("Original message to edit", window, cx);
5457        });
5458        thread_view.update_in(cx, |thread_view, window, cx| {
5459            thread_view.send(window, cx);
5460        });
5461
5462        cx.run_until_parked();
5463
5464        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5465            let thread = view.thread().unwrap().read(cx);
5466            assert_eq!(thread.entries().len(), 1);
5467
5468            let editor = view
5469                .entry_view_state
5470                .read(cx)
5471                .entry(0)
5472                .unwrap()
5473                .message_editor()
5474                .unwrap()
5475                .clone();
5476
5477            (editor, thread.session_id().clone())
5478        });
5479
5480        // Focus
5481        cx.focus(&user_message_editor);
5482
5483        thread_view.read_with(cx, |view, _cx| {
5484            assert_eq!(view.editing_message, Some(0));
5485        });
5486
5487        // Edit
5488        user_message_editor.update_in(cx, |editor, window, cx| {
5489            editor.set_text("Edited message content", window, cx);
5490        });
5491
5492        thread_view.read_with(cx, |view, _cx| {
5493            assert_eq!(view.editing_message, Some(0));
5494        });
5495
5496        // Finish streaming response
5497        cx.update(|_, cx| {
5498            connection.send_update(
5499                session_id.clone(),
5500                acp::SessionUpdate::AgentMessageChunk {
5501                    content: acp::ContentBlock::Text(acp::TextContent {
5502                        text: "Response".into(),
5503                        annotations: None,
5504                    }),
5505                },
5506                cx,
5507            );
5508            connection.end_turn(session_id, acp::StopReason::EndTurn);
5509        });
5510
5511        thread_view.read_with(cx, |view, _cx| {
5512            assert_eq!(view.editing_message, Some(0));
5513        });
5514
5515        cx.run_until_parked();
5516
5517        // Should still be editing
5518        cx.update(|window, cx| {
5519            assert!(user_message_editor.focus_handle(cx).is_focused(window));
5520            assert_eq!(thread_view.read(cx).editing_message, Some(0));
5521            assert_eq!(
5522                user_message_editor.read(cx).text(cx),
5523                "Edited message content"
5524            );
5525        });
5526    }
5527
5528    #[gpui::test]
5529    async fn test_interrupt(cx: &mut TestAppContext) {
5530        init_test(cx);
5531
5532        let connection = StubAgentConnection::new();
5533
5534        let (thread_view, cx) =
5535            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5536        add_to_workspace(thread_view.clone(), cx);
5537
5538        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5539        message_editor.update_in(cx, |editor, window, cx| {
5540            editor.set_text("Message 1", window, cx);
5541        });
5542        thread_view.update_in(cx, |thread_view, window, cx| {
5543            thread_view.send(window, cx);
5544        });
5545
5546        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5547            let thread = view.thread().unwrap();
5548
5549            (thread.clone(), thread.read(cx).session_id().clone())
5550        });
5551
5552        cx.run_until_parked();
5553
5554        cx.update(|_, cx| {
5555            connection.send_update(
5556                session_id.clone(),
5557                acp::SessionUpdate::AgentMessageChunk {
5558                    content: "Message 1 resp".into(),
5559                },
5560                cx,
5561            );
5562        });
5563
5564        cx.run_until_parked();
5565
5566        thread.read_with(cx, |thread, cx| {
5567            assert_eq!(
5568                thread.to_markdown(cx),
5569                indoc::indoc! {"
5570                    ## User
5571
5572                    Message 1
5573
5574                    ## Assistant
5575
5576                    Message 1 resp
5577
5578                "}
5579            )
5580        });
5581
5582        message_editor.update_in(cx, |editor, window, cx| {
5583            editor.set_text("Message 2", window, cx);
5584        });
5585        thread_view.update_in(cx, |thread_view, window, cx| {
5586            thread_view.send(window, cx);
5587        });
5588
5589        cx.update(|_, cx| {
5590            // Simulate a response sent after beginning to cancel
5591            connection.send_update(
5592                session_id.clone(),
5593                acp::SessionUpdate::AgentMessageChunk {
5594                    content: "onse".into(),
5595                },
5596                cx,
5597            );
5598        });
5599
5600        cx.run_until_parked();
5601
5602        // Last Message 1 response should appear before Message 2
5603        thread.read_with(cx, |thread, cx| {
5604            assert_eq!(
5605                thread.to_markdown(cx),
5606                indoc::indoc! {"
5607                    ## User
5608
5609                    Message 1
5610
5611                    ## Assistant
5612
5613                    Message 1 response
5614
5615                    ## User
5616
5617                    Message 2
5618
5619                "}
5620            )
5621        });
5622
5623        cx.update(|_, cx| {
5624            connection.send_update(
5625                session_id.clone(),
5626                acp::SessionUpdate::AgentMessageChunk {
5627                    content: "Message 2 response".into(),
5628                },
5629                cx,
5630            );
5631            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5632        });
5633
5634        cx.run_until_parked();
5635
5636        thread.read_with(cx, |thread, cx| {
5637            assert_eq!(
5638                thread.to_markdown(cx),
5639                indoc::indoc! {"
5640                    ## User
5641
5642                    Message 1
5643
5644                    ## Assistant
5645
5646                    Message 1 response
5647
5648                    ## User
5649
5650                    Message 2
5651
5652                    ## Assistant
5653
5654                    Message 2 response
5655
5656                "}
5657            )
5658        });
5659    }
5660}