thread_view.rs

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