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