thread_view.rs

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