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