thread_view.rs

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