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