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