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));
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                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1559                            this.expanded_tool_calls.remove(&tool_call_id);
1560                            cx.notify();
1561                        }
1562                    })),
1563            )
1564            .into_any_element()
1565    }
1566
1567    fn render_resource_link(
1568        &self,
1569        resource_link: &acp::ResourceLink,
1570        cx: &Context<Self>,
1571    ) -> AnyElement {
1572        let uri: SharedString = resource_link.uri.clone().into();
1573
1574        let label: SharedString = if let Some(path) = resource_link.uri.strip_prefix("file://") {
1575            path.to_string().into()
1576        } else {
1577            uri.clone()
1578        };
1579
1580        let button_id = SharedString::from(format!("item-{}", uri));
1581
1582        div()
1583            .ml(px(7.))
1584            .pl_2p5()
1585            .border_l_1()
1586            .border_color(self.tool_card_border_color(cx))
1587            .overflow_hidden()
1588            .child(
1589                Button::new(button_id, label)
1590                    .label_size(LabelSize::Small)
1591                    .color(Color::Muted)
1592                    .icon(IconName::ArrowUpRight)
1593                    .icon_size(IconSize::XSmall)
1594                    .icon_color(Color::Muted)
1595                    .truncate(true)
1596                    .on_click(cx.listener({
1597                        let workspace = self.workspace.clone();
1598                        move |_, _, window, cx: &mut Context<Self>| {
1599                            Self::open_link(uri.clone(), &workspace, window, cx);
1600                        }
1601                    })),
1602            )
1603            .into_any_element()
1604    }
1605
1606    fn render_permission_buttons(
1607        &self,
1608        options: &[acp::PermissionOption],
1609        entry_ix: usize,
1610        tool_call_id: acp::ToolCallId,
1611        empty_content: bool,
1612        cx: &Context<Self>,
1613    ) -> Div {
1614        h_flex()
1615            .py_1()
1616            .pl_2()
1617            .pr_1()
1618            .gap_1()
1619            .justify_between()
1620            .flex_wrap()
1621            .when(!empty_content, |this| {
1622                this.border_t_1()
1623                    .border_color(self.tool_card_border_color(cx))
1624            })
1625            .child(
1626                div()
1627                    .min_w(rems_from_px(145.))
1628                    .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1629            )
1630            .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1631                let option_id = SharedString::from(option.id.0.clone());
1632                Button::new((option_id, entry_ix), option.name.clone())
1633                    .map(|this| match option.kind {
1634                        acp::PermissionOptionKind::AllowOnce => {
1635                            this.icon(IconName::Check).icon_color(Color::Success)
1636                        }
1637                        acp::PermissionOptionKind::AllowAlways => {
1638                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1639                        }
1640                        acp::PermissionOptionKind::RejectOnce => {
1641                            this.icon(IconName::Close).icon_color(Color::Error)
1642                        }
1643                        acp::PermissionOptionKind::RejectAlways => {
1644                            this.icon(IconName::Close).icon_color(Color::Error)
1645                        }
1646                    })
1647                    .icon_position(IconPosition::Start)
1648                    .icon_size(IconSize::XSmall)
1649                    .label_size(LabelSize::Small)
1650                    .on_click(cx.listener({
1651                        let tool_call_id = tool_call_id.clone();
1652                        let option_id = option.id.clone();
1653                        let option_kind = option.kind;
1654                        move |this, _, _, cx| {
1655                            this.authorize_tool_call(
1656                                tool_call_id.clone(),
1657                                option_id.clone(),
1658                                option_kind,
1659                                cx,
1660                            );
1661                        }
1662                    }))
1663            })))
1664    }
1665
1666    fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
1667        let bar = |n: u64, width_class: &str| {
1668            let bg_color = cx.theme().colors().element_active;
1669            let base = h_flex().h_1().rounded_full();
1670
1671            let modified = match width_class {
1672                "w_4_5" => base.w_3_4(),
1673                "w_1_4" => base.w_1_4(),
1674                "w_2_4" => base.w_2_4(),
1675                "w_3_5" => base.w_3_5(),
1676                "w_2_5" => base.w_2_5(),
1677                _ => base.w_1_2(),
1678            };
1679
1680            modified.with_animation(
1681                ElementId::Integer(n),
1682                Animation::new(Duration::from_secs(2)).repeat(),
1683                move |tab, delta| {
1684                    let delta = (delta - 0.15 * n as f32) / 0.7;
1685                    let delta = 1.0 - (0.5 - delta).abs() * 2.;
1686                    let delta = ease_in_out(delta.clamp(0., 1.));
1687                    let delta = 0.1 + 0.9 * delta;
1688
1689                    tab.bg(bg_color.opacity(delta))
1690                },
1691            )
1692        };
1693
1694        v_flex()
1695            .p_3()
1696            .gap_1()
1697            .rounded_b_md()
1698            .bg(cx.theme().colors().editor_background)
1699            .child(bar(0, "w_4_5"))
1700            .child(bar(1, "w_1_4"))
1701            .child(bar(2, "w_2_4"))
1702            .child(bar(3, "w_3_5"))
1703            .child(bar(4, "w_2_5"))
1704            .into_any_element()
1705    }
1706
1707    fn render_diff_editor(
1708        &self,
1709        entry_ix: usize,
1710        diff: &Entity<acp_thread::Diff>,
1711        tool_call: &ToolCall,
1712        cx: &Context<Self>,
1713    ) -> AnyElement {
1714        let tool_progress = matches!(
1715            &tool_call.status,
1716            ToolCallStatus::InProgress | ToolCallStatus::Pending
1717        );
1718
1719        v_flex()
1720            .h_full()
1721            .child(
1722                if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
1723                    && let Some(editor) = entry.editor_for_diff(diff)
1724                    && diff.read(cx).has_revealed_range(cx)
1725                {
1726                    editor.into_any_element()
1727                } else if tool_progress {
1728                    self.render_diff_loading(cx)
1729                } else {
1730                    Empty.into_any()
1731                },
1732            )
1733            .into_any()
1734    }
1735
1736    fn render_terminal_tool_call(
1737        &self,
1738        entry_ix: usize,
1739        terminal: &Entity<acp_thread::Terminal>,
1740        tool_call: &ToolCall,
1741        window: &Window,
1742        cx: &Context<Self>,
1743    ) -> AnyElement {
1744        let terminal_data = terminal.read(cx);
1745        let working_dir = terminal_data.working_dir();
1746        let command = terminal_data.command();
1747        let started_at = terminal_data.started_at();
1748
1749        let tool_failed = matches!(
1750            &tool_call.status,
1751            ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
1752        );
1753
1754        let output = terminal_data.output();
1755        let command_finished = output.is_some();
1756        let truncated_output = output.is_some_and(|output| output.was_content_truncated);
1757        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
1758
1759        let command_failed = command_finished
1760            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
1761
1762        let time_elapsed = if let Some(output) = output {
1763            output.ended_at.duration_since(started_at)
1764        } else {
1765            started_at.elapsed()
1766        };
1767
1768        let header_bg = cx
1769            .theme()
1770            .colors()
1771            .element_background
1772            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1773        let border_color = cx.theme().colors().border.opacity(0.6);
1774
1775        let working_dir = working_dir
1776            .as_ref()
1777            .map(|path| format!("{}", path.display()))
1778            .unwrap_or_else(|| "current directory".to_string());
1779
1780        let header = h_flex()
1781            .id(SharedString::from(format!(
1782                "terminal-tool-header-{}",
1783                terminal.entity_id()
1784            )))
1785            .flex_none()
1786            .gap_1()
1787            .justify_between()
1788            .rounded_t_md()
1789            .child(
1790                div()
1791                    .id(("command-target-path", terminal.entity_id()))
1792                    .w_full()
1793                    .max_w_full()
1794                    .overflow_x_scroll()
1795                    .child(
1796                        Label::new(working_dir)
1797                            .buffer_font(cx)
1798                            .size(LabelSize::XSmall)
1799                            .color(Color::Muted),
1800                    ),
1801            )
1802            .when(!command_finished, |header| {
1803                header
1804                    .gap_1p5()
1805                    .child(
1806                        Button::new(
1807                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
1808                            "Stop",
1809                        )
1810                        .icon(IconName::Stop)
1811                        .icon_position(IconPosition::Start)
1812                        .icon_size(IconSize::Small)
1813                        .icon_color(Color::Error)
1814                        .label_size(LabelSize::Small)
1815                        .tooltip(move |window, cx| {
1816                            Tooltip::with_meta(
1817                                "Stop This Command",
1818                                None,
1819                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
1820                                window,
1821                                cx,
1822                            )
1823                        })
1824                        .on_click({
1825                            let terminal = terminal.clone();
1826                            cx.listener(move |_this, _event, _window, cx| {
1827                                let inner_terminal = terminal.read(cx).inner().clone();
1828                                inner_terminal.update(cx, |inner_terminal, _cx| {
1829                                    inner_terminal.kill_active_task();
1830                                });
1831                            })
1832                        }),
1833                    )
1834                    .child(Divider::vertical())
1835                    .child(
1836                        Icon::new(IconName::ArrowCircle)
1837                            .size(IconSize::XSmall)
1838                            .color(Color::Info)
1839                            .with_animation(
1840                                "arrow-circle",
1841                                Animation::new(Duration::from_secs(2)).repeat(),
1842                                |icon, delta| {
1843                                    icon.transform(Transformation::rotate(percentage(delta)))
1844                                },
1845                            ),
1846                    )
1847            })
1848            .when(tool_failed || command_failed, |header| {
1849                header.child(
1850                    div()
1851                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
1852                        .child(
1853                            Icon::new(IconName::Close)
1854                                .size(IconSize::Small)
1855                                .color(Color::Error),
1856                        )
1857                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
1858                            this.tooltip(Tooltip::text(format!(
1859                                "Exited with code {}",
1860                                status.code().unwrap_or(-1),
1861                            )))
1862                        }),
1863                )
1864            })
1865            .when(truncated_output, |header| {
1866                let tooltip = if let Some(output) = output {
1867                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
1868                        "Output exceeded terminal max lines and was \
1869                            truncated, the model received the first 16 KB."
1870                            .to_string()
1871                    } else {
1872                        format!(
1873                            "Output is {} long—to avoid unexpected token usage, \
1874                                only 16 KB was sent back to the model.",
1875                            format_file_size(output.original_content_len as u64, true),
1876                        )
1877                    }
1878                } else {
1879                    "Output was truncated".to_string()
1880                };
1881
1882                header.child(
1883                    h_flex()
1884                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
1885                        .gap_1()
1886                        .child(
1887                            Icon::new(IconName::Info)
1888                                .size(IconSize::XSmall)
1889                                .color(Color::Ignored),
1890                        )
1891                        .child(
1892                            Label::new("Truncated")
1893                                .color(Color::Muted)
1894                                .size(LabelSize::XSmall),
1895                        )
1896                        .tooltip(Tooltip::text(tooltip)),
1897                )
1898            })
1899            .when(time_elapsed > Duration::from_secs(10), |header| {
1900                header.child(
1901                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
1902                        .buffer_font(cx)
1903                        .color(Color::Muted)
1904                        .size(LabelSize::XSmall),
1905                )
1906            })
1907            .child(
1908                Disclosure::new(
1909                    SharedString::from(format!(
1910                        "terminal-tool-disclosure-{}",
1911                        terminal.entity_id()
1912                    )),
1913                    self.terminal_expanded,
1914                )
1915                .opened_icon(IconName::ChevronUp)
1916                .closed_icon(IconName::ChevronDown)
1917                .on_click(cx.listener(move |this, _event, _window, _cx| {
1918                    this.terminal_expanded = !this.terminal_expanded;
1919                })),
1920            );
1921
1922        let terminal_view = self
1923            .entry_view_state
1924            .read(cx)
1925            .entry(entry_ix)
1926            .and_then(|entry| entry.terminal(terminal));
1927        let show_output = self.terminal_expanded && terminal_view.is_some();
1928
1929        v_flex()
1930            .mb_2()
1931            .border_1()
1932            .when(tool_failed || command_failed, |card| card.border_dashed())
1933            .border_color(border_color)
1934            .rounded_lg()
1935            .overflow_hidden()
1936            .child(
1937                v_flex()
1938                    .py_1p5()
1939                    .pl_2()
1940                    .pr_1p5()
1941                    .gap_0p5()
1942                    .bg(header_bg)
1943                    .text_xs()
1944                    .child(header)
1945                    .child(
1946                        MarkdownElement::new(
1947                            command.clone(),
1948                            terminal_command_markdown_style(window, cx),
1949                        )
1950                        .code_block_renderer(
1951                            markdown::CodeBlockRenderer::Default {
1952                                copy_button: false,
1953                                copy_button_on_hover: true,
1954                                border: false,
1955                            },
1956                        ),
1957                    ),
1958            )
1959            .when(show_output, |this| {
1960                this.child(
1961                    div()
1962                        .pt_2()
1963                        .border_t_1()
1964                        .when(tool_failed || command_failed, |card| card.border_dashed())
1965                        .border_color(border_color)
1966                        .bg(cx.theme().colors().editor_background)
1967                        .rounded_b_md()
1968                        .text_ui_sm(cx)
1969                        .children(terminal_view.clone()),
1970                )
1971            })
1972            .into_any()
1973    }
1974
1975    fn render_agent_logo(&self) -> AnyElement {
1976        Icon::new(self.agent.logo())
1977            .color(Color::Muted)
1978            .size(IconSize::XLarge)
1979            .into_any_element()
1980    }
1981
1982    fn render_error_agent_logo(&self) -> AnyElement {
1983        let logo = Icon::new(self.agent.logo())
1984            .color(Color::Muted)
1985            .size(IconSize::XLarge)
1986            .into_any_element();
1987
1988        h_flex()
1989            .relative()
1990            .justify_center()
1991            .child(div().opacity(0.3).child(logo))
1992            .child(
1993                h_flex()
1994                    .absolute()
1995                    .right_1()
1996                    .bottom_0()
1997                    .child(Icon::new(IconName::XCircleFilled).color(Color::Error)),
1998            )
1999            .into_any_element()
2000    }
2001
2002    fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2003        let project_context = self
2004            .as_native_thread(cx)?
2005            .read(cx)
2006            .project_context()
2007            .read(cx);
2008
2009        let user_rules_text = if project_context.user_rules.is_empty() {
2010            None
2011        } else if project_context.user_rules.len() == 1 {
2012            let user_rules = &project_context.user_rules[0];
2013
2014            match user_rules.title.as_ref() {
2015                Some(title) => Some(format!("Using \"{title}\" user rule")),
2016                None => Some("Using user rule".into()),
2017            }
2018        } else {
2019            Some(format!(
2020                "Using {} user rules",
2021                project_context.user_rules.len()
2022            ))
2023        };
2024
2025        let first_user_rules_id = project_context
2026            .user_rules
2027            .first()
2028            .map(|user_rules| user_rules.uuid.0);
2029
2030        let rules_files = project_context
2031            .worktrees
2032            .iter()
2033            .filter_map(|worktree| worktree.rules_file.as_ref())
2034            .collect::<Vec<_>>();
2035
2036        let rules_file_text = match rules_files.as_slice() {
2037            &[] => None,
2038            &[rules_file] => Some(format!(
2039                "Using project {:?} file",
2040                rules_file.path_in_worktree
2041            )),
2042            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2043        };
2044
2045        if user_rules_text.is_none() && rules_file_text.is_none() {
2046            return None;
2047        }
2048
2049        Some(
2050            v_flex()
2051                .px_2p5()
2052                .gap_1()
2053                .when_some(user_rules_text, |parent, user_rules_text| {
2054                    parent.child(
2055                        h_flex()
2056                            .group("user-rules")
2057                            .id("user-rules")
2058                            .w_full()
2059                            .child(
2060                                Icon::new(IconName::Reader)
2061                                    .size(IconSize::XSmall)
2062                                    .color(Color::Disabled),
2063                            )
2064                            .child(
2065                                Label::new(user_rules_text)
2066                                    .size(LabelSize::XSmall)
2067                                    .color(Color::Muted)
2068                                    .truncate()
2069                                    .buffer_font(cx)
2070                                    .ml_1p5()
2071                                    .mr_0p5(),
2072                            )
2073                            .child(
2074                                IconButton::new("open-prompt-library", IconName::ArrowUpRight)
2075                                    .shape(ui::IconButtonShape::Square)
2076                                    .icon_size(IconSize::XSmall)
2077                                    .icon_color(Color::Ignored)
2078                                    .visible_on_hover("user-rules")
2079                                    // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary`  keybinding
2080                                    .tooltip(Tooltip::text("View User Rules")),
2081                            )
2082                            .on_click(move |_event, window, cx| {
2083                                window.dispatch_action(
2084                                    Box::new(OpenRulesLibrary {
2085                                        prompt_to_select: first_user_rules_id,
2086                                    }),
2087                                    cx,
2088                                )
2089                            }),
2090                    )
2091                })
2092                .when_some(rules_file_text, |parent, rules_file_text| {
2093                    parent.child(
2094                        h_flex()
2095                            .group("project-rules")
2096                            .id("project-rules")
2097                            .w_full()
2098                            .child(
2099                                Icon::new(IconName::Reader)
2100                                    .size(IconSize::XSmall)
2101                                    .color(Color::Disabled),
2102                            )
2103                            .child(
2104                                Label::new(rules_file_text)
2105                                    .size(LabelSize::XSmall)
2106                                    .color(Color::Muted)
2107                                    .buffer_font(cx)
2108                                    .ml_1p5()
2109                                    .mr_0p5(),
2110                            )
2111                            .child(
2112                                IconButton::new("open-rule", IconName::ArrowUpRight)
2113                                    .shape(ui::IconButtonShape::Square)
2114                                    .icon_size(IconSize::XSmall)
2115                                    .icon_color(Color::Ignored)
2116                                    .visible_on_hover("project-rules")
2117                                    .tooltip(Tooltip::text("View Project Rules")),
2118                            )
2119                            .on_click(cx.listener(Self::handle_open_rules)),
2120                    )
2121                })
2122                .into_any(),
2123        )
2124    }
2125
2126    fn render_empty_state(&self, cx: &App) -> AnyElement {
2127        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
2128
2129        v_flex()
2130            .size_full()
2131            .items_center()
2132            .justify_center()
2133            .child(if loading {
2134                h_flex()
2135                    .justify_center()
2136                    .child(self.render_agent_logo())
2137                    .with_animation(
2138                        "pulsating_icon",
2139                        Animation::new(Duration::from_secs(2))
2140                            .repeat()
2141                            .with_easing(pulsating_between(0.4, 1.0)),
2142                        |icon, delta| icon.opacity(delta),
2143                    )
2144                    .into_any()
2145            } else {
2146                self.render_agent_logo().into_any_element()
2147            })
2148            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
2149                div()
2150                    .child(LoadingLabel::new("").size(LabelSize::Large))
2151                    .into_any_element()
2152            } else {
2153                Headline::new(self.agent.empty_state_headline())
2154                    .size(HeadlineSize::Medium)
2155                    .into_any_element()
2156            }))
2157            .child(
2158                div()
2159                    .max_w_1_2()
2160                    .text_sm()
2161                    .text_center()
2162                    .map(|this| {
2163                        if loading {
2164                            this.invisible()
2165                        } else {
2166                            this.text_color(cx.theme().colors().text_muted)
2167                        }
2168                    })
2169                    .child(self.agent.empty_state_message()),
2170            )
2171            .into_any()
2172    }
2173
2174    fn render_auth_required_state(
2175        &self,
2176        connection: &Rc<dyn AgentConnection>,
2177        description: Option<&Entity<Markdown>>,
2178        configuration_view: Option<&AnyView>,
2179        window: &mut Window,
2180        cx: &Context<Self>,
2181    ) -> Div {
2182        v_flex()
2183            .p_2()
2184            .gap_2()
2185            .flex_1()
2186            .items_center()
2187            .justify_center()
2188            .child(
2189                v_flex()
2190                    .items_center()
2191                    .justify_center()
2192                    .child(self.render_error_agent_logo())
2193                    .child(h_flex().mt_4().mb_1().justify_center().child(
2194                        Headline::new(self.agent.empty_state_headline()).size(HeadlineSize::Medium),
2195                    ))
2196                    .into_any(),
2197            )
2198            .children(description.map(|desc| {
2199                div().text_ui(cx).text_center().child(
2200                    self.render_markdown(desc.clone(), default_markdown_style(false, window, cx)),
2201                )
2202            }))
2203            .children(
2204                configuration_view
2205                    .cloned()
2206                    .map(|view| div().px_4().w_full().max_w_128().child(view)),
2207            )
2208            .child(h_flex().mt_1p5().justify_center().children(
2209                connection.auth_methods().iter().map(|method| {
2210                    Button::new(SharedString::from(method.id.0.clone()), method.name.clone())
2211                        .on_click({
2212                            let method_id = method.id.clone();
2213                            cx.listener(move |this, _, window, cx| {
2214                                this.authenticate(method_id.clone(), window, cx)
2215                            })
2216                        })
2217                }),
2218            ))
2219    }
2220
2221    fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
2222        let mut container = v_flex()
2223            .items_center()
2224            .justify_center()
2225            .child(self.render_error_agent_logo())
2226            .child(
2227                v_flex()
2228                    .mt_4()
2229                    .mb_2()
2230                    .gap_0p5()
2231                    .text_center()
2232                    .items_center()
2233                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
2234                    .child(
2235                        Label::new(e.to_string())
2236                            .size(LabelSize::Small)
2237                            .color(Color::Muted),
2238                    ),
2239            );
2240
2241        if let LoadError::Unsupported {
2242            upgrade_message,
2243            upgrade_command,
2244            ..
2245        } = &e
2246        {
2247            let upgrade_message = upgrade_message.clone();
2248            let upgrade_command = upgrade_command.clone();
2249            container = container.child(
2250                Button::new("upgrade", upgrade_message)
2251                    .tooltip(Tooltip::text(upgrade_command.clone()))
2252                    .on_click(cx.listener(move |this, _, window, cx| {
2253                        let task = this
2254                            .workspace
2255                            .update(cx, |workspace, cx| {
2256                                let project = workspace.project().read(cx);
2257                                let cwd = project.first_project_directory(cx);
2258                                let shell = project.terminal_settings(&cwd, cx).shell.clone();
2259                                let spawn_in_terminal = task::SpawnInTerminal {
2260                                    id: task::TaskId("upgrade".to_string()),
2261                                    full_label: upgrade_command.clone(),
2262                                    label: upgrade_command.clone(),
2263                                    command: Some(upgrade_command.clone()),
2264                                    args: Vec::new(),
2265                                    command_label: upgrade_command.clone(),
2266                                    cwd,
2267                                    env: Default::default(),
2268                                    use_new_terminal: true,
2269                                    allow_concurrent_runs: true,
2270                                    reveal: Default::default(),
2271                                    reveal_target: Default::default(),
2272                                    hide: Default::default(),
2273                                    shell,
2274                                    show_summary: true,
2275                                    show_command: true,
2276                                    show_rerun: false,
2277                                };
2278                                workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2279                            })
2280                            .ok();
2281                        let Some(task) = task else { return };
2282                        cx.spawn_in(window, async move |this, cx| {
2283                            if let Some(Ok(_)) = task.await {
2284                                this.update_in(cx, |this, window, cx| {
2285                                    this.reset(window, cx);
2286                                })
2287                                .ok();
2288                            }
2289                        })
2290                        .detach()
2291                    })),
2292            );
2293        } else if let LoadError::NotInstalled {
2294            install_message,
2295            install_command,
2296            ..
2297        } = e
2298        {
2299            let install_message = install_message.clone();
2300            let install_command = install_command.clone();
2301            container = container.child(
2302                Button::new("install", install_message)
2303                    .tooltip(Tooltip::text(install_command.clone()))
2304                    .on_click(cx.listener(move |this, _, window, cx| {
2305                        let task = this
2306                            .workspace
2307                            .update(cx, |workspace, cx| {
2308                                let project = workspace.project().read(cx);
2309                                let cwd = project.first_project_directory(cx);
2310                                let shell = project.terminal_settings(&cwd, cx).shell.clone();
2311                                let spawn_in_terminal = task::SpawnInTerminal {
2312                                    id: task::TaskId("install".to_string()),
2313                                    full_label: install_command.clone(),
2314                                    label: install_command.clone(),
2315                                    command: Some(install_command.clone()),
2316                                    args: Vec::new(),
2317                                    command_label: install_command.clone(),
2318                                    cwd,
2319                                    env: Default::default(),
2320                                    use_new_terminal: true,
2321                                    allow_concurrent_runs: true,
2322                                    reveal: Default::default(),
2323                                    reveal_target: Default::default(),
2324                                    hide: Default::default(),
2325                                    shell,
2326                                    show_summary: true,
2327                                    show_command: true,
2328                                    show_rerun: false,
2329                                };
2330                                workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2331                            })
2332                            .ok();
2333                        let Some(task) = task else { return };
2334                        cx.spawn_in(window, async move |this, cx| {
2335                            if let Some(Ok(_)) = task.await {
2336                                this.update_in(cx, |this, window, cx| {
2337                                    this.reset(window, cx);
2338                                })
2339                                .ok();
2340                            }
2341                        })
2342                        .detach()
2343                    })),
2344            );
2345        }
2346
2347        container.into_any()
2348    }
2349
2350    fn render_activity_bar(
2351        &self,
2352        thread_entity: &Entity<AcpThread>,
2353        window: &mut Window,
2354        cx: &Context<Self>,
2355    ) -> Option<AnyElement> {
2356        let thread = thread_entity.read(cx);
2357        let action_log = thread.action_log();
2358        let changed_buffers = action_log.read(cx).changed_buffers(cx);
2359        let plan = thread.plan();
2360
2361        if changed_buffers.is_empty() && plan.is_empty() {
2362            return None;
2363        }
2364
2365        let editor_bg_color = cx.theme().colors().editor_background;
2366        let active_color = cx.theme().colors().element_selected;
2367        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2368
2369        let pending_edits = thread.has_pending_edit_tool_calls();
2370
2371        v_flex()
2372            .mt_1()
2373            .mx_2()
2374            .bg(bg_edit_files_disclosure)
2375            .border_1()
2376            .border_b_0()
2377            .border_color(cx.theme().colors().border)
2378            .rounded_t_md()
2379            .shadow(vec![gpui::BoxShadow {
2380                color: gpui::black().opacity(0.15),
2381                offset: point(px(1.), px(-1.)),
2382                blur_radius: px(3.),
2383                spread_radius: px(0.),
2384            }])
2385            .when(!plan.is_empty(), |this| {
2386                this.child(self.render_plan_summary(plan, window, cx))
2387                    .when(self.plan_expanded, |parent| {
2388                        parent.child(self.render_plan_entries(plan, window, cx))
2389                    })
2390            })
2391            .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2392                this.child(Divider::horizontal().color(DividerColor::Border))
2393            })
2394            .when(!changed_buffers.is_empty(), |this| {
2395                this.child(self.render_edits_summary(
2396                    action_log,
2397                    &changed_buffers,
2398                    self.edits_expanded,
2399                    pending_edits,
2400                    window,
2401                    cx,
2402                ))
2403                .when(self.edits_expanded, |parent| {
2404                    parent.child(self.render_edited_files(
2405                        action_log,
2406                        &changed_buffers,
2407                        pending_edits,
2408                        cx,
2409                    ))
2410                })
2411            })
2412            .into_any()
2413            .into()
2414    }
2415
2416    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2417        let stats = plan.stats();
2418
2419        let title = if let Some(entry) = stats.in_progress_entry
2420            && !self.plan_expanded
2421        {
2422            h_flex()
2423                .w_full()
2424                .cursor_default()
2425                .gap_1()
2426                .text_xs()
2427                .text_color(cx.theme().colors().text_muted)
2428                .justify_between()
2429                .child(
2430                    h_flex()
2431                        .gap_1()
2432                        .child(
2433                            Label::new("Current:")
2434                                .size(LabelSize::Small)
2435                                .color(Color::Muted),
2436                        )
2437                        .child(MarkdownElement::new(
2438                            entry.content.clone(),
2439                            plan_label_markdown_style(&entry.status, window, cx),
2440                        )),
2441                )
2442                .when(stats.pending > 0, |this| {
2443                    this.child(
2444                        Label::new(format!("{} left", stats.pending))
2445                            .size(LabelSize::Small)
2446                            .color(Color::Muted)
2447                            .mr_1(),
2448                    )
2449                })
2450        } else {
2451            let status_label = if stats.pending == 0 {
2452                "All Done".to_string()
2453            } else if stats.completed == 0 {
2454                format!("{} Tasks", plan.entries.len())
2455            } else {
2456                format!("{}/{}", stats.completed, plan.entries.len())
2457            };
2458
2459            h_flex()
2460                .w_full()
2461                .gap_1()
2462                .justify_between()
2463                .child(
2464                    Label::new("Plan")
2465                        .size(LabelSize::Small)
2466                        .color(Color::Muted),
2467                )
2468                .child(
2469                    Label::new(status_label)
2470                        .size(LabelSize::Small)
2471                        .color(Color::Muted)
2472                        .mr_1(),
2473                )
2474        };
2475
2476        h_flex()
2477            .p_1()
2478            .justify_between()
2479            .when(self.plan_expanded, |this| {
2480                this.border_b_1().border_color(cx.theme().colors().border)
2481            })
2482            .child(
2483                h_flex()
2484                    .id("plan_summary")
2485                    .w_full()
2486                    .gap_1()
2487                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2488                    .child(title)
2489                    .on_click(cx.listener(|this, _, _, cx| {
2490                        this.plan_expanded = !this.plan_expanded;
2491                        cx.notify();
2492                    })),
2493            )
2494    }
2495
2496    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2497        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2498            let element = h_flex()
2499                .py_1()
2500                .px_2()
2501                .gap_2()
2502                .justify_between()
2503                .bg(cx.theme().colors().editor_background)
2504                .when(index < plan.entries.len() - 1, |parent| {
2505                    parent.border_color(cx.theme().colors().border).border_b_1()
2506                })
2507                .child(
2508                    h_flex()
2509                        .id(("plan_entry", index))
2510                        .gap_1p5()
2511                        .max_w_full()
2512                        .overflow_x_scroll()
2513                        .text_xs()
2514                        .text_color(cx.theme().colors().text_muted)
2515                        .child(match entry.status {
2516                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2517                                .size(IconSize::Small)
2518                                .color(Color::Muted)
2519                                .into_any_element(),
2520                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2521                                .size(IconSize::Small)
2522                                .color(Color::Accent)
2523                                .with_animation(
2524                                    "running",
2525                                    Animation::new(Duration::from_secs(2)).repeat(),
2526                                    |icon, delta| {
2527                                        icon.transform(Transformation::rotate(percentage(delta)))
2528                                    },
2529                                )
2530                                .into_any_element(),
2531                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2532                                .size(IconSize::Small)
2533                                .color(Color::Success)
2534                                .into_any_element(),
2535                        })
2536                        .child(MarkdownElement::new(
2537                            entry.content.clone(),
2538                            plan_label_markdown_style(&entry.status, window, cx),
2539                        )),
2540                );
2541
2542            Some(element)
2543        }))
2544    }
2545
2546    fn render_edits_summary(
2547        &self,
2548        action_log: &Entity<ActionLog>,
2549        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2550        expanded: bool,
2551        pending_edits: bool,
2552        window: &mut Window,
2553        cx: &Context<Self>,
2554    ) -> Div {
2555        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2556
2557        let focus_handle = self.focus_handle(cx);
2558
2559        h_flex()
2560            .p_1()
2561            .justify_between()
2562            .when(expanded, |this| {
2563                this.border_b_1().border_color(cx.theme().colors().border)
2564            })
2565            .child(
2566                h_flex()
2567                    .id("edits-container")
2568                    .w_full()
2569                    .gap_1()
2570                    .child(Disclosure::new("edits-disclosure", expanded))
2571                    .map(|this| {
2572                        if pending_edits {
2573                            this.child(
2574                                Label::new(format!(
2575                                    "Editing {} {}",
2576                                    changed_buffers.len(),
2577                                    if changed_buffers.len() == 1 {
2578                                        "file"
2579                                    } else {
2580                                        "files"
2581                                    }
2582                                ))
2583                                .color(Color::Muted)
2584                                .size(LabelSize::Small)
2585                                .with_animation(
2586                                    "edit-label",
2587                                    Animation::new(Duration::from_secs(2))
2588                                        .repeat()
2589                                        .with_easing(pulsating_between(0.3, 0.7)),
2590                                    |label, delta| label.alpha(delta),
2591                                ),
2592                            )
2593                        } else {
2594                            this.child(
2595                                Label::new("Edits")
2596                                    .size(LabelSize::Small)
2597                                    .color(Color::Muted),
2598                            )
2599                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
2600                            .child(
2601                                Label::new(format!(
2602                                    "{} {}",
2603                                    changed_buffers.len(),
2604                                    if changed_buffers.len() == 1 {
2605                                        "file"
2606                                    } else {
2607                                        "files"
2608                                    }
2609                                ))
2610                                .size(LabelSize::Small)
2611                                .color(Color::Muted),
2612                            )
2613                        }
2614                    })
2615                    .on_click(cx.listener(|this, _, _, cx| {
2616                        this.edits_expanded = !this.edits_expanded;
2617                        cx.notify();
2618                    })),
2619            )
2620            .child(
2621                h_flex()
2622                    .gap_1()
2623                    .child(
2624                        IconButton::new("review-changes", IconName::ListTodo)
2625                            .icon_size(IconSize::Small)
2626                            .tooltip({
2627                                let focus_handle = focus_handle.clone();
2628                                move |window, cx| {
2629                                    Tooltip::for_action_in(
2630                                        "Review Changes",
2631                                        &OpenAgentDiff,
2632                                        &focus_handle,
2633                                        window,
2634                                        cx,
2635                                    )
2636                                }
2637                            })
2638                            .on_click(cx.listener(|_, _, window, cx| {
2639                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2640                            })),
2641                    )
2642                    .child(Divider::vertical().color(DividerColor::Border))
2643                    .child(
2644                        Button::new("reject-all-changes", "Reject All")
2645                            .label_size(LabelSize::Small)
2646                            .disabled(pending_edits)
2647                            .when(pending_edits, |this| {
2648                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2649                            })
2650                            .key_binding(
2651                                KeyBinding::for_action_in(
2652                                    &RejectAll,
2653                                    &focus_handle.clone(),
2654                                    window,
2655                                    cx,
2656                                )
2657                                .map(|kb| kb.size(rems_from_px(10.))),
2658                            )
2659                            .on_click({
2660                                let action_log = action_log.clone();
2661                                cx.listener(move |_, _, _, cx| {
2662                                    action_log.update(cx, |action_log, cx| {
2663                                        action_log.reject_all_edits(cx).detach();
2664                                    })
2665                                })
2666                            }),
2667                    )
2668                    .child(
2669                        Button::new("keep-all-changes", "Keep All")
2670                            .label_size(LabelSize::Small)
2671                            .disabled(pending_edits)
2672                            .when(pending_edits, |this| {
2673                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2674                            })
2675                            .key_binding(
2676                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
2677                                    .map(|kb| kb.size(rems_from_px(10.))),
2678                            )
2679                            .on_click({
2680                                let action_log = action_log.clone();
2681                                cx.listener(move |_, _, _, cx| {
2682                                    action_log.update(cx, |action_log, cx| {
2683                                        action_log.keep_all_edits(cx);
2684                                    })
2685                                })
2686                            }),
2687                    ),
2688            )
2689    }
2690
2691    fn render_edited_files(
2692        &self,
2693        action_log: &Entity<ActionLog>,
2694        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2695        pending_edits: bool,
2696        cx: &Context<Self>,
2697    ) -> Div {
2698        let editor_bg_color = cx.theme().colors().editor_background;
2699
2700        v_flex().children(changed_buffers.iter().enumerate().flat_map(
2701            |(index, (buffer, _diff))| {
2702                let file = buffer.read(cx).file()?;
2703                let path = file.path();
2704
2705                let file_path = path.parent().and_then(|parent| {
2706                    let parent_str = parent.to_string_lossy();
2707
2708                    if parent_str.is_empty() {
2709                        None
2710                    } else {
2711                        Some(
2712                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
2713                                .color(Color::Muted)
2714                                .size(LabelSize::XSmall)
2715                                .buffer_font(cx),
2716                        )
2717                    }
2718                });
2719
2720                let file_name = path.file_name().map(|name| {
2721                    Label::new(name.to_string_lossy().to_string())
2722                        .size(LabelSize::XSmall)
2723                        .buffer_font(cx)
2724                });
2725
2726                let file_icon = FileIcons::get_icon(path, cx)
2727                    .map(Icon::from_path)
2728                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2729                    .unwrap_or_else(|| {
2730                        Icon::new(IconName::File)
2731                            .color(Color::Muted)
2732                            .size(IconSize::Small)
2733                    });
2734
2735                let overlay_gradient = linear_gradient(
2736                    90.,
2737                    linear_color_stop(editor_bg_color, 1.),
2738                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
2739                );
2740
2741                let element = h_flex()
2742                    .group("edited-code")
2743                    .id(("file-container", index))
2744                    .relative()
2745                    .py_1()
2746                    .pl_2()
2747                    .pr_1()
2748                    .gap_2()
2749                    .justify_between()
2750                    .bg(editor_bg_color)
2751                    .when(index < changed_buffers.len() - 1, |parent| {
2752                        parent.border_color(cx.theme().colors().border).border_b_1()
2753                    })
2754                    .child(
2755                        h_flex()
2756                            .id(("file-name", index))
2757                            .pr_8()
2758                            .gap_1p5()
2759                            .max_w_full()
2760                            .overflow_x_scroll()
2761                            .child(file_icon)
2762                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
2763                            .on_click({
2764                                let buffer = buffer.clone();
2765                                cx.listener(move |this, _, window, cx| {
2766                                    this.open_edited_buffer(&buffer, window, cx);
2767                                })
2768                            }),
2769                    )
2770                    .child(
2771                        h_flex()
2772                            .gap_1()
2773                            .visible_on_hover("edited-code")
2774                            .child(
2775                                Button::new("review", "Review")
2776                                    .label_size(LabelSize::Small)
2777                                    .on_click({
2778                                        let buffer = buffer.clone();
2779                                        cx.listener(move |this, _, window, cx| {
2780                                            this.open_edited_buffer(&buffer, window, cx);
2781                                        })
2782                                    }),
2783                            )
2784                            .child(Divider::vertical().color(DividerColor::BorderVariant))
2785                            .child(
2786                                Button::new("reject-file", "Reject")
2787                                    .label_size(LabelSize::Small)
2788                                    .disabled(pending_edits)
2789                                    .on_click({
2790                                        let buffer = buffer.clone();
2791                                        let action_log = action_log.clone();
2792                                        move |_, _, cx| {
2793                                            action_log.update(cx, |action_log, cx| {
2794                                                action_log
2795                                                    .reject_edits_in_ranges(
2796                                                        buffer.clone(),
2797                                                        vec![Anchor::MIN..Anchor::MAX],
2798                                                        cx,
2799                                                    )
2800                                                    .detach_and_log_err(cx);
2801                                            })
2802                                        }
2803                                    }),
2804                            )
2805                            .child(
2806                                Button::new("keep-file", "Keep")
2807                                    .label_size(LabelSize::Small)
2808                                    .disabled(pending_edits)
2809                                    .on_click({
2810                                        let buffer = buffer.clone();
2811                                        let action_log = action_log.clone();
2812                                        move |_, _, cx| {
2813                                            action_log.update(cx, |action_log, cx| {
2814                                                action_log.keep_edits_in_range(
2815                                                    buffer.clone(),
2816                                                    Anchor::MIN..Anchor::MAX,
2817                                                    cx,
2818                                                );
2819                                            })
2820                                        }
2821                                    }),
2822                            ),
2823                    )
2824                    .child(
2825                        div()
2826                            .id("gradient-overlay")
2827                            .absolute()
2828                            .h_full()
2829                            .w_12()
2830                            .top_0()
2831                            .bottom_0()
2832                            .right(px(152.))
2833                            .bg(overlay_gradient),
2834                    );
2835
2836                Some(element)
2837            },
2838        ))
2839    }
2840
2841    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2842        let focus_handle = self.message_editor.focus_handle(cx);
2843        let editor_bg_color = cx.theme().colors().editor_background;
2844        let (expand_icon, expand_tooltip) = if self.editor_expanded {
2845            (IconName::Minimize, "Minimize Message Editor")
2846        } else {
2847            (IconName::Maximize, "Expand Message Editor")
2848        };
2849
2850        v_flex()
2851            .on_action(cx.listener(Self::expand_message_editor))
2852            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
2853                if let Some(profile_selector) = this.profile_selector.as_ref() {
2854                    profile_selector.read(cx).menu_handle().toggle(window, cx);
2855                }
2856            }))
2857            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
2858                if let Some(model_selector) = this.model_selector.as_ref() {
2859                    model_selector
2860                        .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
2861                }
2862            }))
2863            .p_2()
2864            .gap_2()
2865            .border_t_1()
2866            .border_color(cx.theme().colors().border)
2867            .bg(editor_bg_color)
2868            .when(self.editor_expanded, |this| {
2869                this.h(vh(0.8, window)).size_full().justify_between()
2870            })
2871            .child(
2872                v_flex()
2873                    .relative()
2874                    .size_full()
2875                    .pt_1()
2876                    .pr_2p5()
2877                    .child(self.message_editor.clone())
2878                    .child(
2879                        h_flex()
2880                            .absolute()
2881                            .top_0()
2882                            .right_0()
2883                            .opacity(0.5)
2884                            .hover(|this| this.opacity(1.0))
2885                            .child(
2886                                IconButton::new("toggle-height", expand_icon)
2887                                    .icon_size(IconSize::Small)
2888                                    .icon_color(Color::Muted)
2889                                    .tooltip({
2890                                        move |window, cx| {
2891                                            Tooltip::for_action_in(
2892                                                expand_tooltip,
2893                                                &ExpandMessageEditor,
2894                                                &focus_handle,
2895                                                window,
2896                                                cx,
2897                                            )
2898                                        }
2899                                    })
2900                                    .on_click(cx.listener(|_, _, window, cx| {
2901                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2902                                    })),
2903                            ),
2904                    ),
2905            )
2906            .child(
2907                h_flex()
2908                    .flex_none()
2909                    .flex_wrap()
2910                    .justify_between()
2911                    .child(
2912                        h_flex()
2913                            .child(self.render_follow_toggle(cx))
2914                            .children(self.render_burn_mode_toggle(cx)),
2915                    )
2916                    .child(
2917                        h_flex()
2918                            .gap_1()
2919                            .children(self.render_token_usage(cx))
2920                            .children(self.profile_selector.clone())
2921                            .children(self.model_selector.clone())
2922                            .child(self.render_send_button(cx)),
2923                    ),
2924            )
2925            .into_any()
2926    }
2927
2928    pub(crate) fn as_native_connection(
2929        &self,
2930        cx: &App,
2931    ) -> Option<Rc<agent2::NativeAgentConnection>> {
2932        let acp_thread = self.thread()?.read(cx);
2933        acp_thread.connection().clone().downcast()
2934    }
2935
2936    pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
2937        let acp_thread = self.thread()?.read(cx);
2938        self.as_native_connection(cx)?
2939            .thread(acp_thread.session_id(), cx)
2940    }
2941
2942    fn is_using_zed_ai_models(&self, cx: &App) -> bool {
2943        self.as_native_thread(cx)
2944            .and_then(|thread| thread.read(cx).model())
2945            .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
2946    }
2947
2948    fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
2949        let thread = self.thread()?.read(cx);
2950        let usage = thread.token_usage()?;
2951        let is_generating = thread.status() != ThreadStatus::Idle;
2952
2953        let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
2954        let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
2955
2956        Some(
2957            h_flex()
2958                .flex_shrink_0()
2959                .gap_0p5()
2960                .mr_1p5()
2961                .child(
2962                    Label::new(used)
2963                        .size(LabelSize::Small)
2964                        .color(Color::Muted)
2965                        .map(|label| {
2966                            if is_generating {
2967                                label
2968                                    .with_animation(
2969                                        "used-tokens-label",
2970                                        Animation::new(Duration::from_secs(2))
2971                                            .repeat()
2972                                            .with_easing(pulsating_between(0.6, 1.)),
2973                                        |label, delta| label.alpha(delta),
2974                                    )
2975                                    .into_any()
2976                            } else {
2977                                label.into_any_element()
2978                            }
2979                        }),
2980                )
2981                .child(
2982                    Label::new("/")
2983                        .size(LabelSize::Small)
2984                        .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
2985                )
2986                .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
2987        )
2988    }
2989
2990    fn toggle_burn_mode(
2991        &mut self,
2992        _: &ToggleBurnMode,
2993        _window: &mut Window,
2994        cx: &mut Context<Self>,
2995    ) {
2996        let Some(thread) = self.as_native_thread(cx) else {
2997            return;
2998        };
2999
3000        thread.update(cx, |thread, cx| {
3001            let current_mode = thread.completion_mode();
3002            thread.set_completion_mode(
3003                match current_mode {
3004                    CompletionMode::Burn => CompletionMode::Normal,
3005                    CompletionMode::Normal => CompletionMode::Burn,
3006                },
3007                cx,
3008            );
3009        });
3010    }
3011
3012    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3013        let thread = self.as_native_thread(cx)?.read(cx);
3014
3015        if thread
3016            .model()
3017            .is_none_or(|model| !model.supports_burn_mode())
3018        {
3019            return None;
3020        }
3021
3022        let active_completion_mode = thread.completion_mode();
3023        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3024        let icon = if burn_mode_enabled {
3025            IconName::ZedBurnModeOn
3026        } else {
3027            IconName::ZedBurnMode
3028        };
3029
3030        Some(
3031            IconButton::new("burn-mode", icon)
3032                .icon_size(IconSize::Small)
3033                .icon_color(Color::Muted)
3034                .toggle_state(burn_mode_enabled)
3035                .selected_icon_color(Color::Error)
3036                .on_click(cx.listener(|this, _event, window, cx| {
3037                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3038                }))
3039                .tooltip(move |_window, cx| {
3040                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3041                        .into()
3042                })
3043                .into_any_element(),
3044        )
3045    }
3046
3047    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3048        let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3049        let is_generating = self
3050            .thread()
3051            .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3052
3053        if is_generating && is_editor_empty {
3054            IconButton::new("stop-generation", IconName::Stop)
3055                .icon_color(Color::Error)
3056                .style(ButtonStyle::Tinted(ui::TintColor::Error))
3057                .tooltip(move |window, cx| {
3058                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3059                })
3060                .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3061                .into_any_element()
3062        } else {
3063            let send_btn_tooltip = if is_editor_empty && !is_generating {
3064                "Type to Send"
3065            } else if is_generating {
3066                "Stop and Send Message"
3067            } else {
3068                "Send"
3069            };
3070
3071            IconButton::new("send-message", IconName::Send)
3072                .style(ButtonStyle::Filled)
3073                .map(|this| {
3074                    if is_editor_empty && !is_generating {
3075                        this.disabled(true).icon_color(Color::Muted)
3076                    } else {
3077                        this.icon_color(Color::Accent)
3078                    }
3079                })
3080                .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3081                .on_click(cx.listener(|this, _, window, cx| {
3082                    this.send(window, cx);
3083                }))
3084                .into_any_element()
3085        }
3086    }
3087
3088    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3089        let following = self
3090            .workspace
3091            .read_with(cx, |workspace, _| {
3092                workspace.is_being_followed(CollaboratorId::Agent)
3093            })
3094            .unwrap_or(false);
3095
3096        IconButton::new("follow-agent", IconName::Crosshair)
3097            .icon_size(IconSize::Small)
3098            .icon_color(Color::Muted)
3099            .toggle_state(following)
3100            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3101            .tooltip(move |window, cx| {
3102                if following {
3103                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
3104                } else {
3105                    Tooltip::with_meta(
3106                        "Follow Agent",
3107                        Some(&Follow),
3108                        "Track the agent's location as it reads and edits files.",
3109                        window,
3110                        cx,
3111                    )
3112                }
3113            })
3114            .on_click(cx.listener(move |this, _, window, cx| {
3115                this.workspace
3116                    .update(cx, |workspace, cx| {
3117                        if following {
3118                            workspace.unfollow(CollaboratorId::Agent, window, cx);
3119                        } else {
3120                            workspace.follow(CollaboratorId::Agent, window, cx);
3121                        }
3122                    })
3123                    .ok();
3124            }))
3125    }
3126
3127    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3128        let workspace = self.workspace.clone();
3129        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3130            Self::open_link(text, &workspace, window, cx);
3131        })
3132    }
3133
3134    fn open_link(
3135        url: SharedString,
3136        workspace: &WeakEntity<Workspace>,
3137        window: &mut Window,
3138        cx: &mut App,
3139    ) {
3140        let Some(workspace) = workspace.upgrade() else {
3141            cx.open_url(&url);
3142            return;
3143        };
3144
3145        if let Some(mention) = MentionUri::parse(&url).log_err() {
3146            workspace.update(cx, |workspace, cx| match mention {
3147                MentionUri::File { abs_path } => {
3148                    let project = workspace.project();
3149                    let Some(path) =
3150                        project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3151                    else {
3152                        return;
3153                    };
3154
3155                    workspace
3156                        .open_path(path, None, true, window, cx)
3157                        .detach_and_log_err(cx);
3158                }
3159                MentionUri::Directory { abs_path } => {
3160                    let project = workspace.project();
3161                    let Some(entry) = project.update(cx, |project, cx| {
3162                        let path = project.find_project_path(abs_path, cx)?;
3163                        project.entry_for_path(&path, cx)
3164                    }) else {
3165                        return;
3166                    };
3167
3168                    project.update(cx, |_, cx| {
3169                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
3170                    });
3171                }
3172                MentionUri::Symbol {
3173                    path, line_range, ..
3174                }
3175                | MentionUri::Selection { path, line_range } => {
3176                    let project = workspace.project();
3177                    let Some((path, _)) = project.update(cx, |project, cx| {
3178                        let path = project.find_project_path(path, cx)?;
3179                        let entry = project.entry_for_path(&path, cx)?;
3180                        Some((path, entry))
3181                    }) else {
3182                        return;
3183                    };
3184
3185                    let item = workspace.open_path(path, None, true, window, cx);
3186                    window
3187                        .spawn(cx, async move |cx| {
3188                            let Some(editor) = item.await?.downcast::<Editor>() else {
3189                                return Ok(());
3190                            };
3191                            let range =
3192                                Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
3193                            editor
3194                                .update_in(cx, |editor, window, cx| {
3195                                    editor.change_selections(
3196                                        SelectionEffects::scroll(Autoscroll::center()),
3197                                        window,
3198                                        cx,
3199                                        |s| s.select_ranges(vec![range]),
3200                                    );
3201                                })
3202                                .ok();
3203                            anyhow::Ok(())
3204                        })
3205                        .detach_and_log_err(cx);
3206                }
3207                MentionUri::Thread { id, name } => {
3208                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3209                        panel.update(cx, |panel, cx| {
3210                            panel.load_agent_thread(
3211                                DbThreadMetadata {
3212                                    id,
3213                                    title: name.into(),
3214                                    updated_at: Default::default(),
3215                                },
3216                                window,
3217                                cx,
3218                            )
3219                        });
3220                    }
3221                }
3222                MentionUri::TextThread { path, .. } => {
3223                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3224                        panel.update(cx, |panel, cx| {
3225                            panel
3226                                .open_saved_prompt_editor(path.as_path().into(), window, cx)
3227                                .detach_and_log_err(cx);
3228                        });
3229                    }
3230                }
3231                MentionUri::Rule { id, .. } => {
3232                    let PromptId::User { uuid } = id else {
3233                        return;
3234                    };
3235                    window.dispatch_action(
3236                        Box::new(OpenRulesLibrary {
3237                            prompt_to_select: Some(uuid.0),
3238                        }),
3239                        cx,
3240                    )
3241                }
3242                MentionUri::Fetch { url } => {
3243                    cx.open_url(url.as_str());
3244                }
3245            })
3246        } else {
3247            cx.open_url(&url);
3248        }
3249    }
3250
3251    fn open_tool_call_location(
3252        &self,
3253        entry_ix: usize,
3254        location_ix: usize,
3255        window: &mut Window,
3256        cx: &mut Context<Self>,
3257    ) -> Option<()> {
3258        let (tool_call_location, agent_location) = self
3259            .thread()?
3260            .read(cx)
3261            .entries()
3262            .get(entry_ix)?
3263            .location(location_ix)?;
3264
3265        let project_path = self
3266            .project
3267            .read(cx)
3268            .find_project_path(&tool_call_location.path, cx)?;
3269
3270        let open_task = self
3271            .workspace
3272            .update(cx, |workspace, cx| {
3273                workspace.open_path(project_path, None, true, window, cx)
3274            })
3275            .log_err()?;
3276        window
3277            .spawn(cx, async move |cx| {
3278                let item = open_task.await?;
3279
3280                let Some(active_editor) = item.downcast::<Editor>() else {
3281                    return anyhow::Ok(());
3282                };
3283
3284                active_editor.update_in(cx, |editor, window, cx| {
3285                    let multibuffer = editor.buffer().read(cx);
3286                    let buffer = multibuffer.as_singleton();
3287                    if agent_location.buffer.upgrade() == buffer {
3288                        let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3289                        let anchor = editor::Anchor::in_buffer(
3290                            excerpt_id.unwrap(),
3291                            buffer.unwrap().read(cx).remote_id(),
3292                            agent_location.position,
3293                        );
3294                        editor.change_selections(Default::default(), window, cx, |selections| {
3295                            selections.select_anchor_ranges([anchor..anchor]);
3296                        })
3297                    } else {
3298                        let row = tool_call_location.line.unwrap_or_default();
3299                        editor.change_selections(Default::default(), window, cx, |selections| {
3300                            selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3301                        })
3302                    }
3303                })?;
3304
3305                anyhow::Ok(())
3306            })
3307            .detach_and_log_err(cx);
3308
3309        None
3310    }
3311
3312    pub fn open_thread_as_markdown(
3313        &self,
3314        workspace: Entity<Workspace>,
3315        window: &mut Window,
3316        cx: &mut App,
3317    ) -> Task<anyhow::Result<()>> {
3318        let markdown_language_task = workspace
3319            .read(cx)
3320            .app_state()
3321            .languages
3322            .language_for_name("Markdown");
3323
3324        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3325            let thread = thread.read(cx);
3326            (thread.title().to_string(), thread.to_markdown(cx))
3327        } else {
3328            return Task::ready(Ok(()));
3329        };
3330
3331        window.spawn(cx, async move |cx| {
3332            let markdown_language = markdown_language_task.await?;
3333
3334            workspace.update_in(cx, |workspace, window, cx| {
3335                let project = workspace.project().clone();
3336
3337                if !project.read(cx).is_local() {
3338                    bail!("failed to open active thread as markdown in remote project");
3339                }
3340
3341                let buffer = project.update(cx, |project, cx| {
3342                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
3343                });
3344                let buffer = cx.new(|cx| {
3345                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3346                });
3347
3348                workspace.add_item_to_active_pane(
3349                    Box::new(cx.new(|cx| {
3350                        let mut editor =
3351                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3352                        editor.set_breadcrumb_header(thread_summary);
3353                        editor
3354                    })),
3355                    None,
3356                    true,
3357                    window,
3358                    cx,
3359                );
3360
3361                anyhow::Ok(())
3362            })??;
3363            anyhow::Ok(())
3364        })
3365    }
3366
3367    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3368        self.list_state.scroll_to(ListOffset::default());
3369        cx.notify();
3370    }
3371
3372    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3373        if let Some(thread) = self.thread() {
3374            let entry_count = thread.read(cx).entries().len();
3375            self.list_state.reset(entry_count);
3376            cx.notify();
3377        }
3378    }
3379
3380    fn notify_with_sound(
3381        &mut self,
3382        caption: impl Into<SharedString>,
3383        icon: IconName,
3384        window: &mut Window,
3385        cx: &mut Context<Self>,
3386    ) {
3387        self.play_notification_sound(window, cx);
3388        self.show_notification(caption, icon, window, cx);
3389    }
3390
3391    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
3392        let settings = AgentSettings::get_global(cx);
3393        if settings.play_sound_when_agent_done && !window.is_window_active() {
3394            Audio::play_sound(Sound::AgentDone, cx);
3395        }
3396    }
3397
3398    fn show_notification(
3399        &mut self,
3400        caption: impl Into<SharedString>,
3401        icon: IconName,
3402        window: &mut Window,
3403        cx: &mut Context<Self>,
3404    ) {
3405        if window.is_window_active() || !self.notifications.is_empty() {
3406            return;
3407        }
3408
3409        let title = self.title(cx);
3410
3411        match AgentSettings::get_global(cx).notify_when_agent_waiting {
3412            NotifyWhenAgentWaiting::PrimaryScreen => {
3413                if let Some(primary) = cx.primary_display() {
3414                    self.pop_up(icon, caption.into(), title, window, primary, cx);
3415                }
3416            }
3417            NotifyWhenAgentWaiting::AllScreens => {
3418                let caption = caption.into();
3419                for screen in cx.displays() {
3420                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
3421                }
3422            }
3423            NotifyWhenAgentWaiting::Never => {
3424                // Don't show anything
3425            }
3426        }
3427    }
3428
3429    fn pop_up(
3430        &mut self,
3431        icon: IconName,
3432        caption: SharedString,
3433        title: SharedString,
3434        window: &mut Window,
3435        screen: Rc<dyn PlatformDisplay>,
3436        cx: &mut Context<Self>,
3437    ) {
3438        let options = AgentNotification::window_options(screen, cx);
3439
3440        let project_name = self.workspace.upgrade().and_then(|workspace| {
3441            workspace
3442                .read(cx)
3443                .project()
3444                .read(cx)
3445                .visible_worktrees(cx)
3446                .next()
3447                .map(|worktree| worktree.read(cx).root_name().to_string())
3448        });
3449
3450        if let Some(screen_window) = cx
3451            .open_window(options, |_, cx| {
3452                cx.new(|_| {
3453                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
3454                })
3455            })
3456            .log_err()
3457            && let Some(pop_up) = screen_window.entity(cx).log_err()
3458        {
3459            self.notification_subscriptions
3460                .entry(screen_window)
3461                .or_insert_with(Vec::new)
3462                .push(cx.subscribe_in(&pop_up, window, {
3463                    |this, _, event, window, cx| match event {
3464                        AgentNotificationEvent::Accepted => {
3465                            let handle = window.window_handle();
3466                            cx.activate(true);
3467
3468                            let workspace_handle = this.workspace.clone();
3469
3470                            // If there are multiple Zed windows, activate the correct one.
3471                            cx.defer(move |cx| {
3472                                handle
3473                                    .update(cx, |_view, window, _cx| {
3474                                        window.activate_window();
3475
3476                                        if let Some(workspace) = workspace_handle.upgrade() {
3477                                            workspace.update(_cx, |workspace, cx| {
3478                                                workspace.focus_panel::<AgentPanel>(window, cx);
3479                                            });
3480                                        }
3481                                    })
3482                                    .log_err();
3483                            });
3484
3485                            this.dismiss_notifications(cx);
3486                        }
3487                        AgentNotificationEvent::Dismissed => {
3488                            this.dismiss_notifications(cx);
3489                        }
3490                    }
3491                }));
3492
3493            self.notifications.push(screen_window);
3494
3495            // If the user manually refocuses the original window, dismiss the popup.
3496            self.notification_subscriptions
3497                .entry(screen_window)
3498                .or_insert_with(Vec::new)
3499                .push({
3500                    let pop_up_weak = pop_up.downgrade();
3501
3502                    cx.observe_window_activation(window, move |_, window, cx| {
3503                        if window.is_window_active()
3504                            && let Some(pop_up) = pop_up_weak.upgrade()
3505                        {
3506                            pop_up.update(cx, |_, cx| {
3507                                cx.emit(AgentNotificationEvent::Dismissed);
3508                            });
3509                        }
3510                    })
3511                });
3512        }
3513    }
3514
3515    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3516        for window in self.notifications.drain(..) {
3517            window
3518                .update(cx, |_, window, _| {
3519                    window.remove_window();
3520                })
3521                .ok();
3522
3523            self.notification_subscriptions.remove(&window);
3524        }
3525    }
3526
3527    fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3528        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3529            .shape(ui::IconButtonShape::Square)
3530            .icon_size(IconSize::Small)
3531            .icon_color(Color::Ignored)
3532            .tooltip(Tooltip::text("Open Thread as Markdown"))
3533            .on_click(cx.listener(move |this, _, window, cx| {
3534                if let Some(workspace) = this.workspace.upgrade() {
3535                    this.open_thread_as_markdown(workspace, window, cx)
3536                        .detach_and_log_err(cx);
3537                }
3538            }));
3539
3540        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3541            .shape(ui::IconButtonShape::Square)
3542            .icon_size(IconSize::Small)
3543            .icon_color(Color::Ignored)
3544            .tooltip(Tooltip::text("Scroll To Top"))
3545            .on_click(cx.listener(move |this, _, _, cx| {
3546                this.scroll_to_top(cx);
3547            }));
3548
3549        h_flex()
3550            .w_full()
3551            .mr_1()
3552            .pb_2()
3553            .px(RESPONSE_PADDING_X)
3554            .opacity(0.4)
3555            .hover(|style| style.opacity(1.))
3556            .flex_wrap()
3557            .justify_end()
3558            .child(open_as_markdown)
3559            .child(scroll_to_top)
3560    }
3561
3562    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
3563        div()
3564            .id("acp-thread-scrollbar")
3565            .occlude()
3566            .on_mouse_move(cx.listener(|_, _, _, cx| {
3567                cx.notify();
3568                cx.stop_propagation()
3569            }))
3570            .on_hover(|_, _, cx| {
3571                cx.stop_propagation();
3572            })
3573            .on_any_mouse_down(|_, _, cx| {
3574                cx.stop_propagation();
3575            })
3576            .on_mouse_up(
3577                MouseButton::Left,
3578                cx.listener(|_, _, _, cx| {
3579                    cx.stop_propagation();
3580                }),
3581            )
3582            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3583                cx.notify();
3584            }))
3585            .h_full()
3586            .absolute()
3587            .right_1()
3588            .top_1()
3589            .bottom_0()
3590            .w(px(12.))
3591            .cursor_default()
3592            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
3593    }
3594
3595    fn render_token_limit_callout(
3596        &self,
3597        line_height: Pixels,
3598        cx: &mut Context<Self>,
3599    ) -> Option<Callout> {
3600        let token_usage = self.thread()?.read(cx).token_usage()?;
3601        let ratio = token_usage.ratio();
3602
3603        let (severity, title) = match ratio {
3604            acp_thread::TokenUsageRatio::Normal => return None,
3605            acp_thread::TokenUsageRatio::Warning => {
3606                (Severity::Warning, "Thread reaching the token limit soon")
3607            }
3608            acp_thread::TokenUsageRatio::Exceeded => {
3609                (Severity::Error, "Thread reached the token limit")
3610            }
3611        };
3612
3613        let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
3614            thread.read(cx).completion_mode() == CompletionMode::Normal
3615                && thread
3616                    .read(cx)
3617                    .model()
3618                    .is_some_and(|model| model.supports_burn_mode())
3619        });
3620
3621        let description = if burn_mode_available {
3622            "To continue, start a new thread from a summary or turn Burn Mode on."
3623        } else {
3624            "To continue, start a new thread from a summary."
3625        };
3626
3627        Some(
3628            Callout::new()
3629                .severity(severity)
3630                .line_height(line_height)
3631                .title(title)
3632                .description(description)
3633                .actions_slot(
3634                    h_flex()
3635                        .gap_0p5()
3636                        .child(
3637                            Button::new("start-new-thread", "Start New Thread")
3638                                .label_size(LabelSize::Small)
3639                                .on_click(cx.listener(|_this, _, _window, _cx| {
3640                                    // todo: Once thread summarization is implemented, start a new thread from a summary.
3641                                })),
3642                        )
3643                        .when(burn_mode_available, |this| {
3644                            this.child(
3645                                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
3646                                    .icon_size(IconSize::XSmall)
3647                                    .on_click(cx.listener(|this, _event, window, cx| {
3648                                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3649                                    })),
3650                            )
3651                        }),
3652                ),
3653        )
3654    }
3655
3656    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
3657        if !self.is_using_zed_ai_models(cx) {
3658            return None;
3659        }
3660
3661        let user_store = self.project.read(cx).user_store().read(cx);
3662        if user_store.is_usage_based_billing_enabled() {
3663            return None;
3664        }
3665
3666        let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
3667
3668        let usage = user_store.model_request_usage()?;
3669
3670        Some(
3671            div()
3672                .child(UsageCallout::new(plan, usage))
3673                .line_height(line_height),
3674        )
3675    }
3676
3677    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3678        self.entry_view_state.update(cx, |entry_view_state, cx| {
3679            entry_view_state.settings_changed(cx);
3680        });
3681    }
3682
3683    pub(crate) fn insert_dragged_files(
3684        &self,
3685        paths: Vec<project::ProjectPath>,
3686        added_worktrees: Vec<Entity<project::Worktree>>,
3687        window: &mut Window,
3688        cx: &mut Context<Self>,
3689    ) {
3690        self.message_editor.update(cx, |message_editor, cx| {
3691            message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
3692        })
3693    }
3694
3695    fn render_thread_retry_status_callout(
3696        &self,
3697        _window: &mut Window,
3698        _cx: &mut Context<Self>,
3699    ) -> Option<Callout> {
3700        let state = self.thread_retry_status.as_ref()?;
3701
3702        let next_attempt_in = state
3703            .duration
3704            .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
3705        if next_attempt_in.is_zero() {
3706            return None;
3707        }
3708
3709        let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
3710
3711        let retry_message = if state.max_attempts == 1 {
3712            if next_attempt_in_secs == 1 {
3713                "Retrying. Next attempt in 1 second.".to_string()
3714            } else {
3715                format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
3716            }
3717        } else if next_attempt_in_secs == 1 {
3718            format!(
3719                "Retrying. Next attempt in 1 second (Attempt {} of {}).",
3720                state.attempt, state.max_attempts,
3721            )
3722        } else {
3723            format!(
3724                "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
3725                state.attempt, state.max_attempts,
3726            )
3727        };
3728
3729        Some(
3730            Callout::new()
3731                .severity(Severity::Warning)
3732                .title(state.last_error.clone())
3733                .description(retry_message),
3734        )
3735    }
3736
3737    fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
3738        let content = match self.thread_error.as_ref()? {
3739            ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3740            ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3741            ThreadError::ModelRequestLimitReached(plan) => {
3742                self.render_model_request_limit_reached_error(*plan, cx)
3743            }
3744            ThreadError::ToolUseLimitReached => {
3745                self.render_tool_use_limit_reached_error(window, cx)?
3746            }
3747        };
3748
3749        Some(div().child(content))
3750    }
3751
3752    fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3753        Callout::new()
3754            .severity(Severity::Error)
3755            .title("Error")
3756            .description(error.clone())
3757            .actions_slot(self.create_copy_button(error.to_string()))
3758            .dismiss_action(self.dismiss_error_button(cx))
3759    }
3760
3761    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3762        const ERROR_MESSAGE: &str =
3763            "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3764
3765        Callout::new()
3766            .severity(Severity::Error)
3767            .title("Free Usage Exceeded")
3768            .description(ERROR_MESSAGE)
3769            .actions_slot(
3770                h_flex()
3771                    .gap_0p5()
3772                    .child(self.upgrade_button(cx))
3773                    .child(self.create_copy_button(ERROR_MESSAGE)),
3774            )
3775            .dismiss_action(self.dismiss_error_button(cx))
3776    }
3777
3778    fn render_model_request_limit_reached_error(
3779        &self,
3780        plan: cloud_llm_client::Plan,
3781        cx: &mut Context<Self>,
3782    ) -> Callout {
3783        let error_message = match plan {
3784            cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3785            cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3786                "Upgrade to Zed Pro for more prompts."
3787            }
3788        };
3789
3790        Callout::new()
3791            .severity(Severity::Error)
3792            .title("Model Prompt Limit Reached")
3793            .description(error_message)
3794            .actions_slot(
3795                h_flex()
3796                    .gap_0p5()
3797                    .child(self.upgrade_button(cx))
3798                    .child(self.create_copy_button(error_message)),
3799            )
3800            .dismiss_action(self.dismiss_error_button(cx))
3801    }
3802
3803    fn render_tool_use_limit_reached_error(
3804        &self,
3805        window: &mut Window,
3806        cx: &mut Context<Self>,
3807    ) -> Option<Callout> {
3808        let thread = self.as_native_thread(cx)?;
3809        let supports_burn_mode = thread
3810            .read(cx)
3811            .model()
3812            .is_some_and(|model| model.supports_burn_mode());
3813
3814        let focus_handle = self.focus_handle(cx);
3815
3816        Some(
3817            Callout::new()
3818                .icon(IconName::Info)
3819                .title("Consecutive tool use limit reached.")
3820                .actions_slot(
3821                    h_flex()
3822                        .gap_0p5()
3823                        .when(supports_burn_mode, |this| {
3824                            this.child(
3825                                Button::new("continue-burn-mode", "Continue with Burn Mode")
3826                                    .style(ButtonStyle::Filled)
3827                                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3828                                    .layer(ElevationIndex::ModalSurface)
3829                                    .label_size(LabelSize::Small)
3830                                    .key_binding(
3831                                        KeyBinding::for_action_in(
3832                                            &ContinueWithBurnMode,
3833                                            &focus_handle,
3834                                            window,
3835                                            cx,
3836                                        )
3837                                        .map(|kb| kb.size(rems_from_px(10.))),
3838                                    )
3839                                    .tooltip(Tooltip::text(
3840                                        "Enable Burn Mode for unlimited tool use.",
3841                                    ))
3842                                    .on_click({
3843                                        cx.listener(move |this, _, _window, cx| {
3844                                            thread.update(cx, |thread, cx| {
3845                                                thread
3846                                                    .set_completion_mode(CompletionMode::Burn, cx);
3847                                            });
3848                                            this.resume_chat(cx);
3849                                        })
3850                                    }),
3851                            )
3852                        })
3853                        .child(
3854                            Button::new("continue-conversation", "Continue")
3855                                .layer(ElevationIndex::ModalSurface)
3856                                .label_size(LabelSize::Small)
3857                                .key_binding(
3858                                    KeyBinding::for_action_in(
3859                                        &ContinueThread,
3860                                        &focus_handle,
3861                                        window,
3862                                        cx,
3863                                    )
3864                                    .map(|kb| kb.size(rems_from_px(10.))),
3865                                )
3866                                .on_click(cx.listener(|this, _, _window, cx| {
3867                                    this.resume_chat(cx);
3868                                })),
3869                        ),
3870                ),
3871        )
3872    }
3873
3874    fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3875        let message = message.into();
3876
3877        IconButton::new("copy", IconName::Copy)
3878            .icon_size(IconSize::Small)
3879            .icon_color(Color::Muted)
3880            .tooltip(Tooltip::text("Copy Error Message"))
3881            .on_click(move |_, _, cx| {
3882                cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3883            })
3884    }
3885
3886    fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3887        IconButton::new("dismiss", IconName::Close)
3888            .icon_size(IconSize::Small)
3889            .icon_color(Color::Muted)
3890            .tooltip(Tooltip::text("Dismiss Error"))
3891            .on_click(cx.listener({
3892                move |this, _, _, cx| {
3893                    this.clear_thread_error(cx);
3894                    cx.notify();
3895                }
3896            }))
3897    }
3898
3899    fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3900        Button::new("upgrade", "Upgrade")
3901            .label_size(LabelSize::Small)
3902            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3903            .on_click(cx.listener({
3904                move |this, _, _, cx| {
3905                    this.clear_thread_error(cx);
3906                    cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3907                }
3908            }))
3909    }
3910
3911    fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3912        self.thread_state = Self::initial_state(
3913            self.agent.clone(),
3914            None,
3915            self.workspace.clone(),
3916            self.project.clone(),
3917            window,
3918            cx,
3919        );
3920        cx.notify();
3921    }
3922}
3923
3924impl Focusable for AcpThreadView {
3925    fn focus_handle(&self, cx: &App) -> FocusHandle {
3926        self.message_editor.focus_handle(cx)
3927    }
3928}
3929
3930impl Render for AcpThreadView {
3931    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3932        let has_messages = self.list_state.item_count() > 0;
3933        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
3934
3935        v_flex()
3936            .size_full()
3937            .key_context("AcpThread")
3938            .on_action(cx.listener(Self::open_agent_diff))
3939            .on_action(cx.listener(Self::toggle_burn_mode))
3940            .bg(cx.theme().colors().panel_background)
3941            .child(match &self.thread_state {
3942                ThreadState::Unauthenticated {
3943                    connection,
3944                    description,
3945                    configuration_view,
3946                    ..
3947                } => self.render_auth_required_state(
3948                    connection,
3949                    description.as_ref(),
3950                    configuration_view.as_ref(),
3951                    window,
3952                    cx,
3953                ),
3954                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3955                ThreadState::LoadError(e) => v_flex()
3956                    .p_2()
3957                    .flex_1()
3958                    .items_center()
3959                    .justify_center()
3960                    .child(self.render_load_error(e, cx)),
3961                ThreadState::Ready { thread, .. } => {
3962                    let thread_clone = thread.clone();
3963
3964                    v_flex().flex_1().map(|this| {
3965                        if has_messages {
3966                            this.child(
3967                                list(
3968                                    self.list_state.clone(),
3969                                    cx.processor(|this, index: usize, window, cx| {
3970                                        let Some((entry, len)) = this.thread().and_then(|thread| {
3971                                            let entries = &thread.read(cx).entries();
3972                                            Some((entries.get(index)?, entries.len()))
3973                                        }) else {
3974                                            return Empty.into_any();
3975                                        };
3976                                        this.render_entry(index, len, entry, window, cx)
3977                                    }),
3978                                )
3979                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3980                                .flex_grow()
3981                                .into_any(),
3982                            )
3983                            .child(self.render_vertical_scrollbar(cx))
3984                            .children(
3985                                match thread_clone.read(cx).status() {
3986                                    ThreadStatus::Idle
3987                                    | ThreadStatus::WaitingForToolConfirmation => None,
3988                                    ThreadStatus::Generating => div()
3989                                        .px_5()
3990                                        .py_2()
3991                                        .child(LoadingLabel::new("").size(LabelSize::Small))
3992                                        .into(),
3993                                },
3994                            )
3995                        } else {
3996                            this.child(self.render_empty_state(cx))
3997                        }
3998                    })
3999                }
4000            })
4001            // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4002            // above so that the scrollbar doesn't render behind it. The current setup allows
4003            // the scrollbar to stop exactly at the activity bar start.
4004            .when(has_messages, |this| match &self.thread_state {
4005                ThreadState::Ready { thread, .. } => {
4006                    this.children(self.render_activity_bar(thread, window, cx))
4007                }
4008                _ => this,
4009            })
4010            .children(self.render_thread_retry_status_callout(window, cx))
4011            .children(self.render_thread_error(window, cx))
4012            .children(
4013                if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4014                    Some(usage_callout.into_any_element())
4015                } else if let Some(token_limit_callout) =
4016                    self.render_token_limit_callout(line_height, cx)
4017                {
4018                    Some(token_limit_callout.into_any_element())
4019                } else {
4020                    None
4021                },
4022            )
4023            .child(self.render_message_editor(window, cx))
4024    }
4025}
4026
4027fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
4028    let theme_settings = ThemeSettings::get_global(cx);
4029    let colors = cx.theme().colors();
4030
4031    let buffer_font_size = TextSize::Small.rems(cx);
4032
4033    let mut text_style = window.text_style();
4034    let line_height = buffer_font_size * 1.75;
4035
4036    let font_family = if buffer_font {
4037        theme_settings.buffer_font.family.clone()
4038    } else {
4039        theme_settings.ui_font.family.clone()
4040    };
4041
4042    let font_size = if buffer_font {
4043        TextSize::Small.rems(cx)
4044    } else {
4045        TextSize::Default.rems(cx)
4046    };
4047
4048    text_style.refine(&TextStyleRefinement {
4049        font_family: Some(font_family),
4050        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
4051        font_features: Some(theme_settings.ui_font.features.clone()),
4052        font_size: Some(font_size.into()),
4053        line_height: Some(line_height.into()),
4054        color: Some(cx.theme().colors().text),
4055        ..Default::default()
4056    });
4057
4058    MarkdownStyle {
4059        base_text_style: text_style.clone(),
4060        syntax: cx.theme().syntax().clone(),
4061        selection_background_color: cx.theme().colors().element_selection_background,
4062        code_block_overflow_x_scroll: true,
4063        table_overflow_x_scroll: true,
4064        heading_level_styles: Some(HeadingLevelStyles {
4065            h1: Some(TextStyleRefinement {
4066                font_size: Some(rems(1.15).into()),
4067                ..Default::default()
4068            }),
4069            h2: Some(TextStyleRefinement {
4070                font_size: Some(rems(1.1).into()),
4071                ..Default::default()
4072            }),
4073            h3: Some(TextStyleRefinement {
4074                font_size: Some(rems(1.05).into()),
4075                ..Default::default()
4076            }),
4077            h4: Some(TextStyleRefinement {
4078                font_size: Some(rems(1.).into()),
4079                ..Default::default()
4080            }),
4081            h5: Some(TextStyleRefinement {
4082                font_size: Some(rems(0.95).into()),
4083                ..Default::default()
4084            }),
4085            h6: Some(TextStyleRefinement {
4086                font_size: Some(rems(0.875).into()),
4087                ..Default::default()
4088            }),
4089        }),
4090        code_block: StyleRefinement {
4091            padding: EdgesRefinement {
4092                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4093                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4094                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4095                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4096            },
4097            margin: EdgesRefinement {
4098                top: Some(Length::Definite(Pixels(8.).into())),
4099                left: Some(Length::Definite(Pixels(0.).into())),
4100                right: Some(Length::Definite(Pixels(0.).into())),
4101                bottom: Some(Length::Definite(Pixels(12.).into())),
4102            },
4103            border_style: Some(BorderStyle::Solid),
4104            border_widths: EdgesRefinement {
4105                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
4106                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
4107                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
4108                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
4109            },
4110            border_color: Some(colors.border_variant),
4111            background: Some(colors.editor_background.into()),
4112            text: Some(TextStyleRefinement {
4113                font_family: Some(theme_settings.buffer_font.family.clone()),
4114                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4115                font_features: Some(theme_settings.buffer_font.features.clone()),
4116                font_size: Some(buffer_font_size.into()),
4117                ..Default::default()
4118            }),
4119            ..Default::default()
4120        },
4121        inline_code: TextStyleRefinement {
4122            font_family: Some(theme_settings.buffer_font.family.clone()),
4123            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4124            font_features: Some(theme_settings.buffer_font.features.clone()),
4125            font_size: Some(buffer_font_size.into()),
4126            background_color: Some(colors.editor_foreground.opacity(0.08)),
4127            ..Default::default()
4128        },
4129        link: TextStyleRefinement {
4130            background_color: Some(colors.editor_foreground.opacity(0.025)),
4131            underline: Some(UnderlineStyle {
4132                color: Some(colors.text_accent.opacity(0.5)),
4133                thickness: px(1.),
4134                ..Default::default()
4135            }),
4136            ..Default::default()
4137        },
4138        ..Default::default()
4139    }
4140}
4141
4142fn plan_label_markdown_style(
4143    status: &acp::PlanEntryStatus,
4144    window: &Window,
4145    cx: &App,
4146) -> MarkdownStyle {
4147    let default_md_style = default_markdown_style(false, window, cx);
4148
4149    MarkdownStyle {
4150        base_text_style: TextStyle {
4151            color: cx.theme().colors().text_muted,
4152            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
4153                Some(gpui::StrikethroughStyle {
4154                    thickness: px(1.),
4155                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
4156                })
4157            } else {
4158                None
4159            },
4160            ..default_md_style.base_text_style
4161        },
4162        ..default_md_style
4163    }
4164}
4165
4166fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
4167    let default_md_style = default_markdown_style(true, window, cx);
4168
4169    MarkdownStyle {
4170        base_text_style: TextStyle {
4171            ..default_md_style.base_text_style
4172        },
4173        selection_background_color: cx.theme().colors().element_selection_background,
4174        ..Default::default()
4175    }
4176}
4177
4178#[cfg(test)]
4179pub(crate) mod tests {
4180    use acp_thread::StubAgentConnection;
4181    use agent_client_protocol::SessionId;
4182    use assistant_context::ContextStore;
4183    use editor::EditorSettings;
4184    use fs::FakeFs;
4185    use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
4186    use project::Project;
4187    use serde_json::json;
4188    use settings::SettingsStore;
4189    use std::any::Any;
4190    use std::path::Path;
4191    use workspace::Item;
4192
4193    use super::*;
4194
4195    #[gpui::test]
4196    async fn test_drop(cx: &mut TestAppContext) {
4197        init_test(cx);
4198
4199        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4200        let weak_view = thread_view.downgrade();
4201        drop(thread_view);
4202        assert!(!weak_view.is_upgradable());
4203    }
4204
4205    #[gpui::test]
4206    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
4207        init_test(cx);
4208
4209        let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4210
4211        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4212        message_editor.update_in(cx, |editor, window, cx| {
4213            editor.set_text("Hello", window, cx);
4214        });
4215
4216        cx.deactivate_window();
4217
4218        thread_view.update_in(cx, |thread_view, window, cx| {
4219            thread_view.send(window, cx);
4220        });
4221
4222        cx.run_until_parked();
4223
4224        assert!(
4225            cx.windows()
4226                .iter()
4227                .any(|window| window.downcast::<AgentNotification>().is_some())
4228        );
4229    }
4230
4231    #[gpui::test]
4232    async fn test_notification_for_error(cx: &mut TestAppContext) {
4233        init_test(cx);
4234
4235        let (thread_view, cx) =
4236            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
4237
4238        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4239        message_editor.update_in(cx, |editor, window, cx| {
4240            editor.set_text("Hello", window, cx);
4241        });
4242
4243        cx.deactivate_window();
4244
4245        thread_view.update_in(cx, |thread_view, window, cx| {
4246            thread_view.send(window, cx);
4247        });
4248
4249        cx.run_until_parked();
4250
4251        assert!(
4252            cx.windows()
4253                .iter()
4254                .any(|window| window.downcast::<AgentNotification>().is_some())
4255        );
4256    }
4257
4258    #[gpui::test]
4259    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
4260        init_test(cx);
4261
4262        let tool_call_id = acp::ToolCallId("1".into());
4263        let tool_call = acp::ToolCall {
4264            id: tool_call_id.clone(),
4265            title: "Label".into(),
4266            kind: acp::ToolKind::Edit,
4267            status: acp::ToolCallStatus::Pending,
4268            content: vec!["hi".into()],
4269            locations: vec![],
4270            raw_input: None,
4271            raw_output: None,
4272        };
4273        let connection =
4274            StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4275                tool_call_id,
4276                vec![acp::PermissionOption {
4277                    id: acp::PermissionOptionId("1".into()),
4278                    name: "Allow".into(),
4279                    kind: acp::PermissionOptionKind::AllowOnce,
4280                }],
4281            )]));
4282
4283        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4284
4285        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4286
4287        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4288        message_editor.update_in(cx, |editor, window, cx| {
4289            editor.set_text("Hello", window, cx);
4290        });
4291
4292        cx.deactivate_window();
4293
4294        thread_view.update_in(cx, |thread_view, window, cx| {
4295            thread_view.send(window, cx);
4296        });
4297
4298        cx.run_until_parked();
4299
4300        assert!(
4301            cx.windows()
4302                .iter()
4303                .any(|window| window.downcast::<AgentNotification>().is_some())
4304        );
4305    }
4306
4307    async fn setup_thread_view(
4308        agent: impl AgentServer + 'static,
4309        cx: &mut TestAppContext,
4310    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4311        let fs = FakeFs::new(cx.executor());
4312        let project = Project::test(fs, [], cx).await;
4313        let (workspace, cx) =
4314            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4315
4316        let context_store =
4317            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4318        let history_store =
4319            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4320
4321        let thread_view = cx.update(|window, cx| {
4322            cx.new(|cx| {
4323                AcpThreadView::new(
4324                    Rc::new(agent),
4325                    None,
4326                    workspace.downgrade(),
4327                    project,
4328                    history_store,
4329                    None,
4330                    window,
4331                    cx,
4332                )
4333            })
4334        });
4335        cx.run_until_parked();
4336        (thread_view, cx)
4337    }
4338
4339    fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4340        let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4341
4342        workspace
4343            .update_in(cx, |workspace, window, cx| {
4344                workspace.add_item_to_active_pane(
4345                    Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4346                    None,
4347                    true,
4348                    window,
4349                    cx,
4350                );
4351            })
4352            .unwrap();
4353    }
4354
4355    struct ThreadViewItem(Entity<AcpThreadView>);
4356
4357    impl Item for ThreadViewItem {
4358        type Event = ();
4359
4360        fn include_in_nav_history() -> bool {
4361            false
4362        }
4363
4364        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
4365            "Test".into()
4366        }
4367    }
4368
4369    impl EventEmitter<()> for ThreadViewItem {}
4370
4371    impl Focusable for ThreadViewItem {
4372        fn focus_handle(&self, cx: &App) -> FocusHandle {
4373            self.0.read(cx).focus_handle(cx)
4374        }
4375    }
4376
4377    impl Render for ThreadViewItem {
4378        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4379            self.0.clone().into_any_element()
4380        }
4381    }
4382
4383    struct StubAgentServer<C> {
4384        connection: C,
4385    }
4386
4387    impl<C> StubAgentServer<C> {
4388        fn new(connection: C) -> Self {
4389            Self { connection }
4390        }
4391    }
4392
4393    impl StubAgentServer<StubAgentConnection> {
4394        fn default_response() -> Self {
4395            let conn = StubAgentConnection::new();
4396            conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4397                content: "Default response".into(),
4398            }]);
4399            Self::new(conn)
4400        }
4401    }
4402
4403    impl<C> AgentServer for StubAgentServer<C>
4404    where
4405        C: 'static + AgentConnection + Send + Clone,
4406    {
4407        fn logo(&self) -> ui::IconName {
4408            ui::IconName::Ai
4409        }
4410
4411        fn name(&self) -> &'static str {
4412            "Test"
4413        }
4414
4415        fn empty_state_headline(&self) -> &'static str {
4416            "Test"
4417        }
4418
4419        fn empty_state_message(&self) -> &'static str {
4420            "Test"
4421        }
4422
4423        fn connect(
4424            &self,
4425            _root_dir: &Path,
4426            _project: &Entity<Project>,
4427            _cx: &mut App,
4428        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4429            Task::ready(Ok(Rc::new(self.connection.clone())))
4430        }
4431
4432        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4433            self
4434        }
4435    }
4436
4437    #[derive(Clone)]
4438    struct SaboteurAgentConnection;
4439
4440    impl AgentConnection for SaboteurAgentConnection {
4441        fn new_thread(
4442            self: Rc<Self>,
4443            project: Entity<Project>,
4444            _cwd: &Path,
4445            cx: &mut gpui::App,
4446        ) -> Task<gpui::Result<Entity<AcpThread>>> {
4447            Task::ready(Ok(cx.new(|cx| {
4448                let action_log = cx.new(|_| ActionLog::new(project.clone()));
4449                AcpThread::new(
4450                    "SaboteurAgentConnection",
4451                    self,
4452                    project,
4453                    action_log,
4454                    SessionId("test".into()),
4455                )
4456            })))
4457        }
4458
4459        fn auth_methods(&self) -> &[acp::AuthMethod] {
4460            &[]
4461        }
4462
4463        fn authenticate(
4464            &self,
4465            _method_id: acp::AuthMethodId,
4466            _cx: &mut App,
4467        ) -> Task<gpui::Result<()>> {
4468            unimplemented!()
4469        }
4470
4471        fn prompt(
4472            &self,
4473            _id: Option<acp_thread::UserMessageId>,
4474            _params: acp::PromptRequest,
4475            _cx: &mut App,
4476        ) -> Task<gpui::Result<acp::PromptResponse>> {
4477            Task::ready(Err(anyhow::anyhow!("Error prompting")))
4478        }
4479
4480        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4481            unimplemented!()
4482        }
4483
4484        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4485            self
4486        }
4487    }
4488
4489    pub(crate) fn init_test(cx: &mut TestAppContext) {
4490        cx.update(|cx| {
4491            let settings_store = SettingsStore::test(cx);
4492            cx.set_global(settings_store);
4493            language::init(cx);
4494            Project::init_settings(cx);
4495            AgentSettings::register(cx);
4496            workspace::init_settings(cx);
4497            ThemeSettings::register(cx);
4498            release_channel::init(SemanticVersion::default(), cx);
4499            EditorSettings::register(cx);
4500            prompt_store::init(cx)
4501        });
4502    }
4503
4504    #[gpui::test]
4505    async fn test_rewind_views(cx: &mut TestAppContext) {
4506        init_test(cx);
4507
4508        let fs = FakeFs::new(cx.executor());
4509        fs.insert_tree(
4510            "/project",
4511            json!({
4512                "test1.txt": "old content 1",
4513                "test2.txt": "old content 2"
4514            }),
4515        )
4516        .await;
4517        let project = Project::test(fs, [Path::new("/project")], cx).await;
4518        let (workspace, cx) =
4519            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4520
4521        let context_store =
4522            cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4523        let history_store =
4524            cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4525
4526        let connection = Rc::new(StubAgentConnection::new());
4527        let thread_view = cx.update(|window, cx| {
4528            cx.new(|cx| {
4529                AcpThreadView::new(
4530                    Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4531                    None,
4532                    workspace.downgrade(),
4533                    project.clone(),
4534                    history_store.clone(),
4535                    None,
4536                    window,
4537                    cx,
4538                )
4539            })
4540        });
4541
4542        cx.run_until_parked();
4543
4544        let thread = thread_view
4545            .read_with(cx, |view, _| view.thread().cloned())
4546            .unwrap();
4547
4548        // First user message
4549        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4550            id: acp::ToolCallId("tool1".into()),
4551            title: "Edit file 1".into(),
4552            kind: acp::ToolKind::Edit,
4553            status: acp::ToolCallStatus::Completed,
4554            content: vec![acp::ToolCallContent::Diff {
4555                diff: acp::Diff {
4556                    path: "/project/test1.txt".into(),
4557                    old_text: Some("old content 1".into()),
4558                    new_text: "new content 1".into(),
4559                },
4560            }],
4561            locations: vec![],
4562            raw_input: None,
4563            raw_output: None,
4564        })]);
4565
4566        thread
4567            .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4568            .await
4569            .unwrap();
4570        cx.run_until_parked();
4571
4572        thread.read_with(cx, |thread, _| {
4573            assert_eq!(thread.entries().len(), 2);
4574        });
4575
4576        thread_view.read_with(cx, |view, cx| {
4577            view.entry_view_state.read_with(cx, |entry_view_state, _| {
4578                assert!(
4579                    entry_view_state
4580                        .entry(0)
4581                        .unwrap()
4582                        .message_editor()
4583                        .is_some()
4584                );
4585                assert!(entry_view_state.entry(1).unwrap().has_content());
4586            });
4587        });
4588
4589        // Second user message
4590        connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4591            id: acp::ToolCallId("tool2".into()),
4592            title: "Edit file 2".into(),
4593            kind: acp::ToolKind::Edit,
4594            status: acp::ToolCallStatus::Completed,
4595            content: vec![acp::ToolCallContent::Diff {
4596                diff: acp::Diff {
4597                    path: "/project/test2.txt".into(),
4598                    old_text: Some("old content 2".into()),
4599                    new_text: "new content 2".into(),
4600                },
4601            }],
4602            locations: vec![],
4603            raw_input: None,
4604            raw_output: None,
4605        })]);
4606
4607        thread
4608            .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4609            .await
4610            .unwrap();
4611        cx.run_until_parked();
4612
4613        let second_user_message_id = thread.read_with(cx, |thread, _| {
4614            assert_eq!(thread.entries().len(), 4);
4615            let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4616                panic!();
4617            };
4618            user_message.id.clone().unwrap()
4619        });
4620
4621        thread_view.read_with(cx, |view, cx| {
4622            view.entry_view_state.read_with(cx, |entry_view_state, _| {
4623                assert!(
4624                    entry_view_state
4625                        .entry(0)
4626                        .unwrap()
4627                        .message_editor()
4628                        .is_some()
4629                );
4630                assert!(entry_view_state.entry(1).unwrap().has_content());
4631                assert!(
4632                    entry_view_state
4633                        .entry(2)
4634                        .unwrap()
4635                        .message_editor()
4636                        .is_some()
4637                );
4638                assert!(entry_view_state.entry(3).unwrap().has_content());
4639            });
4640        });
4641
4642        // Rewind to first message
4643        thread
4644            .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4645            .await
4646            .unwrap();
4647
4648        cx.run_until_parked();
4649
4650        thread.read_with(cx, |thread, _| {
4651            assert_eq!(thread.entries().len(), 2);
4652        });
4653
4654        thread_view.read_with(cx, |view, cx| {
4655            view.entry_view_state.read_with(cx, |entry_view_state, _| {
4656                assert!(
4657                    entry_view_state
4658                        .entry(0)
4659                        .unwrap()
4660                        .message_editor()
4661                        .is_some()
4662                );
4663                assert!(entry_view_state.entry(1).unwrap().has_content());
4664
4665                // Old views should be dropped
4666                assert!(entry_view_state.entry(2).is_none());
4667                assert!(entry_view_state.entry(3).is_none());
4668            });
4669        });
4670    }
4671
4672    #[gpui::test]
4673    async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4674        init_test(cx);
4675
4676        let connection = StubAgentConnection::new();
4677
4678        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4679            content: acp::ContentBlock::Text(acp::TextContent {
4680                text: "Response".into(),
4681                annotations: None,
4682            }),
4683        }]);
4684
4685        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4686        add_to_workspace(thread_view.clone(), cx);
4687
4688        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4689        message_editor.update_in(cx, |editor, window, cx| {
4690            editor.set_text("Original message to edit", window, cx);
4691        });
4692        thread_view.update_in(cx, |thread_view, window, cx| {
4693            thread_view.send(window, cx);
4694        });
4695
4696        cx.run_until_parked();
4697
4698        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4699            assert_eq!(view.editing_message, None);
4700
4701            view.entry_view_state
4702                .read(cx)
4703                .entry(0)
4704                .unwrap()
4705                .message_editor()
4706                .unwrap()
4707                .clone()
4708        });
4709
4710        // Focus
4711        cx.focus(&user_message_editor);
4712        thread_view.read_with(cx, |view, _cx| {
4713            assert_eq!(view.editing_message, Some(0));
4714        });
4715
4716        // Edit
4717        user_message_editor.update_in(cx, |editor, window, cx| {
4718            editor.set_text("Edited message content", window, cx);
4719        });
4720
4721        // Cancel
4722        user_message_editor.update_in(cx, |_editor, window, cx| {
4723            window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4724        });
4725
4726        thread_view.read_with(cx, |view, _cx| {
4727            assert_eq!(view.editing_message, None);
4728        });
4729
4730        user_message_editor.read_with(cx, |editor, cx| {
4731            assert_eq!(editor.text(cx), "Original message to edit");
4732        });
4733    }
4734
4735    #[gpui::test]
4736    async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4737        init_test(cx);
4738
4739        let connection = StubAgentConnection::new();
4740
4741        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4742        add_to_workspace(thread_view.clone(), cx);
4743
4744        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4745        let mut events = cx.events(&message_editor);
4746        message_editor.update_in(cx, |editor, window, cx| {
4747            editor.set_text("", window, cx);
4748        });
4749
4750        message_editor.update_in(cx, |_editor, window, cx| {
4751            window.dispatch_action(Box::new(Chat), cx);
4752        });
4753        cx.run_until_parked();
4754        // We shouldn't have received any messages
4755        assert!(matches!(
4756            events.try_next(),
4757            Err(futures::channel::mpsc::TryRecvError { .. })
4758        ));
4759    }
4760
4761    #[gpui::test]
4762    async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4763        init_test(cx);
4764
4765        let connection = StubAgentConnection::new();
4766
4767        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4768            content: acp::ContentBlock::Text(acp::TextContent {
4769                text: "Response".into(),
4770                annotations: None,
4771            }),
4772        }]);
4773
4774        let (thread_view, cx) =
4775            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4776        add_to_workspace(thread_view.clone(), cx);
4777
4778        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4779        message_editor.update_in(cx, |editor, window, cx| {
4780            editor.set_text("Original message to edit", window, cx);
4781        });
4782        thread_view.update_in(cx, |thread_view, window, cx| {
4783            thread_view.send(window, cx);
4784        });
4785
4786        cx.run_until_parked();
4787
4788        let user_message_editor = thread_view.read_with(cx, |view, cx| {
4789            assert_eq!(view.editing_message, None);
4790            assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4791
4792            view.entry_view_state
4793                .read(cx)
4794                .entry(0)
4795                .unwrap()
4796                .message_editor()
4797                .unwrap()
4798                .clone()
4799        });
4800
4801        // Focus
4802        cx.focus(&user_message_editor);
4803
4804        // Edit
4805        user_message_editor.update_in(cx, |editor, window, cx| {
4806            editor.set_text("Edited message content", window, cx);
4807        });
4808
4809        // Send
4810        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4811            content: acp::ContentBlock::Text(acp::TextContent {
4812                text: "New Response".into(),
4813                annotations: None,
4814            }),
4815        }]);
4816
4817        user_message_editor.update_in(cx, |_editor, window, cx| {
4818            window.dispatch_action(Box::new(Chat), cx);
4819        });
4820
4821        cx.run_until_parked();
4822
4823        thread_view.read_with(cx, |view, cx| {
4824            assert_eq!(view.editing_message, None);
4825
4826            let entries = view.thread().unwrap().read(cx).entries();
4827            assert_eq!(entries.len(), 2);
4828            assert_eq!(
4829                entries[0].to_markdown(cx),
4830                "## User\n\nEdited message content\n\n"
4831            );
4832            assert_eq!(
4833                entries[1].to_markdown(cx),
4834                "## Assistant\n\nNew Response\n\n"
4835            );
4836
4837            let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4838                assert!(!state.entry(1).unwrap().has_content());
4839                state.entry(0).unwrap().message_editor().unwrap().clone()
4840            });
4841
4842            assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4843        })
4844    }
4845
4846    #[gpui::test]
4847    async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4848        init_test(cx);
4849
4850        let connection = StubAgentConnection::new();
4851
4852        let (thread_view, cx) =
4853            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4854        add_to_workspace(thread_view.clone(), cx);
4855
4856        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4857        message_editor.update_in(cx, |editor, window, cx| {
4858            editor.set_text("Original message to edit", window, cx);
4859        });
4860        thread_view.update_in(cx, |thread_view, window, cx| {
4861            thread_view.send(window, cx);
4862        });
4863
4864        cx.run_until_parked();
4865
4866        let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4867            let thread = view.thread().unwrap().read(cx);
4868            assert_eq!(thread.entries().len(), 1);
4869
4870            let editor = view
4871                .entry_view_state
4872                .read(cx)
4873                .entry(0)
4874                .unwrap()
4875                .message_editor()
4876                .unwrap()
4877                .clone();
4878
4879            (editor, thread.session_id().clone())
4880        });
4881
4882        // Focus
4883        cx.focus(&user_message_editor);
4884
4885        thread_view.read_with(cx, |view, _cx| {
4886            assert_eq!(view.editing_message, Some(0));
4887        });
4888
4889        // Edit
4890        user_message_editor.update_in(cx, |editor, window, cx| {
4891            editor.set_text("Edited message content", window, cx);
4892        });
4893
4894        thread_view.read_with(cx, |view, _cx| {
4895            assert_eq!(view.editing_message, Some(0));
4896        });
4897
4898        // Finish streaming response
4899        cx.update(|_, cx| {
4900            connection.send_update(
4901                session_id.clone(),
4902                acp::SessionUpdate::AgentMessageChunk {
4903                    content: acp::ContentBlock::Text(acp::TextContent {
4904                        text: "Response".into(),
4905                        annotations: None,
4906                    }),
4907                },
4908                cx,
4909            );
4910            connection.end_turn(session_id, acp::StopReason::EndTurn);
4911        });
4912
4913        thread_view.read_with(cx, |view, _cx| {
4914            assert_eq!(view.editing_message, Some(0));
4915        });
4916
4917        cx.run_until_parked();
4918
4919        // Should still be editing
4920        cx.update(|window, cx| {
4921            assert!(user_message_editor.focus_handle(cx).is_focused(window));
4922            assert_eq!(thread_view.read(cx).editing_message, Some(0));
4923            assert_eq!(
4924                user_message_editor.read(cx).text(cx),
4925                "Edited message content"
4926            );
4927        });
4928    }
4929
4930    #[gpui::test]
4931    async fn test_interrupt(cx: &mut TestAppContext) {
4932        init_test(cx);
4933
4934        let connection = StubAgentConnection::new();
4935
4936        let (thread_view, cx) =
4937            setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4938        add_to_workspace(thread_view.clone(), cx);
4939
4940        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4941        message_editor.update_in(cx, |editor, window, cx| {
4942            editor.set_text("Message 1", window, cx);
4943        });
4944        thread_view.update_in(cx, |thread_view, window, cx| {
4945            thread_view.send(window, cx);
4946        });
4947
4948        let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4949            let thread = view.thread().unwrap();
4950
4951            (thread.clone(), thread.read(cx).session_id().clone())
4952        });
4953
4954        cx.run_until_parked();
4955
4956        cx.update(|_, cx| {
4957            connection.send_update(
4958                session_id.clone(),
4959                acp::SessionUpdate::AgentMessageChunk {
4960                    content: "Message 1 resp".into(),
4961                },
4962                cx,
4963            );
4964        });
4965
4966        cx.run_until_parked();
4967
4968        thread.read_with(cx, |thread, cx| {
4969            assert_eq!(
4970                thread.to_markdown(cx),
4971                indoc::indoc! {"
4972                    ## User
4973
4974                    Message 1
4975
4976                    ## Assistant
4977
4978                    Message 1 resp
4979
4980                "}
4981            )
4982        });
4983
4984        message_editor.update_in(cx, |editor, window, cx| {
4985            editor.set_text("Message 2", window, cx);
4986        });
4987        thread_view.update_in(cx, |thread_view, window, cx| {
4988            thread_view.send(window, cx);
4989        });
4990
4991        cx.update(|_, cx| {
4992            // Simulate a response sent after beginning to cancel
4993            connection.send_update(
4994                session_id.clone(),
4995                acp::SessionUpdate::AgentMessageChunk {
4996                    content: "onse".into(),
4997                },
4998                cx,
4999            );
5000        });
5001
5002        cx.run_until_parked();
5003
5004        // Last Message 1 response should appear before Message 2
5005        thread.read_with(cx, |thread, cx| {
5006            assert_eq!(
5007                thread.to_markdown(cx),
5008                indoc::indoc! {"
5009                    ## User
5010
5011                    Message 1
5012
5013                    ## Assistant
5014
5015                    Message 1 response
5016
5017                    ## User
5018
5019                    Message 2
5020
5021                "}
5022            )
5023        });
5024
5025        cx.update(|_, cx| {
5026            connection.send_update(
5027                session_id.clone(),
5028                acp::SessionUpdate::AgentMessageChunk {
5029                    content: "Message 2 response".into(),
5030                },
5031                cx,
5032            );
5033            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5034        });
5035
5036        cx.run_until_parked();
5037
5038        thread.read_with(cx, |thread, cx| {
5039            assert_eq!(
5040                thread.to_markdown(cx),
5041                indoc::indoc! {"
5042                    ## User
5043
5044                    Message 1
5045
5046                    ## Assistant
5047
5048                    Message 1 response
5049
5050                    ## User
5051
5052                    Message 2
5053
5054                    ## Assistant
5055
5056                    Message 2 response
5057
5058                "}
5059            )
5060        });
5061    }
5062}