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