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