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