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