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