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