thread_view.rs

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