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