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