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