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        let pending_edits = thread.has_pending_edit_tool_calls();
3075
3076        v_flex()
3077            .mt_1()
3078            .mx_2()
3079            .bg(bg_edit_files_disclosure)
3080            .border_1()
3081            .border_b_0()
3082            .border_color(cx.theme().colors().border)
3083            .rounded_t_md()
3084            .shadow(vec![gpui::BoxShadow {
3085                color: gpui::black().opacity(0.15),
3086                offset: point(px(1.), px(-1.)),
3087                blur_radius: px(3.),
3088                spread_radius: px(0.),
3089            }])
3090            .when(!plan.is_empty(), |this| {
3091                this.child(self.render_plan_summary(plan, window, cx))
3092                    .when(self.plan_expanded, |parent| {
3093                        parent.child(self.render_plan_entries(plan, window, cx))
3094                    })
3095            })
3096            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3097                this.child(Divider::horizontal().color(DividerColor::Border))
3098            })
3099            .when(!changed_buffers.is_empty(), |this| {
3100                this.child(self.render_edits_summary(
3101                    &changed_buffers,
3102                    self.edits_expanded,
3103                    pending_edits,
3104                    window,
3105                    cx,
3106                ))
3107                .when(self.edits_expanded, |parent| {
3108                    parent.child(self.render_edited_files(
3109                        action_log,
3110                        &changed_buffers,
3111                        pending_edits,
3112                        cx,
3113                    ))
3114                })
3115            })
3116            .into_any()
3117            .into()
3118    }
3119
3120    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3121        let stats = plan.stats();
3122
3123        let title = if let Some(entry) = stats.in_progress_entry
3124            && !self.plan_expanded
3125        {
3126            h_flex()
3127                .w_full()
3128                .cursor_default()
3129                .gap_1()
3130                .text_xs()
3131                .text_color(cx.theme().colors().text_muted)
3132                .justify_between()
3133                .child(
3134                    h_flex()
3135                        .gap_1()
3136                        .child(
3137                            Label::new("Current:")
3138                                .size(LabelSize::Small)
3139                                .color(Color::Muted),
3140                        )
3141                        .child(MarkdownElement::new(
3142                            entry.content.clone(),
3143                            plan_label_markdown_style(&entry.status, window, cx),
3144                        )),
3145                )
3146                .when(stats.pending > 0, |this| {
3147                    this.child(
3148                        Label::new(format!("{} left", stats.pending))
3149                            .size(LabelSize::Small)
3150                            .color(Color::Muted)
3151                            .mr_1(),
3152                    )
3153                })
3154        } else {
3155            let status_label = if stats.pending == 0 {
3156                "All Done".to_string()
3157            } else if stats.completed == 0 {
3158                format!("{} Tasks", plan.entries.len())
3159            } else {
3160                format!("{}/{}", stats.completed, plan.entries.len())
3161            };
3162
3163            h_flex()
3164                .w_full()
3165                .gap_1()
3166                .justify_between()
3167                .child(
3168                    Label::new("Plan")
3169                        .size(LabelSize::Small)
3170                        .color(Color::Muted),
3171                )
3172                .child(
3173                    Label::new(status_label)
3174                        .size(LabelSize::Small)
3175                        .color(Color::Muted)
3176                        .mr_1(),
3177                )
3178        };
3179
3180        h_flex()
3181            .p_1()
3182            .justify_between()
3183            .when(self.plan_expanded, |this| {
3184                this.border_b_1().border_color(cx.theme().colors().border)
3185            })
3186            .child(
3187                h_flex()
3188                    .id("plan_summary")
3189                    .w_full()
3190                    .gap_1()
3191                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3192                    .child(title)
3193                    .on_click(cx.listener(|this, _, _, cx| {
3194                        this.plan_expanded = !this.plan_expanded;
3195                        cx.notify();
3196                    })),
3197            )
3198    }
3199
3200    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3201        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3202            let element = h_flex()
3203                .py_1()
3204                .px_2()
3205                .gap_2()
3206                .justify_between()
3207                .bg(cx.theme().colors().editor_background)
3208                .when(index < plan.entries.len() - 1, |parent| {
3209                    parent.border_color(cx.theme().colors().border).border_b_1()
3210                })
3211                .child(
3212                    h_flex()
3213                        .id(("plan_entry", index))
3214                        .gap_1p5()
3215                        .max_w_full()
3216                        .overflow_x_scroll()
3217                        .text_xs()
3218                        .text_color(cx.theme().colors().text_muted)
3219                        .child(match entry.status {
3220                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3221                                .size(IconSize::Small)
3222                                .color(Color::Muted)
3223                                .into_any_element(),
3224                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3225                                .size(IconSize::Small)
3226                                .color(Color::Accent)
3227                                .with_animation(
3228                                    "running",
3229                                    Animation::new(Duration::from_secs(2)).repeat(),
3230                                    |icon, delta| {
3231                                        icon.transform(Transformation::rotate(percentage(delta)))
3232                                    },
3233                                )
3234                                .into_any_element(),
3235                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3236                                .size(IconSize::Small)
3237                                .color(Color::Success)
3238                                .into_any_element(),
3239                        })
3240                        .child(MarkdownElement::new(
3241                            entry.content.clone(),
3242                            plan_label_markdown_style(&entry.status, window, cx),
3243                        )),
3244                );
3245
3246            Some(element)
3247        }))
3248    }
3249
3250    fn render_edits_summary(
3251        &self,
3252        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3253        expanded: bool,
3254        pending_edits: bool,
3255        window: &mut Window,
3256        cx: &Context<Self>,
3257    ) -> Div {
3258        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3259
3260        let focus_handle = self.focus_handle(cx);
3261
3262        h_flex()
3263            .p_1()
3264            .justify_between()
3265            .flex_wrap()
3266            .when(expanded, |this| {
3267                this.border_b_1().border_color(cx.theme().colors().border)
3268            })
3269            .child(
3270                h_flex()
3271                    .id("edits-container")
3272                    .gap_1()
3273                    .child(Disclosure::new("edits-disclosure", expanded))
3274                    .map(|this| {
3275                        if pending_edits {
3276                            this.child(
3277                                Label::new(format!(
3278                                    "Editing {} {}",
3279                                    changed_buffers.len(),
3280                                    if changed_buffers.len() == 1 {
3281                                        "file"
3282                                    } else {
3283                                        "files"
3284                                    }
3285                                ))
3286                                .color(Color::Muted)
3287                                .size(LabelSize::Small)
3288                                .with_animation(
3289                                    "edit-label",
3290                                    Animation::new(Duration::from_secs(2))
3291                                        .repeat()
3292                                        .with_easing(pulsating_between(0.3, 0.7)),
3293                                    |label, delta| label.alpha(delta),
3294                                ),
3295                            )
3296                        } else {
3297                            this.child(
3298                                Label::new("Edits")
3299                                    .size(LabelSize::Small)
3300                                    .color(Color::Muted),
3301                            )
3302                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
3303                            .child(
3304                                Label::new(format!(
3305                                    "{} {}",
3306                                    changed_buffers.len(),
3307                                    if changed_buffers.len() == 1 {
3308                                        "file"
3309                                    } else {
3310                                        "files"
3311                                    }
3312                                ))
3313                                .size(LabelSize::Small)
3314                                .color(Color::Muted),
3315                            )
3316                        }
3317                    })
3318                    .on_click(cx.listener(|this, _, _, cx| {
3319                        this.edits_expanded = !this.edits_expanded;
3320                        cx.notify();
3321                    })),
3322            )
3323            .child(
3324                h_flex()
3325                    .gap_1()
3326                    .child(
3327                        IconButton::new("review-changes", IconName::ListTodo)
3328                            .icon_size(IconSize::Small)
3329                            .tooltip({
3330                                let focus_handle = focus_handle.clone();
3331                                move |window, cx| {
3332                                    Tooltip::for_action_in(
3333                                        "Review Changes",
3334                                        &OpenAgentDiff,
3335                                        &focus_handle,
3336                                        window,
3337                                        cx,
3338                                    )
3339                                }
3340                            })
3341                            .on_click(cx.listener(|_, _, window, cx| {
3342                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3343                            })),
3344                    )
3345                    .child(Divider::vertical().color(DividerColor::Border))
3346                    .child(
3347                        Button::new("reject-all-changes", "Reject All")
3348                            .label_size(LabelSize::Small)
3349                            .disabled(pending_edits)
3350                            .when(pending_edits, |this| {
3351                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3352                            })
3353                            .key_binding(
3354                                KeyBinding::for_action_in(
3355                                    &RejectAll,
3356                                    &focus_handle.clone(),
3357                                    window,
3358                                    cx,
3359                                )
3360                                .map(|kb| kb.size(rems_from_px(10.))),
3361                            )
3362                            .on_click(cx.listener(move |this, _, window, cx| {
3363                                this.reject_all(&RejectAll, window, cx);
3364                            })),
3365                    )
3366                    .child(
3367                        Button::new("keep-all-changes", "Keep All")
3368                            .label_size(LabelSize::Small)
3369                            .disabled(pending_edits)
3370                            .when(pending_edits, |this| {
3371                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3372                            })
3373                            .key_binding(
3374                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3375                                    .map(|kb| kb.size(rems_from_px(10.))),
3376                            )
3377                            .on_click(cx.listener(move |this, _, window, cx| {
3378                                this.keep_all(&KeepAll, window, cx);
3379                            })),
3380                    ),
3381            )
3382    }
3383
3384    fn render_edited_files(
3385        &self,
3386        action_log: &Entity<ActionLog>,
3387        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3388        pending_edits: bool,
3389        cx: &Context<Self>,
3390    ) -> Div {
3391        let editor_bg_color = cx.theme().colors().editor_background;
3392
3393        v_flex().children(changed_buffers.iter().enumerate().flat_map(
3394            |(index, (buffer, _diff))| {
3395                let file = buffer.read(cx).file()?;
3396                let path = file.path();
3397
3398                let file_path = path.parent().and_then(|parent| {
3399                    let parent_str = parent.to_string_lossy();
3400
3401                    if parent_str.is_empty() {
3402                        None
3403                    } else {
3404                        Some(
3405                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3406                                .color(Color::Muted)
3407                                .size(LabelSize::XSmall)
3408                                .buffer_font(cx),
3409                        )
3410                    }
3411                });
3412
3413                let file_name = path.file_name().map(|name| {
3414                    Label::new(name.to_string_lossy().to_string())
3415                        .size(LabelSize::XSmall)
3416                        .buffer_font(cx)
3417                });
3418
3419                let file_icon = FileIcons::get_icon(path, cx)
3420                    .map(Icon::from_path)
3421                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3422                    .unwrap_or_else(|| {
3423                        Icon::new(IconName::File)
3424                            .color(Color::Muted)
3425                            .size(IconSize::Small)
3426                    });
3427
3428                let overlay_gradient = linear_gradient(
3429                    90.,
3430                    linear_color_stop(editor_bg_color, 1.),
3431                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3432                );
3433
3434                let element = h_flex()
3435                    .group("edited-code")
3436                    .id(("file-container", index))
3437                    .py_1()
3438                    .pl_2()
3439                    .pr_1()
3440                    .gap_2()
3441                    .justify_between()
3442                    .bg(editor_bg_color)
3443                    .when(index < changed_buffers.len() - 1, |parent| {
3444                        parent.border_color(cx.theme().colors().border).border_b_1()
3445                    })
3446                    .child(
3447                        h_flex()
3448                            .relative()
3449                            .id(("file-name", index))
3450                            .pr_8()
3451                            .gap_1p5()
3452                            .max_w_full()
3453                            .overflow_x_scroll()
3454                            .child(file_icon)
3455                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3456                            .child(
3457                                div()
3458                                    .absolute()
3459                                    .h_full()
3460                                    .w_12()
3461                                    .top_0()
3462                                    .bottom_0()
3463                                    .right_0()
3464                                    .bg(overlay_gradient),
3465                            )
3466                            .on_click({
3467                                let buffer = buffer.clone();
3468                                cx.listener(move |this, _, window, cx| {
3469                                    this.open_edited_buffer(&buffer, window, cx);
3470                                })
3471                            }),
3472                    )
3473                    .child(
3474                        h_flex()
3475                            .gap_1()
3476                            .visible_on_hover("edited-code")
3477                            .child(
3478                                Button::new("review", "Review")
3479                                    .label_size(LabelSize::Small)
3480                                    .on_click({
3481                                        let buffer = buffer.clone();
3482                                        cx.listener(move |this, _, window, cx| {
3483                                            this.open_edited_buffer(&buffer, window, cx);
3484                                        })
3485                                    }),
3486                            )
3487                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3488                            .child(
3489                                Button::new("reject-file", "Reject")
3490                                    .label_size(LabelSize::Small)
3491                                    .disabled(pending_edits)
3492                                    .on_click({
3493                                        let buffer = buffer.clone();
3494                                        let action_log = action_log.clone();
3495                                        move |_, _, cx| {
3496                                            action_log.update(cx, |action_log, cx| {
3497                                                action_log
3498                                                    .reject_edits_in_ranges(
3499                                                        buffer.clone(),
3500                                                        vec![Anchor::MIN..Anchor::MAX],
3501                                                        cx,
3502                                                    )
3503                                                    .detach_and_log_err(cx);
3504                                            })
3505                                        }
3506                                    }),
3507                            )
3508                            .child(
3509                                Button::new("keep-file", "Keep")
3510                                    .label_size(LabelSize::Small)
3511                                    .disabled(pending_edits)
3512                                    .on_click({
3513                                        let buffer = buffer.clone();
3514                                        let action_log = action_log.clone();
3515                                        move |_, _, cx| {
3516                                            action_log.update(cx, |action_log, cx| {
3517                                                action_log.keep_edits_in_range(
3518                                                    buffer.clone(),
3519                                                    Anchor::MIN..Anchor::MAX,
3520                                                    cx,
3521                                                );
3522                                            })
3523                                        }
3524                                    }),
3525                            ),
3526                    );
3527
3528                Some(element)
3529            },
3530        ))
3531    }
3532
3533    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3534        let focus_handle = self.message_editor.focus_handle(cx);
3535        let editor_bg_color = cx.theme().colors().editor_background;
3536        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3537            (IconName::Minimize, "Minimize Message Editor")
3538        } else {
3539            (IconName::Maximize, "Expand Message Editor")
3540        };
3541
3542        let backdrop = div()
3543            .size_full()
3544            .absolute()
3545            .inset_0()
3546            .bg(cx.theme().colors().panel_background)
3547            .opacity(0.8)
3548            .block_mouse_except_scroll();
3549
3550        let enable_editor = match self.thread_state {
3551            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3552            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3553        };
3554
3555        v_flex()
3556            .on_action(cx.listener(Self::expand_message_editor))
3557            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3558                if let Some(profile_selector) = this.profile_selector.as_ref() {
3559                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3560                }
3561            }))
3562            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3563                if let Some(model_selector) = this.model_selector.as_ref() {
3564                    model_selector
3565                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3566                }
3567            }))
3568            .p_2()
3569            .gap_2()
3570            .border_t_1()
3571            .border_color(cx.theme().colors().border)
3572            .bg(editor_bg_color)
3573            .when(self.editor_expanded, |this| {
3574                this.h(vh(0.8, window)).size_full().justify_between()
3575            })
3576            .child(
3577                v_flex()
3578                    .relative()
3579                    .size_full()
3580                    .pt_1()
3581                    .pr_2p5()
3582                    .child(self.message_editor.clone())
3583                    .child(
3584                        h_flex()
3585                            .absolute()
3586                            .top_0()
3587                            .right_0()
3588                            .opacity(0.5)
3589                            .hover(|this| this.opacity(1.0))
3590                            .child(
3591                                IconButton::new("toggle-height", expand_icon)
3592                                    .icon_size(IconSize::Small)
3593                                    .icon_color(Color::Muted)
3594                                    .tooltip({
3595                                        move |window, cx| {
3596                                            Tooltip::for_action_in(
3597                                                expand_tooltip,
3598                                                &ExpandMessageEditor,
3599                                                &focus_handle,
3600                                                window,
3601                                                cx,
3602                                            )
3603                                        }
3604                                    })
3605                                    .on_click(cx.listener(|_, _, window, cx| {
3606                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3607                                    })),
3608                            ),
3609                    ),
3610            )
3611            .child(
3612                h_flex()
3613                    .flex_none()
3614                    .flex_wrap()
3615                    .justify_between()
3616                    .child(
3617                        h_flex()
3618                            .child(self.render_follow_toggle(cx))
3619                            .children(self.render_burn_mode_toggle(cx)),
3620                    )
3621                    .child(
3622                        h_flex()
3623                            .gap_1()
3624                            .children(self.render_token_usage(cx))
3625                            .children(self.profile_selector.clone())
3626                            .children(self.model_selector.clone())
3627                            .child(self.render_send_button(cx)),
3628                    ),
3629            )
3630            .when(!enable_editor, |this| this.child(backdrop))
3631            .into_any()
3632    }
3633
3634    pub(crate) fn as_native_connection(
3635        &self,
3636        cx: &App,
3637    ) -> Option<Rc<agent2::NativeAgentConnection>> {
3638        let acp_thread = self.thread()?.read(cx);
3639        acp_thread.connection().clone().downcast()
3640    }
3641
3642    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3643        let acp_thread = self.thread()?.read(cx);
3644        self.as_native_connection(cx)?
3645            .thread(acp_thread.session_id(), cx)
3646    }
3647
3648    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3649        self.as_native_thread(cx)
3650            .and_then(|thread| thread.read(cx).model())
3651            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3652    }
3653
3654    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3655        let thread = self.thread()?.read(cx);
3656        let usage = thread.token_usage()?;
3657        let is_generating = thread.status() != ThreadStatus::Idle;
3658
3659        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3660        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3661
3662        Some(
3663            h_flex()
3664                .flex_shrink_0()
3665                .gap_0p5()
3666                .mr_1p5()
3667                .child(
3668                    Label::new(used)
3669                        .size(LabelSize::Small)
3670                        .color(Color::Muted)
3671                        .map(|label| {
3672                            if is_generating {
3673                                label
3674                                    .with_animation(
3675                                        "used-tokens-label",
3676                                        Animation::new(Duration::from_secs(2))
3677                                            .repeat()
3678                                            .with_easing(pulsating_between(0.3, 0.8)),
3679                                        |label, delta| label.alpha(delta),
3680                                    )
3681                                    .into_any()
3682                            } else {
3683                                label.into_any_element()
3684                            }
3685                        }),
3686                )
3687                .child(
3688                    Label::new("/")
3689                        .size(LabelSize::Small)
3690                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3691                )
3692                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3693        )
3694    }
3695
3696    fn toggle_burn_mode(
3697        &mut self,
3698        _: &ToggleBurnMode,
3699        _window: &mut Window,
3700        cx: &mut Context<Self>,
3701    ) {
3702        let Some(thread) = self.as_native_thread(cx) else {
3703            return;
3704        };
3705
3706        thread.update(cx, |thread, cx| {
3707            let current_mode = thread.completion_mode();
3708            thread.set_completion_mode(
3709                match current_mode {
3710                    CompletionMode::Burn => CompletionMode::Normal,
3711                    CompletionMode::Normal => CompletionMode::Burn,
3712                },
3713                cx,
3714            );
3715        });
3716    }
3717
3718    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3719        let Some(thread) = self.thread() else {
3720            return;
3721        };
3722        let action_log = thread.read(cx).action_log().clone();
3723        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3724    }
3725
3726    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3727        let Some(thread) = self.thread() else {
3728            return;
3729        };
3730        let action_log = thread.read(cx).action_log().clone();
3731        action_log
3732            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3733            .detach();
3734    }
3735
3736    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3737        let thread = self.as_native_thread(cx)?.read(cx);
3738
3739        if thread
3740            .model()
3741            .is_none_or(|model| !model.supports_burn_mode())
3742        {
3743            return None;
3744        }
3745
3746        let active_completion_mode = thread.completion_mode();
3747        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3748        let icon = if burn_mode_enabled {
3749            IconName::ZedBurnModeOn
3750        } else {
3751            IconName::ZedBurnMode
3752        };
3753
3754        Some(
3755            IconButton::new("burn-mode", icon)
3756                .icon_size(IconSize::Small)
3757                .icon_color(Color::Muted)
3758                .toggle_state(burn_mode_enabled)
3759                .selected_icon_color(Color::Error)
3760                .on_click(cx.listener(|this, _event, window, cx| {
3761                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3762                }))
3763                .tooltip(move |_window, cx| {
3764                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3765                        .into()
3766                })
3767                .into_any_element(),
3768        )
3769    }
3770
3771    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3772        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3773        let is_generating = self
3774            .thread()
3775            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3776
3777        if self.is_loading_contents {
3778            div()
3779                .id("loading-message-content")
3780                .px_1()
3781                .tooltip(Tooltip::text("Loading Added Context…"))
3782                .child(loading_contents_spinner(IconSize::default()))
3783                .into_any_element()
3784        } else if is_generating && is_editor_empty {
3785            IconButton::new("stop-generation", IconName::Stop)
3786                .icon_color(Color::Error)
3787                .style(ButtonStyle::Tinted(ui::TintColor::Error))
3788                .tooltip(move |window, cx| {
3789                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3790                })
3791                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3792                .into_any_element()
3793        } else {
3794            let send_btn_tooltip = if is_editor_empty && !is_generating {
3795                "Type to Send"
3796            } else if is_generating {
3797                "Stop and Send Message"
3798            } else {
3799                "Send"
3800            };
3801
3802            IconButton::new("send-message", IconName::Send)
3803                .style(ButtonStyle::Filled)
3804                .map(|this| {
3805                    if is_editor_empty && !is_generating {
3806                        this.disabled(true).icon_color(Color::Muted)
3807                    } else {
3808                        this.icon_color(Color::Accent)
3809                    }
3810                })
3811                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3812                .on_click(cx.listener(|this, _, window, cx| {
3813                    this.send(window, cx);
3814                }))
3815                .into_any_element()
3816        }
3817    }
3818
3819    fn is_following(&self, cx: &App) -> bool {
3820        match self.thread().map(|thread| thread.read(cx).status()) {
3821            Some(ThreadStatus::Generating) => self
3822                .workspace
3823                .read_with(cx, |workspace, _| {
3824                    workspace.is_being_followed(CollaboratorId::Agent)
3825                })
3826                .unwrap_or(false),
3827            _ => self.should_be_following,
3828        }
3829    }
3830
3831    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3832        let following = self.is_following(cx);
3833
3834        self.should_be_following = !following;
3835        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3836            self.workspace
3837                .update(cx, |workspace, cx| {
3838                    if following {
3839                        workspace.unfollow(CollaboratorId::Agent, window, cx);
3840                    } else {
3841                        workspace.follow(CollaboratorId::Agent, window, cx);
3842                    }
3843                })
3844                .ok();
3845        }
3846
3847        telemetry::event!("Follow Agent Selected", following = !following);
3848    }
3849
3850    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3851        let following = self.is_following(cx);
3852
3853        let tooltip_label = if following {
3854            if self.agent.name() == "Zed Agent" {
3855                format!("Stop Following the {}", self.agent.name())
3856            } else {
3857                format!("Stop Following {}", self.agent.name())
3858            }
3859        } else {
3860            if self.agent.name() == "Zed Agent" {
3861                format!("Follow the {}", self.agent.name())
3862            } else {
3863                format!("Follow {}", self.agent.name())
3864            }
3865        };
3866
3867        IconButton::new("follow-agent", IconName::Crosshair)
3868            .icon_size(IconSize::Small)
3869            .icon_color(Color::Muted)
3870            .toggle_state(following)
3871            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3872            .tooltip(move |window, cx| {
3873                if following {
3874                    Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
3875                } else {
3876                    Tooltip::with_meta(
3877                        tooltip_label.clone(),
3878                        Some(&Follow),
3879                        "Track the agent's location as it reads and edits files.",
3880                        window,
3881                        cx,
3882                    )
3883                }
3884            })
3885            .on_click(cx.listener(move |this, _, window, cx| {
3886                this.toggle_following(window, cx);
3887            }))
3888    }
3889
3890    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3891        let workspace = self.workspace.clone();
3892        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3893            Self::open_link(text, &workspace, window, cx);
3894        })
3895    }
3896
3897    fn open_link(
3898        url: SharedString,
3899        workspace: &WeakEntity<Workspace>,
3900        window: &mut Window,
3901        cx: &mut App,
3902    ) {
3903        let Some(workspace) = workspace.upgrade() else {
3904            cx.open_url(&url);
3905            return;
3906        };
3907
3908        if let Some(mention) = MentionUri::parse(&url).log_err() {
3909            workspace.update(cx, |workspace, cx| match mention {
3910                MentionUri::File { abs_path } => {
3911                    let project = workspace.project();
3912                    let Some(path) =
3913                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3914                    else {
3915                        return;
3916                    };
3917
3918                    workspace
3919                        .open_path(path, None, true, window, cx)
3920                        .detach_and_log_err(cx);
3921                }
3922                MentionUri::PastedImage => {}
3923                MentionUri::Directory { abs_path } => {
3924                    let project = workspace.project();
3925                    let Some(entry) = project.update(cx, |project, cx| {
3926                        let path = project.find_project_path(abs_path, cx)?;
3927                        project.entry_for_path(&path, cx)
3928                    }) else {
3929                        return;
3930                    };
3931
3932                    project.update(cx, |_, cx| {
3933                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
3934                    });
3935                }
3936                MentionUri::Symbol {
3937                    abs_path: path,
3938                    line_range,
3939                    ..
3940                }
3941                | MentionUri::Selection {
3942                    abs_path: Some(path),
3943                    line_range,
3944                } => {
3945                    let project = workspace.project();
3946                    let Some((path, _)) = project.update(cx, |project, cx| {
3947                        let path = project.find_project_path(path, cx)?;
3948                        let entry = project.entry_for_path(&path, cx)?;
3949                        Some((path, entry))
3950                    }) else {
3951                        return;
3952                    };
3953
3954                    let item = workspace.open_path(path, None, true, window, cx);
3955                    window
3956                        .spawn(cx, async move |cx| {
3957                            let Some(editor) = item.await?.downcast::<Editor>() else {
3958                                return Ok(());
3959                            };
3960                            let range = Point::new(*line_range.start(), 0)
3961                                ..Point::new(*line_range.start(), 0);
3962                            editor
3963                                .update_in(cx, |editor, window, cx| {
3964                                    editor.change_selections(
3965                                        SelectionEffects::scroll(Autoscroll::center()),
3966                                        window,
3967                                        cx,
3968                                        |s| s.select_ranges(vec![range]),
3969                                    );
3970                                })
3971                                .ok();
3972                            anyhow::Ok(())
3973                        })
3974                        .detach_and_log_err(cx);
3975                }
3976                MentionUri::Selection { abs_path: None, .. } => {}
3977                MentionUri::Thread { id, name } => {
3978                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3979                        panel.update(cx, |panel, cx| {
3980                            panel.load_agent_thread(
3981                                DbThreadMetadata {
3982                                    id,
3983                                    title: name.into(),
3984                                    updated_at: Default::default(),
3985                                },
3986                                window,
3987                                cx,
3988                            )
3989                        });
3990                    }
3991                }
3992                MentionUri::TextThread { path, .. } => {
3993                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3994                        panel.update(cx, |panel, cx| {
3995                            panel
3996                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
3997                                .detach_and_log_err(cx);
3998                        });
3999                    }
4000                }
4001                MentionUri::Rule { id, .. } => {
4002                    let PromptId::User { uuid } = id else {
4003                        return;
4004                    };
4005                    window.dispatch_action(
4006                        Box::new(OpenRulesLibrary {
4007                            prompt_to_select: Some(uuid.0),
4008                        }),
4009                        cx,
4010                    )
4011                }
4012                MentionUri::Fetch { url } => {
4013                    cx.open_url(url.as_str());
4014                }
4015            })
4016        } else {
4017            cx.open_url(&url);
4018        }
4019    }
4020
4021    fn open_tool_call_location(
4022        &self,
4023        entry_ix: usize,
4024        location_ix: usize,
4025        window: &mut Window,
4026        cx: &mut Context<Self>,
4027    ) -> Option<()> {
4028        let (tool_call_location, agent_location) = self
4029            .thread()?
4030            .read(cx)
4031            .entries()
4032            .get(entry_ix)?
4033            .location(location_ix)?;
4034
4035        let project_path = self
4036            .project
4037            .read(cx)
4038            .find_project_path(&tool_call_location.path, cx)?;
4039
4040        let open_task = self
4041            .workspace
4042            .update(cx, |workspace, cx| {
4043                workspace.open_path(project_path, None, true, window, cx)
4044            })
4045            .log_err()?;
4046        window
4047            .spawn(cx, async move |cx| {
4048                let item = open_task.await?;
4049
4050                let Some(active_editor) = item.downcast::<Editor>() else {
4051                    return anyhow::Ok(());
4052                };
4053
4054                active_editor.update_in(cx, |editor, window, cx| {
4055                    let multibuffer = editor.buffer().read(cx);
4056                    let buffer = multibuffer.as_singleton();
4057                    if agent_location.buffer.upgrade() == buffer {
4058                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4059                        let anchor = editor::Anchor::in_buffer(
4060                            excerpt_id.unwrap(),
4061                            buffer.unwrap().read(cx).remote_id(),
4062                            agent_location.position,
4063                        );
4064                        editor.change_selections(Default::default(), window, cx, |selections| {
4065                            selections.select_anchor_ranges([anchor..anchor]);
4066                        })
4067                    } else {
4068                        let row = tool_call_location.line.unwrap_or_default();
4069                        editor.change_selections(Default::default(), window, cx, |selections| {
4070                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4071                        })
4072                    }
4073                })?;
4074
4075                anyhow::Ok(())
4076            })
4077            .detach_and_log_err(cx);
4078
4079        None
4080    }
4081
4082    pub fn open_thread_as_markdown(
4083        &self,
4084        workspace: Entity<Workspace>,
4085        window: &mut Window,
4086        cx: &mut App,
4087    ) -> Task<Result<()>> {
4088        let markdown_language_task = workspace
4089            .read(cx)
4090            .app_state()
4091            .languages
4092            .language_for_name("Markdown");
4093
4094        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4095            let thread = thread.read(cx);
4096            (thread.title().to_string(), thread.to_markdown(cx))
4097        } else {
4098            return Task::ready(Ok(()));
4099        };
4100
4101        window.spawn(cx, async move |cx| {
4102            let markdown_language = markdown_language_task.await?;
4103
4104            workspace.update_in(cx, |workspace, window, cx| {
4105                let project = workspace.project().clone();
4106
4107                if !project.read(cx).is_local() {
4108                    bail!("failed to open active thread as markdown in remote project");
4109                }
4110
4111                let buffer = project.update(cx, |project, cx| {
4112                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
4113                });
4114                let buffer = cx.new(|cx| {
4115                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4116                });
4117
4118                workspace.add_item_to_active_pane(
4119                    Box::new(cx.new(|cx| {
4120                        let mut editor =
4121                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4122                        editor.set_breadcrumb_header(thread_summary);
4123                        editor
4124                    })),
4125                    None,
4126                    true,
4127                    window,
4128                    cx,
4129                );
4130
4131                anyhow::Ok(())
4132            })??;
4133            anyhow::Ok(())
4134        })
4135    }
4136
4137    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4138        self.list_state.scroll_to(ListOffset::default());
4139        cx.notify();
4140    }
4141
4142    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4143        if let Some(thread) = self.thread() {
4144            let entry_count = thread.read(cx).entries().len();
4145            self.list_state.reset(entry_count);
4146            cx.notify();
4147        }
4148    }
4149
4150    fn notify_with_sound(
4151        &mut self,
4152        caption: impl Into<SharedString>,
4153        icon: IconName,
4154        window: &mut Window,
4155        cx: &mut Context<Self>,
4156    ) {
4157        self.play_notification_sound(window, cx);
4158        self.show_notification(caption, icon, window, cx);
4159    }
4160
4161    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4162        let settings = AgentSettings::get_global(cx);
4163        if settings.play_sound_when_agent_done && !window.is_window_active() {
4164            Audio::play_sound(Sound::AgentDone, cx);
4165        }
4166    }
4167
4168    fn show_notification(
4169        &mut self,
4170        caption: impl Into<SharedString>,
4171        icon: IconName,
4172        window: &mut Window,
4173        cx: &mut Context<Self>,
4174    ) {
4175        if window.is_window_active() || !self.notifications.is_empty() {
4176            return;
4177        }
4178
4179        // TODO: Change this once we have title summarization for external agents.
4180        let title = self.agent.name();
4181
4182        match AgentSettings::get_global(cx).notify_when_agent_waiting {
4183            NotifyWhenAgentWaiting::PrimaryScreen => {
4184                if let Some(primary) = cx.primary_display() {
4185                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4186                }
4187            }
4188            NotifyWhenAgentWaiting::AllScreens => {
4189                let caption = caption.into();
4190                for screen in cx.displays() {
4191                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4192                }
4193            }
4194            NotifyWhenAgentWaiting::Never => {
4195                // Don't show anything
4196            }
4197        }
4198    }
4199
4200    fn pop_up(
4201        &mut self,
4202        icon: IconName,
4203        caption: SharedString,
4204        title: SharedString,
4205        window: &mut Window,
4206        screen: Rc<dyn PlatformDisplay>,
4207        cx: &mut Context<Self>,
4208    ) {
4209        let options = AgentNotification::window_options(screen, cx);
4210
4211        let project_name = self.workspace.upgrade().and_then(|workspace| {
4212            workspace
4213                .read(cx)
4214                .project()
4215                .read(cx)
4216                .visible_worktrees(cx)
4217                .next()
4218                .map(|worktree| worktree.read(cx).root_name().to_string())
4219        });
4220
4221        if let Some(screen_window) = cx
4222            .open_window(options, |_, cx| {
4223                cx.new(|_| {
4224                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4225                })
4226            })
4227            .log_err()
4228            && let Some(pop_up) = screen_window.entity(cx).log_err()
4229        {
4230            self.notification_subscriptions
4231                .entry(screen_window)
4232                .or_insert_with(Vec::new)
4233                .push(cx.subscribe_in(&pop_up, window, {
4234                    |this, _, event, window, cx| match event {
4235                        AgentNotificationEvent::Accepted => {
4236                            let handle = window.window_handle();
4237                            cx.activate(true);
4238
4239                            let workspace_handle = this.workspace.clone();
4240
4241                            // If there are multiple Zed windows, activate the correct one.
4242                            cx.defer(move |cx| {
4243                                handle
4244                                    .update(cx, |_view, window, _cx| {
4245                                        window.activate_window();
4246
4247                                        if let Some(workspace) = workspace_handle.upgrade() {
4248                                            workspace.update(_cx, |workspace, cx| {
4249                                                workspace.focus_panel::<AgentPanel>(window, cx);
4250                                            });
4251                                        }
4252                                    })
4253                                    .log_err();
4254                            });
4255
4256                            this.dismiss_notifications(cx);
4257                        }
4258                        AgentNotificationEvent::Dismissed => {
4259                            this.dismiss_notifications(cx);
4260                        }
4261                    }
4262                }));
4263
4264            self.notifications.push(screen_window);
4265
4266            // If the user manually refocuses the original window, dismiss the popup.
4267            self.notification_subscriptions
4268                .entry(screen_window)
4269                .or_insert_with(Vec::new)
4270                .push({
4271                    let pop_up_weak = pop_up.downgrade();
4272
4273                    cx.observe_window_activation(window, move |_, window, cx| {
4274                        if window.is_window_active()
4275                            && let Some(pop_up) = pop_up_weak.upgrade()
4276                        {
4277                            pop_up.update(cx, |_, cx| {
4278                                cx.emit(AgentNotificationEvent::Dismissed);
4279                            });
4280                        }
4281                    })
4282                });
4283        }
4284    }
4285
4286    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4287        for window in self.notifications.drain(..) {
4288            window
4289                .update(cx, |_, window, _| {
4290                    window.remove_window();
4291                })
4292                .ok();
4293
4294            self.notification_subscriptions.remove(&window);
4295        }
4296    }
4297
4298    fn render_thread_controls(
4299        &self,
4300        thread: &Entity<AcpThread>,
4301        cx: &Context<Self>,
4302    ) -> impl IntoElement {
4303        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4304        if is_generating {
4305            return h_flex().id("thread-controls-container").child(
4306                div()
4307                    .py_2()
4308                    .px(rems_from_px(22.))
4309                    .child(SpinnerLabel::new().size(LabelSize::Small)),
4310            );
4311        }
4312
4313        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4314            .shape(ui::IconButtonShape::Square)
4315            .icon_size(IconSize::Small)
4316            .icon_color(Color::Ignored)
4317            .tooltip(Tooltip::text("Open Thread as Markdown"))
4318            .on_click(cx.listener(move |this, _, window, cx| {
4319                if let Some(workspace) = this.workspace.upgrade() {
4320                    this.open_thread_as_markdown(workspace, window, cx)
4321                        .detach_and_log_err(cx);
4322                }
4323            }));
4324
4325        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4326            .shape(ui::IconButtonShape::Square)
4327            .icon_size(IconSize::Small)
4328            .icon_color(Color::Ignored)
4329            .tooltip(Tooltip::text("Scroll To Top"))
4330            .on_click(cx.listener(move |this, _, _, cx| {
4331                this.scroll_to_top(cx);
4332            }));
4333
4334        let mut container = h_flex()
4335            .id("thread-controls-container")
4336            .group("thread-controls-container")
4337            .w_full()
4338            .py_2()
4339            .px_5()
4340            .gap_px()
4341            .opacity(0.6)
4342            .hover(|style| style.opacity(1.))
4343            .flex_wrap()
4344            .justify_end();
4345
4346        if AgentSettings::get_global(cx).enable_feedback
4347            && self
4348                .thread()
4349                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4350        {
4351            let feedback = self.thread_feedback.feedback;
4352
4353            container = container
4354                .child(
4355                    div().visible_on_hover("thread-controls-container").child(
4356                        Label::new(match feedback {
4357                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4358                            Some(ThreadFeedback::Negative) => {
4359                                "We appreciate your feedback and will use it to improve."
4360                            }
4361                            None => {
4362                                "Rating the thread sends all of your current conversation to the Zed team."
4363                            }
4364                        })
4365                        .color(Color::Muted)
4366                        .size(LabelSize::XSmall)
4367                        .truncate(),
4368                    ),
4369                )
4370                .child(
4371                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4372                        .shape(ui::IconButtonShape::Square)
4373                        .icon_size(IconSize::Small)
4374                        .icon_color(match feedback {
4375                            Some(ThreadFeedback::Positive) => Color::Accent,
4376                            _ => Color::Ignored,
4377                        })
4378                        .tooltip(Tooltip::text("Helpful Response"))
4379                        .on_click(cx.listener(move |this, _, window, cx| {
4380                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4381                        })),
4382                )
4383                .child(
4384                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4385                        .shape(ui::IconButtonShape::Square)
4386                        .icon_size(IconSize::Small)
4387                        .icon_color(match feedback {
4388                            Some(ThreadFeedback::Negative) => Color::Accent,
4389                            _ => Color::Ignored,
4390                        })
4391                        .tooltip(Tooltip::text("Not Helpful"))
4392                        .on_click(cx.listener(move |this, _, window, cx| {
4393                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4394                        })),
4395                );
4396        }
4397
4398        container.child(open_as_markdown).child(scroll_to_top)
4399    }
4400
4401    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4402        h_flex()
4403            .key_context("AgentFeedbackMessageEditor")
4404            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4405                this.thread_feedback.dismiss_comments();
4406                cx.notify();
4407            }))
4408            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4409                this.submit_feedback_message(cx);
4410            }))
4411            .p_2()
4412            .mb_2()
4413            .mx_5()
4414            .gap_1()
4415            .rounded_md()
4416            .border_1()
4417            .border_color(cx.theme().colors().border)
4418            .bg(cx.theme().colors().editor_background)
4419            .child(div().w_full().child(editor))
4420            .child(
4421                h_flex()
4422                    .child(
4423                        IconButton::new("dismiss-feedback-message", IconName::Close)
4424                            .icon_color(Color::Error)
4425                            .icon_size(IconSize::XSmall)
4426                            .shape(ui::IconButtonShape::Square)
4427                            .on_click(cx.listener(move |this, _, _window, cx| {
4428                                this.thread_feedback.dismiss_comments();
4429                                cx.notify();
4430                            })),
4431                    )
4432                    .child(
4433                        IconButton::new("submit-feedback-message", IconName::Return)
4434                            .icon_size(IconSize::XSmall)
4435                            .shape(ui::IconButtonShape::Square)
4436                            .on_click(cx.listener(move |this, _, _window, cx| {
4437                                this.submit_feedback_message(cx);
4438                            })),
4439                    ),
4440            )
4441    }
4442
4443    fn handle_feedback_click(
4444        &mut self,
4445        feedback: ThreadFeedback,
4446        window: &mut Window,
4447        cx: &mut Context<Self>,
4448    ) {
4449        let Some(thread) = self.thread().cloned() else {
4450            return;
4451        };
4452
4453        self.thread_feedback.submit(thread, feedback, window, cx);
4454        cx.notify();
4455    }
4456
4457    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4458        let Some(thread) = self.thread().cloned() else {
4459            return;
4460        };
4461
4462        self.thread_feedback.submit_comments(thread, cx);
4463        cx.notify();
4464    }
4465
4466    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4467        div()
4468            .id("acp-thread-scrollbar")
4469            .occlude()
4470            .on_mouse_move(cx.listener(|_, _, _, cx| {
4471                cx.notify();
4472                cx.stop_propagation()
4473            }))
4474            .on_hover(|_, _, cx| {
4475                cx.stop_propagation();
4476            })
4477            .on_any_mouse_down(|_, _, cx| {
4478                cx.stop_propagation();
4479            })
4480            .on_mouse_up(
4481                MouseButton::Left,
4482                cx.listener(|_, _, _, cx| {
4483                    cx.stop_propagation();
4484                }),
4485            )
4486            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4487                cx.notify();
4488            }))
4489            .h_full()
4490            .absolute()
4491            .right_1()
4492            .top_1()
4493            .bottom_0()
4494            .w(px(12.))
4495            .cursor_default()
4496            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4497    }
4498
4499    fn render_token_limit_callout(
4500        &self,
4501        line_height: Pixels,
4502        cx: &mut Context<Self>,
4503    ) -> Option<Callout> {
4504        let token_usage = self.thread()?.read(cx).token_usage()?;
4505        let ratio = token_usage.ratio();
4506
4507        let (severity, title) = match ratio {
4508            acp_thread::TokenUsageRatio::Normal => return None,
4509            acp_thread::TokenUsageRatio::Warning => {
4510                (Severity::Warning, "Thread reaching the token limit soon")
4511            }
4512            acp_thread::TokenUsageRatio::Exceeded => {
4513                (Severity::Error, "Thread reached the token limit")
4514            }
4515        };
4516
4517        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4518            thread.read(cx).completion_mode() == CompletionMode::Normal
4519                && thread
4520                    .read(cx)
4521                    .model()
4522                    .is_some_and(|model| model.supports_burn_mode())
4523        });
4524
4525        let description = if burn_mode_available {
4526            "To continue, start a new thread from a summary or turn Burn Mode on."
4527        } else {
4528            "To continue, start a new thread from a summary."
4529        };
4530
4531        Some(
4532            Callout::new()
4533                .severity(severity)
4534                .line_height(line_height)
4535                .title(title)
4536                .description(description)
4537                .actions_slot(
4538                    h_flex()
4539                        .gap_0p5()
4540                        .child(
4541                            Button::new("start-new-thread", "Start New Thread")
4542                                .label_size(LabelSize::Small)
4543                                .on_click(cx.listener(|this, _, window, cx| {
4544                                    let Some(thread) = this.thread() else {
4545                                        return;
4546                                    };
4547                                    let session_id = thread.read(cx).session_id().clone();
4548                                    window.dispatch_action(
4549                                        crate::NewNativeAgentThreadFromSummary {
4550                                            from_session_id: session_id,
4551                                        }
4552                                        .boxed_clone(),
4553                                        cx,
4554                                    );
4555                                })),
4556                        )
4557                        .when(burn_mode_available, |this| {
4558                            this.child(
4559                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4560                                    .icon_size(IconSize::XSmall)
4561                                    .on_click(cx.listener(|this, _event, window, cx| {
4562                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4563                                    })),
4564                            )
4565                        }),
4566                ),
4567        )
4568    }
4569
4570    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4571        if !self.is_using_zed_ai_models(cx) {
4572            return None;
4573        }
4574
4575        let user_store = self.project.read(cx).user_store().read(cx);
4576        if user_store.is_usage_based_billing_enabled() {
4577            return None;
4578        }
4579
4580        let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4581
4582        let usage = user_store.model_request_usage()?;
4583
4584        Some(
4585            div()
4586                .child(UsageCallout::new(plan, usage))
4587                .line_height(line_height),
4588        )
4589    }
4590
4591    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4592        self.entry_view_state.update(cx, |entry_view_state, cx| {
4593            entry_view_state.settings_changed(cx);
4594        });
4595    }
4596
4597    pub(crate) fn insert_dragged_files(
4598        &self,
4599        paths: Vec<project::ProjectPath>,
4600        added_worktrees: Vec<Entity<project::Worktree>>,
4601        window: &mut Window,
4602        cx: &mut Context<Self>,
4603    ) {
4604        self.message_editor.update(cx, |message_editor, cx| {
4605            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4606        })
4607    }
4608
4609    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4610        self.message_editor.update(cx, |message_editor, cx| {
4611            message_editor.insert_selections(window, cx);
4612        })
4613    }
4614
4615    fn render_thread_retry_status_callout(
4616        &self,
4617        _window: &mut Window,
4618        _cx: &mut Context<Self>,
4619    ) -> Option<Callout> {
4620        let state = self.thread_retry_status.as_ref()?;
4621
4622        let next_attempt_in = state
4623            .duration
4624            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4625        if next_attempt_in.is_zero() {
4626            return None;
4627        }
4628
4629        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4630
4631        let retry_message = if state.max_attempts == 1 {
4632            if next_attempt_in_secs == 1 {
4633                "Retrying. Next attempt in 1 second.".to_string()
4634            } else {
4635                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4636            }
4637        } else if next_attempt_in_secs == 1 {
4638            format!(
4639                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4640                state.attempt, state.max_attempts,
4641            )
4642        } else {
4643            format!(
4644                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4645                state.attempt, state.max_attempts,
4646            )
4647        };
4648
4649        Some(
4650            Callout::new()
4651                .severity(Severity::Warning)
4652                .title(state.last_error.clone())
4653                .description(retry_message),
4654        )
4655    }
4656
4657    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4658        let content = match self.thread_error.as_ref()? {
4659            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4660            ThreadError::AuthenticationRequired(error) => {
4661                self.render_authentication_required_error(error.clone(), cx)
4662            }
4663            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4664            ThreadError::ModelRequestLimitReached(plan) => {
4665                self.render_model_request_limit_reached_error(*plan, cx)
4666            }
4667            ThreadError::ToolUseLimitReached => {
4668                self.render_tool_use_limit_reached_error(window, cx)?
4669            }
4670        };
4671
4672        Some(div().child(content))
4673    }
4674
4675    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4676        let can_resume = self
4677            .thread()
4678            .map_or(false, |thread| thread.read(cx).can_resume(cx));
4679
4680        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4681            let thread = thread.read(cx);
4682            let supports_burn_mode = thread
4683                .model()
4684                .map_or(false, |model| model.supports_burn_mode());
4685            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4686        });
4687
4688        Callout::new()
4689            .severity(Severity::Error)
4690            .title("Error")
4691            .icon(IconName::XCircle)
4692            .description(error.clone())
4693            .actions_slot(
4694                h_flex()
4695                    .gap_0p5()
4696                    .when(can_resume && can_enable_burn_mode, |this| {
4697                        this.child(
4698                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4699                                .icon(IconName::ZedBurnMode)
4700                                .icon_position(IconPosition::Start)
4701                                .icon_size(IconSize::Small)
4702                                .label_size(LabelSize::Small)
4703                                .on_click(cx.listener(|this, _, window, cx| {
4704                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4705                                    this.resume_chat(cx);
4706                                })),
4707                        )
4708                    })
4709                    .when(can_resume, |this| {
4710                        this.child(
4711                            Button::new("retry", "Retry")
4712                                .icon(IconName::RotateCw)
4713                                .icon_position(IconPosition::Start)
4714                                .icon_size(IconSize::Small)
4715                                .label_size(LabelSize::Small)
4716                                .on_click(cx.listener(|this, _, _window, cx| {
4717                                    this.resume_chat(cx);
4718                                })),
4719                        )
4720                    })
4721                    .child(self.create_copy_button(error.to_string())),
4722            )
4723            .dismiss_action(self.dismiss_error_button(cx))
4724    }
4725
4726    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4727        const ERROR_MESSAGE: &str =
4728            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4729
4730        Callout::new()
4731            .severity(Severity::Error)
4732            .icon(IconName::XCircle)
4733            .title("Free Usage Exceeded")
4734            .description(ERROR_MESSAGE)
4735            .actions_slot(
4736                h_flex()
4737                    .gap_0p5()
4738                    .child(self.upgrade_button(cx))
4739                    .child(self.create_copy_button(ERROR_MESSAGE)),
4740            )
4741            .dismiss_action(self.dismiss_error_button(cx))
4742    }
4743
4744    fn render_authentication_required_error(
4745        &self,
4746        error: SharedString,
4747        cx: &mut Context<Self>,
4748    ) -> Callout {
4749        Callout::new()
4750            .severity(Severity::Error)
4751            .title("Authentication Required")
4752            .icon(IconName::XCircle)
4753            .description(error.clone())
4754            .actions_slot(
4755                h_flex()
4756                    .gap_0p5()
4757                    .child(self.authenticate_button(cx))
4758                    .child(self.create_copy_button(error)),
4759            )
4760            .dismiss_action(self.dismiss_error_button(cx))
4761    }
4762
4763    fn render_model_request_limit_reached_error(
4764        &self,
4765        plan: cloud_llm_client::Plan,
4766        cx: &mut Context<Self>,
4767    ) -> Callout {
4768        let error_message = match plan {
4769            cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4770            cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4771                "Upgrade to Zed Pro for more prompts."
4772            }
4773        };
4774
4775        Callout::new()
4776            .severity(Severity::Error)
4777            .title("Model Prompt Limit Reached")
4778            .icon(IconName::XCircle)
4779            .description(error_message)
4780            .actions_slot(
4781                h_flex()
4782                    .gap_0p5()
4783                    .child(self.upgrade_button(cx))
4784                    .child(self.create_copy_button(error_message)),
4785            )
4786            .dismiss_action(self.dismiss_error_button(cx))
4787    }
4788
4789    fn render_tool_use_limit_reached_error(
4790        &self,
4791        window: &mut Window,
4792        cx: &mut Context<Self>,
4793    ) -> Option<Callout> {
4794        let thread = self.as_native_thread(cx)?;
4795        let supports_burn_mode = thread
4796            .read(cx)
4797            .model()
4798            .is_some_and(|model| model.supports_burn_mode());
4799
4800        let focus_handle = self.focus_handle(cx);
4801
4802        Some(
4803            Callout::new()
4804                .icon(IconName::Info)
4805                .title("Consecutive tool use limit reached.")
4806                .actions_slot(
4807                    h_flex()
4808                        .gap_0p5()
4809                        .when(supports_burn_mode, |this| {
4810                            this.child(
4811                                Button::new("continue-burn-mode", "Continue with Burn Mode")
4812                                    .style(ButtonStyle::Filled)
4813                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4814                                    .layer(ElevationIndex::ModalSurface)
4815                                    .label_size(LabelSize::Small)
4816                                    .key_binding(
4817                                        KeyBinding::for_action_in(
4818                                            &ContinueWithBurnMode,
4819                                            &focus_handle,
4820                                            window,
4821                                            cx,
4822                                        )
4823                                        .map(|kb| kb.size(rems_from_px(10.))),
4824                                    )
4825                                    .tooltip(Tooltip::text(
4826                                        "Enable Burn Mode for unlimited tool use.",
4827                                    ))
4828                                    .on_click({
4829                                        cx.listener(move |this, _, _window, cx| {
4830                                            thread.update(cx, |thread, cx| {
4831                                                thread
4832                                                    .set_completion_mode(CompletionMode::Burn, cx);
4833                                            });
4834                                            this.resume_chat(cx);
4835                                        })
4836                                    }),
4837                            )
4838                        })
4839                        .child(
4840                            Button::new("continue-conversation", "Continue")
4841                                .layer(ElevationIndex::ModalSurface)
4842                                .label_size(LabelSize::Small)
4843                                .key_binding(
4844                                    KeyBinding::for_action_in(
4845                                        &ContinueThread,
4846                                        &focus_handle,
4847                                        window,
4848                                        cx,
4849                                    )
4850                                    .map(|kb| kb.size(rems_from_px(10.))),
4851                                )
4852                                .on_click(cx.listener(|this, _, _window, cx| {
4853                                    this.resume_chat(cx);
4854                                })),
4855                        ),
4856                ),
4857        )
4858    }
4859
4860    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4861        let message = message.into();
4862
4863        IconButton::new("copy", IconName::Copy)
4864            .icon_size(IconSize::Small)
4865            .icon_color(Color::Muted)
4866            .tooltip(Tooltip::text("Copy Error Message"))
4867            .on_click(move |_, _, cx| {
4868                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4869            })
4870    }
4871
4872    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4873        IconButton::new("dismiss", IconName::Close)
4874            .icon_size(IconSize::Small)
4875            .icon_color(Color::Muted)
4876            .tooltip(Tooltip::text("Dismiss Error"))
4877            .on_click(cx.listener({
4878                move |this, _, _, cx| {
4879                    this.clear_thread_error(cx);
4880                    cx.notify();
4881                }
4882            }))
4883    }
4884
4885    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4886        Button::new("authenticate", "Authenticate")
4887            .label_size(LabelSize::Small)
4888            .style(ButtonStyle::Filled)
4889            .on_click(cx.listener({
4890                move |this, _, window, cx| {
4891                    let agent = this.agent.clone();
4892                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
4893                        return;
4894                    };
4895
4896                    let connection = thread.read(cx).connection().clone();
4897                    let err = AuthRequired {
4898                        description: None,
4899                        provider_id: None,
4900                    };
4901                    this.clear_thread_error(cx);
4902                    let this = cx.weak_entity();
4903                    window.defer(cx, |window, cx| {
4904                        Self::handle_auth_required(this, err, agent, connection, window, cx);
4905                    })
4906                }
4907            }))
4908    }
4909
4910    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4911        let agent = self.agent.clone();
4912        let ThreadState::Ready { thread, .. } = &self.thread_state else {
4913            return;
4914        };
4915
4916        let connection = thread.read(cx).connection().clone();
4917        let err = AuthRequired {
4918            description: None,
4919            provider_id: None,
4920        };
4921        self.clear_thread_error(cx);
4922        let this = cx.weak_entity();
4923        window.defer(cx, |window, cx| {
4924            Self::handle_auth_required(this, err, agent, connection, window, cx);
4925        })
4926    }
4927
4928    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4929        Button::new("upgrade", "Upgrade")
4930            .label_size(LabelSize::Small)
4931            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4932            .on_click(cx.listener({
4933                move |this, _, _, cx| {
4934                    this.clear_thread_error(cx);
4935                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4936                }
4937            }))
4938    }
4939
4940    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4941        let task = match entry {
4942            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4943                history.delete_thread(thread.id.clone(), cx)
4944            }),
4945            HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4946                history.delete_text_thread(context.path.clone(), cx)
4947            }),
4948        };
4949        task.detach_and_log_err(cx);
4950    }
4951}
4952
4953fn loading_contents_spinner(size: IconSize) -> AnyElement {
4954    Icon::new(IconName::LoadCircle)
4955        .size(size)
4956        .color(Color::Accent)
4957        .with_animation(
4958            "load_context_circle",
4959            Animation::new(Duration::from_secs(3)).repeat(),
4960            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4961        )
4962        .into_any_element()
4963}
4964
4965impl Focusable for AcpThreadView {
4966    fn focus_handle(&self, cx: &App) -> FocusHandle {
4967        match self.thread_state {
4968            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
4969                self.message_editor.focus_handle(cx)
4970            }
4971            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
4972                self.focus_handle.clone()
4973            }
4974        }
4975    }
4976}
4977
4978impl Render for AcpThreadView {
4979    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4980        let has_messages = self.list_state.item_count() > 0;
4981        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4982
4983        v_flex()
4984            .size_full()
4985            .key_context("AcpThread")
4986            .on_action(cx.listener(Self::open_agent_diff))
4987            .on_action(cx.listener(Self::toggle_burn_mode))
4988            .on_action(cx.listener(Self::keep_all))
4989            .on_action(cx.listener(Self::reject_all))
4990            .track_focus(&self.focus_handle)
4991            .bg(cx.theme().colors().panel_background)
4992            .child(match &self.thread_state {
4993                ThreadState::Unauthenticated {
4994                    connection,
4995                    description,
4996                    configuration_view,
4997                    pending_auth_method,
4998                    ..
4999                } => self.render_auth_required_state(
5000                    connection,
5001                    description.as_ref(),
5002                    configuration_view.as_ref(),
5003                    pending_auth_method.as_ref(),
5004                    window,
5005                    cx,
5006                ),
5007                ThreadState::Loading { .. } => v_flex()
5008                    .flex_1()
5009                    .child(self.render_recent_history(window, cx)),
5010                ThreadState::LoadError(e) => v_flex()
5011                    .flex_1()
5012                    .size_full()
5013                    .items_center()
5014                    .justify_end()
5015                    .child(self.render_load_error(e, window, cx)),
5016                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5017                    if has_messages {
5018                        this.child(
5019                            list(
5020                                self.list_state.clone(),
5021                                cx.processor(|this, index: usize, window, cx| {
5022                                    let Some((entry, len)) = this.thread().and_then(|thread| {
5023                                        let entries = &thread.read(cx).entries();
5024                                        Some((entries.get(index)?, entries.len()))
5025                                    }) else {
5026                                        return Empty.into_any();
5027                                    };
5028                                    this.render_entry(index, len, entry, window, cx)
5029                                }),
5030                            )
5031                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5032                            .flex_grow()
5033                            .into_any(),
5034                        )
5035                        .child(self.render_vertical_scrollbar(cx))
5036                    } else {
5037                        this.child(self.render_recent_history(window, cx))
5038                    }
5039                }),
5040            })
5041            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5042            // above so that the scrollbar doesn't render behind it. The current setup allows
5043            // the scrollbar to stop exactly at the activity bar start.
5044            .when(has_messages, |this| match &self.thread_state {
5045                ThreadState::Ready { thread, .. } => {
5046                    this.children(self.render_activity_bar(thread, window, cx))
5047                }
5048                _ => this,
5049            })
5050            .children(self.render_thread_retry_status_callout(window, cx))
5051            .children(self.render_thread_error(window, cx))
5052            .children(
5053                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5054                    Some(usage_callout.into_any_element())
5055                } else {
5056                    self.render_token_limit_callout(line_height, cx)
5057                        .map(|token_limit_callout| token_limit_callout.into_any_element())
5058                },
5059            )
5060            .child(self.render_message_editor(window, cx))
5061    }
5062}
5063
5064fn default_markdown_style(
5065    buffer_font: bool,
5066    muted_text: bool,
5067    window: &Window,
5068    cx: &App,
5069) -> MarkdownStyle {
5070    let theme_settings = ThemeSettings::get_global(cx);
5071    let colors = cx.theme().colors();
5072
5073    let buffer_font_size = TextSize::Small.rems(cx);
5074
5075    let mut text_style = window.text_style();
5076    let line_height = buffer_font_size * 1.75;
5077
5078    let font_family = if buffer_font {
5079        theme_settings.buffer_font.family.clone()
5080    } else {
5081        theme_settings.ui_font.family.clone()
5082    };
5083
5084    let font_size = if buffer_font {
5085        TextSize::Small.rems(cx)
5086    } else {
5087        TextSize::Default.rems(cx)
5088    };
5089
5090    let text_color = if muted_text {
5091        colors.text_muted
5092    } else {
5093        colors.text
5094    };
5095
5096    text_style.refine(&TextStyleRefinement {
5097        font_family: Some(font_family),
5098        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5099        font_features: Some(theme_settings.ui_font.features.clone()),
5100        font_size: Some(font_size.into()),
5101        line_height: Some(line_height.into()),
5102        color: Some(text_color),
5103        ..Default::default()
5104    });
5105
5106    MarkdownStyle {
5107        base_text_style: text_style.clone(),
5108        syntax: cx.theme().syntax().clone(),
5109        selection_background_color: colors.element_selection_background,
5110        code_block_overflow_x_scroll: true,
5111        table_overflow_x_scroll: true,
5112        heading_level_styles: Some(HeadingLevelStyles {
5113            h1: Some(TextStyleRefinement {
5114                font_size: Some(rems(1.15).into()),
5115                ..Default::default()
5116            }),
5117            h2: Some(TextStyleRefinement {
5118                font_size: Some(rems(1.1).into()),
5119                ..Default::default()
5120            }),
5121            h3: Some(TextStyleRefinement {
5122                font_size: Some(rems(1.05).into()),
5123                ..Default::default()
5124            }),
5125            h4: Some(TextStyleRefinement {
5126                font_size: Some(rems(1.).into()),
5127                ..Default::default()
5128            }),
5129            h5: Some(TextStyleRefinement {
5130                font_size: Some(rems(0.95).into()),
5131                ..Default::default()
5132            }),
5133            h6: Some(TextStyleRefinement {
5134                font_size: Some(rems(0.875).into()),
5135                ..Default::default()
5136            }),
5137        }),
5138        code_block: StyleRefinement {
5139            padding: EdgesRefinement {
5140                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5141                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5142                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5143                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5144            },
5145            margin: EdgesRefinement {
5146                top: Some(Length::Definite(Pixels(8.).into())),
5147                left: Some(Length::Definite(Pixels(0.).into())),
5148                right: Some(Length::Definite(Pixels(0.).into())),
5149                bottom: Some(Length::Definite(Pixels(12.).into())),
5150            },
5151            border_style: Some(BorderStyle::Solid),
5152            border_widths: EdgesRefinement {
5153                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5154                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5155                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5156                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5157            },
5158            border_color: Some(colors.border_variant),
5159            background: Some(colors.editor_background.into()),
5160            text: Some(TextStyleRefinement {
5161                font_family: Some(theme_settings.buffer_font.family.clone()),
5162                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5163                font_features: Some(theme_settings.buffer_font.features.clone()),
5164                font_size: Some(buffer_font_size.into()),
5165                ..Default::default()
5166            }),
5167            ..Default::default()
5168        },
5169        inline_code: TextStyleRefinement {
5170            font_family: Some(theme_settings.buffer_font.family.clone()),
5171            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5172            font_features: Some(theme_settings.buffer_font.features.clone()),
5173            font_size: Some(buffer_font_size.into()),
5174            background_color: Some(colors.editor_foreground.opacity(0.08)),
5175            ..Default::default()
5176        },
5177        link: TextStyleRefinement {
5178            background_color: Some(colors.editor_foreground.opacity(0.025)),
5179            underline: Some(UnderlineStyle {
5180                color: Some(colors.text_accent.opacity(0.5)),
5181                thickness: px(1.),
5182                ..Default::default()
5183            }),
5184            ..Default::default()
5185        },
5186        ..Default::default()
5187    }
5188}
5189
5190fn plan_label_markdown_style(
5191    status: &acp::PlanEntryStatus,
5192    window: &Window,
5193    cx: &App,
5194) -> MarkdownStyle {
5195    let default_md_style = default_markdown_style(false, false, window, cx);
5196
5197    MarkdownStyle {
5198        base_text_style: TextStyle {
5199            color: cx.theme().colors().text_muted,
5200            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5201                Some(gpui::StrikethroughStyle {
5202                    thickness: px(1.),
5203                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5204                })
5205            } else {
5206                None
5207            },
5208            ..default_md_style.base_text_style
5209        },
5210        ..default_md_style
5211    }
5212}
5213
5214fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5215    let default_md_style = default_markdown_style(true, false, window, cx);
5216
5217    MarkdownStyle {
5218        base_text_style: TextStyle {
5219            ..default_md_style.base_text_style
5220        },
5221        selection_background_color: cx.theme().colors().element_selection_background,
5222        ..Default::default()
5223    }
5224}
5225
5226#[cfg(test)]
5227pub(crate) mod tests {
5228    use acp_thread::StubAgentConnection;
5229    use agent_client_protocol::SessionId;
5230    use assistant_context::ContextStore;
5231    use editor::EditorSettings;
5232    use fs::FakeFs;
5233    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5234    use project::Project;
5235    use serde_json::json;
5236    use settings::SettingsStore;
5237    use std::any::Any;
5238    use std::path::Path;
5239    use workspace::Item;
5240
5241    use super::*;
5242
5243    #[gpui::test]
5244    async fn test_drop(cx: &mut TestAppContext) {
5245        init_test(cx);
5246
5247        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5248        let weak_view = thread_view.downgrade();
5249        drop(thread_view);
5250        assert!(!weak_view.is_upgradable());
5251    }
5252
5253    #[gpui::test]
5254    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5255        init_test(cx);
5256
5257        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5258
5259        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5260        message_editor.update_in(cx, |editor, window, cx| {
5261            editor.set_text("Hello", window, cx);
5262        });
5263
5264        cx.deactivate_window();
5265
5266        thread_view.update_in(cx, |thread_view, window, cx| {
5267            thread_view.send(window, cx);
5268        });
5269
5270        cx.run_until_parked();
5271
5272        assert!(
5273            cx.windows()
5274                .iter()
5275                .any(|window| window.downcast::<AgentNotification>().is_some())
5276        );
5277    }
5278
5279    #[gpui::test]
5280    async fn test_notification_for_error(cx: &mut TestAppContext) {
5281        init_test(cx);
5282
5283        let (thread_view, cx) =
5284            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5285
5286        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5287        message_editor.update_in(cx, |editor, window, cx| {
5288            editor.set_text("Hello", window, cx);
5289        });
5290
5291        cx.deactivate_window();
5292
5293        thread_view.update_in(cx, |thread_view, window, cx| {
5294            thread_view.send(window, cx);
5295        });
5296
5297        cx.run_until_parked();
5298
5299        assert!(
5300            cx.windows()
5301                .iter()
5302                .any(|window| window.downcast::<AgentNotification>().is_some())
5303        );
5304    }
5305
5306    #[gpui::test]
5307    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5308        init_test(cx);
5309
5310        let tool_call_id = acp::ToolCallId("1".into());
5311        let tool_call = acp::ToolCall {
5312            id: tool_call_id.clone(),
5313            title: "Label".into(),
5314            kind: acp::ToolKind::Edit,
5315            status: acp::ToolCallStatus::Pending,
5316            content: vec!["hi".into()],
5317            locations: vec![],
5318            raw_input: None,
5319            raw_output: None,
5320        };
5321        let connection =
5322            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5323                tool_call_id,
5324                vec![acp::PermissionOption {
5325                    id: acp::PermissionOptionId("1".into()),
5326                    name: "Allow".into(),
5327                    kind: acp::PermissionOptionKind::AllowOnce,
5328                }],
5329            )]));
5330
5331        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5332
5333        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5334
5335        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5336        message_editor.update_in(cx, |editor, window, cx| {
5337            editor.set_text("Hello", window, cx);
5338        });
5339
5340        cx.deactivate_window();
5341
5342        thread_view.update_in(cx, |thread_view, window, cx| {
5343            thread_view.send(window, cx);
5344        });
5345
5346        cx.run_until_parked();
5347
5348        assert!(
5349            cx.windows()
5350                .iter()
5351                .any(|window| window.downcast::<AgentNotification>().is_some())
5352        );
5353    }
5354
5355    async fn setup_thread_view(
5356        agent: impl AgentServer + 'static,
5357        cx: &mut TestAppContext,
5358    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5359        let fs = FakeFs::new(cx.executor());
5360        let project = Project::test(fs, [], cx).await;
5361        let (workspace, cx) =
5362            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5363
5364        let context_store =
5365            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5366        let history_store =
5367            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5368
5369        let thread_view = cx.update(|window, cx| {
5370            cx.new(|cx| {
5371                AcpThreadView::new(
5372                    Rc::new(agent),
5373                    None,
5374                    None,
5375                    workspace.downgrade(),
5376                    project,
5377                    history_store,
5378                    None,
5379                    window,
5380                    cx,
5381                )
5382            })
5383        });
5384        cx.run_until_parked();
5385        (thread_view, cx)
5386    }
5387
5388    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5389        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5390
5391        workspace
5392            .update_in(cx, |workspace, window, cx| {
5393                workspace.add_item_to_active_pane(
5394                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5395                    None,
5396                    true,
5397                    window,
5398                    cx,
5399                );
5400            })
5401            .unwrap();
5402    }
5403
5404    struct ThreadViewItem(Entity<AcpThreadView>);
5405
5406    impl Item for ThreadViewItem {
5407        type Event = ();
5408
5409        fn include_in_nav_history() -> bool {
5410            false
5411        }
5412
5413        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5414            "Test".into()
5415        }
5416    }
5417
5418    impl EventEmitter<()> for ThreadViewItem {}
5419
5420    impl Focusable for ThreadViewItem {
5421        fn focus_handle(&self, cx: &App) -> FocusHandle {
5422            self.0.read(cx).focus_handle(cx)
5423        }
5424    }
5425
5426    impl Render for ThreadViewItem {
5427        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5428            self.0.clone().into_any_element()
5429        }
5430    }
5431
5432    struct StubAgentServer<C> {
5433        connection: C,
5434    }
5435
5436    impl<C> StubAgentServer<C> {
5437        fn new(connection: C) -> Self {
5438            Self { connection }
5439        }
5440    }
5441
5442    impl StubAgentServer<StubAgentConnection> {
5443        fn default_response() -> Self {
5444            let conn = StubAgentConnection::new();
5445            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5446                content: "Default response".into(),
5447            }]);
5448            Self::new(conn)
5449        }
5450    }
5451
5452    impl<C> AgentServer for StubAgentServer<C>
5453    where
5454        C: 'static + AgentConnection + Send + Clone,
5455    {
5456        fn telemetry_id(&self) -> &'static str {
5457            "test"
5458        }
5459
5460        fn logo(&self) -> ui::IconName {
5461            ui::IconName::Ai
5462        }
5463
5464        fn name(&self) -> SharedString {
5465            "Test".into()
5466        }
5467
5468        fn connect(
5469            &self,
5470            _root_dir: &Path,
5471            _delegate: AgentServerDelegate,
5472            _cx: &mut App,
5473        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5474            Task::ready(Ok(Rc::new(self.connection.clone())))
5475        }
5476
5477        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5478            self
5479        }
5480    }
5481
5482    #[derive(Clone)]
5483    struct SaboteurAgentConnection;
5484
5485    impl AgentConnection for SaboteurAgentConnection {
5486        fn new_thread(
5487            self: Rc<Self>,
5488            project: Entity<Project>,
5489            _cwd: &Path,
5490            cx: &mut gpui::App,
5491        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5492            Task::ready(Ok(cx.new(|cx| {
5493                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5494                AcpThread::new(
5495                    "SaboteurAgentConnection",
5496                    self,
5497                    project,
5498                    action_log,
5499                    SessionId("test".into()),
5500                    watch::Receiver::constant(acp::PromptCapabilities {
5501                        image: true,
5502                        audio: true,
5503                        embedded_context: true,
5504                    }),
5505                    cx,
5506                )
5507            })))
5508        }
5509
5510        fn auth_methods(&self) -> &[acp::AuthMethod] {
5511            &[]
5512        }
5513
5514        fn authenticate(
5515            &self,
5516            _method_id: acp::AuthMethodId,
5517            _cx: &mut App,
5518        ) -> Task<gpui::Result<()>> {
5519            unimplemented!()
5520        }
5521
5522        fn prompt(
5523            &self,
5524            _id: Option<acp_thread::UserMessageId>,
5525            _params: acp::PromptRequest,
5526            _cx: &mut App,
5527        ) -> Task<gpui::Result<acp::PromptResponse>> {
5528            Task::ready(Err(anyhow::anyhow!("Error prompting")))
5529        }
5530
5531        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5532            unimplemented!()
5533        }
5534
5535        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5536            self
5537        }
5538    }
5539
5540    pub(crate) fn init_test(cx: &mut TestAppContext) {
5541        cx.update(|cx| {
5542            let settings_store = SettingsStore::test(cx);
5543            cx.set_global(settings_store);
5544            language::init(cx);
5545            Project::init_settings(cx);
5546            AgentSettings::register(cx);
5547            workspace::init_settings(cx);
5548            ThemeSettings::register(cx);
5549            release_channel::init(SemanticVersion::default(), cx);
5550            EditorSettings::register(cx);
5551            prompt_store::init(cx)
5552        });
5553    }
5554
5555    #[gpui::test]
5556    async fn test_rewind_views(cx: &mut TestAppContext) {
5557        init_test(cx);
5558
5559        let fs = FakeFs::new(cx.executor());
5560        fs.insert_tree(
5561            "/project",
5562            json!({
5563                "test1.txt": "old content 1",
5564                "test2.txt": "old content 2"
5565            }),
5566        )
5567        .await;
5568        let project = Project::test(fs, [Path::new("/project")], cx).await;
5569        let (workspace, cx) =
5570            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5571
5572        let context_store =
5573            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5574        let history_store =
5575            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5576
5577        let connection = Rc::new(StubAgentConnection::new());
5578        let thread_view = cx.update(|window, cx| {
5579            cx.new(|cx| {
5580                AcpThreadView::new(
5581                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5582                    None,
5583                    None,
5584                    workspace.downgrade(),
5585                    project.clone(),
5586                    history_store.clone(),
5587                    None,
5588                    window,
5589                    cx,
5590                )
5591            })
5592        });
5593
5594        cx.run_until_parked();
5595
5596        let thread = thread_view
5597            .read_with(cx, |view, _| view.thread().cloned())
5598            .unwrap();
5599
5600        // First user message
5601        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5602            id: acp::ToolCallId("tool1".into()),
5603            title: "Edit file 1".into(),
5604            kind: acp::ToolKind::Edit,
5605            status: acp::ToolCallStatus::Completed,
5606            content: vec![acp::ToolCallContent::Diff {
5607                diff: acp::Diff {
5608                    path: "/project/test1.txt".into(),
5609                    old_text: Some("old content 1".into()),
5610                    new_text: "new content 1".into(),
5611                },
5612            }],
5613            locations: vec![],
5614            raw_input: None,
5615            raw_output: None,
5616        })]);
5617
5618        thread
5619            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5620            .await
5621            .unwrap();
5622        cx.run_until_parked();
5623
5624        thread.read_with(cx, |thread, _| {
5625            assert_eq!(thread.entries().len(), 2);
5626        });
5627
5628        thread_view.read_with(cx, |view, cx| {
5629            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5630                assert!(
5631                    entry_view_state
5632                        .entry(0)
5633                        .unwrap()
5634                        .message_editor()
5635                        .is_some()
5636                );
5637                assert!(entry_view_state.entry(1).unwrap().has_content());
5638            });
5639        });
5640
5641        // Second user message
5642        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5643            id: acp::ToolCallId("tool2".into()),
5644            title: "Edit file 2".into(),
5645            kind: acp::ToolKind::Edit,
5646            status: acp::ToolCallStatus::Completed,
5647            content: vec![acp::ToolCallContent::Diff {
5648                diff: acp::Diff {
5649                    path: "/project/test2.txt".into(),
5650                    old_text: Some("old content 2".into()),
5651                    new_text: "new content 2".into(),
5652                },
5653            }],
5654            locations: vec![],
5655            raw_input: None,
5656            raw_output: None,
5657        })]);
5658
5659        thread
5660            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5661            .await
5662            .unwrap();
5663        cx.run_until_parked();
5664
5665        let second_user_message_id = thread.read_with(cx, |thread, _| {
5666            assert_eq!(thread.entries().len(), 4);
5667            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5668                panic!();
5669            };
5670            user_message.id.clone().unwrap()
5671        });
5672
5673        thread_view.read_with(cx, |view, cx| {
5674            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5675                assert!(
5676                    entry_view_state
5677                        .entry(0)
5678                        .unwrap()
5679                        .message_editor()
5680                        .is_some()
5681                );
5682                assert!(entry_view_state.entry(1).unwrap().has_content());
5683                assert!(
5684                    entry_view_state
5685                        .entry(2)
5686                        .unwrap()
5687                        .message_editor()
5688                        .is_some()
5689                );
5690                assert!(entry_view_state.entry(3).unwrap().has_content());
5691            });
5692        });
5693
5694        // Rewind to first message
5695        thread
5696            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5697            .await
5698            .unwrap();
5699
5700        cx.run_until_parked();
5701
5702        thread.read_with(cx, |thread, _| {
5703            assert_eq!(thread.entries().len(), 2);
5704        });
5705
5706        thread_view.read_with(cx, |view, cx| {
5707            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5708                assert!(
5709                    entry_view_state
5710                        .entry(0)
5711                        .unwrap()
5712                        .message_editor()
5713                        .is_some()
5714                );
5715                assert!(entry_view_state.entry(1).unwrap().has_content());
5716
5717                // Old views should be dropped
5718                assert!(entry_view_state.entry(2).is_none());
5719                assert!(entry_view_state.entry(3).is_none());
5720            });
5721        });
5722    }
5723
5724    #[gpui::test]
5725    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5726        init_test(cx);
5727
5728        let connection = StubAgentConnection::new();
5729
5730        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5731            content: acp::ContentBlock::Text(acp::TextContent {
5732                text: "Response".into(),
5733                annotations: None,
5734            }),
5735        }]);
5736
5737        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5738        add_to_workspace(thread_view.clone(), cx);
5739
5740        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5741        message_editor.update_in(cx, |editor, window, cx| {
5742            editor.set_text("Original message to edit", window, cx);
5743        });
5744        thread_view.update_in(cx, |thread_view, window, cx| {
5745            thread_view.send(window, cx);
5746        });
5747
5748        cx.run_until_parked();
5749
5750        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5751            assert_eq!(view.editing_message, None);
5752
5753            view.entry_view_state
5754                .read(cx)
5755                .entry(0)
5756                .unwrap()
5757                .message_editor()
5758                .unwrap()
5759                .clone()
5760        });
5761
5762        // Focus
5763        cx.focus(&user_message_editor);
5764        thread_view.read_with(cx, |view, _cx| {
5765            assert_eq!(view.editing_message, Some(0));
5766        });
5767
5768        // Edit
5769        user_message_editor.update_in(cx, |editor, window, cx| {
5770            editor.set_text("Edited message content", window, cx);
5771        });
5772
5773        // Cancel
5774        user_message_editor.update_in(cx, |_editor, window, cx| {
5775            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5776        });
5777
5778        thread_view.read_with(cx, |view, _cx| {
5779            assert_eq!(view.editing_message, None);
5780        });
5781
5782        user_message_editor.read_with(cx, |editor, cx| {
5783            assert_eq!(editor.text(cx), "Original message to edit");
5784        });
5785    }
5786
5787    #[gpui::test]
5788    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5789        init_test(cx);
5790
5791        let connection = StubAgentConnection::new();
5792
5793        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5794        add_to_workspace(thread_view.clone(), cx);
5795
5796        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5797        let mut events = cx.events(&message_editor);
5798        message_editor.update_in(cx, |editor, window, cx| {
5799            editor.set_text("", window, cx);
5800        });
5801
5802        message_editor.update_in(cx, |_editor, window, cx| {
5803            window.dispatch_action(Box::new(Chat), cx);
5804        });
5805        cx.run_until_parked();
5806        // We shouldn't have received any messages
5807        assert!(matches!(
5808            events.try_next(),
5809            Err(futures::channel::mpsc::TryRecvError { .. })
5810        ));
5811    }
5812
5813    #[gpui::test]
5814    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5815        init_test(cx);
5816
5817        let connection = StubAgentConnection::new();
5818
5819        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5820            content: acp::ContentBlock::Text(acp::TextContent {
5821                text: "Response".into(),
5822                annotations: None,
5823            }),
5824        }]);
5825
5826        let (thread_view, cx) =
5827            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5828        add_to_workspace(thread_view.clone(), cx);
5829
5830        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5831        message_editor.update_in(cx, |editor, window, cx| {
5832            editor.set_text("Original message to edit", window, cx);
5833        });
5834        thread_view.update_in(cx, |thread_view, window, cx| {
5835            thread_view.send(window, cx);
5836        });
5837
5838        cx.run_until_parked();
5839
5840        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5841            assert_eq!(view.editing_message, None);
5842            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5843
5844            view.entry_view_state
5845                .read(cx)
5846                .entry(0)
5847                .unwrap()
5848                .message_editor()
5849                .unwrap()
5850                .clone()
5851        });
5852
5853        // Focus
5854        cx.focus(&user_message_editor);
5855
5856        // Edit
5857        user_message_editor.update_in(cx, |editor, window, cx| {
5858            editor.set_text("Edited message content", window, cx);
5859        });
5860
5861        // Send
5862        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5863            content: acp::ContentBlock::Text(acp::TextContent {
5864                text: "New Response".into(),
5865                annotations: None,
5866            }),
5867        }]);
5868
5869        user_message_editor.update_in(cx, |_editor, window, cx| {
5870            window.dispatch_action(Box::new(Chat), cx);
5871        });
5872
5873        cx.run_until_parked();
5874
5875        thread_view.read_with(cx, |view, cx| {
5876            assert_eq!(view.editing_message, None);
5877
5878            let entries = view.thread().unwrap().read(cx).entries();
5879            assert_eq!(entries.len(), 2);
5880            assert_eq!(
5881                entries[0].to_markdown(cx),
5882                "## User\n\nEdited message content\n\n"
5883            );
5884            assert_eq!(
5885                entries[1].to_markdown(cx),
5886                "## Assistant\n\nNew Response\n\n"
5887            );
5888
5889            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5890                assert!(!state.entry(1).unwrap().has_content());
5891                state.entry(0).unwrap().message_editor().unwrap().clone()
5892            });
5893
5894            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5895        })
5896    }
5897
5898    #[gpui::test]
5899    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5900        init_test(cx);
5901
5902        let connection = StubAgentConnection::new();
5903
5904        let (thread_view, cx) =
5905            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5906        add_to_workspace(thread_view.clone(), cx);
5907
5908        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5909        message_editor.update_in(cx, |editor, window, cx| {
5910            editor.set_text("Original message to edit", window, cx);
5911        });
5912        thread_view.update_in(cx, |thread_view, window, cx| {
5913            thread_view.send(window, cx);
5914        });
5915
5916        cx.run_until_parked();
5917
5918        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5919            let thread = view.thread().unwrap().read(cx);
5920            assert_eq!(thread.entries().len(), 1);
5921
5922            let editor = view
5923                .entry_view_state
5924                .read(cx)
5925                .entry(0)
5926                .unwrap()
5927                .message_editor()
5928                .unwrap()
5929                .clone();
5930
5931            (editor, thread.session_id().clone())
5932        });
5933
5934        // Focus
5935        cx.focus(&user_message_editor);
5936
5937        thread_view.read_with(cx, |view, _cx| {
5938            assert_eq!(view.editing_message, Some(0));
5939        });
5940
5941        // Edit
5942        user_message_editor.update_in(cx, |editor, window, cx| {
5943            editor.set_text("Edited message content", window, cx);
5944        });
5945
5946        thread_view.read_with(cx, |view, _cx| {
5947            assert_eq!(view.editing_message, Some(0));
5948        });
5949
5950        // Finish streaming response
5951        cx.update(|_, cx| {
5952            connection.send_update(
5953                session_id.clone(),
5954                acp::SessionUpdate::AgentMessageChunk {
5955                    content: acp::ContentBlock::Text(acp::TextContent {
5956                        text: "Response".into(),
5957                        annotations: None,
5958                    }),
5959                },
5960                cx,
5961            );
5962            connection.end_turn(session_id, acp::StopReason::EndTurn);
5963        });
5964
5965        thread_view.read_with(cx, |view, _cx| {
5966            assert_eq!(view.editing_message, Some(0));
5967        });
5968
5969        cx.run_until_parked();
5970
5971        // Should still be editing
5972        cx.update(|window, cx| {
5973            assert!(user_message_editor.focus_handle(cx).is_focused(window));
5974            assert_eq!(thread_view.read(cx).editing_message, Some(0));
5975            assert_eq!(
5976                user_message_editor.read(cx).text(cx),
5977                "Edited message content"
5978            );
5979        });
5980    }
5981
5982    #[gpui::test]
5983    async fn test_interrupt(cx: &mut TestAppContext) {
5984        init_test(cx);
5985
5986        let connection = StubAgentConnection::new();
5987
5988        let (thread_view, cx) =
5989            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5990        add_to_workspace(thread_view.clone(), cx);
5991
5992        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5993        message_editor.update_in(cx, |editor, window, cx| {
5994            editor.set_text("Message 1", window, cx);
5995        });
5996        thread_view.update_in(cx, |thread_view, window, cx| {
5997            thread_view.send(window, cx);
5998        });
5999
6000        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6001            let thread = view.thread().unwrap();
6002
6003            (thread.clone(), thread.read(cx).session_id().clone())
6004        });
6005
6006        cx.run_until_parked();
6007
6008        cx.update(|_, cx| {
6009            connection.send_update(
6010                session_id.clone(),
6011                acp::SessionUpdate::AgentMessageChunk {
6012                    content: "Message 1 resp".into(),
6013                },
6014                cx,
6015            );
6016        });
6017
6018        cx.run_until_parked();
6019
6020        thread.read_with(cx, |thread, cx| {
6021            assert_eq!(
6022                thread.to_markdown(cx),
6023                indoc::indoc! {"
6024                    ## User
6025
6026                    Message 1
6027
6028                    ## Assistant
6029
6030                    Message 1 resp
6031
6032                "}
6033            )
6034        });
6035
6036        message_editor.update_in(cx, |editor, window, cx| {
6037            editor.set_text("Message 2", window, cx);
6038        });
6039        thread_view.update_in(cx, |thread_view, window, cx| {
6040            thread_view.send(window, cx);
6041        });
6042
6043        cx.update(|_, cx| {
6044            // Simulate a response sent after beginning to cancel
6045            connection.send_update(
6046                session_id.clone(),
6047                acp::SessionUpdate::AgentMessageChunk {
6048                    content: "onse".into(),
6049                },
6050                cx,
6051            );
6052        });
6053
6054        cx.run_until_parked();
6055
6056        // Last Message 1 response should appear before Message 2
6057        thread.read_with(cx, |thread, cx| {
6058            assert_eq!(
6059                thread.to_markdown(cx),
6060                indoc::indoc! {"
6061                    ## User
6062
6063                    Message 1
6064
6065                    ## Assistant
6066
6067                    Message 1 response
6068
6069                    ## User
6070
6071                    Message 2
6072
6073                "}
6074            )
6075        });
6076
6077        cx.update(|_, cx| {
6078            connection.send_update(
6079                session_id.clone(),
6080                acp::SessionUpdate::AgentMessageChunk {
6081                    content: "Message 2 response".into(),
6082                },
6083                cx,
6084            );
6085            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6086        });
6087
6088        cx.run_until_parked();
6089
6090        thread.read_with(cx, |thread, cx| {
6091            assert_eq!(
6092                thread.to_markdown(cx),
6093                indoc::indoc! {"
6094                    ## User
6095
6096                    Message 1
6097
6098                    ## Assistant
6099
6100                    Message 1 response
6101
6102                    ## User
6103
6104                    Message 2
6105
6106                    ## Assistant
6107
6108                    Message 2 response
6109
6110                "}
6111            )
6112        });
6113    }
6114}