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