thread_view.rs

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