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_3()
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                return self.render_not_installed(None, window, cx);
2830            }
2831            LoadError::Unsupported {
2832                command: path,
2833                current_version,
2834            } => {
2835                return self.render_not_installed(Some((path, current_version)), window, cx);
2836            }
2837            LoadError::Exited { .. } => ("Server exited with status {status}".into(), None),
2838            LoadError::Other(msg) => (
2839                msg.into(),
2840                Some(self.create_copy_button(msg.to_string()).into_any_element()),
2841            ),
2842        };
2843
2844        Callout::new()
2845            .severity(Severity::Error)
2846            .icon(IconName::XCircleFilled)
2847            .title("Failed to Launch")
2848            .description(message)
2849            .actions_slot(div().children(action_slot))
2850            .into_any_element()
2851    }
2852
2853    fn install_agent(&self, window: &mut Window, cx: &mut Context<Self>) {
2854        telemetry::event!("Agent Install CLI", agent = self.agent.telemetry_id());
2855        let Some(install_command) = self.agent.install_command().map(|s| s.to_owned()) else {
2856            return;
2857        };
2858        let task = self
2859            .workspace
2860            .update(cx, |workspace, cx| {
2861                let project = workspace.project().read(cx);
2862                let cwd = project.first_project_directory(cx);
2863                let shell = project.terminal_settings(&cwd, cx).shell.clone();
2864                let spawn_in_terminal = task::SpawnInTerminal {
2865                    id: task::TaskId(install_command.clone()),
2866                    full_label: install_command.clone(),
2867                    label: install_command.clone(),
2868                    command: Some(install_command.clone()),
2869                    args: Vec::new(),
2870                    command_label: install_command.clone(),
2871                    cwd,
2872                    env: Default::default(),
2873                    use_new_terminal: true,
2874                    allow_concurrent_runs: true,
2875                    reveal: Default::default(),
2876                    reveal_target: Default::default(),
2877                    hide: Default::default(),
2878                    shell,
2879                    show_summary: true,
2880                    show_command: true,
2881                    show_rerun: false,
2882                };
2883                workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2884            })
2885            .ok();
2886        let Some(task) = task else { return };
2887        cx.spawn_in(window, async move |this, cx| {
2888            if let Some(Ok(_)) = task.await {
2889                this.update_in(cx, |this, window, cx| {
2890                    this.reset(window, cx);
2891                })
2892                .ok();
2893            }
2894        })
2895        .detach()
2896    }
2897
2898    fn render_not_installed(
2899        &self,
2900        existing_version: Option<(&SharedString, &SharedString)>,
2901        window: &mut Window,
2902        cx: &mut Context<Self>,
2903    ) -> AnyElement {
2904        let install_command = self.agent.install_command().unwrap_or_default();
2905
2906        self.install_command_markdown.update(cx, |markdown, cx| {
2907            if !markdown.source().contains(&install_command) {
2908                markdown.replace(format!("```\n{}\n```", install_command), cx);
2909            }
2910        });
2911
2912        let (heading_label, description_label, button_label) =
2913            if let Some((path, version)) = existing_version {
2914                (
2915                    format!("Upgrade {} to work with Zed", self.agent.name()),
2916                    format!(
2917                        "Currently using {}, which is only version {}",
2918                        path, version
2919                    ),
2920                    format!("Upgrade {}", self.agent.name()),
2921                )
2922            } else {
2923                (
2924                    format!("Get Started with {} in Zed", self.agent.name()),
2925                    "Use Google's new coding agent directly in Zed.".to_string(),
2926                    format!("Install {}", self.agent.name()),
2927                )
2928            };
2929
2930        v_flex()
2931            .w_full()
2932            .p_3p5()
2933            .gap_2p5()
2934            .border_t_1()
2935            .border_color(cx.theme().colors().border)
2936            .bg(linear_gradient(
2937                180.,
2938                linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
2939                linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
2940            ))
2941            .child(
2942                v_flex().gap_0p5().child(Label::new(heading_label)).child(
2943                    Label::new(description_label)
2944                        .size(LabelSize::Small)
2945                        .color(Color::Muted),
2946                ),
2947            )
2948            .child(
2949                Button::new("install_gemini", button_label)
2950                    .full_width()
2951                    .size(ButtonSize::Medium)
2952                    .style(ButtonStyle::Tinted(TintColor::Accent))
2953                    .label_size(LabelSize::Small)
2954                    .icon(IconName::TerminalGhost)
2955                    .icon_color(Color::Muted)
2956                    .icon_size(IconSize::Small)
2957                    .icon_position(IconPosition::Start)
2958                    .on_click(cx.listener(|this, _, window, cx| this.install_agent(window, cx))),
2959            )
2960            .child(
2961                Label::new("Or, run the following command in your terminal:")
2962                    .size(LabelSize::Small)
2963                    .color(Color::Muted),
2964            )
2965            .child(MarkdownElement::new(
2966                self.install_command_markdown.clone(),
2967                default_markdown_style(false, false, window, cx),
2968            ))
2969            .into_any_element()
2970    }
2971
2972    fn render_activity_bar(
2973        &self,
2974        thread_entity: &Entity<AcpThread>,
2975        window: &mut Window,
2976        cx: &Context<Self>,
2977    ) -> Option<AnyElement> {
2978        let thread = thread_entity.read(cx);
2979        let action_log = thread.action_log();
2980        let changed_buffers = action_log.read(cx).changed_buffers(cx);
2981        let plan = thread.plan();
2982
2983        if changed_buffers.is_empty() && plan.is_empty() {
2984            return None;
2985        }
2986
2987        let editor_bg_color = cx.theme().colors().editor_background;
2988        let active_color = cx.theme().colors().element_selected;
2989        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2990
2991        let pending_edits = thread.has_pending_edit_tool_calls();
2992
2993        v_flex()
2994            .mt_1()
2995            .mx_2()
2996            .bg(bg_edit_files_disclosure)
2997            .border_1()
2998            .border_b_0()
2999            .border_color(cx.theme().colors().border)
3000            .rounded_t_md()
3001            .shadow(vec![gpui::BoxShadow {
3002                color: gpui::black().opacity(0.15),
3003                offset: point(px(1.), px(-1.)),
3004                blur_radius: px(3.),
3005                spread_radius: px(0.),
3006            }])
3007            .when(!plan.is_empty(), |this| {
3008                this.child(self.render_plan_summary(plan, window, cx))
3009                    .when(self.plan_expanded, |parent| {
3010                        parent.child(self.render_plan_entries(plan, window, cx))
3011                    })
3012            })
3013            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3014                this.child(Divider::horizontal().color(DividerColor::Border))
3015            })
3016            .when(!changed_buffers.is_empty(), |this| {
3017                this.child(self.render_edits_summary(
3018                    &changed_buffers,
3019                    self.edits_expanded,
3020                    pending_edits,
3021                    window,
3022                    cx,
3023                ))
3024                .when(self.edits_expanded, |parent| {
3025                    parent.child(self.render_edited_files(
3026                        action_log,
3027                        &changed_buffers,
3028                        pending_edits,
3029                        cx,
3030                    ))
3031                })
3032            })
3033            .into_any()
3034            .into()
3035    }
3036
3037    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3038        let stats = plan.stats();
3039
3040        let title = if let Some(entry) = stats.in_progress_entry
3041            && !self.plan_expanded
3042        {
3043            h_flex()
3044                .w_full()
3045                .cursor_default()
3046                .gap_1()
3047                .text_xs()
3048                .text_color(cx.theme().colors().text_muted)
3049                .justify_between()
3050                .child(
3051                    h_flex()
3052                        .gap_1()
3053                        .child(
3054                            Label::new("Current:")
3055                                .size(LabelSize::Small)
3056                                .color(Color::Muted),
3057                        )
3058                        .child(MarkdownElement::new(
3059                            entry.content.clone(),
3060                            plan_label_markdown_style(&entry.status, window, cx),
3061                        )),
3062                )
3063                .when(stats.pending > 0, |this| {
3064                    this.child(
3065                        Label::new(format!("{} left", stats.pending))
3066                            .size(LabelSize::Small)
3067                            .color(Color::Muted)
3068                            .mr_1(),
3069                    )
3070                })
3071        } else {
3072            let status_label = if stats.pending == 0 {
3073                "All Done".to_string()
3074            } else if stats.completed == 0 {
3075                format!("{} Tasks", plan.entries.len())
3076            } else {
3077                format!("{}/{}", stats.completed, plan.entries.len())
3078            };
3079
3080            h_flex()
3081                .w_full()
3082                .gap_1()
3083                .justify_between()
3084                .child(
3085                    Label::new("Plan")
3086                        .size(LabelSize::Small)
3087                        .color(Color::Muted),
3088                )
3089                .child(
3090                    Label::new(status_label)
3091                        .size(LabelSize::Small)
3092                        .color(Color::Muted)
3093                        .mr_1(),
3094                )
3095        };
3096
3097        h_flex()
3098            .p_1()
3099            .justify_between()
3100            .when(self.plan_expanded, |this| {
3101                this.border_b_1().border_color(cx.theme().colors().border)
3102            })
3103            .child(
3104                h_flex()
3105                    .id("plan_summary")
3106                    .w_full()
3107                    .gap_1()
3108                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3109                    .child(title)
3110                    .on_click(cx.listener(|this, _, _, cx| {
3111                        this.plan_expanded = !this.plan_expanded;
3112                        cx.notify();
3113                    })),
3114            )
3115    }
3116
3117    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3118        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3119            let element = h_flex()
3120                .py_1()
3121                .px_2()
3122                .gap_2()
3123                .justify_between()
3124                .bg(cx.theme().colors().editor_background)
3125                .when(index < plan.entries.len() - 1, |parent| {
3126                    parent.border_color(cx.theme().colors().border).border_b_1()
3127                })
3128                .child(
3129                    h_flex()
3130                        .id(("plan_entry", index))
3131                        .gap_1p5()
3132                        .max_w_full()
3133                        .overflow_x_scroll()
3134                        .text_xs()
3135                        .text_color(cx.theme().colors().text_muted)
3136                        .child(match entry.status {
3137                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3138                                .size(IconSize::Small)
3139                                .color(Color::Muted)
3140                                .into_any_element(),
3141                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3142                                .size(IconSize::Small)
3143                                .color(Color::Accent)
3144                                .with_animation(
3145                                    "running",
3146                                    Animation::new(Duration::from_secs(2)).repeat(),
3147                                    |icon, delta| {
3148                                        icon.transform(Transformation::rotate(percentage(delta)))
3149                                    },
3150                                )
3151                                .into_any_element(),
3152                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3153                                .size(IconSize::Small)
3154                                .color(Color::Success)
3155                                .into_any_element(),
3156                        })
3157                        .child(MarkdownElement::new(
3158                            entry.content.clone(),
3159                            plan_label_markdown_style(&entry.status, window, cx),
3160                        )),
3161                );
3162
3163            Some(element)
3164        }))
3165    }
3166
3167    fn render_edits_summary(
3168        &self,
3169        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3170        expanded: bool,
3171        pending_edits: bool,
3172        window: &mut Window,
3173        cx: &Context<Self>,
3174    ) -> Div {
3175        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3176
3177        let focus_handle = self.focus_handle(cx);
3178
3179        h_flex()
3180            .p_1()
3181            .justify_between()
3182            .flex_wrap()
3183            .when(expanded, |this| {
3184                this.border_b_1().border_color(cx.theme().colors().border)
3185            })
3186            .child(
3187                h_flex()
3188                    .id("edits-container")
3189                    .gap_1()
3190                    .child(Disclosure::new("edits-disclosure", expanded))
3191                    .map(|this| {
3192                        if pending_edits {
3193                            this.child(
3194                                Label::new(format!(
3195                                    "Editing {} {}",
3196                                    changed_buffers.len(),
3197                                    if changed_buffers.len() == 1 {
3198                                        "file"
3199                                    } else {
3200                                        "files"
3201                                    }
3202                                ))
3203                                .color(Color::Muted)
3204                                .size(LabelSize::Small)
3205                                .with_animation(
3206                                    "edit-label",
3207                                    Animation::new(Duration::from_secs(2))
3208                                        .repeat()
3209                                        .with_easing(pulsating_between(0.3, 0.7)),
3210                                    |label, delta| label.alpha(delta),
3211                                ),
3212                            )
3213                        } else {
3214                            this.child(
3215                                Label::new("Edits")
3216                                    .size(LabelSize::Small)
3217                                    .color(Color::Muted),
3218                            )
3219                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
3220                            .child(
3221                                Label::new(format!(
3222                                    "{} {}",
3223                                    changed_buffers.len(),
3224                                    if changed_buffers.len() == 1 {
3225                                        "file"
3226                                    } else {
3227                                        "files"
3228                                    }
3229                                ))
3230                                .size(LabelSize::Small)
3231                                .color(Color::Muted),
3232                            )
3233                        }
3234                    })
3235                    .on_click(cx.listener(|this, _, _, cx| {
3236                        this.edits_expanded = !this.edits_expanded;
3237                        cx.notify();
3238                    })),
3239            )
3240            .child(
3241                h_flex()
3242                    .gap_1()
3243                    .child(
3244                        IconButton::new("review-changes", IconName::ListTodo)
3245                            .icon_size(IconSize::Small)
3246                            .tooltip({
3247                                let focus_handle = focus_handle.clone();
3248                                move |window, cx| {
3249                                    Tooltip::for_action_in(
3250                                        "Review Changes",
3251                                        &OpenAgentDiff,
3252                                        &focus_handle,
3253                                        window,
3254                                        cx,
3255                                    )
3256                                }
3257                            })
3258                            .on_click(cx.listener(|_, _, window, cx| {
3259                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3260                            })),
3261                    )
3262                    .child(Divider::vertical().color(DividerColor::Border))
3263                    .child(
3264                        Button::new("reject-all-changes", "Reject All")
3265                            .label_size(LabelSize::Small)
3266                            .disabled(pending_edits)
3267                            .when(pending_edits, |this| {
3268                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3269                            })
3270                            .key_binding(
3271                                KeyBinding::for_action_in(
3272                                    &RejectAll,
3273                                    &focus_handle.clone(),
3274                                    window,
3275                                    cx,
3276                                )
3277                                .map(|kb| kb.size(rems_from_px(10.))),
3278                            )
3279                            .on_click(cx.listener(move |this, _, window, cx| {
3280                                this.reject_all(&RejectAll, window, cx);
3281                            })),
3282                    )
3283                    .child(
3284                        Button::new("keep-all-changes", "Keep All")
3285                            .label_size(LabelSize::Small)
3286                            .disabled(pending_edits)
3287                            .when(pending_edits, |this| {
3288                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3289                            })
3290                            .key_binding(
3291                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3292                                    .map(|kb| kb.size(rems_from_px(10.))),
3293                            )
3294                            .on_click(cx.listener(move |this, _, window, cx| {
3295                                this.keep_all(&KeepAll, window, cx);
3296                            })),
3297                    ),
3298            )
3299    }
3300
3301    fn render_edited_files(
3302        &self,
3303        action_log: &Entity<ActionLog>,
3304        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3305        pending_edits: bool,
3306        cx: &Context<Self>,
3307    ) -> Div {
3308        let editor_bg_color = cx.theme().colors().editor_background;
3309
3310        v_flex().children(changed_buffers.iter().enumerate().flat_map(
3311            |(index, (buffer, _diff))| {
3312                let file = buffer.read(cx).file()?;
3313                let path = file.path();
3314
3315                let file_path = path.parent().and_then(|parent| {
3316                    let parent_str = parent.to_string_lossy();
3317
3318                    if parent_str.is_empty() {
3319                        None
3320                    } else {
3321                        Some(
3322                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3323                                .color(Color::Muted)
3324                                .size(LabelSize::XSmall)
3325                                .buffer_font(cx),
3326                        )
3327                    }
3328                });
3329
3330                let file_name = path.file_name().map(|name| {
3331                    Label::new(name.to_string_lossy().to_string())
3332                        .size(LabelSize::XSmall)
3333                        .buffer_font(cx)
3334                });
3335
3336                let file_icon = FileIcons::get_icon(path, cx)
3337                    .map(Icon::from_path)
3338                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3339                    .unwrap_or_else(|| {
3340                        Icon::new(IconName::File)
3341                            .color(Color::Muted)
3342                            .size(IconSize::Small)
3343                    });
3344
3345                let overlay_gradient = linear_gradient(
3346                    90.,
3347                    linear_color_stop(editor_bg_color, 1.),
3348                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3349                );
3350
3351                let element = h_flex()
3352                    .group("edited-code")
3353                    .id(("file-container", index))
3354                    .py_1()
3355                    .pl_2()
3356                    .pr_1()
3357                    .gap_2()
3358                    .justify_between()
3359                    .bg(editor_bg_color)
3360                    .when(index < changed_buffers.len() - 1, |parent| {
3361                        parent.border_color(cx.theme().colors().border).border_b_1()
3362                    })
3363                    .child(
3364                        h_flex()
3365                            .relative()
3366                            .id(("file-name", index))
3367                            .pr_8()
3368                            .gap_1p5()
3369                            .max_w_full()
3370                            .overflow_x_scroll()
3371                            .child(file_icon)
3372                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
3373                            .child(
3374                                div()
3375                                    .absolute()
3376                                    .h_full()
3377                                    .w_12()
3378                                    .top_0()
3379                                    .bottom_0()
3380                                    .right_0()
3381                                    .bg(overlay_gradient),
3382                            )
3383                            .on_click({
3384                                let buffer = buffer.clone();
3385                                cx.listener(move |this, _, window, cx| {
3386                                    this.open_edited_buffer(&buffer, window, cx);
3387                                })
3388                            }),
3389                    )
3390                    .child(
3391                        h_flex()
3392                            .gap_1()
3393                            .visible_on_hover("edited-code")
3394                            .child(
3395                                Button::new("review", "Review")
3396                                    .label_size(LabelSize::Small)
3397                                    .on_click({
3398                                        let buffer = buffer.clone();
3399                                        cx.listener(move |this, _, window, cx| {
3400                                            this.open_edited_buffer(&buffer, window, cx);
3401                                        })
3402                                    }),
3403                            )
3404                            .child(Divider::vertical().color(DividerColor::BorderVariant))
3405                            .child(
3406                                Button::new("reject-file", "Reject")
3407                                    .label_size(LabelSize::Small)
3408                                    .disabled(pending_edits)
3409                                    .on_click({
3410                                        let buffer = buffer.clone();
3411                                        let action_log = action_log.clone();
3412                                        move |_, _, cx| {
3413                                            action_log.update(cx, |action_log, cx| {
3414                                                action_log
3415                                                    .reject_edits_in_ranges(
3416                                                        buffer.clone(),
3417                                                        vec![Anchor::MIN..Anchor::MAX],
3418                                                        cx,
3419                                                    )
3420                                                    .detach_and_log_err(cx);
3421                                            })
3422                                        }
3423                                    }),
3424                            )
3425                            .child(
3426                                Button::new("keep-file", "Keep")
3427                                    .label_size(LabelSize::Small)
3428                                    .disabled(pending_edits)
3429                                    .on_click({
3430                                        let buffer = buffer.clone();
3431                                        let action_log = action_log.clone();
3432                                        move |_, _, cx| {
3433                                            action_log.update(cx, |action_log, cx| {
3434                                                action_log.keep_edits_in_range(
3435                                                    buffer.clone(),
3436                                                    Anchor::MIN..Anchor::MAX,
3437                                                    cx,
3438                                                );
3439                                            })
3440                                        }
3441                                    }),
3442                            ),
3443                    );
3444
3445                Some(element)
3446            },
3447        ))
3448    }
3449
3450    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3451        let focus_handle = self.message_editor.focus_handle(cx);
3452        let editor_bg_color = cx.theme().colors().editor_background;
3453        let (expand_icon, expand_tooltip) = if self.editor_expanded {
3454            (IconName::Minimize, "Minimize Message Editor")
3455        } else {
3456            (IconName::Maximize, "Expand Message Editor")
3457        };
3458
3459        let backdrop = div()
3460            .size_full()
3461            .absolute()
3462            .inset_0()
3463            .bg(cx.theme().colors().panel_background)
3464            .opacity(0.8)
3465            .block_mouse_except_scroll();
3466
3467        let enable_editor = match self.thread_state {
3468            ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3469            ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3470        };
3471
3472        v_flex()
3473            .on_action(cx.listener(Self::expand_message_editor))
3474            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3475                if let Some(profile_selector) = this.profile_selector.as_ref() {
3476                    profile_selector.read(cx).menu_handle().toggle(window, cx);
3477                }
3478            }))
3479            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3480                if let Some(model_selector) = this.model_selector.as_ref() {
3481                    model_selector
3482                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3483                }
3484            }))
3485            .p_2()
3486            .gap_2()
3487            .border_t_1()
3488            .border_color(cx.theme().colors().border)
3489            .bg(editor_bg_color)
3490            .when(self.editor_expanded, |this| {
3491                this.h(vh(0.8, window)).size_full().justify_between()
3492            })
3493            .child(
3494                v_flex()
3495                    .relative()
3496                    .size_full()
3497                    .pt_1()
3498                    .pr_2p5()
3499                    .child(self.message_editor.clone())
3500                    .child(
3501                        h_flex()
3502                            .absolute()
3503                            .top_0()
3504                            .right_0()
3505                            .opacity(0.5)
3506                            .hover(|this| this.opacity(1.0))
3507                            .child(
3508                                IconButton::new("toggle-height", expand_icon)
3509                                    .icon_size(IconSize::Small)
3510                                    .icon_color(Color::Muted)
3511                                    .tooltip({
3512                                        move |window, cx| {
3513                                            Tooltip::for_action_in(
3514                                                expand_tooltip,
3515                                                &ExpandMessageEditor,
3516                                                &focus_handle,
3517                                                window,
3518                                                cx,
3519                                            )
3520                                        }
3521                                    })
3522                                    .on_click(cx.listener(|_, _, window, cx| {
3523                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3524                                    })),
3525                            ),
3526                    ),
3527            )
3528            .child(
3529                h_flex()
3530                    .flex_none()
3531                    .flex_wrap()
3532                    .justify_between()
3533                    .child(
3534                        h_flex()
3535                            .child(self.render_follow_toggle(cx))
3536                            .children(self.render_burn_mode_toggle(cx)),
3537                    )
3538                    .child(
3539                        h_flex()
3540                            .gap_1()
3541                            .children(self.render_token_usage(cx))
3542                            .children(self.profile_selector.clone())
3543                            .children(self.model_selector.clone())
3544                            .child(self.render_send_button(cx)),
3545                    ),
3546            )
3547            .when(!enable_editor, |this| this.child(backdrop))
3548            .into_any()
3549    }
3550
3551    pub(crate) fn as_native_connection(
3552        &self,
3553        cx: &App,
3554    ) -> Option<Rc<agent2::NativeAgentConnection>> {
3555        let acp_thread = self.thread()?.read(cx);
3556        acp_thread.connection().clone().downcast()
3557    }
3558
3559    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3560        let acp_thread = self.thread()?.read(cx);
3561        self.as_native_connection(cx)?
3562            .thread(acp_thread.session_id(), cx)
3563    }
3564
3565    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3566        self.as_native_thread(cx)
3567            .and_then(|thread| thread.read(cx).model())
3568            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3569    }
3570
3571    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3572        let thread = self.thread()?.read(cx);
3573        let usage = thread.token_usage()?;
3574        let is_generating = thread.status() != ThreadStatus::Idle;
3575
3576        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3577        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3578
3579        Some(
3580            h_flex()
3581                .flex_shrink_0()
3582                .gap_0p5()
3583                .mr_1p5()
3584                .child(
3585                    Label::new(used)
3586                        .size(LabelSize::Small)
3587                        .color(Color::Muted)
3588                        .map(|label| {
3589                            if is_generating {
3590                                label
3591                                    .with_animation(
3592                                        "used-tokens-label",
3593                                        Animation::new(Duration::from_secs(2))
3594                                            .repeat()
3595                                            .with_easing(pulsating_between(0.3, 0.8)),
3596                                        |label, delta| label.alpha(delta),
3597                                    )
3598                                    .into_any()
3599                            } else {
3600                                label.into_any_element()
3601                            }
3602                        }),
3603                )
3604                .child(
3605                    Label::new("/")
3606                        .size(LabelSize::Small)
3607                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3608                )
3609                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3610        )
3611    }
3612
3613    fn toggle_burn_mode(
3614        &mut self,
3615        _: &ToggleBurnMode,
3616        _window: &mut Window,
3617        cx: &mut Context<Self>,
3618    ) {
3619        let Some(thread) = self.as_native_thread(cx) else {
3620            return;
3621        };
3622
3623        thread.update(cx, |thread, cx| {
3624            let current_mode = thread.completion_mode();
3625            thread.set_completion_mode(
3626                match current_mode {
3627                    CompletionMode::Burn => CompletionMode::Normal,
3628                    CompletionMode::Normal => CompletionMode::Burn,
3629                },
3630                cx,
3631            );
3632        });
3633    }
3634
3635    fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3636        let Some(thread) = self.thread() else {
3637            return;
3638        };
3639        let action_log = thread.read(cx).action_log().clone();
3640        action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3641    }
3642
3643    fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3644        let Some(thread) = self.thread() else {
3645            return;
3646        };
3647        let action_log = thread.read(cx).action_log().clone();
3648        action_log
3649            .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3650            .detach();
3651    }
3652
3653    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3654        let thread = self.as_native_thread(cx)?.read(cx);
3655
3656        if thread
3657            .model()
3658            .is_none_or(|model| !model.supports_burn_mode())
3659        {
3660            return None;
3661        }
3662
3663        let active_completion_mode = thread.completion_mode();
3664        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3665        let icon = if burn_mode_enabled {
3666            IconName::ZedBurnModeOn
3667        } else {
3668            IconName::ZedBurnMode
3669        };
3670
3671        Some(
3672            IconButton::new("burn-mode", icon)
3673                .icon_size(IconSize::Small)
3674                .icon_color(Color::Muted)
3675                .toggle_state(burn_mode_enabled)
3676                .selected_icon_color(Color::Error)
3677                .on_click(cx.listener(|this, _event, window, cx| {
3678                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3679                }))
3680                .tooltip(move |_window, cx| {
3681                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3682                        .into()
3683                })
3684                .into_any_element(),
3685        )
3686    }
3687
3688    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3689        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3690        let is_generating = self
3691            .thread()
3692            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3693
3694        if self.is_loading_contents {
3695            div()
3696                .id("loading-message-content")
3697                .px_1()
3698                .tooltip(Tooltip::text("Loading Added Context…"))
3699                .child(loading_contents_spinner(IconSize::default()))
3700                .into_any_element()
3701        } else if is_generating && is_editor_empty {
3702            IconButton::new("stop-generation", IconName::Stop)
3703                .icon_color(Color::Error)
3704                .style(ButtonStyle::Tinted(ui::TintColor::Error))
3705                .tooltip(move |window, cx| {
3706                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3707                })
3708                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3709                .into_any_element()
3710        } else {
3711            let send_btn_tooltip = if is_editor_empty && !is_generating {
3712                "Type to Send"
3713            } else if is_generating {
3714                "Stop and Send Message"
3715            } else {
3716                "Send"
3717            };
3718
3719            IconButton::new("send-message", IconName::Send)
3720                .style(ButtonStyle::Filled)
3721                .map(|this| {
3722                    if is_editor_empty && !is_generating {
3723                        this.disabled(true).icon_color(Color::Muted)
3724                    } else {
3725                        this.icon_color(Color::Accent)
3726                    }
3727                })
3728                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3729                .on_click(cx.listener(|this, _, window, cx| {
3730                    this.send(window, cx);
3731                }))
3732                .into_any_element()
3733        }
3734    }
3735
3736    fn is_following(&self, cx: &App) -> bool {
3737        match self.thread().map(|thread| thread.read(cx).status()) {
3738            Some(ThreadStatus::Generating) => self
3739                .workspace
3740                .read_with(cx, |workspace, _| {
3741                    workspace.is_being_followed(CollaboratorId::Agent)
3742                })
3743                .unwrap_or(false),
3744            _ => self.should_be_following,
3745        }
3746    }
3747
3748    fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3749        let following = self.is_following(cx);
3750
3751        self.should_be_following = !following;
3752        if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3753            self.workspace
3754                .update(cx, |workspace, cx| {
3755                    if following {
3756                        workspace.unfollow(CollaboratorId::Agent, window, cx);
3757                    } else {
3758                        workspace.follow(CollaboratorId::Agent, window, cx);
3759                    }
3760                })
3761                .ok();
3762        }
3763
3764        telemetry::event!("Follow Agent Selected", following = !following);
3765    }
3766
3767    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3768        let following = self.is_following(cx);
3769
3770        let tooltip_label = if following {
3771            if self.agent.name() == "Zed Agent" {
3772                format!("Stop Following the {}", self.agent.name())
3773            } else {
3774                format!("Stop Following {}", self.agent.name())
3775            }
3776        } else {
3777            if self.agent.name() == "Zed Agent" {
3778                format!("Follow the {}", self.agent.name())
3779            } else {
3780                format!("Follow {}", self.agent.name())
3781            }
3782        };
3783
3784        IconButton::new("follow-agent", IconName::Crosshair)
3785            .icon_size(IconSize::Small)
3786            .icon_color(Color::Muted)
3787            .toggle_state(following)
3788            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3789            .tooltip(move |window, cx| {
3790                if following {
3791                    Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
3792                } else {
3793                    Tooltip::with_meta(
3794                        tooltip_label.clone(),
3795                        Some(&Follow),
3796                        "Track the agent's location as it reads and edits files.",
3797                        window,
3798                        cx,
3799                    )
3800                }
3801            })
3802            .on_click(cx.listener(move |this, _, window, cx| {
3803                this.toggle_following(window, cx);
3804            }))
3805    }
3806
3807    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3808        let workspace = self.workspace.clone();
3809        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3810            Self::open_link(text, &workspace, window, cx);
3811        })
3812    }
3813
3814    fn open_link(
3815        url: SharedString,
3816        workspace: &WeakEntity<Workspace>,
3817        window: &mut Window,
3818        cx: &mut App,
3819    ) {
3820        let Some(workspace) = workspace.upgrade() else {
3821            cx.open_url(&url);
3822            return;
3823        };
3824
3825        if let Some(mention) = MentionUri::parse(&url).log_err() {
3826            workspace.update(cx, |workspace, cx| match mention {
3827                MentionUri::File { abs_path } => {
3828                    let project = workspace.project();
3829                    let Some(path) =
3830                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3831                    else {
3832                        return;
3833                    };
3834
3835                    workspace
3836                        .open_path(path, None, true, window, cx)
3837                        .detach_and_log_err(cx);
3838                }
3839                MentionUri::PastedImage => {}
3840                MentionUri::Directory { abs_path } => {
3841                    let project = workspace.project();
3842                    let Some(entry) = project.update(cx, |project, cx| {
3843                        let path = project.find_project_path(abs_path, cx)?;
3844                        project.entry_for_path(&path, cx)
3845                    }) else {
3846                        return;
3847                    };
3848
3849                    project.update(cx, |_, cx| {
3850                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
3851                    });
3852                }
3853                MentionUri::Symbol {
3854                    abs_path: path,
3855                    line_range,
3856                    ..
3857                }
3858                | MentionUri::Selection {
3859                    abs_path: Some(path),
3860                    line_range,
3861                } => {
3862                    let project = workspace.project();
3863                    let Some((path, _)) = project.update(cx, |project, cx| {
3864                        let path = project.find_project_path(path, cx)?;
3865                        let entry = project.entry_for_path(&path, cx)?;
3866                        Some((path, entry))
3867                    }) else {
3868                        return;
3869                    };
3870
3871                    let item = workspace.open_path(path, None, true, window, cx);
3872                    window
3873                        .spawn(cx, async move |cx| {
3874                            let Some(editor) = item.await?.downcast::<Editor>() else {
3875                                return Ok(());
3876                            };
3877                            let range = Point::new(*line_range.start(), 0)
3878                                ..Point::new(*line_range.start(), 0);
3879                            editor
3880                                .update_in(cx, |editor, window, cx| {
3881                                    editor.change_selections(
3882                                        SelectionEffects::scroll(Autoscroll::center()),
3883                                        window,
3884                                        cx,
3885                                        |s| s.select_ranges(vec![range]),
3886                                    );
3887                                })
3888                                .ok();
3889                            anyhow::Ok(())
3890                        })
3891                        .detach_and_log_err(cx);
3892                }
3893                MentionUri::Selection { abs_path: None, .. } => {}
3894                MentionUri::Thread { id, name } => {
3895                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3896                        panel.update(cx, |panel, cx| {
3897                            panel.load_agent_thread(
3898                                DbThreadMetadata {
3899                                    id,
3900                                    title: name.into(),
3901                                    updated_at: Default::default(),
3902                                },
3903                                window,
3904                                cx,
3905                            )
3906                        });
3907                    }
3908                }
3909                MentionUri::TextThread { path, .. } => {
3910                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3911                        panel.update(cx, |panel, cx| {
3912                            panel
3913                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
3914                                .detach_and_log_err(cx);
3915                        });
3916                    }
3917                }
3918                MentionUri::Rule { id, .. } => {
3919                    let PromptId::User { uuid } = id else {
3920                        return;
3921                    };
3922                    window.dispatch_action(
3923                        Box::new(OpenRulesLibrary {
3924                            prompt_to_select: Some(uuid.0),
3925                        }),
3926                        cx,
3927                    )
3928                }
3929                MentionUri::Fetch { url } => {
3930                    cx.open_url(url.as_str());
3931                }
3932            })
3933        } else {
3934            cx.open_url(&url);
3935        }
3936    }
3937
3938    fn open_tool_call_location(
3939        &self,
3940        entry_ix: usize,
3941        location_ix: usize,
3942        window: &mut Window,
3943        cx: &mut Context<Self>,
3944    ) -> Option<()> {
3945        let (tool_call_location, agent_location) = self
3946            .thread()?
3947            .read(cx)
3948            .entries()
3949            .get(entry_ix)?
3950            .location(location_ix)?;
3951
3952        let project_path = self
3953            .project
3954            .read(cx)
3955            .find_project_path(&tool_call_location.path, cx)?;
3956
3957        let open_task = self
3958            .workspace
3959            .update(cx, |workspace, cx| {
3960                workspace.open_path(project_path, None, true, window, cx)
3961            })
3962            .log_err()?;
3963        window
3964            .spawn(cx, async move |cx| {
3965                let item = open_task.await?;
3966
3967                let Some(active_editor) = item.downcast::<Editor>() else {
3968                    return anyhow::Ok(());
3969                };
3970
3971                active_editor.update_in(cx, |editor, window, cx| {
3972                    let multibuffer = editor.buffer().read(cx);
3973                    let buffer = multibuffer.as_singleton();
3974                    if agent_location.buffer.upgrade() == buffer {
3975                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3976                        let anchor = editor::Anchor::in_buffer(
3977                            excerpt_id.unwrap(),
3978                            buffer.unwrap().read(cx).remote_id(),
3979                            agent_location.position,
3980                        );
3981                        editor.change_selections(Default::default(), window, cx, |selections| {
3982                            selections.select_anchor_ranges([anchor..anchor]);
3983                        })
3984                    } else {
3985                        let row = tool_call_location.line.unwrap_or_default();
3986                        editor.change_selections(Default::default(), window, cx, |selections| {
3987                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3988                        })
3989                    }
3990                })?;
3991
3992                anyhow::Ok(())
3993            })
3994            .detach_and_log_err(cx);
3995
3996        None
3997    }
3998
3999    pub fn open_thread_as_markdown(
4000        &self,
4001        workspace: Entity<Workspace>,
4002        window: &mut Window,
4003        cx: &mut App,
4004    ) -> Task<anyhow::Result<()>> {
4005        let markdown_language_task = workspace
4006            .read(cx)
4007            .app_state()
4008            .languages
4009            .language_for_name("Markdown");
4010
4011        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4012            let thread = thread.read(cx);
4013            (thread.title().to_string(), thread.to_markdown(cx))
4014        } else {
4015            return Task::ready(Ok(()));
4016        };
4017
4018        window.spawn(cx, async move |cx| {
4019            let markdown_language = markdown_language_task.await?;
4020
4021            workspace.update_in(cx, |workspace, window, cx| {
4022                let project = workspace.project().clone();
4023
4024                if !project.read(cx).is_local() {
4025                    bail!("failed to open active thread as markdown in remote project");
4026                }
4027
4028                let buffer = project.update(cx, |project, cx| {
4029                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
4030                });
4031                let buffer = cx.new(|cx| {
4032                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4033                });
4034
4035                workspace.add_item_to_active_pane(
4036                    Box::new(cx.new(|cx| {
4037                        let mut editor =
4038                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4039                        editor.set_breadcrumb_header(thread_summary);
4040                        editor
4041                    })),
4042                    None,
4043                    true,
4044                    window,
4045                    cx,
4046                );
4047
4048                anyhow::Ok(())
4049            })??;
4050            anyhow::Ok(())
4051        })
4052    }
4053
4054    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4055        self.list_state.scroll_to(ListOffset::default());
4056        cx.notify();
4057    }
4058
4059    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4060        if let Some(thread) = self.thread() {
4061            let entry_count = thread.read(cx).entries().len();
4062            self.list_state.reset(entry_count);
4063            cx.notify();
4064        }
4065    }
4066
4067    fn notify_with_sound(
4068        &mut self,
4069        caption: impl Into<SharedString>,
4070        icon: IconName,
4071        window: &mut Window,
4072        cx: &mut Context<Self>,
4073    ) {
4074        self.play_notification_sound(window, cx);
4075        self.show_notification(caption, icon, window, cx);
4076    }
4077
4078    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4079        let settings = AgentSettings::get_global(cx);
4080        if settings.play_sound_when_agent_done && !window.is_window_active() {
4081            Audio::play_sound(Sound::AgentDone, cx);
4082        }
4083    }
4084
4085    fn show_notification(
4086        &mut self,
4087        caption: impl Into<SharedString>,
4088        icon: IconName,
4089        window: &mut Window,
4090        cx: &mut Context<Self>,
4091    ) {
4092        if window.is_window_active() || !self.notifications.is_empty() {
4093            return;
4094        }
4095
4096        // TODO: Change this once we have title summarization for external agents.
4097        let title = self.agent.name();
4098
4099        match AgentSettings::get_global(cx).notify_when_agent_waiting {
4100            NotifyWhenAgentWaiting::PrimaryScreen => {
4101                if let Some(primary) = cx.primary_display() {
4102                    self.pop_up(icon, caption.into(), title, window, primary, cx);
4103                }
4104            }
4105            NotifyWhenAgentWaiting::AllScreens => {
4106                let caption = caption.into();
4107                for screen in cx.displays() {
4108                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4109                }
4110            }
4111            NotifyWhenAgentWaiting::Never => {
4112                // Don't show anything
4113            }
4114        }
4115    }
4116
4117    fn pop_up(
4118        &mut self,
4119        icon: IconName,
4120        caption: SharedString,
4121        title: SharedString,
4122        window: &mut Window,
4123        screen: Rc<dyn PlatformDisplay>,
4124        cx: &mut Context<Self>,
4125    ) {
4126        let options = AgentNotification::window_options(screen, cx);
4127
4128        let project_name = self.workspace.upgrade().and_then(|workspace| {
4129            workspace
4130                .read(cx)
4131                .project()
4132                .read(cx)
4133                .visible_worktrees(cx)
4134                .next()
4135                .map(|worktree| worktree.read(cx).root_name().to_string())
4136        });
4137
4138        if let Some(screen_window) = cx
4139            .open_window(options, |_, cx| {
4140                cx.new(|_| {
4141                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4142                })
4143            })
4144            .log_err()
4145            && let Some(pop_up) = screen_window.entity(cx).log_err()
4146        {
4147            self.notification_subscriptions
4148                .entry(screen_window)
4149                .or_insert_with(Vec::new)
4150                .push(cx.subscribe_in(&pop_up, window, {
4151                    |this, _, event, window, cx| match event {
4152                        AgentNotificationEvent::Accepted => {
4153                            let handle = window.window_handle();
4154                            cx.activate(true);
4155
4156                            let workspace_handle = this.workspace.clone();
4157
4158                            // If there are multiple Zed windows, activate the correct one.
4159                            cx.defer(move |cx| {
4160                                handle
4161                                    .update(cx, |_view, window, _cx| {
4162                                        window.activate_window();
4163
4164                                        if let Some(workspace) = workspace_handle.upgrade() {
4165                                            workspace.update(_cx, |workspace, cx| {
4166                                                workspace.focus_panel::<AgentPanel>(window, cx);
4167                                            });
4168                                        }
4169                                    })
4170                                    .log_err();
4171                            });
4172
4173                            this.dismiss_notifications(cx);
4174                        }
4175                        AgentNotificationEvent::Dismissed => {
4176                            this.dismiss_notifications(cx);
4177                        }
4178                    }
4179                }));
4180
4181            self.notifications.push(screen_window);
4182
4183            // If the user manually refocuses the original window, dismiss the popup.
4184            self.notification_subscriptions
4185                .entry(screen_window)
4186                .or_insert_with(Vec::new)
4187                .push({
4188                    let pop_up_weak = pop_up.downgrade();
4189
4190                    cx.observe_window_activation(window, move |_, window, cx| {
4191                        if window.is_window_active()
4192                            && let Some(pop_up) = pop_up_weak.upgrade()
4193                        {
4194                            pop_up.update(cx, |_, cx| {
4195                                cx.emit(AgentNotificationEvent::Dismissed);
4196                            });
4197                        }
4198                    })
4199                });
4200        }
4201    }
4202
4203    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4204        for window in self.notifications.drain(..) {
4205            window
4206                .update(cx, |_, window, _| {
4207                    window.remove_window();
4208                })
4209                .ok();
4210
4211            self.notification_subscriptions.remove(&window);
4212        }
4213    }
4214
4215    fn render_thread_controls(
4216        &self,
4217        thread: &Entity<AcpThread>,
4218        cx: &Context<Self>,
4219    ) -> impl IntoElement {
4220        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4221        if is_generating {
4222            return h_flex().id("thread-controls-container").child(
4223                div()
4224                    .py_2()
4225                    .px(rems_from_px(22.))
4226                    .child(SpinnerLabel::new().size(LabelSize::Small)),
4227            );
4228        }
4229
4230        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4231            .shape(ui::IconButtonShape::Square)
4232            .icon_size(IconSize::Small)
4233            .icon_color(Color::Ignored)
4234            .tooltip(Tooltip::text("Open Thread as Markdown"))
4235            .on_click(cx.listener(move |this, _, window, cx| {
4236                if let Some(workspace) = this.workspace.upgrade() {
4237                    this.open_thread_as_markdown(workspace, window, cx)
4238                        .detach_and_log_err(cx);
4239                }
4240            }));
4241
4242        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4243            .shape(ui::IconButtonShape::Square)
4244            .icon_size(IconSize::Small)
4245            .icon_color(Color::Ignored)
4246            .tooltip(Tooltip::text("Scroll To Top"))
4247            .on_click(cx.listener(move |this, _, _, cx| {
4248                this.scroll_to_top(cx);
4249            }));
4250
4251        let mut container = h_flex()
4252            .id("thread-controls-container")
4253            .group("thread-controls-container")
4254            .w_full()
4255            .py_2()
4256            .px_5()
4257            .gap_px()
4258            .opacity(0.6)
4259            .hover(|style| style.opacity(1.))
4260            .flex_wrap()
4261            .justify_end();
4262
4263        if AgentSettings::get_global(cx).enable_feedback
4264            && self
4265                .thread()
4266                .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4267        {
4268            let feedback = self.thread_feedback.feedback;
4269
4270            container = container
4271                .child(
4272                    div().visible_on_hover("thread-controls-container").child(
4273                        Label::new(match feedback {
4274                            Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4275                            Some(ThreadFeedback::Negative) => {
4276                                "We appreciate your feedback and will use it to improve."
4277                            }
4278                            None => {
4279                                "Rating the thread sends all of your current conversation to the Zed team."
4280                            }
4281                        })
4282                        .color(Color::Muted)
4283                        .size(LabelSize::XSmall)
4284                        .truncate(),
4285                    ),
4286                )
4287                .child(
4288                    IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4289                        .shape(ui::IconButtonShape::Square)
4290                        .icon_size(IconSize::Small)
4291                        .icon_color(match feedback {
4292                            Some(ThreadFeedback::Positive) => Color::Accent,
4293                            _ => Color::Ignored,
4294                        })
4295                        .tooltip(Tooltip::text("Helpful Response"))
4296                        .on_click(cx.listener(move |this, _, window, cx| {
4297                            this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4298                        })),
4299                )
4300                .child(
4301                    IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4302                        .shape(ui::IconButtonShape::Square)
4303                        .icon_size(IconSize::Small)
4304                        .icon_color(match feedback {
4305                            Some(ThreadFeedback::Negative) => Color::Accent,
4306                            _ => Color::Ignored,
4307                        })
4308                        .tooltip(Tooltip::text("Not Helpful"))
4309                        .on_click(cx.listener(move |this, _, window, cx| {
4310                            this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4311                        })),
4312                );
4313        }
4314
4315        container.child(open_as_markdown).child(scroll_to_top)
4316    }
4317
4318    fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4319        h_flex()
4320            .key_context("AgentFeedbackMessageEditor")
4321            .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4322                this.thread_feedback.dismiss_comments();
4323                cx.notify();
4324            }))
4325            .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4326                this.submit_feedback_message(cx);
4327            }))
4328            .p_2()
4329            .mb_2()
4330            .mx_5()
4331            .gap_1()
4332            .rounded_md()
4333            .border_1()
4334            .border_color(cx.theme().colors().border)
4335            .bg(cx.theme().colors().editor_background)
4336            .child(div().w_full().child(editor))
4337            .child(
4338                h_flex()
4339                    .child(
4340                        IconButton::new("dismiss-feedback-message", IconName::Close)
4341                            .icon_color(Color::Error)
4342                            .icon_size(IconSize::XSmall)
4343                            .shape(ui::IconButtonShape::Square)
4344                            .on_click(cx.listener(move |this, _, _window, cx| {
4345                                this.thread_feedback.dismiss_comments();
4346                                cx.notify();
4347                            })),
4348                    )
4349                    .child(
4350                        IconButton::new("submit-feedback-message", IconName::Return)
4351                            .icon_size(IconSize::XSmall)
4352                            .shape(ui::IconButtonShape::Square)
4353                            .on_click(cx.listener(move |this, _, _window, cx| {
4354                                this.submit_feedback_message(cx);
4355                            })),
4356                    ),
4357            )
4358    }
4359
4360    fn handle_feedback_click(
4361        &mut self,
4362        feedback: ThreadFeedback,
4363        window: &mut Window,
4364        cx: &mut Context<Self>,
4365    ) {
4366        let Some(thread) = self.thread().cloned() else {
4367            return;
4368        };
4369
4370        self.thread_feedback.submit(thread, feedback, window, cx);
4371        cx.notify();
4372    }
4373
4374    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4375        let Some(thread) = self.thread().cloned() else {
4376            return;
4377        };
4378
4379        self.thread_feedback.submit_comments(thread, cx);
4380        cx.notify();
4381    }
4382
4383    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4384        div()
4385            .id("acp-thread-scrollbar")
4386            .occlude()
4387            .on_mouse_move(cx.listener(|_, _, _, cx| {
4388                cx.notify();
4389                cx.stop_propagation()
4390            }))
4391            .on_hover(|_, _, cx| {
4392                cx.stop_propagation();
4393            })
4394            .on_any_mouse_down(|_, _, cx| {
4395                cx.stop_propagation();
4396            })
4397            .on_mouse_up(
4398                MouseButton::Left,
4399                cx.listener(|_, _, _, cx| {
4400                    cx.stop_propagation();
4401                }),
4402            )
4403            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4404                cx.notify();
4405            }))
4406            .h_full()
4407            .absolute()
4408            .right_1()
4409            .top_1()
4410            .bottom_0()
4411            .w(px(12.))
4412            .cursor_default()
4413            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4414    }
4415
4416    fn render_token_limit_callout(
4417        &self,
4418        line_height: Pixels,
4419        cx: &mut Context<Self>,
4420    ) -> Option<Callout> {
4421        let token_usage = self.thread()?.read(cx).token_usage()?;
4422        let ratio = token_usage.ratio();
4423
4424        let (severity, title) = match ratio {
4425            acp_thread::TokenUsageRatio::Normal => return None,
4426            acp_thread::TokenUsageRatio::Warning => {
4427                (Severity::Warning, "Thread reaching the token limit soon")
4428            }
4429            acp_thread::TokenUsageRatio::Exceeded => {
4430                (Severity::Error, "Thread reached the token limit")
4431            }
4432        };
4433
4434        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4435            thread.read(cx).completion_mode() == CompletionMode::Normal
4436                && thread
4437                    .read(cx)
4438                    .model()
4439                    .is_some_and(|model| model.supports_burn_mode())
4440        });
4441
4442        let description = if burn_mode_available {
4443            "To continue, start a new thread from a summary or turn Burn Mode on."
4444        } else {
4445            "To continue, start a new thread from a summary."
4446        };
4447
4448        Some(
4449            Callout::new()
4450                .severity(severity)
4451                .line_height(line_height)
4452                .title(title)
4453                .description(description)
4454                .actions_slot(
4455                    h_flex()
4456                        .gap_0p5()
4457                        .child(
4458                            Button::new("start-new-thread", "Start New Thread")
4459                                .label_size(LabelSize::Small)
4460                                .on_click(cx.listener(|this, _, window, cx| {
4461                                    let Some(thread) = this.thread() else {
4462                                        return;
4463                                    };
4464                                    let session_id = thread.read(cx).session_id().clone();
4465                                    window.dispatch_action(
4466                                        crate::NewNativeAgentThreadFromSummary {
4467                                            from_session_id: session_id,
4468                                        }
4469                                        .boxed_clone(),
4470                                        cx,
4471                                    );
4472                                })),
4473                        )
4474                        .when(burn_mode_available, |this| {
4475                            this.child(
4476                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4477                                    .icon_size(IconSize::XSmall)
4478                                    .on_click(cx.listener(|this, _event, window, cx| {
4479                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4480                                    })),
4481                            )
4482                        }),
4483                ),
4484        )
4485    }
4486
4487    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4488        if !self.is_using_zed_ai_models(cx) {
4489            return None;
4490        }
4491
4492        let user_store = self.project.read(cx).user_store().read(cx);
4493        if user_store.is_usage_based_billing_enabled() {
4494            return None;
4495        }
4496
4497        let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4498
4499        let usage = user_store.model_request_usage()?;
4500
4501        Some(
4502            div()
4503                .child(UsageCallout::new(plan, usage))
4504                .line_height(line_height),
4505        )
4506    }
4507
4508    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4509        self.entry_view_state.update(cx, |entry_view_state, cx| {
4510            entry_view_state.settings_changed(cx);
4511        });
4512    }
4513
4514    pub(crate) fn insert_dragged_files(
4515        &self,
4516        paths: Vec<project::ProjectPath>,
4517        added_worktrees: Vec<Entity<project::Worktree>>,
4518        window: &mut Window,
4519        cx: &mut Context<Self>,
4520    ) {
4521        self.message_editor.update(cx, |message_editor, cx| {
4522            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4523        })
4524    }
4525
4526    pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4527        self.message_editor.update(cx, |message_editor, cx| {
4528            message_editor.insert_selections(window, cx);
4529        })
4530    }
4531
4532    fn render_thread_retry_status_callout(
4533        &self,
4534        _window: &mut Window,
4535        _cx: &mut Context<Self>,
4536    ) -> Option<Callout> {
4537        let state = self.thread_retry_status.as_ref()?;
4538
4539        let next_attempt_in = state
4540            .duration
4541            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4542        if next_attempt_in.is_zero() {
4543            return None;
4544        }
4545
4546        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4547
4548        let retry_message = if state.max_attempts == 1 {
4549            if next_attempt_in_secs == 1 {
4550                "Retrying. Next attempt in 1 second.".to_string()
4551            } else {
4552                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4553            }
4554        } else if next_attempt_in_secs == 1 {
4555            format!(
4556                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4557                state.attempt, state.max_attempts,
4558            )
4559        } else {
4560            format!(
4561                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4562                state.attempt, state.max_attempts,
4563            )
4564        };
4565
4566        Some(
4567            Callout::new()
4568                .severity(Severity::Warning)
4569                .title(state.last_error.clone())
4570                .description(retry_message),
4571        )
4572    }
4573
4574    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4575        let content = match self.thread_error.as_ref()? {
4576            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4577            ThreadError::AuthenticationRequired(error) => {
4578                self.render_authentication_required_error(error.clone(), cx)
4579            }
4580            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4581            ThreadError::ModelRequestLimitReached(plan) => {
4582                self.render_model_request_limit_reached_error(*plan, cx)
4583            }
4584            ThreadError::ToolUseLimitReached => {
4585                self.render_tool_use_limit_reached_error(window, cx)?
4586            }
4587        };
4588
4589        Some(div().child(content))
4590    }
4591
4592    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4593        let can_resume = self
4594            .thread()
4595            .map_or(false, |thread| thread.read(cx).can_resume(cx));
4596
4597        let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4598            let thread = thread.read(cx);
4599            let supports_burn_mode = thread
4600                .model()
4601                .map_or(false, |model| model.supports_burn_mode());
4602            supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4603        });
4604
4605        Callout::new()
4606            .severity(Severity::Error)
4607            .title("Error")
4608            .icon(IconName::XCircle)
4609            .description(error.clone())
4610            .actions_slot(
4611                h_flex()
4612                    .gap_0p5()
4613                    .when(can_resume && can_enable_burn_mode, |this| {
4614                        this.child(
4615                            Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4616                                .icon(IconName::ZedBurnMode)
4617                                .icon_position(IconPosition::Start)
4618                                .icon_size(IconSize::Small)
4619                                .label_size(LabelSize::Small)
4620                                .on_click(cx.listener(|this, _, window, cx| {
4621                                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4622                                    this.resume_chat(cx);
4623                                })),
4624                        )
4625                    })
4626                    .when(can_resume, |this| {
4627                        this.child(
4628                            Button::new("retry", "Retry")
4629                                .icon(IconName::RotateCw)
4630                                .icon_position(IconPosition::Start)
4631                                .icon_size(IconSize::Small)
4632                                .label_size(LabelSize::Small)
4633                                .on_click(cx.listener(|this, _, _window, cx| {
4634                                    this.resume_chat(cx);
4635                                })),
4636                        )
4637                    })
4638                    .child(self.create_copy_button(error.to_string())),
4639            )
4640            .dismiss_action(self.dismiss_error_button(cx))
4641    }
4642
4643    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4644        const ERROR_MESSAGE: &str =
4645            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4646
4647        Callout::new()
4648            .severity(Severity::Error)
4649            .icon(IconName::XCircle)
4650            .title("Free Usage Exceeded")
4651            .description(ERROR_MESSAGE)
4652            .actions_slot(
4653                h_flex()
4654                    .gap_0p5()
4655                    .child(self.upgrade_button(cx))
4656                    .child(self.create_copy_button(ERROR_MESSAGE)),
4657            )
4658            .dismiss_action(self.dismiss_error_button(cx))
4659    }
4660
4661    fn render_authentication_required_error(
4662        &self,
4663        error: SharedString,
4664        cx: &mut Context<Self>,
4665    ) -> Callout {
4666        Callout::new()
4667            .severity(Severity::Error)
4668            .title("Authentication Required")
4669            .icon(IconName::XCircle)
4670            .description(error.clone())
4671            .actions_slot(
4672                h_flex()
4673                    .gap_0p5()
4674                    .child(self.authenticate_button(cx))
4675                    .child(self.create_copy_button(error)),
4676            )
4677            .dismiss_action(self.dismiss_error_button(cx))
4678    }
4679
4680    fn render_model_request_limit_reached_error(
4681        &self,
4682        plan: cloud_llm_client::Plan,
4683        cx: &mut Context<Self>,
4684    ) -> Callout {
4685        let error_message = match plan {
4686            cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4687            cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4688                "Upgrade to Zed Pro for more prompts."
4689            }
4690        };
4691
4692        Callout::new()
4693            .severity(Severity::Error)
4694            .title("Model Prompt Limit Reached")
4695            .icon(IconName::XCircle)
4696            .description(error_message)
4697            .actions_slot(
4698                h_flex()
4699                    .gap_0p5()
4700                    .child(self.upgrade_button(cx))
4701                    .child(self.create_copy_button(error_message)),
4702            )
4703            .dismiss_action(self.dismiss_error_button(cx))
4704    }
4705
4706    fn render_tool_use_limit_reached_error(
4707        &self,
4708        window: &mut Window,
4709        cx: &mut Context<Self>,
4710    ) -> Option<Callout> {
4711        let thread = self.as_native_thread(cx)?;
4712        let supports_burn_mode = thread
4713            .read(cx)
4714            .model()
4715            .is_some_and(|model| model.supports_burn_mode());
4716
4717        let focus_handle = self.focus_handle(cx);
4718
4719        Some(
4720            Callout::new()
4721                .icon(IconName::Info)
4722                .title("Consecutive tool use limit reached.")
4723                .actions_slot(
4724                    h_flex()
4725                        .gap_0p5()
4726                        .when(supports_burn_mode, |this| {
4727                            this.child(
4728                                Button::new("continue-burn-mode", "Continue with Burn Mode")
4729                                    .style(ButtonStyle::Filled)
4730                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4731                                    .layer(ElevationIndex::ModalSurface)
4732                                    .label_size(LabelSize::Small)
4733                                    .key_binding(
4734                                        KeyBinding::for_action_in(
4735                                            &ContinueWithBurnMode,
4736                                            &focus_handle,
4737                                            window,
4738                                            cx,
4739                                        )
4740                                        .map(|kb| kb.size(rems_from_px(10.))),
4741                                    )
4742                                    .tooltip(Tooltip::text(
4743                                        "Enable Burn Mode for unlimited tool use.",
4744                                    ))
4745                                    .on_click({
4746                                        cx.listener(move |this, _, _window, cx| {
4747                                            thread.update(cx, |thread, cx| {
4748                                                thread
4749                                                    .set_completion_mode(CompletionMode::Burn, cx);
4750                                            });
4751                                            this.resume_chat(cx);
4752                                        })
4753                                    }),
4754                            )
4755                        })
4756                        .child(
4757                            Button::new("continue-conversation", "Continue")
4758                                .layer(ElevationIndex::ModalSurface)
4759                                .label_size(LabelSize::Small)
4760                                .key_binding(
4761                                    KeyBinding::for_action_in(
4762                                        &ContinueThread,
4763                                        &focus_handle,
4764                                        window,
4765                                        cx,
4766                                    )
4767                                    .map(|kb| kb.size(rems_from_px(10.))),
4768                                )
4769                                .on_click(cx.listener(|this, _, _window, cx| {
4770                                    this.resume_chat(cx);
4771                                })),
4772                        ),
4773                ),
4774        )
4775    }
4776
4777    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4778        let message = message.into();
4779
4780        IconButton::new("copy", IconName::Copy)
4781            .icon_size(IconSize::Small)
4782            .icon_color(Color::Muted)
4783            .tooltip(Tooltip::text("Copy Error Message"))
4784            .on_click(move |_, _, cx| {
4785                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4786            })
4787    }
4788
4789    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4790        IconButton::new("dismiss", IconName::Close)
4791            .icon_size(IconSize::Small)
4792            .icon_color(Color::Muted)
4793            .tooltip(Tooltip::text("Dismiss Error"))
4794            .on_click(cx.listener({
4795                move |this, _, _, cx| {
4796                    this.clear_thread_error(cx);
4797                    cx.notify();
4798                }
4799            }))
4800    }
4801
4802    fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4803        Button::new("authenticate", "Authenticate")
4804            .label_size(LabelSize::Small)
4805            .style(ButtonStyle::Filled)
4806            .on_click(cx.listener({
4807                move |this, _, window, cx| {
4808                    let agent = this.agent.clone();
4809                    let ThreadState::Ready { thread, .. } = &this.thread_state else {
4810                        return;
4811                    };
4812
4813                    let connection = thread.read(cx).connection().clone();
4814                    let err = AuthRequired {
4815                        description: None,
4816                        provider_id: None,
4817                    };
4818                    this.clear_thread_error(cx);
4819                    let this = cx.weak_entity();
4820                    window.defer(cx, |window, cx| {
4821                        Self::handle_auth_required(this, err, agent, connection, window, cx);
4822                    })
4823                }
4824            }))
4825    }
4826
4827    pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4828        let agent = self.agent.clone();
4829        let ThreadState::Ready { thread, .. } = &self.thread_state else {
4830            return;
4831        };
4832
4833        let connection = thread.read(cx).connection().clone();
4834        let err = AuthRequired {
4835            description: None,
4836            provider_id: None,
4837        };
4838        self.clear_thread_error(cx);
4839        let this = cx.weak_entity();
4840        window.defer(cx, |window, cx| {
4841            Self::handle_auth_required(this, err, agent, connection, window, cx);
4842        })
4843    }
4844
4845    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4846        Button::new("upgrade", "Upgrade")
4847            .label_size(LabelSize::Small)
4848            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4849            .on_click(cx.listener({
4850                move |this, _, _, cx| {
4851                    this.clear_thread_error(cx);
4852                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4853                }
4854            }))
4855    }
4856
4857    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4858        self.thread_state = Self::initial_state(
4859            self.agent.clone(),
4860            None,
4861            self.workspace.clone(),
4862            self.project.clone(),
4863            window,
4864            cx,
4865        );
4866        cx.notify();
4867    }
4868
4869    pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4870        let task = match entry {
4871            HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4872                history.delete_thread(thread.id.clone(), cx)
4873            }),
4874            HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4875                history.delete_text_thread(context.path.clone(), cx)
4876            }),
4877        };
4878        task.detach_and_log_err(cx);
4879    }
4880}
4881
4882fn loading_contents_spinner(size: IconSize) -> AnyElement {
4883    Icon::new(IconName::LoadCircle)
4884        .size(size)
4885        .color(Color::Accent)
4886        .with_animation(
4887            "load_context_circle",
4888            Animation::new(Duration::from_secs(3)).repeat(),
4889            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4890        )
4891        .into_any_element()
4892}
4893
4894impl Focusable for AcpThreadView {
4895    fn focus_handle(&self, cx: &App) -> FocusHandle {
4896        match self.thread_state {
4897            ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
4898                self.message_editor.focus_handle(cx)
4899            }
4900            ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
4901                self.focus_handle.clone()
4902            }
4903        }
4904    }
4905}
4906
4907impl Render for AcpThreadView {
4908    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4909        let has_messages = self.list_state.item_count() > 0;
4910        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4911
4912        v_flex()
4913            .size_full()
4914            .key_context("AcpThread")
4915            .on_action(cx.listener(Self::open_agent_diff))
4916            .on_action(cx.listener(Self::toggle_burn_mode))
4917            .on_action(cx.listener(Self::keep_all))
4918            .on_action(cx.listener(Self::reject_all))
4919            .track_focus(&self.focus_handle)
4920            .bg(cx.theme().colors().panel_background)
4921            .child(match &self.thread_state {
4922                ThreadState::Unauthenticated {
4923                    connection,
4924                    description,
4925                    configuration_view,
4926                    pending_auth_method,
4927                    ..
4928                } => self.render_auth_required_state(
4929                    connection,
4930                    description.as_ref(),
4931                    configuration_view.as_ref(),
4932                    pending_auth_method.as_ref(),
4933                    window,
4934                    cx,
4935                ),
4936                ThreadState::Loading { .. } => v_flex()
4937                    .flex_1()
4938                    .child(self.render_recent_history(window, cx)),
4939                ThreadState::LoadError(e) => v_flex()
4940                    .flex_1()
4941                    .size_full()
4942                    .items_center()
4943                    .justify_end()
4944                    .child(self.render_load_error(e, window, cx)),
4945                ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
4946                    if has_messages {
4947                        this.child(
4948                            list(
4949                                self.list_state.clone(),
4950                                cx.processor(|this, index: usize, window, cx| {
4951                                    let Some((entry, len)) = this.thread().and_then(|thread| {
4952                                        let entries = &thread.read(cx).entries();
4953                                        Some((entries.get(index)?, entries.len()))
4954                                    }) else {
4955                                        return Empty.into_any();
4956                                    };
4957                                    this.render_entry(index, len, entry, window, cx)
4958                                }),
4959                            )
4960                            .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4961                            .flex_grow()
4962                            .into_any(),
4963                        )
4964                        .child(self.render_vertical_scrollbar(cx))
4965                    } else {
4966                        this.child(self.render_recent_history(window, cx))
4967                    }
4968                }),
4969            })
4970            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4971            // above so that the scrollbar doesn't render behind it. The current setup allows
4972            // the scrollbar to stop exactly at the activity bar start.
4973            .when(has_messages, |this| match &self.thread_state {
4974                ThreadState::Ready { thread, .. } => {
4975                    this.children(self.render_activity_bar(thread, window, cx))
4976                }
4977                _ => this,
4978            })
4979            .children(self.render_thread_retry_status_callout(window, cx))
4980            .children(self.render_thread_error(window, cx))
4981            .children(
4982                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4983                    Some(usage_callout.into_any_element())
4984                } else {
4985                    self.render_token_limit_callout(line_height, cx)
4986                        .map(|token_limit_callout| token_limit_callout.into_any_element())
4987                },
4988            )
4989            .child(self.render_message_editor(window, cx))
4990    }
4991}
4992
4993fn default_markdown_style(
4994    buffer_font: bool,
4995    muted_text: bool,
4996    window: &Window,
4997    cx: &App,
4998) -> MarkdownStyle {
4999    let theme_settings = ThemeSettings::get_global(cx);
5000    let colors = cx.theme().colors();
5001
5002    let buffer_font_size = TextSize::Small.rems(cx);
5003
5004    let mut text_style = window.text_style();
5005    let line_height = buffer_font_size * 1.75;
5006
5007    let font_family = if buffer_font {
5008        theme_settings.buffer_font.family.clone()
5009    } else {
5010        theme_settings.ui_font.family.clone()
5011    };
5012
5013    let font_size = if buffer_font {
5014        TextSize::Small.rems(cx)
5015    } else {
5016        TextSize::Default.rems(cx)
5017    };
5018
5019    let text_color = if muted_text {
5020        colors.text_muted
5021    } else {
5022        colors.text
5023    };
5024
5025    text_style.refine(&TextStyleRefinement {
5026        font_family: Some(font_family),
5027        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5028        font_features: Some(theme_settings.ui_font.features.clone()),
5029        font_size: Some(font_size.into()),
5030        line_height: Some(line_height.into()),
5031        color: Some(text_color),
5032        ..Default::default()
5033    });
5034
5035    MarkdownStyle {
5036        base_text_style: text_style.clone(),
5037        syntax: cx.theme().syntax().clone(),
5038        selection_background_color: colors.element_selection_background,
5039        code_block_overflow_x_scroll: true,
5040        table_overflow_x_scroll: true,
5041        heading_level_styles: Some(HeadingLevelStyles {
5042            h1: Some(TextStyleRefinement {
5043                font_size: Some(rems(1.15).into()),
5044                ..Default::default()
5045            }),
5046            h2: Some(TextStyleRefinement {
5047                font_size: Some(rems(1.1).into()),
5048                ..Default::default()
5049            }),
5050            h3: Some(TextStyleRefinement {
5051                font_size: Some(rems(1.05).into()),
5052                ..Default::default()
5053            }),
5054            h4: Some(TextStyleRefinement {
5055                font_size: Some(rems(1.).into()),
5056                ..Default::default()
5057            }),
5058            h5: Some(TextStyleRefinement {
5059                font_size: Some(rems(0.95).into()),
5060                ..Default::default()
5061            }),
5062            h6: Some(TextStyleRefinement {
5063                font_size: Some(rems(0.875).into()),
5064                ..Default::default()
5065            }),
5066        }),
5067        code_block: StyleRefinement {
5068            padding: EdgesRefinement {
5069                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5070                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5071                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5072                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5073            },
5074            margin: EdgesRefinement {
5075                top: Some(Length::Definite(Pixels(8.).into())),
5076                left: Some(Length::Definite(Pixels(0.).into())),
5077                right: Some(Length::Definite(Pixels(0.).into())),
5078                bottom: Some(Length::Definite(Pixels(12.).into())),
5079            },
5080            border_style: Some(BorderStyle::Solid),
5081            border_widths: EdgesRefinement {
5082                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5083                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5084                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5085                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5086            },
5087            border_color: Some(colors.border_variant),
5088            background: Some(colors.editor_background.into()),
5089            text: Some(TextStyleRefinement {
5090                font_family: Some(theme_settings.buffer_font.family.clone()),
5091                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5092                font_features: Some(theme_settings.buffer_font.features.clone()),
5093                font_size: Some(buffer_font_size.into()),
5094                ..Default::default()
5095            }),
5096            ..Default::default()
5097        },
5098        inline_code: TextStyleRefinement {
5099            font_family: Some(theme_settings.buffer_font.family.clone()),
5100            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5101            font_features: Some(theme_settings.buffer_font.features.clone()),
5102            font_size: Some(buffer_font_size.into()),
5103            background_color: Some(colors.editor_foreground.opacity(0.08)),
5104            ..Default::default()
5105        },
5106        link: TextStyleRefinement {
5107            background_color: Some(colors.editor_foreground.opacity(0.025)),
5108            underline: Some(UnderlineStyle {
5109                color: Some(colors.text_accent.opacity(0.5)),
5110                thickness: px(1.),
5111                ..Default::default()
5112            }),
5113            ..Default::default()
5114        },
5115        ..Default::default()
5116    }
5117}
5118
5119fn plan_label_markdown_style(
5120    status: &acp::PlanEntryStatus,
5121    window: &Window,
5122    cx: &App,
5123) -> MarkdownStyle {
5124    let default_md_style = default_markdown_style(false, false, window, cx);
5125
5126    MarkdownStyle {
5127        base_text_style: TextStyle {
5128            color: cx.theme().colors().text_muted,
5129            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5130                Some(gpui::StrikethroughStyle {
5131                    thickness: px(1.),
5132                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5133                })
5134            } else {
5135                None
5136            },
5137            ..default_md_style.base_text_style
5138        },
5139        ..default_md_style
5140    }
5141}
5142
5143fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5144    let default_md_style = default_markdown_style(true, false, window, cx);
5145
5146    MarkdownStyle {
5147        base_text_style: TextStyle {
5148            ..default_md_style.base_text_style
5149        },
5150        selection_background_color: cx.theme().colors().element_selection_background,
5151        ..Default::default()
5152    }
5153}
5154
5155#[cfg(test)]
5156pub(crate) mod tests {
5157    use acp_thread::StubAgentConnection;
5158    use agent_client_protocol::SessionId;
5159    use assistant_context::ContextStore;
5160    use editor::EditorSettings;
5161    use fs::FakeFs;
5162    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5163    use project::Project;
5164    use serde_json::json;
5165    use settings::SettingsStore;
5166    use std::any::Any;
5167    use std::path::Path;
5168    use workspace::Item;
5169
5170    use super::*;
5171
5172    #[gpui::test]
5173    async fn test_drop(cx: &mut TestAppContext) {
5174        init_test(cx);
5175
5176        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5177        let weak_view = thread_view.downgrade();
5178        drop(thread_view);
5179        assert!(!weak_view.is_upgradable());
5180    }
5181
5182    #[gpui::test]
5183    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5184        init_test(cx);
5185
5186        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5187
5188        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5189        message_editor.update_in(cx, |editor, window, cx| {
5190            editor.set_text("Hello", window, cx);
5191        });
5192
5193        cx.deactivate_window();
5194
5195        thread_view.update_in(cx, |thread_view, window, cx| {
5196            thread_view.send(window, cx);
5197        });
5198
5199        cx.run_until_parked();
5200
5201        assert!(
5202            cx.windows()
5203                .iter()
5204                .any(|window| window.downcast::<AgentNotification>().is_some())
5205        );
5206    }
5207
5208    #[gpui::test]
5209    async fn test_notification_for_error(cx: &mut TestAppContext) {
5210        init_test(cx);
5211
5212        let (thread_view, cx) =
5213            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5214
5215        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5216        message_editor.update_in(cx, |editor, window, cx| {
5217            editor.set_text("Hello", window, cx);
5218        });
5219
5220        cx.deactivate_window();
5221
5222        thread_view.update_in(cx, |thread_view, window, cx| {
5223            thread_view.send(window, cx);
5224        });
5225
5226        cx.run_until_parked();
5227
5228        assert!(
5229            cx.windows()
5230                .iter()
5231                .any(|window| window.downcast::<AgentNotification>().is_some())
5232        );
5233    }
5234
5235    #[gpui::test]
5236    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5237        init_test(cx);
5238
5239        let tool_call_id = acp::ToolCallId("1".into());
5240        let tool_call = acp::ToolCall {
5241            id: tool_call_id.clone(),
5242            title: "Label".into(),
5243            kind: acp::ToolKind::Edit,
5244            status: acp::ToolCallStatus::Pending,
5245            content: vec!["hi".into()],
5246            locations: vec![],
5247            raw_input: None,
5248            raw_output: None,
5249        };
5250        let connection =
5251            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5252                tool_call_id,
5253                vec![acp::PermissionOption {
5254                    id: acp::PermissionOptionId("1".into()),
5255                    name: "Allow".into(),
5256                    kind: acp::PermissionOptionKind::AllowOnce,
5257                }],
5258            )]));
5259
5260        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5261
5262        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5263
5264        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5265        message_editor.update_in(cx, |editor, window, cx| {
5266            editor.set_text("Hello", window, cx);
5267        });
5268
5269        cx.deactivate_window();
5270
5271        thread_view.update_in(cx, |thread_view, window, cx| {
5272            thread_view.send(window, cx);
5273        });
5274
5275        cx.run_until_parked();
5276
5277        assert!(
5278            cx.windows()
5279                .iter()
5280                .any(|window| window.downcast::<AgentNotification>().is_some())
5281        );
5282    }
5283
5284    async fn setup_thread_view(
5285        agent: impl AgentServer + 'static,
5286        cx: &mut TestAppContext,
5287    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5288        let fs = FakeFs::new(cx.executor());
5289        let project = Project::test(fs, [], cx).await;
5290        let (workspace, cx) =
5291            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5292
5293        let context_store =
5294            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5295        let history_store =
5296            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5297
5298        let thread_view = cx.update(|window, cx| {
5299            cx.new(|cx| {
5300                AcpThreadView::new(
5301                    Rc::new(agent),
5302                    None,
5303                    None,
5304                    workspace.downgrade(),
5305                    project,
5306                    history_store,
5307                    None,
5308                    window,
5309                    cx,
5310                )
5311            })
5312        });
5313        cx.run_until_parked();
5314        (thread_view, cx)
5315    }
5316
5317    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5318        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5319
5320        workspace
5321            .update_in(cx, |workspace, window, cx| {
5322                workspace.add_item_to_active_pane(
5323                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5324                    None,
5325                    true,
5326                    window,
5327                    cx,
5328                );
5329            })
5330            .unwrap();
5331    }
5332
5333    struct ThreadViewItem(Entity<AcpThreadView>);
5334
5335    impl Item for ThreadViewItem {
5336        type Event = ();
5337
5338        fn include_in_nav_history() -> bool {
5339            false
5340        }
5341
5342        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5343            "Test".into()
5344        }
5345    }
5346
5347    impl EventEmitter<()> for ThreadViewItem {}
5348
5349    impl Focusable for ThreadViewItem {
5350        fn focus_handle(&self, cx: &App) -> FocusHandle {
5351            self.0.read(cx).focus_handle(cx)
5352        }
5353    }
5354
5355    impl Render for ThreadViewItem {
5356        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5357            self.0.clone().into_any_element()
5358        }
5359    }
5360
5361    struct StubAgentServer<C> {
5362        connection: C,
5363    }
5364
5365    impl<C> StubAgentServer<C> {
5366        fn new(connection: C) -> Self {
5367            Self { connection }
5368        }
5369    }
5370
5371    impl StubAgentServer<StubAgentConnection> {
5372        fn default_response() -> Self {
5373            let conn = StubAgentConnection::new();
5374            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5375                content: "Default response".into(),
5376            }]);
5377            Self::new(conn)
5378        }
5379    }
5380
5381    impl<C> AgentServer for StubAgentServer<C>
5382    where
5383        C: 'static + AgentConnection + Send + Clone,
5384    {
5385        fn telemetry_id(&self) -> &'static str {
5386            "test"
5387        }
5388
5389        fn logo(&self) -> ui::IconName {
5390            ui::IconName::Ai
5391        }
5392
5393        fn name(&self) -> SharedString {
5394            "Test".into()
5395        }
5396
5397        fn empty_state_headline(&self) -> SharedString {
5398            "Test".into()
5399        }
5400
5401        fn empty_state_message(&self) -> SharedString {
5402            "Test".into()
5403        }
5404
5405        fn install_command(&self) -> Option<&'static str> {
5406            None
5407        }
5408
5409        fn connect(
5410            &self,
5411            _root_dir: &Path,
5412            _project: &Entity<Project>,
5413            _cx: &mut App,
5414        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5415            Task::ready(Ok(Rc::new(self.connection.clone())))
5416        }
5417
5418        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5419            self
5420        }
5421    }
5422
5423    #[derive(Clone)]
5424    struct SaboteurAgentConnection;
5425
5426    impl AgentConnection for SaboteurAgentConnection {
5427        fn new_thread(
5428            self: Rc<Self>,
5429            project: Entity<Project>,
5430            _cwd: &Path,
5431            cx: &mut gpui::App,
5432        ) -> Task<gpui::Result<Entity<AcpThread>>> {
5433            Task::ready(Ok(cx.new(|cx| {
5434                let action_log = cx.new(|_| ActionLog::new(project.clone()));
5435                AcpThread::new(
5436                    "SaboteurAgentConnection",
5437                    self,
5438                    project,
5439                    action_log,
5440                    SessionId("test".into()),
5441                    watch::Receiver::constant(acp::PromptCapabilities {
5442                        image: true,
5443                        audio: true,
5444                        embedded_context: true,
5445                    }),
5446                    cx,
5447                )
5448            })))
5449        }
5450
5451        fn auth_methods(&self) -> &[acp::AuthMethod] {
5452            &[]
5453        }
5454
5455        fn authenticate(
5456            &self,
5457            _method_id: acp::AuthMethodId,
5458            _cx: &mut App,
5459        ) -> Task<gpui::Result<()>> {
5460            unimplemented!()
5461        }
5462
5463        fn prompt(
5464            &self,
5465            _id: Option<acp_thread::UserMessageId>,
5466            _params: acp::PromptRequest,
5467            _cx: &mut App,
5468        ) -> Task<gpui::Result<acp::PromptResponse>> {
5469            Task::ready(Err(anyhow::anyhow!("Error prompting")))
5470        }
5471
5472        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5473            unimplemented!()
5474        }
5475
5476        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5477            self
5478        }
5479    }
5480
5481    pub(crate) fn init_test(cx: &mut TestAppContext) {
5482        cx.update(|cx| {
5483            let settings_store = SettingsStore::test(cx);
5484            cx.set_global(settings_store);
5485            language::init(cx);
5486            Project::init_settings(cx);
5487            AgentSettings::register(cx);
5488            workspace::init_settings(cx);
5489            ThemeSettings::register(cx);
5490            release_channel::init(SemanticVersion::default(), cx);
5491            EditorSettings::register(cx);
5492            prompt_store::init(cx)
5493        });
5494    }
5495
5496    #[gpui::test]
5497    async fn test_rewind_views(cx: &mut TestAppContext) {
5498        init_test(cx);
5499
5500        let fs = FakeFs::new(cx.executor());
5501        fs.insert_tree(
5502            "/project",
5503            json!({
5504                "test1.txt": "old content 1",
5505                "test2.txt": "old content 2"
5506            }),
5507        )
5508        .await;
5509        let project = Project::test(fs, [Path::new("/project")], cx).await;
5510        let (workspace, cx) =
5511            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5512
5513        let context_store =
5514            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5515        let history_store =
5516            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5517
5518        let connection = Rc::new(StubAgentConnection::new());
5519        let thread_view = cx.update(|window, cx| {
5520            cx.new(|cx| {
5521                AcpThreadView::new(
5522                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5523                    None,
5524                    None,
5525                    workspace.downgrade(),
5526                    project.clone(),
5527                    history_store.clone(),
5528                    None,
5529                    window,
5530                    cx,
5531                )
5532            })
5533        });
5534
5535        cx.run_until_parked();
5536
5537        let thread = thread_view
5538            .read_with(cx, |view, _| view.thread().cloned())
5539            .unwrap();
5540
5541        // First user message
5542        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5543            id: acp::ToolCallId("tool1".into()),
5544            title: "Edit file 1".into(),
5545            kind: acp::ToolKind::Edit,
5546            status: acp::ToolCallStatus::Completed,
5547            content: vec![acp::ToolCallContent::Diff {
5548                diff: acp::Diff {
5549                    path: "/project/test1.txt".into(),
5550                    old_text: Some("old content 1".into()),
5551                    new_text: "new content 1".into(),
5552                },
5553            }],
5554            locations: vec![],
5555            raw_input: None,
5556            raw_output: None,
5557        })]);
5558
5559        thread
5560            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5561            .await
5562            .unwrap();
5563        cx.run_until_parked();
5564
5565        thread.read_with(cx, |thread, _| {
5566            assert_eq!(thread.entries().len(), 2);
5567        });
5568
5569        thread_view.read_with(cx, |view, cx| {
5570            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5571                assert!(
5572                    entry_view_state
5573                        .entry(0)
5574                        .unwrap()
5575                        .message_editor()
5576                        .is_some()
5577                );
5578                assert!(entry_view_state.entry(1).unwrap().has_content());
5579            });
5580        });
5581
5582        // Second user message
5583        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5584            id: acp::ToolCallId("tool2".into()),
5585            title: "Edit file 2".into(),
5586            kind: acp::ToolKind::Edit,
5587            status: acp::ToolCallStatus::Completed,
5588            content: vec![acp::ToolCallContent::Diff {
5589                diff: acp::Diff {
5590                    path: "/project/test2.txt".into(),
5591                    old_text: Some("old content 2".into()),
5592                    new_text: "new content 2".into(),
5593                },
5594            }],
5595            locations: vec![],
5596            raw_input: None,
5597            raw_output: None,
5598        })]);
5599
5600        thread
5601            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5602            .await
5603            .unwrap();
5604        cx.run_until_parked();
5605
5606        let second_user_message_id = thread.read_with(cx, |thread, _| {
5607            assert_eq!(thread.entries().len(), 4);
5608            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5609                panic!();
5610            };
5611            user_message.id.clone().unwrap()
5612        });
5613
5614        thread_view.read_with(cx, |view, cx| {
5615            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5616                assert!(
5617                    entry_view_state
5618                        .entry(0)
5619                        .unwrap()
5620                        .message_editor()
5621                        .is_some()
5622                );
5623                assert!(entry_view_state.entry(1).unwrap().has_content());
5624                assert!(
5625                    entry_view_state
5626                        .entry(2)
5627                        .unwrap()
5628                        .message_editor()
5629                        .is_some()
5630                );
5631                assert!(entry_view_state.entry(3).unwrap().has_content());
5632            });
5633        });
5634
5635        // Rewind to first message
5636        thread
5637            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5638            .await
5639            .unwrap();
5640
5641        cx.run_until_parked();
5642
5643        thread.read_with(cx, |thread, _| {
5644            assert_eq!(thread.entries().len(), 2);
5645        });
5646
5647        thread_view.read_with(cx, |view, cx| {
5648            view.entry_view_state.read_with(cx, |entry_view_state, _| {
5649                assert!(
5650                    entry_view_state
5651                        .entry(0)
5652                        .unwrap()
5653                        .message_editor()
5654                        .is_some()
5655                );
5656                assert!(entry_view_state.entry(1).unwrap().has_content());
5657
5658                // Old views should be dropped
5659                assert!(entry_view_state.entry(2).is_none());
5660                assert!(entry_view_state.entry(3).is_none());
5661            });
5662        });
5663    }
5664
5665    #[gpui::test]
5666    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5667        init_test(cx);
5668
5669        let connection = StubAgentConnection::new();
5670
5671        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5672            content: acp::ContentBlock::Text(acp::TextContent {
5673                text: "Response".into(),
5674                annotations: None,
5675            }),
5676        }]);
5677
5678        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5679        add_to_workspace(thread_view.clone(), cx);
5680
5681        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5682        message_editor.update_in(cx, |editor, window, cx| {
5683            editor.set_text("Original message to edit", window, cx);
5684        });
5685        thread_view.update_in(cx, |thread_view, window, cx| {
5686            thread_view.send(window, cx);
5687        });
5688
5689        cx.run_until_parked();
5690
5691        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5692            assert_eq!(view.editing_message, None);
5693
5694            view.entry_view_state
5695                .read(cx)
5696                .entry(0)
5697                .unwrap()
5698                .message_editor()
5699                .unwrap()
5700                .clone()
5701        });
5702
5703        // Focus
5704        cx.focus(&user_message_editor);
5705        thread_view.read_with(cx, |view, _cx| {
5706            assert_eq!(view.editing_message, Some(0));
5707        });
5708
5709        // Edit
5710        user_message_editor.update_in(cx, |editor, window, cx| {
5711            editor.set_text("Edited message content", window, cx);
5712        });
5713
5714        // Cancel
5715        user_message_editor.update_in(cx, |_editor, window, cx| {
5716            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5717        });
5718
5719        thread_view.read_with(cx, |view, _cx| {
5720            assert_eq!(view.editing_message, None);
5721        });
5722
5723        user_message_editor.read_with(cx, |editor, cx| {
5724            assert_eq!(editor.text(cx), "Original message to edit");
5725        });
5726    }
5727
5728    #[gpui::test]
5729    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5730        init_test(cx);
5731
5732        let connection = StubAgentConnection::new();
5733
5734        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5735        add_to_workspace(thread_view.clone(), cx);
5736
5737        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5738        let mut events = cx.events(&message_editor);
5739        message_editor.update_in(cx, |editor, window, cx| {
5740            editor.set_text("", window, cx);
5741        });
5742
5743        message_editor.update_in(cx, |_editor, window, cx| {
5744            window.dispatch_action(Box::new(Chat), cx);
5745        });
5746        cx.run_until_parked();
5747        // We shouldn't have received any messages
5748        assert!(matches!(
5749            events.try_next(),
5750            Err(futures::channel::mpsc::TryRecvError { .. })
5751        ));
5752    }
5753
5754    #[gpui::test]
5755    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5756        init_test(cx);
5757
5758        let connection = StubAgentConnection::new();
5759
5760        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5761            content: acp::ContentBlock::Text(acp::TextContent {
5762                text: "Response".into(),
5763                annotations: None,
5764            }),
5765        }]);
5766
5767        let (thread_view, cx) =
5768            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5769        add_to_workspace(thread_view.clone(), cx);
5770
5771        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5772        message_editor.update_in(cx, |editor, window, cx| {
5773            editor.set_text("Original message to edit", window, cx);
5774        });
5775        thread_view.update_in(cx, |thread_view, window, cx| {
5776            thread_view.send(window, cx);
5777        });
5778
5779        cx.run_until_parked();
5780
5781        let user_message_editor = thread_view.read_with(cx, |view, cx| {
5782            assert_eq!(view.editing_message, None);
5783            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5784
5785            view.entry_view_state
5786                .read(cx)
5787                .entry(0)
5788                .unwrap()
5789                .message_editor()
5790                .unwrap()
5791                .clone()
5792        });
5793
5794        // Focus
5795        cx.focus(&user_message_editor);
5796
5797        // Edit
5798        user_message_editor.update_in(cx, |editor, window, cx| {
5799            editor.set_text("Edited message content", window, cx);
5800        });
5801
5802        // Send
5803        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5804            content: acp::ContentBlock::Text(acp::TextContent {
5805                text: "New Response".into(),
5806                annotations: None,
5807            }),
5808        }]);
5809
5810        user_message_editor.update_in(cx, |_editor, window, cx| {
5811            window.dispatch_action(Box::new(Chat), cx);
5812        });
5813
5814        cx.run_until_parked();
5815
5816        thread_view.read_with(cx, |view, cx| {
5817            assert_eq!(view.editing_message, None);
5818
5819            let entries = view.thread().unwrap().read(cx).entries();
5820            assert_eq!(entries.len(), 2);
5821            assert_eq!(
5822                entries[0].to_markdown(cx),
5823                "## User\n\nEdited message content\n\n"
5824            );
5825            assert_eq!(
5826                entries[1].to_markdown(cx),
5827                "## Assistant\n\nNew Response\n\n"
5828            );
5829
5830            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5831                assert!(!state.entry(1).unwrap().has_content());
5832                state.entry(0).unwrap().message_editor().unwrap().clone()
5833            });
5834
5835            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5836        })
5837    }
5838
5839    #[gpui::test]
5840    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5841        init_test(cx);
5842
5843        let connection = StubAgentConnection::new();
5844
5845        let (thread_view, cx) =
5846            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5847        add_to_workspace(thread_view.clone(), cx);
5848
5849        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5850        message_editor.update_in(cx, |editor, window, cx| {
5851            editor.set_text("Original message to edit", window, cx);
5852        });
5853        thread_view.update_in(cx, |thread_view, window, cx| {
5854            thread_view.send(window, cx);
5855        });
5856
5857        cx.run_until_parked();
5858
5859        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5860            let thread = view.thread().unwrap().read(cx);
5861            assert_eq!(thread.entries().len(), 1);
5862
5863            let editor = view
5864                .entry_view_state
5865                .read(cx)
5866                .entry(0)
5867                .unwrap()
5868                .message_editor()
5869                .unwrap()
5870                .clone();
5871
5872            (editor, thread.session_id().clone())
5873        });
5874
5875        // Focus
5876        cx.focus(&user_message_editor);
5877
5878        thread_view.read_with(cx, |view, _cx| {
5879            assert_eq!(view.editing_message, Some(0));
5880        });
5881
5882        // Edit
5883        user_message_editor.update_in(cx, |editor, window, cx| {
5884            editor.set_text("Edited message content", window, cx);
5885        });
5886
5887        thread_view.read_with(cx, |view, _cx| {
5888            assert_eq!(view.editing_message, Some(0));
5889        });
5890
5891        // Finish streaming response
5892        cx.update(|_, cx| {
5893            connection.send_update(
5894                session_id.clone(),
5895                acp::SessionUpdate::AgentMessageChunk {
5896                    content: acp::ContentBlock::Text(acp::TextContent {
5897                        text: "Response".into(),
5898                        annotations: None,
5899                    }),
5900                },
5901                cx,
5902            );
5903            connection.end_turn(session_id, acp::StopReason::EndTurn);
5904        });
5905
5906        thread_view.read_with(cx, |view, _cx| {
5907            assert_eq!(view.editing_message, Some(0));
5908        });
5909
5910        cx.run_until_parked();
5911
5912        // Should still be editing
5913        cx.update(|window, cx| {
5914            assert!(user_message_editor.focus_handle(cx).is_focused(window));
5915            assert_eq!(thread_view.read(cx).editing_message, Some(0));
5916            assert_eq!(
5917                user_message_editor.read(cx).text(cx),
5918                "Edited message content"
5919            );
5920        });
5921    }
5922
5923    #[gpui::test]
5924    async fn test_interrupt(cx: &mut TestAppContext) {
5925        init_test(cx);
5926
5927        let connection = StubAgentConnection::new();
5928
5929        let (thread_view, cx) =
5930            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5931        add_to_workspace(thread_view.clone(), cx);
5932
5933        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5934        message_editor.update_in(cx, |editor, window, cx| {
5935            editor.set_text("Message 1", window, cx);
5936        });
5937        thread_view.update_in(cx, |thread_view, window, cx| {
5938            thread_view.send(window, cx);
5939        });
5940
5941        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5942            let thread = view.thread().unwrap();
5943
5944            (thread.clone(), thread.read(cx).session_id().clone())
5945        });
5946
5947        cx.run_until_parked();
5948
5949        cx.update(|_, cx| {
5950            connection.send_update(
5951                session_id.clone(),
5952                acp::SessionUpdate::AgentMessageChunk {
5953                    content: "Message 1 resp".into(),
5954                },
5955                cx,
5956            );
5957        });
5958
5959        cx.run_until_parked();
5960
5961        thread.read_with(cx, |thread, cx| {
5962            assert_eq!(
5963                thread.to_markdown(cx),
5964                indoc::indoc! {"
5965                    ## User
5966
5967                    Message 1
5968
5969                    ## Assistant
5970
5971                    Message 1 resp
5972
5973                "}
5974            )
5975        });
5976
5977        message_editor.update_in(cx, |editor, window, cx| {
5978            editor.set_text("Message 2", window, cx);
5979        });
5980        thread_view.update_in(cx, |thread_view, window, cx| {
5981            thread_view.send(window, cx);
5982        });
5983
5984        cx.update(|_, cx| {
5985            // Simulate a response sent after beginning to cancel
5986            connection.send_update(
5987                session_id.clone(),
5988                acp::SessionUpdate::AgentMessageChunk {
5989                    content: "onse".into(),
5990                },
5991                cx,
5992            );
5993        });
5994
5995        cx.run_until_parked();
5996
5997        // Last Message 1 response should appear before Message 2
5998        thread.read_with(cx, |thread, cx| {
5999            assert_eq!(
6000                thread.to_markdown(cx),
6001                indoc::indoc! {"
6002                    ## User
6003
6004                    Message 1
6005
6006                    ## Assistant
6007
6008                    Message 1 response
6009
6010                    ## User
6011
6012                    Message 2
6013
6014                "}
6015            )
6016        });
6017
6018        cx.update(|_, cx| {
6019            connection.send_update(
6020                session_id.clone(),
6021                acp::SessionUpdate::AgentMessageChunk {
6022                    content: "Message 2 response".into(),
6023                },
6024                cx,
6025            );
6026            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6027        });
6028
6029        cx.run_until_parked();
6030
6031        thread.read_with(cx, |thread, cx| {
6032            assert_eq!(
6033                thread.to_markdown(cx),
6034                indoc::indoc! {"
6035                    ## User
6036
6037                    Message 1
6038
6039                    ## Assistant
6040
6041                    Message 1 response
6042
6043                    ## User
6044
6045                    Message 2
6046
6047                    ## Assistant
6048
6049                    Message 2 response
6050
6051                "}
6052            )
6053        });
6054    }
6055}