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